diff --git a/.gitignore b/.gitignore index 19d96d0b046a5..5125de360b83e 100644 --- a/.gitignore +++ b/.gitignore @@ -58,6 +58,7 @@ internal/ !tests/baselines/reference/project/nodeModules*/**/* .idea yarn.lock +yarn-error.log .parallelperf.* tests/cases/user/*/package-lock.json tests/cases/user/*/node_modules/ diff --git a/.gitmodules b/.gitmodules index e5cf4c016e931..bd4620625cfd6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,24 +2,19 @@ path = tests/cases/user/TypeScript-React-Starter/TypeScript-React-Starter url = https://github.com/Microsoft/TypeScript-React-Starter ignore = all - shallow = true [submodule "tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter"] path = tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter url = https://github.com/Microsoft/TypeScript-Node-Starter.git ignore = all - shallow = true [submodule "tests/cases/user/TypeScript-React-Native-Starter/TypeScript-React-Native-Starter"] path = tests/cases/user/TypeScript-React-Native-Starter/TypeScript-React-Native-Starter url = https://github.com/Microsoft/TypeScript-React-Native-Starter.git ignore = all - shallow = true [submodule "tests/cases/user/TypeScript-Vue-Starter/TypeScript-Vue-Starter"] path = tests/cases/user/TypeScript-Vue-Starter/TypeScript-Vue-Starter url = https://github.com/Microsoft/TypeScript-Vue-Starter.git ignore = all - shallow = true [submodule "tests/cases/user/TypeScript-WeChat-Starter/TypeScript-WeChat-Starter"] path = tests/cases/user/TypeScript-WeChat-Starter/TypeScript-WeChat-Starter url = https://github.com/Microsoft/TypeScript-WeChat-Starter.git ignore = all - shallow = true diff --git a/.travis.yml b/.travis.yml index 06e912c55f5dd..b4a5227c34ae4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,7 @@ branches: - master - release-2.5 - release-2.6 + - release-2.7 install: - npm uninstall typescript --no-save diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6dbb7e514a0da..1d11db2f87b61 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,14 @@ Issues that ask questions answered in the FAQ will be closed without elaboration ## 2. Search for Duplicates -[Search the existing issues](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) before logging a new one. +[Search the existing issues](https://github.com/Microsoft/TypeScript/search?type=Issues) before logging a new one. + +Some search tips: + * *Don't* restrict your search to only open issues. An issue with a title similar to yours may have been closed as a duplicate of one with a less-findable title. + * Check for synonyms. For example, if your bug involves an interface, it likely also occurs with type aliases or classes. + * Search for the title of the issue you're about to log. This sounds obvious but 80% of the time this is sufficient to find a duplicate when one exists. + * Read more than the first page of results. Many bugs here use the same words so relevancy sorting is not particularly strong. + * If you have a crash, search for the first few topmost function names shown in the call stack. ## 3. Do you have a question? @@ -183,3 +190,10 @@ jake baseline-accept ``` to establish the new baselines as the desired behavior. This will change the files in `tests\baselines\reference`, which should be included as part of your commit. It's important to carefully validate changes in the baselines. + +## Localization + +All strings the user may see are stored in [`diagnosticMessages.json`](./src/compiler/diagnosticMessages.json). +If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in [`diagnosticInformationMap.generated.ts`](./src/compiler/diagnosticInformationMap.generated.ts). + +See [coding guidelines on diagnostic messages](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#diagnostic-messages). diff --git a/Gulpfile.ts b/Gulpfile.ts index aedde5c33d955..2909b10471aa2 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -145,8 +145,14 @@ const es2017LibrarySource = [ const es2017LibrarySourceMap = es2017LibrarySource.map(source => ({ target: "lib." + source, sources: ["header.d.ts", source] })); +const es2018LibrarySource = []; +const es2018LibrarySourceMap = es2018LibrarySource.map(source => + ({ target: "lib." + source, sources: ["header.d.ts", source] })); + const esnextLibrarySource = [ - "esnext.asynciterable.d.ts" + "esnext.asynciterable.d.ts", + "esnext.array.d.ts", + "esnext.promise.d.ts" ]; const esnextLibrarySourceMap = esnextLibrarySource.map(source => @@ -166,6 +172,7 @@ const librarySourceMap = [ { target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] }, { target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] }, { target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] }, + { target: "lib.es2018.d.ts", sources: ["header.d.ts", "es2018.d.ts"] }, { target: "lib.esnext.d.ts", sources: ["header.d.ts", "esnext.d.ts"] }, // JavaScript + all host library @@ -173,8 +180,9 @@ const librarySourceMap = [ { target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }, { target: "lib.es2016.full.d.ts", sources: ["header.d.ts", "es2016.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, { target: "lib.es2017.full.d.ts", sources: ["header.d.ts", "es2017.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, + { target: "lib.es2018.full.d.ts", sources: ["header.d.ts", "es2018.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, { target: "lib.esnext.full.d.ts", sources: ["header.d.ts", "esnext.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, -].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, esnextLibrarySourceMap); +].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, es2018LibrarySourceMap, esnextLibrarySourceMap); const libraryTargets = librarySourceMap.map(f => path.join(builtLocalDirectory, f.target)); @@ -673,14 +681,14 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: workerCount = cmdLineOptions.workers; } - if (tests || runners || light || taskConfigsFolder) { - writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit); - } - if (tests && tests.toLocaleLowerCase() === "rwc") { testTimeout = 400000; } + if (tests || runners || light || testTimeout || taskConfigsFolder) { + writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, testTimeout); + } + const colors = cmdLineOptions.colors; const reporter = cmdLineOptions.reporter || defaultReporter; @@ -865,8 +873,17 @@ function cleanTestDirs(done: (e?: any) => void) { } // used to pass data from jake command line directly to run.js -function writeTestConfigFile(tests: string, runners: string, light: boolean, taskConfigsFolder?: string, workerCount?: number, stackTraceLimit?: string) { - const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, runner: runners ? runners.split(",") : undefined, light, workerCount, stackTraceLimit, taskConfigsFolder, noColor: !cmdLineOptions.colors }); +function writeTestConfigFile(tests: string, runners: string, light: boolean, taskConfigsFolder?: string, workerCount?: number, stackTraceLimit?: string, timeout?: number) { + const testConfigContents = JSON.stringify({ + test: tests ? [tests] : undefined, + runner: runners ? runners.split(",") : undefined, + light, + workerCount, + stackTraceLimit, + taskConfigsFolder, + noColor: !cmdLineOptions.colors, + timeout, + }); console.log("Running tests with config: " + testConfigContents); fs.writeFileSync("test.config", testConfigContents); } diff --git a/Jakefile.js b/Jakefile.js index 4f39d6af5c6cf..2026544a249bc 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -130,6 +130,7 @@ var harnessSources = harnessCoreSources.concat([ "textStorage.ts", "moduleResolution.ts", "tsconfigParsing.ts", + "asserts.ts", "builder.ts", "commandLineParsing.ts", "configurationExtension.ts", @@ -205,8 +206,16 @@ var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) { return { target: "lib." + source, sources: ["header.d.ts", source] }; }); +var es2018LibrarySource = []; + +var es2018LibrarySourceMap = es2018LibrarySource.map(function (source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + var esnextLibrarySource = [ - "esnext.asynciterable.d.ts" + "esnext.asynciterable.d.ts", + "esnext.array.d.ts", + "esnext.promise.d.ts" ]; var esnextLibrarySourceMap = esnextLibrarySource.map(function (source) { @@ -227,6 +236,7 @@ var librarySourceMap = [ { target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] }, { target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] }, { target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] }, + { target: "lib.es2018.d.ts", sources: ["header.d.ts", "es2018.d.ts"] }, { target: "lib.esnext.d.ts", sources: ["header.d.ts", "esnext.d.ts"] }, // JavaScript + all host library @@ -234,8 +244,9 @@ var librarySourceMap = [ { target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }, { target: "lib.es2016.full.d.ts", sources: ["header.d.ts", "es2016.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, { target: "lib.es2017.full.d.ts", sources: ["header.d.ts", "es2017.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, + { target: "lib.es2018.full.d.ts", sources: ["header.d.ts", "es2018.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, { target: "lib.esnext.full.d.ts", sources: ["header.d.ts", "esnext.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") }, -].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, esnextLibrarySourceMap); +].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, es2018LibrarySourceMap, esnextLibrarySourceMap); var libraryTargets = librarySourceMap.map(function (f) { return path.join(builtLocalDirectory, f.target); @@ -848,7 +859,7 @@ function cleanTestDirs() { } // used to pass data from jake command line directly to run.js -function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors) { +function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors, testTimeout) { var testConfigContents = JSON.stringify({ runners: runners ? runners.split(",") : undefined, test: tests ? [tests] : undefined, @@ -856,7 +867,8 @@ function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCou workerCount: workerCount, taskConfigsFolder: taskConfigsFolder, stackTraceLimit: stackTraceLimit, - noColor: !colors + noColor: !colors, + timeout: testTimeout }); fs.writeFileSync('test.config', testConfigContents); } @@ -898,14 +910,14 @@ function runConsoleTests(defaultReporter, runInParallel) { workerCount = process.env.workerCount || process.env.p || os.cpus().length; } - if (tests || runners || light || taskConfigsFolder) { - writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors); - } - if (tests && tests.toLocaleLowerCase() === "rwc") { testTimeout = 800000; } + if (tests || runners || light || testTimeout || taskConfigsFolder) { + writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors, testTimeout); + } + var colorsFlag = process.env.color || process.env.colors; var colors = colorsFlag !== "false" && colorsFlag !== "0"; var reporter = process.env.reporter || process.env.r || defaultReporter; @@ -1192,6 +1204,7 @@ var tslintRules = [ "debugAssertRule", "nextLineRule", "noBomRule", + "noDoubleSpaceRule", "noIncrementDecrementRule", "noInOperatorRule", "noTypeAssertionWhitespaceRule", diff --git a/issue_template.md b/issue_template.md index dbc021c28adaf..22acf3e9cc513 100644 --- a/issue_template.md +++ b/issue_template.md @@ -15,3 +15,5 @@ **Expected behavior:** **Actual behavior:** + +**Related:** diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index ec9453bb00c99..0e37b0689e02f 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -69,5 +69,3 @@ function createCancellationToken(args) { } } module.exports = createCancellationToken; - -//# sourceMappingURL=cancellationToken.js.map diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..8326f8fc73983 --- /dev/null +++ b/lib/cs/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Modifikátor {0} nejde použít s deklarací import.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Modifikátor {0} nejde použít s deklarací interface.", + "A_0_parameter_must_be_the_first_parameter_2680": "Parametr {0} musí být prvním parametrem.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Parametr vzoru vazby nemůže být u podpisu implementace nepovinný.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Příkaz break se dá použít jenom uvnitř nadřazené iterace nebo příkazu switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Příkaz break může skočit jenom na popisek nadřazeného příkazu.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Třída může implementovat jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Deklarace třídy bez modifikátoru default musí mít název.", + "A_class_may_only_extend_another_class_2311": "Třída může rozšířit jenom jinou třídu.", + "A_class_may_only_implement_another_class_or_interface_2422": "Třída může implementovat jenom jinou třídu nebo rozhraní.", + "A_class_member_cannot_have_the_0_keyword_1248": "Člen třídy nemůže mít klíčové slovo {0}.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Výraz s čárkou není v názvu počítané vlastnosti povolený.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Název počítané vlastnosti nemůže odkazovat na parametr typu z jeho nadřazeného typu.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Název vypočítané vlastnosti v deklaraci vlastnosti třídy musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Název vypočítané vlastnosti v přetížené metodě musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Název vypočítané vlastnosti v literálu typu musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Název vypočítané vlastnosti v ambientním kontextu musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Název vypočítané vlastnosti v rozhraní musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Název počítané vlastnosti musí být typu string, number, symbol nebo any.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Název počítané vlastnosti ve formátu {0} musí být typu symbol.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Ke členu konstantního výčtu se dá získat přístup jenom pomocí řetězcového literálu.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Inicializátor const v ambientním kontextu musí být řetězec (string) nebo číselný literál.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Konstruktor nemůže obsahovat volání super, pokud jeho třída rozšiřuje null.", + "A_constructor_cannot_have_a_this_parameter_2681": "Konstruktor nemůže mít parametr this.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Příkaz continue se dá použít jenom uvnitř příkazu nadřazené iterace.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Příkaz continue může přejít jenom na popisek příkazu nadřazené iterace.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Modifikátor declare se nedá použít v kontextu, který už je ambientní.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Pro deklaraci na nejvyšší úrovni v souboru .d.ts se vyžaduje modifikátor declare.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorátor může dekorovat jenom implementaci metody, ne přetížení.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzule default nemůže být v příkazu switch víc než jednou.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "V modulu ve stylu ECMAScriptu se dá použít jenom výchozí export.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Určitý kontrolní výraz přiřazení '!' není v tomto kontextu povolený.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Destrukturační deklarace musí obsahovat inicializátor.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Volání dynamického importu v ES5/ES3 vyžaduje konstruktor Promise. Ujistěte se, že máte deklaraci konstruktoru Promise, nebo do možnosti --lib přidejte ES2015.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Volání dynamického importu vrací Promise. Ujistěte se, že pro ni máte deklaraci, nebo do možnosti --lib přidejte ES2015.", + "A_file_cannot_have_a_reference_to_itself_1006": "Soubor nemůže odkazovat sám na sebe.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Příkaz for-await-of se povoluje jenom v asynchronní funkci nebo asynchronním generátoru.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Funkce, která vrací hodnotu never, nemůže mít dosažitelný koncový bod.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Funkce volaná klíčovým slovem new nemůže mít typ this, který je void.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Funkce, jejíž deklarovaný typ není void ani any, musí vracet hodnotu.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Generátor nemůže mít anotaci typu void.", + "A_get_accessor_cannot_have_parameters_1054": "Přístupový objekt get nemůže obsahovat parametry.", + "A_get_accessor_must_return_a_value_2378": "Přístupový objekt get musí vracet hodnotu.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicializátor členu v deklaraci výčtu nemůže odkazovat na členy deklarované až po výčtu, a to ani členy definované v jiných výčtech.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Třída mixin musí mít konstruktor s jediným parametrem rest typu any[].", + "A_module_cannot_have_multiple_default_exports_2528": "Modul nemůže mít víc výchozích exportů.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklarace oboru názvů nemůže být v jiném souboru než třída nebo funkce, se kterou se slučuje.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklarace oboru názvů nemůže být umístěná před třídou nebo funkcí, se kterou se slučuje.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklarace oboru názvů je povolená jenom v oboru názvů nebo v modulu.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicializátor parametru je povolený jenom v implementaci funkce nebo konstruktoru.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Vlastnost parametru se nedá deklarovat pomocí parametru rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Vlastnost parametru je povolená jenom v implementaci konstruktoru.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Vlastnost parametru se nedá deklarovat pomocí vzoru vazby.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Cesta v možnosti extends musí být relativní nebo mít kořen, ale {0} nic z toho nesplňuje.", + "A_promise_must_have_a_then_method_1059": "Příslib musí mít metodu then.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Vlastnost třídy, jejíž typ je jedinečný symbol, musí být static a readonly.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Vlastnost rozhraní nebo literálu typu, jehož typ je jedinečný symbol, musí být readonly.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Povinný parametr nemůže následovat po nepovinném parametru.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nemůže obsahovat vzor vazby.", + "A_rest_element_cannot_have_an_initializer_1186": "Element rest nemůže obsahovat inicializátor.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Element rest musí být ve vzoru destrukturalizace poslední.", + "A_rest_parameter_cannot_be_optional_1047": "Parametr rest nemůže být nepovinný.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Parametr rest nemůže obsahovat inicializátor.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Parametr rest musí být posledním v seznamu parametrů.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Parametr rest musí být typu pole.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Příkaz return se dá použít jenom v těle funkce.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Řada záznamů, které mění mapování importů do umístění vyhledávání relativních vůči baseUrl.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Přístupový objekt set nemůže obsahovat anotaci návratového typu.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Přístupový objekt set nemůže obsahovat nepovinný parametr.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Přístupový objekt get nemůže obsahovat parametr rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Přístupový objekt set musí obsahovat přesně jeden parametr.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Parametr přístupového objektu set nemůže obsahovat inicializátor.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Podpis s implementací nemůže používat typ řetězcového literálu.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Pokud třída obsahuje inicializované vlastnosti nebo má vlastnosti parametru, musí být volání super první příkaz v konstruktoru.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ochrana typu this není kompatibilní s ochranou typu založeného na parametru.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ this je k dispozici jenom v nestatických členech třídy nebo rozhraní.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Soubor tsconfig.json je už v {0} definovaný.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Seznam elementů typu řazené kolekce členů nemůže být prázdný.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Výraz potvrzení typu se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Vlastnost literálu typu nemůže mít inicializátor.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Predikát typu nemůže odkazovat na parametr rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predikát typu nemůže odkazovat na element {0} ve vzoru vazby.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predikát typu je povolený jenom na pozici návratového typu funkcí a metod.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Typ predikátu typu musí být přiřaditelný k typu jeho parametru.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Proměnná, jejíž typ je jedinečný symbol, musí být const.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Výraz yield je povolený jenom v těle generátoru.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "K abstraktní metodě {0} ve třídě {1} nejde získat přístup prostřednictvím výrazu super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstraktní metody se můžou vyskytovat jenom v abstraktní třídě.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "K abstraktní vlastnosti {0} ve třídě {1} nelze získat přístup v konstruktoru.", + "Accessibility_modifier_already_seen_1028": "Modifikátor dostupnosti se už jednou vyskytl.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Přístupové objekty jsou dostupné, jenom když je cílem ECMAScript 5 a vyšší verze.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", + "Add_0_to_existing_import_declaration_from_1_90015": "Přidá {0} k existující deklaraci importu z {1}.", + "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", + "Add_missing_super_call_90001": "Přidejte chybějící volání metody super().", + "Add_this_to_unresolved_variable_90008": "Přidejte k nerozpoznané proměnné this.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Přidání souboru tsconfig.json vám pomůže uspořádat projekty, které obsahují jak soubory TypeScript, tak soubory JavaScript. Další informace najdete na adrese https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Další kontroly", + "Advanced_Options_6178": "Upřesnit možnosti", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Všechny deklarace {0} musí mít stejné parametry typu.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", + "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Když se zadá příznak --isolatedModules, nepovolují se ambientní výčty.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Deklarace ambientního modulu nemůže uvádět relativní název modulu.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Ambientní moduly se nedají zanořovat do jiných modulů nebo oborů názvů.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Modul AMD nemůže obsahovat víc přiřazení názvů.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Abstraktní přístupový objekt nemůže mít implementaci.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Přístupový objekt nemůže být deklarovaný v ambientním kontextu.", + "An_accessor_cannot_have_type_parameters_1094": "Přístupový objekt nemůže obsahovat parametry typu.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Deklarace ambientního modulu je povolená jenom na nejvyšší úrovni v souboru.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Aritmetický operand musí být typu any, number nebo typu výčtu.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Asynchronní funkce nebo metoda v ES5/ES3 vyžaduje konstruktor Promise. Ujistěte se, že máte deklaraci konstruktoru Promise, nebo do možnosti --lib přidejte ES2015.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Funkce nebo metoda async musí mít platný návratový typ pro await.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Asynchronní funkce nebo metoda musí vracet hodnotu příslibu. Přesvědčte se, že pro ni máte deklaraci, nebo zahrňte ES2015 do možnosti --lib.", + "An_async_iterator_must_have_a_next_method_2519": "Asynchronní iterátor musí mít metodu next().", + "An_enum_member_cannot_have_a_numeric_name_2452": "Člen výčtu nemůže mít číselný název.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Přiřazení exportu jde použít jenom v modulu.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Přiřazení exportu se nedá použít v modulu s jinými exportovanými elementy.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Přiřazení exportu se nedá používat v oboru názvů.", + "An_export_assignment_cannot_have_modifiers_1120": "Přiřazení exportu nemůže mít modifikátory.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Deklarace exportu jde použít jenom v modulu.", + "An_export_declaration_cannot_have_modifiers_1193": "Deklarace exportu nemůže mít modifikátory.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Rozšířená řídicí hodnota Unicode musí být mezi 0x0 a 0x10FFFF (včetně).", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementace se nedá deklarovat v ambientních kontextech.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Deklarace importu jde použít jenom v oboru názvů nebo modulu.", + "An_import_declaration_cannot_have_modifiers_1191": "Deklarace importu nemůže mít modifikátory.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Cesta pro import nemůže končit příponou {0}. Zvažte možnost importovat místo toho {1}.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Argument výrazu indexu musí být typu string, number, symbol nebo any.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Signatura indexu indexu nemůže obsahovat parametr rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Signatura indexu musí mít anotaci typu.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Signatura indexu musí mít právě jeden parametr.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "V parametru signatury indexu nemůže být otazník.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "V parametru signatury indexu nemůže být modifikátor přístupnosti.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "V parametru signatury indexu nemůže být inicializátor.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "V parametru signatury indexu nemůže být anotace typu.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr signatury indexu musí být typu string nebo number.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Rozhraní může rozšířit jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Rozhraní může rozšiřovat jenom třídu nebo jiné rozhraní.", + "An_interface_property_cannot_have_an_initializer_1246": "Vlastnost rozhraní nemůže mít inicializátor.", + "An_iterator_must_have_a_next_method_2489": "Iterátor musí mít metodu next().", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Literál objektu nemůže obsahovat několik přístupových objektů get/set se stejným názvem.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Literál objektu nemůže mít víc vlastností se stejným názvem ve striktním režimu.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Literál objektu nemůže obsahovat vlastnost a přístupový objekt se stejným názvem.", + "An_object_member_cannot_be_declared_optional_1162": "Člen objektu nemůže být deklarovaný jako nepovinný.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Signatura přetížení nemůže být deklarovaný jako generátor.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unární výraz s operátorem {0} se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "Annotate_with_type_from_JSDoc_95009": "Přidat poznámku s typem z JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Přidat poznámky s typy z JSDoc", + "Argument_expression_expected_1135": "Očekává se výraz argumentu.", + "Argument_for_0_option_must_be_Colon_1_6046": "Argument možnosti {0} musí být {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Argument typu {0} nejde přiřadit k parametru typu {1}.", + "Array_element_destructuring_pattern_expected_1181": "Očekával se destrukturační vzor elementu pole.", + "Asterisk_Slash_expected_1010": "Očekával se znak */.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Rozšíření pro globální rozsah může být jenom přímo vnořené v externích modulech nebo deklaracích ambientního modulu.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Rozšíření pro globální rozsah by měla mít modifikátor declare, pokud se neobjeví v kontextu, který je už ambientní.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Automatické zjišťování pro psaní je povolené v projektu {0}. Spouští se speciální průchod řešení pro modul {1} prostřednictvím umístění mezipaměti {2}.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Výrazy základní třídy nemůžou odkazovat na parametry typu třídy.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Návratový typ {0} základního konstruktoru není typu třída ani rozhraní.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Všechny základní konstruktory musí mít stejný návratový typ.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Základní adresář pro překlad neabsolutních názvů modulů.", + "Basic_Options_6172": "Základní možnosti", + "Binary_digit_expected_1177": "Očekává se binární číslice.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Element vazby {0} má implicitně typ {1}.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Proměnná bloku {0} se používá před vlastní deklarací.", + "Call_decorator_expression_90028": "Výraz pro volání dekoratéru", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Signatura volání s chybějící anotací návratového typu má implicitně návratový typ any.", + "Call_target_does_not_contain_any_signatures_2346": "Cíl volání neobsahuje žádné signatury.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "K {0}.{1} nelze získat přístup, protože {0} je typ, nikoli názvový prostor. Chtěli jste načíst typ vlastnosti {1} v {0} pomocí {0}[{1}]?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Typ konstruktoru {0} se nedá přiřadit k typu konstruktoru {1}.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Abstraktní typ konstruktoru nejde přiřadit neabstraktnímu typu konstruktoru.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Nejde přiřadit k vlastnosti {0}, protože je konstantní nebo jen pro čtení.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Nejde přiřadit k položce {0}, to není proměnná.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Modul {0} se nedá rozšířit, protože se překládá do entity, která není modul.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Modul {0} se nedá rozšířit, protože se překládá na entitu, která není modul.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Moduly nejde kompilovat pomocí možnosti {0}, pokud příznak --module nemá hodnotu amd nebo system.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Když se zadá příznak --isolatedModules, nejde kompilovat obory názvů.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Nejde vytvořit instance abstraktní třídy.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "{0} se nedá exportovat. Z modulu je možné exportovat jenom místní deklarace.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Třída {0} se nedá rozšířit. Konstruktor třídy je označený jako privátní.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Nejde rozšířit rozhraní {0}. Měli jste na mysli 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Soubor tsconfig.json nejde najít v zadaném adresáři: {0}", + "Cannot_find_global_type_0_2318": "Globální typ {0} se nenašel.", + "Cannot_find_global_value_0_2468": "Globální hodnota {0} se nenašla.", + "Cannot_find_module_0_2307": "Nenašel se modul {0}.", + "Cannot_find_name_0_2304": "Název {0} se nenašel.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Nepovedlo se najít název {0}. Měli jste na mysli {1}?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Název {0} se nedá najít. Měli jste na mysli člena instance this.{0}?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Název {0} se nedá najít. Měli jste na mysli statický člen {1}.{0}?", + "Cannot_find_namespace_0_2503": "Nenašel se obor názvů {0}.", + "Cannot_find_parameter_0_1225": "Nenašel se parametr {0}.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nenašla se společná cesta podadresářů pro vstupní soubory.", + "Cannot_find_type_definition_file_for_0_2688": "Nejde najít soubor definice pro {0}.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Soubory deklarací typů nejde importovat. Zvažte možnost místo {1} naimportovat {0}.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Proměnnou {0} s vnějším oborem nejde inicializovat ve stejném oboru jako deklaraci {1} s oborem bloku.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nejde vyvolat výraz, v jehož typu chybí signatura volání. Typ {0} nemá žádné kompatibilní signatury volání.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Typ nejde znovu exportovat, pokud je zadaný příznak --isolatedModules.", + "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", + "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", + "Cannot_redeclare_exported_variable_0_2323": "Exportovanou proměnnou {0} není možné znovu deklarovat.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Nejde předeklarovat identifikátor {0} v klauzuli catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Pokud se nezadá příznak -jsx, nepůjde JSX použít.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Nejde používat importy, exporty nebo rozšíření modulu, pokud má příznak --module hodnotu none.", + "Cannot_use_namespace_0_as_a_type_2709": "Obor názvů {0} nejde použít jako typ.", + "Cannot_use_namespace_0_as_a_value_2708": "Obor názvů {0} nejde použít jako hodnotu.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Nejde použít new s výrazem, kterému v typu chybí volání nebo signatura konstruktu.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Do souboru {0} se nedá zapisovat, protože by se přepsal více vstupními soubory.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Do souboru {0} se nedá zapisovat, protože by přepsal vstupní soubor.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Proměnná klauzule catch nemůže mít anotaci typu.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Proměnná klauzule catch nemůže mít inicializátor.", + "Change_0_to_1_90014": "Změnit {0} na {1}", + "Change_extends_to_implements_90003": "Změňte extends na implements.", + "Change_spelling_to_0_90022": "Změnit pravopis na {0}", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Kontroluje se, jestli je {0} nejdelší odpovídající předpona pro {1}–{2}.", + "Circular_definition_of_import_alias_0_2303": "Cyklická definice aliasu importu {0}", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Při překladu konfigurace se zjistila cykličnost: {0}.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Třída {0} definuje členský přístupový objekt instance {1}, ale rozšířená třída {2} ho definuje jako členskou funkci instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Třída {0} definuje členskou funkci instance {1}, ale rozšířená třída {2} ji definuje jako členský přístupový objekt instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Třída {0} definuje členskou funkci instance {1}, ale rozšířená třída {2} ji definuje jako vlastnost člena instance.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Třída {0} definuje vlastnost člena instance {1}, ale rozšířená třída {2} ji definuje jako členskou funkci instance.", + "Class_0_incorrectly_extends_base_class_1_2415": "Třída {0} nesprávně rozšiřuje základní třídu {1}.", + "Class_0_incorrectly_implements_interface_1_2420": "Třída {0} nesprávně implementuje rozhraní {1}.", + "Class_0_used_before_its_declaration_2449": "Třída {0} se používá dříve, než se deklaruje.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklarace tříd nemůžou obsahovat více než jednu značku @augments nebo @extends.", + "Class_name_cannot_be_0_2414": "Třída nemůže mít název {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Statická strana třídy {0} nesprávně rozšiřuje statickou stranu základní třídy {1}.", + "Classes_can_only_extend_a_single_class_1174": "Třídy můžou rozšířit jenom jednu třídu.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Třídy obsahující abstraktní metody musí být označené jako abstraktní.", + "Command_line_Options_6171": "Možnosti příkazového řádku", + "Compilation_complete_Watching_for_file_changes_6042": "Kompilace je hotová. Sledují se změny souborů.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.", + "Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Ve výčtu, jehož členy mají hodnoty typu string, se nepovolují vypočítané hodnoty.", + "Concatenate_and_emit_output_to_single_file_6001": "Zřetězit a generovat výstup do jednoho souboru", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Našly se konfliktní definice pro: {0} v {1} a {2}. Zvažte možnost nainstalovat specifickou verzi této knihovny, aby se konflikt vyřešil.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Podpis konstruktoru s chybějící anotací návratového typu má implicitně návratový typ any.", + "Constructor_implementation_is_missing_2390": "Chybí implementace konstruktoru.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Konstruktor třídy {0} je privátní a dostupný jenom v rámci deklarace třídy.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor třídy {0} je chráněný a dostupný jenom v rámci deklarace třídy.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory odvozených tříd musí obsahovat volání příkazu super.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář – přeskakuje se vyhledávání ve složce node_modules.", + "Convert_function_0_to_class_95002": "Převést funkci {0} na třídu", + "Convert_function_to_an_ES2015_class_95001": "Převést funkci na třídu ES2015", + "Convert_to_default_import_95013": "Převést na výchozí import", + "Corrupted_locale_file_0_6051": "Soubor národního prostředí {0} je poškozený.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nenašel se soubor deklarací pro modul {0}. {1} má implicitně typ any.", + "Could_not_write_file_0_Colon_1_5033": "Nedá se zapisovat do souboru {0}: {1}", + "DIRECTORY_6038": "ADRESÁŘ", + "Declaration_expected_1146": "Očekává se deklarace.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Název deklarace je v konfliktu s integrovaným globálním identifikátorem {0}.", + "Declaration_or_statement_expected_1128": "Očekává se deklarace nebo příkaz.", + "Declare_method_0_90023": "Deklarujte metodu {0}.", + "Declare_property_0_90016": "Deklarujte vlastnost {0}.", + "Declare_static_method_0_90024": "Deklarujte statickou metodu {0}.", + "Declare_static_property_0_90027": "Deklarujte statickou vlastnost {0}.", + "Decorators_are_not_valid_here_1206": "Dekorátory tady nejsou platné.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekorátory nejde použít na víc přístupových objektů get/set se stejným názvem.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Výchozí export modulu má nebo používá privátní název {0}.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Zastaralé] Použijte místo toho --jsxFactory. Určí objekt vyvolaný pro createElement při cílení na generování JSX react.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Zastaralé] Použijte místo toho --outFile. Zřetězí a vygeneruje výstup do jednoho souboru.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Zastaralé] Použijte místo toho --skipLibCheck. Přeskočí kontrolu typů výchozích souborů deklarací knihovny.", + "Digit_expected_1124": "Očekává se číslice.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Adresář {0} neexistuje. Všechna vyhledávání v něm se přeskočí.", + "Disable_checking_for_this_file_90018": "Zakázat kontrolu tohoto souboru", + "Disable_size_limitations_on_JavaScript_projects_6162": "Zakázat omezení velikosti v projektech JavaScriptu", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Zakáže striktní kontroly generických signatur v typech funkcí.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Zakažte odkazy na stejný soubor s nekonzistentně použitými malými a velkými písmeny.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Nepřidávat odkazy se třemi lomítky nebo importované moduly do seznamu kompilovaných souborů", + "Do_not_emit_comments_to_output_6009": "Negenerovat komentáře pro výstup", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Negenerovat deklarace pro kód s anotací @internal", + "Do_not_emit_outputs_6010": "Negenerovat výstupy", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Negenerovat výstupy, pokud byly oznámeny chyby", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Negenerujte direktivy use strict ve výstupu modulu.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Nemazat deklarace konstantního výčtu v generovaném kódu", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Negenerovat v kompilovaném výstupu vlastní pomocné funkce jako __extends", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Nezahrnovat výchozí soubor knihovny (lib.d.ts)", + "Do_not_report_errors_on_unreachable_code_6077": "Neoznamují se chyby v nedosažitelném kódu.", + "Do_not_report_errors_on_unused_labels_6074": "Neoznamují se chyby v nepoužívaných popiscích.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Nepřekládat skutečnou cestu symbolických odkazů", + "Do_not_truncate_error_messages_6165": "Nezkracovat chybové zprávy", + "Duplicate_declaration_0_2718": "Duplicitní deklarace pro: {0}", + "Duplicate_function_implementation_2393": "Duplicitní implementace funkce", + "Duplicate_identifier_0_2300": "Duplicitní identifikátor {0}", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Duplicitní identifikátor {0}. Kompilátor si vyhrazuje název {1} v oboru nejvyšší úrovně pro daný modul.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Duplicitní identifikátor {0}. Kompilátor rezervuje název {1} v oboru nejvyšší úrovně modulu, který obsahuje asynchronní funkce.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Duplicitní identifikátor {0}. Kompilátor používá deklaraci {1} pro podporu asynchronních funkcí.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Duplicitní identifikátor arguments. Kompilátor pomocí identifikátoru arguments inicializuje parametry rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Duplicitní identifikátor _newTarget. Kompilátor používá deklaraci proměnné _newTarget k zachycení odkazu na metavlastnost new.target.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Duplicitní identifikátor _super. Kompilátor pomocí identifikátoru _super zaznamenává odkaz na základní třídu.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Duplicitní identifikátor _this. Kompilátor pomocí deklarace proměnné _this zaznamenává odkaz na příkaz this.", + "Duplicate_label_0_1114": "Duplicitní popisek {0}", + "Duplicate_number_index_signature_2375": "Duplicitní podpis číselného indexu", + "Duplicate_string_index_signature_2374": "Duplicitní signatury řetězcového indexu", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Když se cílí na moduly ECMAScript 2015, nejde dynamický import použít.", + "Dynamic_import_cannot_have_type_arguments_1326": "Dynamický import nemůže mít argumenty typu.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamický import musí mít jako argument jeden specifikátor.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element má implicitně typ any, protože indexový výraz není typu number.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Element má implicitně typ any, protože typ {0} nemá žádnou signaturu indexu.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Vygeneruje na začátku výstupních souborů značku pořadí bajtů ve formátu UTF-8.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.", + "Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.", + "Enable_strict_checking_of_function_types_6186": "Povolte striktní kontrolu typů funkcí.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.", + "Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.", + "Enable_tracing_of_the_name_resolution_process_6085": "Povolte trasování procesu překladu IP adres.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Zapíná experimentální podporu asynchronních funkcí ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Povolí experimentální podporu pro dekorátory ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Povolí experimentální podporu pro generování metadat typu pro dekorátory.", + "Enum_0_used_before_its_declaration_2450": "Výčet {0} se používá dříve, než se deklaruje.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Všechny deklarace výčtu musí být konstantní nebo nekonstantní.", + "Enum_member_expected_1132": "Očekává se člen výčtu.", + "Enum_member_must_have_initializer_1061": "Člen výčtu musí mít inicializátor.", + "Enum_name_cannot_be_0_2431": "Název výčtu nemůže být {0}.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Typ výčtu {0} má členy s inicializátory, které nejsou literály.", + "Examples_Colon_0_6026": "Příklady: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Nadměrná hloubka zásobníku při porovnávání typů {0} a {1}", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Očekávané argumenty typu {0}–{1}; zadejte je se značkou @extends.", + "Expected_0_arguments_but_got_1_2554": "Očekával se tento počet argumentů: {0}. Počet předaných argumentů: {1}", + "Expected_0_arguments_but_got_1_or_more_2556": "Očekával se tento počet argumentů: {0}. Počet předaných argumentů: {1} nebo více.", + "Expected_0_type_arguments_but_got_1_2558": "Očekávaly se argumenty typu {0}, ale předaly se argumenty typu {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Očekávané argumenty typu {0}; zadejte je se značkou @extends.", + "Expected_at_least_0_arguments_but_got_1_2555": "Očekával se aspoň tento počet argumentů: {0}. Počet předaných argumentů: {1}", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Očekával se aspoň tento počet argumentů: {0}. Počet předaných argumentů: {1} nebo více.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Očekávala se odpovídající ukončující značka JSX pro {0}.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Pro fragment JSX se očekávala odpovídající uzavírací značka.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Očekávaný typ pole {0} v souboru package.json byl string, obdržený je {1}.", + "Experimental_Options_6177": "Experimentální možnosti", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Experimentální podpora dekorátorů je funkce, která se v budoucím vydání změní. Toto upozornění odstraníte nastavením možnosti experimentalDecorators.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explicitně zadaný druh překladu modulu: {0}.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Přiřazení exportu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít export default nebo jiný formát modulu.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Když má příznak --module hodnotu system, nepodporuje se přiřazení exportu.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Konflikty deklarace exportu s exportovanou deklarací {0}", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Deklarace exportu nejsou povolené v oboru názvů.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Soubor exportovaného úseku kódu externího balíčku {0} není modul. Kontaktuje prosím autora balíčku, aby aktualizoval jeho definici.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Soubor exportovaného úseku kódu externího balíčku nemůže obsahovat odkazy se třemi lomítky. Kontaktuje prosím autora balíčku, aby aktualizoval jeho definici.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Alias exportovaného typu {0} má nebo používá privátní název {1}.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Exportovaná proměnná {0} má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Exportovaná proměnná {0} má nebo používá název {1} z privátního modulu {2}.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Exportovaná proměnná {0} má nebo používá privátní název {1}.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exporty a přiřazení exportů nejsou povolené v rozšířeních modulů.", + "Expression_expected_1109": "Očekával se výraz.", + "Expression_or_comma_expected_1137": "Očekával se výraz nebo čárka.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Výraz se přeloží na identifikátor _super, pomocí kterého kompilátor zaznamenává odkaz na základní třídu.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Výraz se přeloží na deklaraci proměnné {0}, kterou kompilátor používá pro podporu asynchronních funkcí.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Výraz se vyhodnocuje na deklaraci proměnné _newTarget, kterou kompilátor používá k zachycení odkazu na metavlastnost new.target.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Výraz se přeloží na deklaraci proměnné _this, pomocí které kompilátor zaznamenává odkazy na příkaz this.", + "Extract_constant_95006": "Extrahovat konstantu", + "Extract_function_95005": "Extrahovat funkci", + "Extract_symbol_95003": "Extrahovat symbol", + "Extract_to_0_in_1_95004": "Extrahovat do {0} v {1}", + "Extract_to_0_in_1_scope_95008": "Extrahovat do {0} v oboru {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extrahovat do {0} v nadřazeném oboru", + "FILE_6035": "SOUBOR", + "FILE_OR_DIRECTORY_6040": "SOUBOR NEBO ADRESÁŘ", + "Failed_to_parse_file_0_Colon_1_5014": "Nepovedlo se parsovat soubor {0}: {1}.", + "Fallthrough_case_in_switch_7029": "Případ Fallthrough v příkazu switch", + "File_0_does_not_exist_6096": "Soubor {0} neexistuje.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Soubor {0} existuje – použijte ho jako výsledek překladu IP adres.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Soubor {0} má nepodporovanou příponu, a proto se přeskočí.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Soubor {0} má nepodporovanou příponu. Jediné podporované přípony jsou {1}.", + "File_0_is_not_a_module_2306": "Soubor {0} není modul.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Soubor {0} není pod kořenovým adresářem rootDir {1}. Očekává se, že rootDir bude obsahovat všechny zdrojové soubory.", + "File_0_not_found_6053": "Soubor {0} se nenašel.", + "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Název souboru {0} se od už zahrnutého názvu souboru {1} liší jenom velikostí písmen.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Název souboru {0} má příponu {1} – odstraňuje se", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specifikace souboru nemůže obsahovat nadřazený adresář (..), který se vyskytuje za rekurzivním zástupným znakem adresáře (**): {0}.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Specifikace souboru nemůže obsahovat víc než jeden rekurzivní zástupný znak adresáře (**): {0}.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specifikace souboru nemůže končit rekurzivním zástupným znakem adresáře (**): {0}.", + "Found_package_json_at_0_6099": "Soubor package.json se našel v {0}.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5. Definice tříd jsou automaticky ve striktním režimu.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5. Moduly jsou automaticky ve striktním režimu.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Výraz funkce s chybějící anotací návratového typu má implicitně návratový typ {0}.", + "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_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é.", + "Generates_corresponding_d_ts_file_6002": "Generuje odpovídající soubor .d.ts.", + "Generates_corresponding_map_file_6043": "Generuje odpovídající soubor .map.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Generátor má implicitně typ {0}, protože nevydává žádné hodnoty. Zvažte možnost přidání návratového typu.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generátory nejsou v ambientním kontextu povolené.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Generátory jsou dostupné jenom při cílení na ECMAScript 2015 nebo novější.", + "Generic_type_0_requires_1_type_argument_s_2314": "Obecný typ {0} vyžaduje argumenty typu {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Obecný typ {0} vyžaduje konkrétní počet argumentů ({1} až {2}).", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Vytvoření instance generického typu jde příliš hluboko a může být nekonečné.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Viditelnost přístupových objektů getter a setter vzájemně nesouhlasí.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Exporty globálního modulu se můžou objevit jenom na nejvyšší úrovni.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Exporty globálního modulu se můžou objevit jenom v souborech deklarací.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Exporty globálního modulu se můžou objevit jenom v souborech modulů.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Globální typ {0} musí být typu třída nebo rozhraní.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Globální typ {0} musí mít parametry typu {1}.", + "Hexadecimal_digit_expected_1125": "Očekávala se šestnáctková číslice.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo. Definice tříd jsou automaticky ve striktním režimu.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo. Moduly jsou automaticky ve striktním režimu.", + "Identifier_expected_1003": "Očekával se identifikátor.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Očekává se identifikátor. __esModule je při transformaci modulů ECMAScript rezervované jako označení exportu.", + "Ignore_this_error_message_90019": "Ignorovat tuto chybovou zprávu", + "Implement_inherited_abstract_class_90007": "Implementujte zděděnou abstraktní třídu.", + "Implement_interface_0_90006": "Implementujte rozhraní {0}.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzule implements exportované třídy {0} má nebo používá privátní název {1}.", + "Import_0_from_module_1_90013": "Import {0} z modulu {1}", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Přiřazení importu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít import * as ns from \"mod\", import {a} from \"mod\", import d from \"mod\" nebo jiný formát modulu.", + "Import_declaration_0_is_using_private_name_1_4000": "Deklarace importu {0} používá privátní název {1}.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklarace importu je v konfliktu s místní deklarací {0}.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Deklarace importu v oboru názvů nemůžou odkazovat na modul.", + "Import_emit_helpers_from_tslib_6139": "Importovat pomocné rutiny pro generování z tslib", + "Import_name_cannot_be_0_2438": "Název importu nemůže být {0}.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Deklarace importu nebo exportu v deklaraci ambientního modulu nemůže odkazovat na modul pomocí jeho relativního názvu.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importy nejsou povolené v rozšířeních modulů. Zvažte jejich přesunutí do uzavírajícího externího modulu.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Inicializátor členu v deklaracích ambientního výčtu musí být konstantní výraz.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Ve výčtu s víc deklaracemi může být jenom u jedné deklarace vynechaný inicializátor u prvního elementu výčtu.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "V inicializátoru člena deklarací výčtu const musí být konstantní výraz.", + "Index_signature_in_type_0_only_permits_reading_2542": "Signatura indexu v typu {0} povoluje jen čtení.", + "Index_signature_is_missing_in_type_0_2329": "V typu {0} chybí signatura indexu.", + "Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Jednotlivé deklarace ve sloučené deklaraci {0} musí být všechny exportované nebo všechny místní.", + "Infer_parameter_types_from_usage_95012": "Odvodit typy parametrů z používání", + "Infer_type_of_0_from_usage_95011": "Odvodit typ {0} z používání", + "Initialize_property_0_in_the_constructor_90020": "Inicializovat vlastnost {0} v konstruktoru", + "Initialize_static_property_0_90021": "Inicializovat statickou vlastnost {0}", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicializátor instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicializátor parametru {0} nemůže odkazovat na identifikátor {1} deklarovaný po něm.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicializátor tomuto elementu vazby neposkytuje žádnou hodnotu. Element vazby nemá žádnou výchozí hodnotu.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializátory nejsou povolené v ambientních kontextech.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializuje projekt TypeScript a vytvoří soubor tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Vložte parametry příkazového řádku a soubory ze souboru.", + "Install_0_95014": "Nainstalovat {0}", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Rozhraní {0} nemůže současně rozšiřovat typ {1} i {2}.", + "Interface_0_incorrectly_extends_interface_1_2430": "Rozhraní {0} nesprávně rozšiřuje rozhraní {1}.", + "Interface_declaration_cannot_have_implements_clause_1176": "Deklarace rozhraní nemůže obsahovat klauzuli implements.", + "Interface_name_cannot_be_0_2427": "Název rozhraní nemůže být {0}.", + "Invalid_character_1127": "Neplatný znak", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Neplatný název modulu v rozšíření. Modul {0} se převede na netypový modul v {1}, který se nedá rozšířit.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "V rozšíření je neplatný název modulu, modul {0} se nedá najít.", + "Invalid_reference_directive_syntax_1084": "Neplatná syntaxe direktivy reference", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Neplatné použití {0}. Definice tříd jsou automaticky ve striktním režimu.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Neplatné použití {0}. Moduly jsou automaticky ve striktním režimu.", + "Invalid_use_of_0_in_strict_mode_1100": "Neplatné použití {0} ve striktním režimu", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Neplatná hodnota pro jsxFactory. {0} není platný identifikátor nebo kvalifikovaný název.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Neplatná hodnota --reactNamespace. {0} není platný identifikátor.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Značka JSDoc @{0} {1} neodpovídá klauzuli extends {2}.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Značka JSDoc @{0} není připojená k třídě.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc ... se může nacházet jen v posledním parametru signatury.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Značka JSDoc @param má název {0}, ale žádný parametr s tímto názvem neexistuje.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Značka JSDoc @typedef by měla mít anotaci typu nebo by za ní měla následovat značka @property nebo @member.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc se můžou používat jenom v dokumentačních komentářích.", + "JSX_attribute_expected_17003": "Očekával se atribut JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atributy JSX musí mít přiřazený neprázdný výraz.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX {0} nemá odpovídající uzavírací značku.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Typ atributů elementu JSX {0} nemůže být typ sjednocení.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Třída elementu JSX nepodporuje atributy, protože nemá vlastnost {0}.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Element JSX má implicitně typ any, protože neexistuje žádné rozhraní JSX.{0}.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Element JSX má implicitně typ any, protože neexistuje globální typ JSX.Element.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Typ elementu JSX {0} nemá žádnou signaturu konstrukce nebo volání.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Typ elementu JSX {0} není funkce konstruktoru pro elementy JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementy JSX nemůžou mít víc atributů se stejným názvem.", + "JSX_expressions_must_have_one_parent_element_2657": "Výrazy JSX musí mít jeden nadřazený element.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Fragment JSX nemá odpovídající uzavírací značku.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Při použití --jsxFactory se nepodporuje fragment JSX.", + "JSX_spread_child_must_be_an_array_type_2609": "Podřízený objekt JSX spread musí být typu pole.", + "Jump_target_cannot_cross_function_boundary_1107": "Cíl odkazu nemůže překročit hranici funkce.", + "KIND_6034": "DRUH", + "LOCATION_6037": "UMÍSTĚNÍ", + "Language_service_is_disabled_9004": "Služba jazyka je zakázaná.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Levá strana operátoru čárky se nepoužívá a nemá žádné vedlejší účinky.", + "Line_break_not_permitted_here_1142": "Na tomto místě se konec řádku nepovoluje.", + "Line_terminator_not_permitted_before_arrow_1200": "Konec řádku před šipkou se nepovoluje.", + "List_of_folders_to_include_type_definitions_from_6161": "Seznam složek, ze kterých se zahrnou definice typů", + "List_of_language_service_plugins_6181": "Seznam modulů plug-in služby jazyka", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Seznam kořenových složek, jejichž kombinovaný obsah představuje strukturu projektu za běhu", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Načítá se {0} z kořenového adresáře {1}, umístění kandidáta {2}.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Načítá se modul {0} ze složky node_modules. Cílový typ souboru je {1}.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Načítá se modul jako soubor/složka, umístění kandidátského modulu: {0}, cílový typ souboru: {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Národní prostředí musí mít tvar nebo . Třeba {0} nebo {1}.", + "Longest_matching_prefix_for_0_is_1_6108": "Nejdelší odpovídající předpona pro {0} je {1}.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Hledání ve složce node_modules, počáteční umístění {0}", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Nastavit volání metody super() jako první příkaz v konstruktoru", + "Member_0_implicitly_has_an_1_type_7008": "Člen {0} má implicitně typ {1}.", + "Merge_conflict_marker_encountered_1185": "Zjistila se značka konfliktu sloučení.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Spojená deklarace {0} nemůže obsahovat výchozí deklaraci exportu. Zvažte namísto toho možnost přidat samostatnou deklaraci export default {0}.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Metavlastnost {0} je povolená jenom v těle deklarace funkce, výrazu funkce nebo konstruktoru.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Metoda {0} nemůže mít implementaci, protože je označená jako abstraktní.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Metoda {0} z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Metoda {0} z exportovaného rozhraní má nebo používá privátní název {1}.", + "Modifiers_cannot_appear_here_1184": "Tady nejde použít modifikátory.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Modul {0} už exportoval člena s názvem {1}. Zvažte možnost vyřešení nejednoznačnosti explicitním opakováním exportu.", + "Module_0_has_no_default_export_1192": "Modul {0} nemá žádný výchozí export.", + "Module_0_has_no_exported_member_1_2305": "V modulu {0} není žádný exportovaný člen {1}.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Modul {0} je skrytý místní deklarací se stejným názvem.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Modul {0} se překládá na nemodulovou entitu a nedá se importovat pomocí tohoto konstruktoru.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Modul {0} používá export = a nedá se použít s možností export *.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Modul {0} se převedl jako ambientní modul deklarovaný v {1}, protože tento soubor nebyl upraven.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Modul {0} se převedl jako lokálně deklarovaný ambientní modul v souboru {1}.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Modul {0} se přeložil na {1}, není ale nastavená možnost --jsx.", + "Module_Resolution_Options_6174": "Možnosti překladu modulů", + "Module_name_0_matched_pattern_1_6092": "Název modulu {0}, odpovídající vzor {1}", + "Module_name_0_was_not_resolved_6090": "======== Název modulu {0} nebyl přeložen. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.", + "Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.", + "NEWLINE_6061": "NOVÝ ŘÁDEK", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Pojmenovaná vlastnost {0} není u typu {1} stejná jako u typu {2}.", + "Namespace_0_has_no_exported_member_1_2694": "Obor názvů {0} nemá žádný exportovaný člen {1}.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Žádný základní konstruktor nemá zadaný počet argumentů typu.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "V konfiguračním souboru {0} se nenašly žádné vstupy. Pro zahrnutí jsou zadané tyto cesty: {1} a pro vyloučení tyto cesty: {2}.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Neabstraktní třída {0} neimplementuje zděděného abstraktního člena {1} ze třídy {2}.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Výraz neabstraktní třídy neimplementuje zděděný abstraktní člen {0} z třídy {1}.", + "Not_all_code_paths_return_a_value_7030": "Ne všechny cesty kódu vracejí hodnotu.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Typ číselného indexu {0} se nedá přiřadit k typu indexu řetězce {1}.", + "Object_is_possibly_null_2531": "Objekt je pravděpodobně null.", + "Object_is_possibly_null_or_undefined_2533": "Objekt je pravděpodobně null nebo undefined.", + "Object_is_possibly_undefined_2532": "Objekt je pravděpodobně undefined.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Literál objektu může specifikovat jenom známé vlastnosti a {0} v typu {1} neexistuje.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Literál objektu může určovat jenom známé vlastnosti, ale {0} v typu {1} neexistuje. Chtěli jste zapsat {2}?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Vlastnost {0} literálu objektu má implicitně typ {1}.", + "Octal_digit_expected_1178": "Očekává se osmičková číslice.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Osmičkové literální typy musí používat syntaxi ES2015. Použijte syntaxi {0}.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Osmičkové literály nejsou povolené v inicializátoru členů výčtů. Použijte syntaxi {0}.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Osmičkové literály nejsou ve striktním režimu povolené.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Osmičkové literály nejsou dostupné při cílení na ECMAScript 5 a vyšší. Použijte syntaxi {0}.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "V příkazu for...in se povoluje deklarovat jenom jednu proměnnou.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "V příkazu for...of se povoluje deklarovat jenom jednu proměnnou.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Klíčovým slovem new se dá volat jenom funkce void.", + "Only_ambient_modules_can_use_quoted_names_1035": "Názvy v uvozovkách můžou mít jenom ambientní moduly.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Spolu s --{0} se podporují jenom moduly amd a system.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "V klauzuli třídy extends se aktuálně podporují jenom identifikátory nebo kvalifikované názvy s volitelnými argumenty typu.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Prostřednictvím klíčového slova super jsou přístupné jenom veřejné a chráněné metody základní třídy.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Operátor {0} nejde použít u typů {1} a {2}.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Možnost {0} je možné zadat jenom v souboru tsconfig.json.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Možnost {0} jde použít jenom při zadání možnosti --inlineSourceMap nebo možnosti --sourceMap.", + "Option_0_cannot_be_specified_with_option_1_5053": "Možnosti {0} a {1} nejde zadat zároveň.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Možnost {0} nejde zadat bez možnosti {1}.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Hodnota možnosti {0} by měla být pole řetězců.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Možnost isolatedModules jde použít jenom v případě, že je poskytnutá možnost --module nebo že možnost target je ES2015 nebo vyšší verze.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Možnost paths se nedá použít bez zadání možnosti --baseUrl.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Možnost project se na příkazovém řádku nedá kombinovat se zdrojovým souborem.", + "Options_Colon_6027": "Možnosti:", + "Output_directory_for_generated_declaration_files_6166": "Výstupní adresář pro vygenerované soubory deklarace", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Signatura přetížení není kompatibilní s implementací funkce.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Signatury přetížení musí být všechny abstraktní nebo neabstraktní.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Signatury přetížení musí být všechny ambientní nebo neambientní.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Signatury přetížení musí být všechny exportované nebo neexportované.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Signatury přetížení musí být všechny nepovinné nebo povinné.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Signatury přetížení musí být všechny veřejné, privátní nebo chráněné.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Parametr {0} se nedá odkazovat v jeho vlastním inicializátoru.", + "Parameter_0_implicitly_has_an_1_type_7006": "Parametr {0} má implicitně typ {1}.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr {0} není na stejné pozici jako parametr {1}.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Parametr {0} signatury volání z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Parametr {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Parametr {0} konstruktoru z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Parametr {0} konstruktoru z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Parametr {0} konstruktoru z exportované třídy má nebo používá privátní název {1}.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Parametr {0} signatury konstruktoru z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Parametr {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Parametr {0} exportované funkce má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Parametr {0} exportované funkce má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Parametr {0} exportované funkce má nebo používá privátní název {1}.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Parametr {0} signatury indexu z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Parametr {0} signatury indexu z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Parametr {0} metody z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Parametr {0} metody z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Parametr {0} veřejné metody z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Parametr {0} veřejné metody z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Parametr {0} veřejné metody z exportované třídy má nebo používá privátní název {1}.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá privátní název {1}.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametr nemůže obsahovat otazník a inicializátor.", + "Parameter_declaration_expected_1138": "Očekává se deklarace parametru.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Typ parametru veřejné metody setter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Typ parametru veřejné metody setter {0} z exportované třídy má nebo používá privátní název {1}.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Typ parametru veřejné statické metody setter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Typ parametru veřejné statické metody setter {0} z exportované třídy má nebo používá privátní název {1}.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Parsovat ve striktním režimu a generovat striktní používání pro každý zdrojový soubor", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Vzor {0} může obsahovat nanejvýš jeden znak * (hvězdička).", + "Prefix_0_with_an_underscore_90025": "Předpona {0} s podtržítkem", + "Print_names_of_files_part_of_the_compilation_6155": "Část kompilace, při které se vypisují názvy souborů", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Část kompilace, při které se vypisují názvy generovaných souborů", + "Print_the_compiler_s_version_6019": "Vytisknout verzi kompilátoru", + "Print_this_message_6017": "Vytisknout tuto zprávu", + "Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.", + "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Vlastnost {0} v typu {1} neexistuje. Měli jste na mysli {2}?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Vlastnost {0} má konfliktní deklarace a v typu {1} není přístupná.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt set nemá anotaci parametrového typu.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Vlastnost {0} v typu {1} nejde přiřadit typu {2}.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Deklaruje se vlastnost {0}, ale její hodnota se vůbec nečte.", + "Property_0_is_incompatible_with_index_signature_2530": "Vlastnost {0} není kompatibilní se signaturou indexu.", + "Property_0_is_missing_in_type_1_2324": "Vlastnost {0} v typu {1} chybí.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Vlastnost {0} je v typu {1} nepovinná, ale vyžaduje se v typu {2}.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Vlastnost {0} je privátní a dostupná jenom ve třídě {1}.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Vlastnost {0} je v typu {1} privátní, ale v typu {2} ne.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Vlastnost {0} je chráněná a je dostupná jenom přes instanci třídy {1}.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Vlastnost {0} je chráněná a je dostupná jenom ve třídě {1} a jejích podtřídách.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Vlastnost {0} je chráněná, ale typ {1} není třída odvozená od {2}.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Vlastnost {0} je v typu {1} chráněná, ale v typu {2} veřejná.", + "Property_0_is_used_before_being_assigned_2565": "Vlastnost {0} je použitá před přiřazením.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Vlastnost {0} rozšířeného atributu JSX nejde přiřadit cílové vlastnosti.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Vlastnost {0} exportovaného výrazu třídy nesmí být privátní nebo chráněná.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Vlastnost {0} exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Vlastnost {0} exportovaného rozhraní má nebo používá privátní název {1}.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Vlastnost {0} typu {1} se nedá přiřadit k typu číselného indexu {2}.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Vlastnost {0} typu {1} se nedá přiřadit k typu indexu řetězce {2}.", + "Property_assignment_expected_1136": "Očekává se přiřazení vlastnosti.", + "Property_destructuring_pattern_expected_1180": "Očekává se vzor destruktoru vlastnosti.", + "Property_or_signature_expected_1131": "Očekává se vlastnost nebo podpis.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Hodnota vlastnosti může být jenom řetězcový literál, číselný literál, true, false, null, literál objektu nebo literál pole.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Při cílení na ES5 nebo ES3 poskytněte plnou podporu iterovatelných proměnných ve for-of, rozšíření a destrukturování.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Veřejná metoda {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Veřejná metoda {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Veřejná metoda {0} z exportované třídy má nebo používá privátní název {1}.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Veřejná vlastnost {0} exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Veřejná vlastnost {0} exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Veřejná vlastnost {0} exportované třídy má nebo používá privátní název {1}.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Veřejná statická metoda {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Veřejná statická metoda {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Veřejná statická metoda {0} z exportované třídy má nebo používá privátní název {1}.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Veřejná statická vlastnost {0} exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Veřejná statická vlastnost {0} exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Veřejná statická vlastnost {0} exportované třídy má nebo používá privátní název {1}.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", + "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", + "Remove_declaration_for_Colon_0_90004": "Odeberte deklaraci pro {0}.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", + "Report_errors_in_js_files_8019": "Ohlásit chyby v souborech .js", + "Report_errors_on_unused_locals_6134": "Umožňuje nahlásit chyby u nevyužitých místních hodnot.", + "Report_errors_on_unused_parameters_6135": "Umožňuje nahlásit chyby u nevyužitých parametrů.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Požadované parametry typu nemůžou být až za volitelnými parametry typu.", + "Resolution_for_module_0_was_found_in_cache_6147": "Překlad pro modul {0} se v mezipaměti nenašel.", + "Resolving_from_node_modules_folder_6118": "Překládá se ze složky node_modules...", + "Resolving_module_0_from_1_6086": "======== Překládá se modul {0} z {1}. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Překládá se název modulu {0} relativní k základní adrese URL {1}–{2}.", + "Resolving_real_path_for_0_result_1_6130": "Překládá se skutečná cesta pro {0}, výsledek {1}.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Překládá se direktiva reference typu {0}, obsažený soubor {1}, kořenový adresář {2}. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Překládá se direktiva reference typu {0}, obsažený soubor {1}, kořenový adresář není nastavený. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Překládá se direktiva reference typu {0}, obsažený soubor není nastavený, kořenový adresář {1}. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Překládá se direktiva reference typu {0}, obsažený soubor není nastavený, kořenový adresář není nastavený. ========", + "Resolving_using_primary_search_paths_6117": "Překládá se pomocí primárních cest hledání...", + "Resolving_with_primary_search_path_0_6121": "Probíhá překlad pomocí primární cesty hledání {0}.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Parametr rest {0} implicitně obsahuje typ any[].", + "Rest_types_may_only_be_created_from_object_types_2700": "Typy rest se dají vytvářet jenom z typů object.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Návratový typ signatury volání z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Návratový typ signatury volání z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Návratový typ signatury konstruktoru z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Návratový typ signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Návratový typ signatury konstruktoru musí jít přiřadit k typu instance třídy.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Návratový typ exportované funkce má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Návratový typ exportované funkce má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Návratový typ exportované funkce má nebo používá privátní název {0}.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Návratový typ signatury indexu z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Návratový typ signatury indexu z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Návratový typ metody z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Návratový typ metody z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá privátní název {1}.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Návratový typ veřejné metody z exportované třídy má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Návratový typ veřejné metody z exportované třídy má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Návratový typ veřejné metody z exportované třídy má nebo používá privátní název {0}.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá privátní název {1}.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Návratový typ veřejné statické metody z exportované třídy má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Návratový typ veřejné statické metody z exportované třídy má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Návratový typ veřejné statické metody z exportované třídy má nebo používá privátní název {0}.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Znovu se používají vyhodnocení modulu z {0}, protože vyhodnocení se oproti původnímu programu nezměnila.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Znovu se používá vyhodnocení modulu {0} do souboru {1} z původního programu.", + "Rewrite_as_the_indexed_access_type_0_90026": "Proveďte přepis jako indexovaný přístupový typ {0}.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nedá se určit kořenový adresář, přeskakují se primární cesty hledání.", + "STRATEGY_6039": "STRATEGIE", + "Scoped_package_detected_looking_in_0_6182": "Zjištěn balíček v oboru, hledání v: {0}", + "Setters_cannot_return_a_value_2408": "Metody setter nemůžou vracet hodnotu.", + "Show_all_compiler_options_6169": "Zobrazí všechny možnosti kompilátoru.", + "Show_diagnostic_information_6149": "Zobrazí diagnostické informace.", + "Show_verbose_diagnostic_information_6150": "Zobrazí podrobné diagnostické informace.", + "Signature_0_must_be_a_type_predicate_1224": "Podpis {0} musí být predikát typu.", + "Skip_type_checking_of_declaration_files_6012": "Přeskočit kontrolu typu souborů deklarace", + "Source_Map_Options_6175": "Možnosti zdrojového mapování", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Specializovaná signatura přetížení nejde přiřadit žádnému nespecializovanému podpisu.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Specifikátor dynamického importu nemůže být elementem Spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Zadejte cílovou verzi ECMAScriptu: ES3 (výchozí), ES5, ES2015, ES2016, ES2017, nebo ESNEXT.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Zadejte generování kódu JSX: preserve, react-native, nebo react.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Zadejte soubory knihovny, které se mají zahrnout do kompilace: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Určete generování kódu modulu: none, commonjs, amd, system, umd, es2015 nebo ESNext.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Zadejte strategii překladu modulu: node (Node.js) nebo classic (TypeScript verze nižší než 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Zadejte funkci objektu pro vytváření JSX, která se použije při zaměření na generování JSX react, např. React.createElement nebo h.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Zdejte sekvenci konce řádku, která se má použít při generování souborů: CRLF (dos) nebo LF (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Zadejte umístění, ve kterém by měl ladicí program najít soubory TypeScript namísto umístění zdroje.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Zadejte umístění, ve kterém by měl ladicí program najít soubory mapy namísto generovaných umístění.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Zadejte kořenový adresář vstupních souborů. Slouží ke kontrole struktury výstupního adresáře pomocí --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operátor rozšíření ve výrazech new je dostupný jenom při cílení na verzi ECMAScript 5 a vyšší.", + "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread se dají vytvářet jenom z typů object.", + "Statement_expected_1129": "Očekává se příkaz.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Příkazy se nepovolují v ambientních kontextech.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statické členy nemůžou odkazovat na parametry typu třídy.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Statická vlastnost {0} je v konfliktu s předdefinovanou vlastností Function.{0} funkce konstruktoru {1}.", + "Strict_Type_Checking_Options_6173": "Možnosti striktní kontroly typů", + "String_literal_expected_1141": "Očekává se řetězcový literál.", + "String_literal_with_double_quotes_expected_1327": "Očekával se řetězcový literál s dvojitými uvozovkami.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylizujte chyby a zprávy pomocí barev a kontextu (experimentální).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Deklarace následných proměnných musí obsahovat stejný typ. Proměnná {0} musí být typu {1}, ale tady je typu {2}.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Nahrazení {0} za vzor {1} má nesprávný typ, očekával se typ string, obdržený je {2}.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Nahrazení {0} ve vzoru {1} může obsahovat nanejvýš jeden znak * (hvězdička).", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Náhrady vzoru {0} by měly být pole.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Nahrazení vzoru {0} nesmí být prázdné pole.", + "Successfully_created_a_tsconfig_json_file_6071": "Soubor tsconfig.json se úspěšně vytvořil.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Volání pomocí super se nepovolují mimo konstruktory a ve funkcích vnořených v konstruktorech.", + "Suppress_excess_property_checks_for_object_literals_6072": "Potlačit nadměrné kontroly vlastností pro literály objektů", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Potlačit chyby noImplicitAny u objektů indexování bez signatur indexu", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Odkaz Symbol neodkazuje na globální objekt konstruktoru Symbol.", + "Syntax_Colon_0_6023": "Syntaxe: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Operátor {0} nejde použít u typu symbol.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Operátor {0} není u logických typů povolený. Můžete ale použít {1}.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Typ Object se dá přiřadit jen k malému počtu dalších typů. Nechtěli jste místo toho použít typ any?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Funkce šipky v ES3 a ES5 nemůže odkazovat na objekt arguments. Zvažte použití standardního výrazu funkce.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "V ES3 a ES5 se na objekt arguments nedá odkazovat v asynchronní funkci nebo metodě. Zvažte možnost použít standardní funkci nebo metodu.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Tělo příkazu if nemůže být prázdný příkaz.", + "The_character_set_of_the_input_files_6163": "Znaková sada vstupních souborů", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Text obsahující funkce nebo modulu je pro analýzu toku řízení příliš dlouhý.", + "The_current_host_does_not_support_the_0_option_5001": "Aktuální hostitel nepodporuje možnost {0}.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Výraz přiřazení exportu musí být identifikátor nebo kvalifikovaný název v ambientním kontextu.", + "The_files_list_in_config_file_0_is_empty_18002": "Seznam files v konfiguračním souboru {0} je prázdný.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "První parametr metody then příslibu musí být zpětné volání.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Levá strana příkazu for...in nemůže být destrukturačním vzorem.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Levá strana příkazu for...in nemůže používat anotaci typu.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Levá strana příkazu for..n musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Levá strana příkazu for...in musí být typu string nebo any.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Levá strana příkazu for...of nemůže používat anotaci typu.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Levá strana příkazu for...of musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Levá strana aritmetické operace musí mít typ any, number nebo být typu výčtu.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Levá strana výrazu přiřazení musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Levá strana výrazu in musí být typu any, string, number nebo symbol.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Levá strana výrazu instanceof musí být typu any, typem objektu nebo parametrem typu.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Národní prostředí, které se používá při zobrazování zpráv uživateli (třeba cs-CZ)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maximální hloubka závislostí pro vyhledávání pod node_modules a načítání javascriptových souborů", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Operandem operátoru delete nemůže být vlastnost určená jen pro čtení.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Operandem operátoru delete musí být odkaz na vlastnost.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operátoru inkrementace nebo dekrementace musí být proměnná nebo přístup k vlastnosti.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Návratový typ konstruktoru elementu JSX musí vracet objektový typ.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Návratový typ funkce dekorátoru parametru funkce musí být void nebo any.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Návratový typ funkce dekorátoru vlastnosti musí být void nebo any.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Návratový typ asynchronní funkce musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "Pravá strana příkazu for...in musí být typu any, typem objektu nebo parametrem typu.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Pravá strana aritmetické operace musí mít typ any, number nebo být typu výčtu.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Pravá strana výrazu in musí být typu any, objektového typu nebo parametrem typu.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Pravá strana výrazu instanceof musí mít typ any nebo typ, který se dá přiřadit k typu rozhraní Function.", + "The_specified_path_does_not_exist_Colon_0_5058": "Zadaná cesta neexistuje: {0}", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Cíl přiřazení musí být proměnná nebo přístup k vlastnosti.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Cílem přiřazení zbytku objektu musí být proměnná nebo přístup k vlastnosti.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Kontext this typu {0} se nedá přiřadit k možnosti this metody typu {1}.", + "The_this_types_of_each_signature_are_incompatible_2685": "Typy this jednotlivých signatur nejsou kompatibilní.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Argument typu pro parametr typu {0} se nemůže odvozovat z využití. Argumenty typu ale můžete zadat explicitně.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Typ vrácený metodou next() asynchronního iterátoru musí být příslib pro typ s vlastností value.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Typ vrácený metodou next() iterátoru musí obsahovat vlastnost value.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Deklarace proměnné příkazu for...in nemůže obsahovat inicializátor.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Deklarace proměnné příkazu for...of nemůže obsahovat inicializátor.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Příkaz with není podporovaný. Všechny symboly s blokem with budou typu any.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci, ale modul {0} se nenašel.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci s názvem {1}, ale modul {0} nemá žádného exportovaného člena {1}.", + "Trailing_comma_not_allowed_1009": "Čárka na konci není povolená.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluje každý soubor jako samostatný modul (podobné jako ts.transpileModule).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Vyzkoušejte deklaraci `npm install @types/{0}`, pokud existuje, nebo přidejte nový soubor deklarací (.d.ts) s deklarací `declare module '{0}';`.", + "Trying_other_entries_in_rootDirs_6110": "Zkoušejí se další položky v rootDirs.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Zkouší se nahrazení {0}, umístění modulu kandidáta: {1}.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Typ řazené kolekce členů {0} o délce {1} se nedá přiřadit k řazené kolekci členů o délce {2}.", + "Type_0_cannot_be_converted_to_type_1_2352": "Typ {0} se nedá převést na typ {1}.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Typ {0} se nedá použít jako typ indexu.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Typ {0} nejde použít k indexování typu {1}.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Typ {0} nevyhovuje omezení {1}.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Typ {0} nemá odpovídající signaturu indexu pro typ {1}.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Typ {0} nemá žádné vlastnosti společné s typem {1}.", + "Type_0_has_no_property_1_2460": "V typu {0} není žádná vlastnost {1}.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "V typu {0} není žádná vlastnost {1} ani žádná signatura indexu řetězce.", + "Type_0_is_not_a_constructor_function_type_2507": "Typ {0} není typ funkce konstruktoru.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Typ {0} nepředstavuje platný návratový typ asynchronní funkce v ES5/ES3, protože neodkazuje na hodnotu konstruktoru kompatibilní s příslibem.", + "Type_0_is_not_an_array_type_2461": "Typ {0} není typ pole.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Typ {0} není typem pole nebo řetězce.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ {0} není typem pole nebo řetězce, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ {0} není typem pole, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_is_not_assignable_to_type_1_2322": "Typ {0} nejde přiřadit typu {1}.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Typ {0} se nedá přiřadit typu {1}. Existují dva různé typy s tímto názvem, ale nesouvisí spolu.", + "Type_0_is_not_comparable_to_type_1_2678": "Typ {0} se nedá porovnat s typem {1}.", + "Type_0_is_not_generic_2315": "Typ {0} není obecný.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Typ {0} neposkytuje žádnou shodu pro podpis {1}.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Typ {0} odkazuje rekurzivně sám na sebe jako na základní typ.", + "Type_alias_0_circularly_references_itself_2456": "Alias typu {0} odkazuje cyklicky sám na sebe.", + "Type_alias_name_cannot_be_0_2457": "Název aliasu typu nemůže být {0}.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "V deklaraci konstruktoru se nemůže objevit anotace typu.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Kandidát na argument typu {1} není platným argumentem typu, protože není nadtypem kandidáta {0}.", + "Type_argument_expected_1140": "Očekává se argument typu.", + "Type_argument_list_cannot_be_empty_1099": "Seznam argumentů typu nemůže být prázdný.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Soubory deklarace typu, které se mají zahrnout do kompilace", + "Type_expected_1110": "Očekával se typ.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Typ se přímo nebo nepřímo odkazuje ve zpětném volání jeho vlastní metody then při splnění.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ musí mít metodu [Symbol.asyncIterator](), která vrací asynchronní iterátor.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ musí mít metodu [Symbol.iterator](), která vrací iterátor.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu await musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterovaných elementů yield* musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu yield v asynchronním generátoru musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu {0} má cyklické omezení.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu {0} má cyklickou výchozí hodnotu.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu {0} exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Parametr typu {0} exportované funkce má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Parametr typu {0} exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Parametr typu {0} exportovaného aliasu typu má nebo používá privátní název {1}.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Parametr typu {0} metody z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Parametr typu {0} veřejné metody z exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Parametr typu {0} veřejné statické metody z exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_declaration_expected_1139": "Očekává se deklarace parametru typu.", + "Type_parameter_list_cannot_be_empty_1098": "Seznam parametrů typu nemůže být prázdný.", + "Type_parameter_name_cannot_be_0_2368": "Název parametru typu nemůže být {0}.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Parametry typu se nemůžou vyskytovat v deklaraci konstruktoru.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Predikát typu {0} nejde přiřadit {1}.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Direktiva odkazu na typ {0} se nepřeložila. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Direktiva odkazu na typ {0} se úspěšně přeložila na {1}, primární: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mají samostatné deklarace privátní vlastnosti {0}.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrů {0} a {1} jsou nekompatibilní.", + "Types_of_property_0_are_incompatible_2326": "Typy vlastnosti {0} nejsou kompatibilní.", + "Unable_to_open_file_0_6050": "Soubor {0} nejde otevřít.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Když se podpis dekorátoru třídy volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Když se podpis dekorátoru metody volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Když se podpis dekorátoru parametru volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Když se podpis dekorátoru vlastnosti volá jako výraz, nejde přeložit.", + "Unexpected_end_of_text_1126": "Neočekávaný konec textu", + "Unexpected_token_1012": "Neočekávaný token", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Neočekávaný token. Očekával se konstruktor, metoda, přístupový objekt nebo vlastnost.", + "Unexpected_token_expected_1179": "Neočekávaný token. Očekává se znak {.", + "Unknown_compiler_option_0_5023": "Neznámá možnost kompilátoru {0}", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Neznámá možnost excludes. Měli jste na mysli exclude?", + "Unknown_type_acquisition_option_0_17010": "Neznámá možnost získání typu {0}", + "Unreachable_code_detected_7027": "Zjistil se nedosažitelný kód.", + "Unsupported_locale_0_6049": "Nepodporované národní prostředí {0}", + "Unterminated_Unicode_escape_sequence_1199": "Neukončená řídicí sekvence Unicode", + "Unterminated_quoted_string_in_response_file_0_6045": "Neukončený řetězec v uvozovkách v souboru odezvy {0}", + "Unterminated_regular_expression_literal_1161": "Neukončený literál regulárního výrazu", + "Unterminated_string_literal_1002": "Neukončený řetězcový literál", + "Unterminated_template_literal_1160": "Neukončený literál šablony", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Volání netypové funkce nemusí přijmout argumenty typu.", + "Unused_label_7028": "Nepoužívaný popisek", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", + "VERSION_6036": "VERZE", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Hodnota typu {0} nemá žádné vlastnosti společné s typem {1}. Chtěli jste ji volat?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Hodnota typu {0} se nedá volat. Nechtěli jste zahrnout new?", + "Variable_0_implicitly_has_an_1_type_7005": "Proměnná {0} má implicitně typ {1}.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "V některých umístěních, kde se nedá určit typ proměnné, má proměnná {0} implicitně typ {1}.", + "Variable_0_is_used_before_being_assigned_2454": "Proměnná {0} je použitá před přiřazením.", + "Variable_declaration_expected_1134": "Očekává se deklarace proměnné.", + "Variable_declaration_list_cannot_be_empty_1123": "Seznam deklarací proměnných nemůže být prázdný.", + "Version_0_6029": "Verze {0}", + "Watch_input_files_6005": "Sledovat vstupní soubory", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nejde přejmenovat elementy definované ve standardní knihovně TypeScriptu.", + "You_cannot_rename_this_element_8000": "Tento element nejde přejmenovat.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Objekt {0} přijímá málo argumentů k tomu, aby se dal použít jako dekoratér. Nechtěli jste ho nejprve volat a napsat @{0}()?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Položka {0} je zadána dvakrát. Atribut s názvem {0} se přepíše.", + "_0_can_only_be_used_in_a_ts_file_8009": "{0} se dá použít jenom v souboru .ts.", + "_0_expected_1005": "Očekával se: {0}.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "{0} obsahuje implicitně návratový typ any, protože neobsahuje anotaci návratového typu a přímo nebo nepřímo se odkazuje v jednom ze svých návratových výrazů.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "{0} má implicitně typ any, protože nemá anotaci typu a odkazuje se přímo nebo nepřímo v jeho vlastním inicializátoru.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0} je primitivum, ale {1} je obálkový objekt. Pokud je to možné, použijte raději {0}.", + "_0_is_declared_but_its_value_is_never_read_6133": "Deklaruje se {0}, ale jeho hodnota se vůbec nečte.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "{0} není platnou metavlastností pro klíčové slovo {1}. Měli jste na mysli {2}?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Na {0} se přímo nebo nepřímo odkazuje ve vlastním základním výrazu.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Na {0} se odkazuje přímo nebo nepřímo v jeho vlastní anotaci typu.", + "_0_list_cannot_be_empty_1097": "Seznam {0} nemůže být prázdný.", + "_0_modifier_already_seen_1030": "Modifikátor {0} se už jednou vyskytl.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Modifikátor {0} se nemůže objevit v elementu třídy.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Modifikátor {0} se nemůže objevit v deklaraci konstruktoru.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Modifikátor {0} nejde použít u vlastnosti dat.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Modifikátor {0} se nemůže objevit v elementu modulu nebo oboru názvů.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Modifikátor {0} se nemůže objevit v parametru.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Modifikátor {0} se nemůže objevit u člena typu.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Modifikátor {0} se nemůže objevit v signatuře indexu.", + "_0_modifier_cannot_be_used_here_1042": "Modifikátor {0} tady nejde použít.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Modifikátor {0} nejde použít v ambientním kontextu.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Modifikátor {0} nejde použít s modifikátorem {1}.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Modifikátor {0} nejde použít s deklarací třídy.", + "_0_modifier_must_precede_1_modifier_1029": "Modifikátor {0} se musí vyskytovat před modifikátorem {1}.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "{0} jenom odkazuje na typ, ale tady se používá jako obor názvů.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "{0} odkazuje jenom na typ, ale používá se tady jako hodnota.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "{0} odkazuje na globální UMD, ale aktuální soubor je modul. Zvažte raději přidání importu.", + "_0_tag_already_specified_1223": "Značka {0} se už specifikovala.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Značku {0} nejde používat nezávisle jako značku JSDoc nejvyšší úrovně.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "{0} s chybějící anotací návratového typu má implicitně návratový typ {1}.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Modifikátor abstract se může objevit jenom v deklaraci třídy, metody nebo vlastnosti.", + "await_expression_is_only_allowed_within_an_async_function_1308": "Výraz await se povoluje jenom ve funkci async.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Výrazy await nejdou použít v inicializátoru parametru.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Možnost baseUrl je nastavená na {0}, pomocí této hodnoty se přeloží název modulu {1}, který není relativní.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "= jde použít jenom ve vlastnosti literálu objektu uvnitř destrukturujícího přiřazení.", + "case_or_default_expected_1130": "Očekává se case nebo default.", + "class_expressions_are_not_currently_supported_9003": "Výrazy class se v současnosti nepodporují.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Deklarace const se dají deklarovat jenom uvnitř bloku.", + "const_declarations_must_be_initialized_1155": "Deklarace const se musejí inicializovat.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Inicializátor člena výčtu const se vyhodnotil na nekonečnou hodnotu.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Inicializátor člena výčtu const se vyhodnotil na nepovolenou hodnotu NaN.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu nebo přiřazení exportu.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Příkaz delete nejde volat u identifikátoru ve striktním režimu.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklarace výčtu se dají použít jenom v souboru .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "Možnost export= se dá použít jenom v souboru .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modifikátor export se nedá použít u ambientních modulů a rozšíření modulů, protože jsou vždy viditelné.", + "extends_clause_already_seen_1172": "Klauzule extends se už jednou vyskytla.", + "extends_clause_must_precede_implements_clause_1173": "Klauzule extends se musí vyskytovat před klauzulí implements.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Klauzule extends exportované třídy {0} má nebo používá privátní název {1}.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Klauzule extends exportovaného rozhraní {0} má nebo používá privátní název {1}.", + "file_6025": "soubor", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Přístupové objekty get a set musí mít stejný typ this.", + "get_and_set_accessor_must_have_the_same_type_2380": "Přístupový objekt get a set musí obsahovat stejný typ.", + "implements_clause_already_seen_1175": "Klauzule implements se už jednou vyskytla.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Klauzule implements se dají použít jenom v souboru .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "Možnost import ... = se dá použít jenom v souboru .ts.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Deklarace rozhraní se dají použít jenom v souboru .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Deklarace let je možné deklarovat jenom uvnitř bloku.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Nepovoluje se používat let jako název v deklaracích let nebo const.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Deklarace modulů se dají použít jenom v souboru .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Pole nejde vytvořit příkazem new T[]. Použijte syntaxi new Array().", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Výraz new s chybějící signaturou konstruktoru v cíli má implicitně typ any.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Kontrolní výrazy nenabývající hodnoty null lze použít jen v souboru .ts.", + "options_6024": "možnosti", + "or_expected_1144": "Očekává se znak { nebo ;.", + "package_json_does_not_have_a_0_field_6100": "package.json nemá pole {0}.", + "package_json_has_0_field_1_that_references_2_6101": "Soubor package.json má pole {0} {1}, které odkazuje na {2}.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modifikátory parametrů se dají použít jenom v souboru .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Je zadaná možnost paths, hledá se vzor, který odpovídá názvu modulu {0}.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modifikátor readonly se může objevit jenom v deklaraci vlastnosti nebo signatuře indexu.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Je nastavená možnost rootDirs, použije se k překladu relativního názvu modulu {0}.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Na vlastnost super se dá odkazovat jenom v odvozené třídě.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Na možnost super je možné odkazovat jenom ve členech odvozených tříd nebo výrazů literálu objektu.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Na vlastnost super se nedá odkazovat v názvu počítané vlastnosti.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Na vlastnost super se nedá odkazovat v argumentech konstruktoru.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Možnost super je povolená jenom ve členech výrazů literálu objektu, pokud je možnost target ES2015 nebo vyšší.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Před přístupem k vlastnosti super v konstruktoru odvozené třídy se musí zavolat super.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Možnost super se musí volat před přístupem k this v konstruktoru odvozené třídy.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Po vlastnosti super musí následovat seznam argumentů nebo přístup ke členu.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Přístup k vlastnostem pomocí super je povolený jenom v konstruktoru, členské funkci nebo členském přístupovém objektu odvozené třídy.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Na vlastnost this se nedá odkazovat v názvu počítaného prostředku.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Na vlastnost this se nedá odkazovat v modulu nebo těle oboru názvů.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Na vlastnost this se nedá odkazovat v inicializátoru statické vlastnosti.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Na vlastnost this se nedá odkazovat v argumentech konstruktoru.", + "this_cannot_be_referenced_in_current_location_2332": "Na vlastnost this se nedá odkazovat v aktuálním umístění.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "Možnost this má implicitně typ any, protože nemá anotaci typu.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Aliasy typu se dají použít jenom v souboru .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Argumenty typu se dají použít jenom v souboru .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Výrazy potvrzení typu se dají použít jenom v souboru .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Deklarace parametru typu se dají použít jenom v souboru .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "Typy se dají použít jenom v souboru .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Typy „jedinečný symbol“ tady nejsou povolené.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy „jedinečný symbol“ jsou povolené jen u proměnných v příkazu proměnné.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typy „jedinečný symbol“ nejde použít v deklaraci proměnné s názvem vazby.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Příkazy with se ve funkčním bloku async nepovolují.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Příkazy with se ve striktním režimu nepovolují.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Výrazy yield nejde použít v inicializátoru parametru." +} \ No newline at end of file diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..96aa622274420 --- /dev/null +++ b/lib/de/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Ein Modifizierer \"{0}\" darf nicht mit einer Importdeklaration verwendet werden.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Ein Modifizierer \"{0}\" darf nicht mit einer Schnittstellendeklaration verwendet werden.", + "A_0_parameter_must_be_the_first_parameter_2680": "Ein \"{0}\"-Parameter muss der erste Parameter sein.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Ein Bindungsmusterparameter darf in einer Implementierungssignatur nicht optional sein.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Eine break-Anweisung darf nur in einer einschließenden iteration- oder switch-Anweisung verwendet werden.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Eine break-Anweisung kann nur zu einer Bezeichnung einer einschließenden Anweisung springen.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Eine Klasse kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten implementieren.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Eine Klassendeklaration ohne den default-Modifizierer muss einen Namen besitzen.", + "A_class_may_only_extend_another_class_2311": "Eine Klasse kann nur eine andere Klasse erweitern.", + "A_class_may_only_implement_another_class_or_interface_2422": "Eine Klasse kann nur eine andere Klasse oder Schnittstelle implementieren.", + "A_class_member_cannot_have_the_0_keyword_1248": "Ein Klassenmember darf nicht das Schlüsselwort \"{0}\" aufweisen.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Ein Kommaausdruck ist in einem berechneten Eigenschaftennamen unzulässig.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Ein berechneter Eigenschaftenname kann nicht aus seinem enthaltenden Typ auf einen Typparameter verweisen.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Ein berechneter Eigenschaftenname in einer Deklaration einer Klasseneigenschaft muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Ein berechneter Eigenschaftenname in einer Methodenüberladung muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Ein berechneter Eigenschaftenname in einem Typliteral muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Ein berechneter Eigenschaftenname in einem Umgebungskontext muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Ein berechneter Eigenschaftenname in einer Schnittstelle muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Ein berechneter Eigenschaftenname muss vom Typ \"string\", \"number\", \"symbol\" oder \"any\" sein.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Ein berechneter Eigenschaftenname in der Form \"{0}\" muss vom Typ \"symbol\" sein.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Auf einen const-Enumerationsmember kann nur mithilfe eines Zeichenfolgenliterals zugegriffen werden.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Bei einem const-Initialisierer in einem Umgebungskontext muss es sich um eine Zeichenfolge oder um ein numerisches Literal handeln.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Ein Konstruktor darf keinen super-Aufruf enthalten, wenn seine Klasse \"null\" erweitert.", + "A_constructor_cannot_have_a_this_parameter_2681": "Ein Konstruktor darf keinen \"this\"-Parameter aufweisen.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Eine continue-Anweisung darf nur in einer einschließenden iteration-Anweisung verwendet werden.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Eine continue-Anweisung kann nur zu einer Bezeichnung einer einschließenden Iterationsanweisung springen.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Ein declare-Modifizierer darf nicht in einem Kontext verwendet werden, der bereits ein Umgebungskontext ist.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Ein declare-Modifizierer ist für eine Deklaration auf oberster Ebene in einer .d.ts-Datei erforderlich.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Ein Decorator-Element kann nur für eine Methodenimplementierung und nicht für eine Überladung verwendet werden.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Eine default-Klausel darf nicht mehrmals in einer switch-Anweisung auftreten.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Ein Standardexport kann nur in einem Modul des Typs ECMAScript verwendet werden.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Eine definitive Zuweisungsassertion \"!\" ist in diesem Kontext nicht zulässig.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Eine destrukturierende Deklaration muss einen Initialisierer besitzen.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Ein dynamischer Importaufruf in ES5/ES3 erfordert den Konstruktor \"Promise\". Stellen Sie sicher, dass Sie über eine Deklaration für den Konstruktor \"Promise\" verfügen, oder schließen Sie \"ES2015\" in Ihre Option \"--lib\" ein.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Ein dynamischer Importaufruf gibt \"Promise\" zurück. Stellen Sie sicher, dass Sie über eine Deklaration für \"Promise\" verfügen, oder schließen Sie ES2015 in Ihre Option \"--lib\" ein.", + "A_file_cannot_have_a_reference_to_itself_1006": "Eine Datei darf keinen Verweis auf sich selbst enthalten.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Eine \"for-await-of\"-Aussage ist nur innerhalb einer Async-Funktion oder eines Async-Generators zulässig.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Eine Funktion, die \"never\" zurückgibt, kann keinen erreichbaren Endpunkt besitzen.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Eine Funktion, die mit dem Schlüsselwort \"new\" aufgerufen wird, darf keinen \"this\"-Typ aufweisen, der \"void\" ist.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Eine Funktion, deren Typ weder als \"void\" noch als \"any\" deklariert ist, muss einen Wert zurückgeben.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Ein Generator darf keine void-Typanmerkung aufweisen.", + "A_get_accessor_cannot_have_parameters_1054": "Eine get-Zugriffsmethode darf keine Parameter haben.", + "A_get_accessor_must_return_a_value_2378": "Eine get-Zugriffsmethode muss einen Wert zurückgeben.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Ein Memberinitialisierer in einer Enumerationsdeklaration darf nicht auf Member verweisen, die anschließend deklariert werden (einschließlich Member, die in anderen Enumerationen definiert sind).", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Eine Mixin-Klasse benötigt einen Konstruktor mit einem einzelnen REST-Parameter des Typs \"any[]\".", + "A_module_cannot_have_multiple_default_exports_2528": "Ein Modul darf nicht mehrere Standardexporte aufweisen.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Eine Namespacedeklaration darf sich nicht in einer anderen Datei als die Klasse oder Funktion befinden, mit der sie zusammengeführt wird.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur in einem Namespace oder Modul zulässig.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Ein Parameterinitialisierer ist nur in einer Funktions- oder Konstruktorimplementierung zulässig.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Eine Parametereigenschaft darf nicht mithilfe eines rest-Parameters deklariert werden.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Eine Parametereigenschaft ist nur in einer Konstruktorimplementierung zulässig.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Eine Parametereigenschaft darf nicht mithilfe eines Bindungsmusters deklariert werden.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Ein Pfad in einer extends-Option muss ein relativer Pfad oder ein Stammpfad sein, aber dies trifft auf \"{0}\" nicht zu.", + "A_promise_must_have_a_then_method_1059": "Ein Zusage muss eine \"then\"-Methode aufweisen.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Eine Eigenschaft einer Klasse, deren Typ ein \"unique symbol\"-Typ ist, muss sowohl \"static\" als auch \"readonly\" sein.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Eine Eigenschaft einer Schnittstelle oder eines Typliterals, deren Typ ein \"unique symbol\"-Typ ist, muss \"readonly\" sein.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Ein erforderlicher Parameter darf nicht auf einen optionalen Parameter folgen.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Ein rest-Element darf kein Bindungsmuster enthalten.", + "A_rest_element_cannot_have_an_initializer_1186": "Ein rest-Element darf keinen Initialisierer aufweisen.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Ein rest-Element muss das letzte Element in einem Destrukturierungsmuster sein.", + "A_rest_parameter_cannot_be_optional_1047": "Ein rest-Parameter darf nicht optional sein.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Ein rest-Parameter darf keinen Initialisierer aufweisen.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Ein rest-Parameter muss in einer Parameterliste der letzte Eintrag sein.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Ein rest-Parameter muss ein Arraytyp sein.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Eine return-Anweisung kann nur in einem Funktionstext verwendet werden.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Eine Reihe von Einträgen, die Importe zum Nachschlagen von Speicherorten in Bezug auf die \"baseUrl\" neu zuordnen.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Eine set-Zugriffsmethode darf keine Rückgabetypanmerkung aufweisen.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Eine set-Zugriffsmethode darf keinen optionalen Parameter aufweisen.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Eine set-Zugriffsmethode darf keinen rest-Parameter aufweisen.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Eine set-Zugriffsmethode muss genau einen Parameter aufweisen.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Ein set-Zugriffsmethodenparameter darf keinen Initialisierer aufweisen.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Eine Signatur mit einer Implementierung darf keinen Zeichenfolgen-Literaltyp verwenden.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Ein super-Aufruf muss die erste Anweisung im Konstruktor sein, wenn eine Klasse initialisierte Eigenschaften oder Parametereigenschaften enthält.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ein auf \"this\" basierender Typwächter ist nicht mit einem parameterbasierten Typwächter kompatibel.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Ein this-Typ ist nur in einem nicht statischen Member einer Klasse oder Schnittstelle verfügbar.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Eine Datei \"tsconfig.json\" ist bereits definiert unter: \"{0}\".", + "A_tuple_type_element_list_cannot_be_empty_1122": "Eine Tupeltyp-Elementliste darf nicht leer sein.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Typassertionsausdrücke sind in der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Typliteraleigenschaften können keinen Initialisierer aufweisen.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Ein Typprädikat darf nicht auf einen rest-Parameter verweisen.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Ein Typprädikat darf nicht auf ein Element \"{0}\" in einem Bindungsmuster verweisen.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Ein Typprädikat ist nur an der Rückgabetypposition für Funktionen und Methoden zulässig.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Der Typ eines Typprädikats muss dem Typ seines Parameters zugewiesen werden können.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Eine Variable, deren Typ ein \"unique symbol\"-Typ ist, muss \"const\" sein.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Ein yield-Ausdruck ist nur in einem Generatortext zulässig.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Auf die abstrakte Methode \"{0}\" in der Klasse \"{1}\" kann nicht über den super-Ausdruck zugegriffen werden.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstrakte Methoden können nur in einer abstrakten Klasse verwendet werden.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Auf die abstrakte Eigenschaft \"{0}\" in der Klasse \"{1}\" kann im Konstruktor nicht zugegriffen werden.", + "Accessibility_modifier_already_seen_1028": "Der Zugriffsmodifizierer ist bereits vorhanden.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Zugriffsmethoden sind nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", + "Add_0_to_existing_import_declaration_from_1_90015": "Fügen Sie \"{0}\" zur vorhandenen Importdeklaration aus \"{1}\" hinzu.", + "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen.", + "Add_missing_super_call_90001": "Fügen Sie den fehlenden super()-Aufruf hinzu.", + "Add_this_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"this.\" hinzufügen.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Das Hinzufügen einer \"tsconfig.json\"-Datei erleichtert die Organisation von Projekten, die sowohl TypeScript- als auch JavaScript-Dateien enthalten. Weitere Informationen finden Sie unter https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Zusätzliche Überprüfungen", + "Advanced_Options_6178": "Erweiterte Optionen", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Alle Deklarationen von \"{0}\" müssen identische Typparameter aufweisen.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Alle Deklarationen einer abstrakten Methode müssen aufeinanderfolgend sein.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.", + "Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "const-Umgebungsenumerationen sind unzulässig, wenn das Flag \"-isolatedModules\" angegeben wird.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Die Umgebungsmoduldeklaration darf keinen relativen Modulnamen angeben.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Umgebungsmodule dürfen nicht in andere Module oder Namespaces geschachtelt werden.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Ein AMD-Modul darf nicht mehrere Namenzuweisungen aufweisen.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Ein abstrakter Accessor kann keine Implementierung aufweisen.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Eine Zugriffsmethode darf nicht in einem Umgebungskontext deklariert werden.", + "An_accessor_cannot_have_type_parameters_1094": "Eine Zugriffsmethode darf keine Typparameter aufweisen.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Eine Umgebungsmoduldeklaration ist nur auf der obersten Ebene in einer Datei zulässig.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Ein arithmetischer Operand muss vom Typ \"any\" bzw. \"number\" oder ein Enumerationstyp sein.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Eine Async-Funktion oder -Methode in ES5/ES3 erfordert den Konstruktur \"Promise\". Stellen Sie sicher, dass Sie über eine Deklaration für den Konstruktor \"Promise\" verfügen, oder schließen Sie \"ES2015\" in Ihre Option \"--lib\" ein.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Eine asynchrone Funktion oder Methode muss einen gültigen awaitable-Rückgabetyp aufweisen.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Eine asynchrone Funktion oder Methode muss \"Promise\" zurückgeben. Stellen Sie sicher, dass Sie über eine Deklaration für \"Promise\" verfügen, oder schließen Sie ES2015 in Ihrer Option \"--lib\" ein.", + "An_async_iterator_must_have_a_next_method_2519": "Ein Async-Iterator muss eine \"next()\"-Async-Methode aufweisen.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Ein Enumerationsmember darf keinen numerischen Namen besitzen.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Eine Exportzuweisung kann nur in einem Modul verwendet werden.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Eine Exportzuweisung darf nicht in einem Modul mit anderen exportierten Elementen verwendet werden.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Eine Exportzuweisung darf nicht in einem Namespace verwendet werden.", + "An_export_assignment_cannot_have_modifiers_1120": "Eine Exportzuweisung darf keine Modifizierer besitzen.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Eine Exportdeklaration kann nur in einem Modul verwendet werden.", + "An_export_declaration_cannot_have_modifiers_1193": "Eine Exportdeklaration darf keine Modifizierer besitzen.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Ein erweiterter Unicode-Escapewert muss zwischen 0x0 und 0x10FFFF (einschließlich) liegen.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Eine Implementierung darf nicht in Umgebungskontexten deklariert werden.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Eine Importdeklaration darf nur in einem Namespace oder Modul verwendet werden.", + "An_import_declaration_cannot_have_modifiers_1191": "Eine Importdeklaration darf keine Modifizierer besitzen.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ein Importpfad darf nicht mit einer Erweiterung \"{0}\" enden. Importieren Sie ggf. stattdessen \"{1}\".", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Ein Indexausdrucksargument muss vom Typ \"string\", \"number\", \"symbol\" oder \"any\" sein.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Eine Indexsignatur darf keinen rest-Parameter besitzen.", + "An_index_signature_must_have_a_type_annotation_1021": "Eine Indexsignatur muss eine Typanmerkung besitzen.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Eine Indexsignatur muss genau einen Parameter besitzen.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Ein Indexsignaturparameter darf kein Fragezeichen aufweisen.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Ein Indexsignaturparameter darf keinen Zugriffsmodifizierer besitzen.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Ein Indexsignaturparameter darf keinen Initialisierer besitzen.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Ein Indexsignaturparameter muss eine Typanmerkung besitzen.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Ein Indexsignaturparameter-Typ muss \"string\" oder \"number\" sein.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Eine Schnittstelle kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten erweitern.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Eine Schnittstelle kann nur eine Klasse oder eine andere Schnittstelle erweitern.", + "An_interface_property_cannot_have_an_initializer_1246": "Schnittstelleneigenschaften können keinen Initialisierer aufweisen.", + "An_iterator_must_have_a_next_method_2489": "Ein Iterator muss eine Methode \"next()\" besitzen.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Ein Objektliteral darf nicht mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen besitzen.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Ein Objektliteral darf im Strict-Modus nicht mehrere Eigenschaften mit dem gleichen Namen besitzen.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Ein Objektliteral darf nicht eine Eigenschaft und eine Zugriffsmethode mit demselben Namen besitzen.", + "An_object_member_cannot_be_declared_optional_1162": "Ein Objektmember darf nicht als optional deklariert werden.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Eine Überladungssignatur darf nicht als ein Generator deklariert werden.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unäre Ausdrücke mit dem Operator \"{0}\" sind auf der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", + "Annotate_with_type_from_JSDoc_95009": "Mit Typ aus JSDoc kommentieren", + "Annotate_with_types_from_JSDoc_95010": "Mit Typen aus JSDoc kommentieren", + "Argument_expression_expected_1135": "Es wurde ein Argumentausdruck erwartet.", + "Argument_for_0_option_must_be_Colon_1_6046": "Das Argument für die Option \"{0}\" muss \"{1}\" sein.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Das Argument vom Typ \"{0}\" kann dem Parameter vom Typ \"{1}\" nicht zugewiesen werden.", + "Array_element_destructuring_pattern_expected_1181": "Ein Arrayelement-Destrukturierungsmuster wurde erwartet.", + "Asterisk_Slash_expected_1010": "\"*/\" wurde erwartet.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Erweiterungen für den globalen Bereich können nur in externen Modulen oder Umgebungsmoduldeklarationen direkt geschachtelt werden.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Erweiterungen für den globalen Bereich sollten den Modifizierer \"declare\" aufweisen, wenn sie nicht bereits in einem Umgebungskontext auftreten.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "In Projekt \"{0}\" ist die automatische Erkennung von Eingaben aktiviert. Es wird ein zusätzlicher Auflösungsdurchlauf für das Modul \"{1}\" unter Verwendung von Cachespeicherort \"{2}\" ausgeführt.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Basisklassenausdrücke können nicht auf Klassentypparameter verweisen.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Der Rückgabetyp \"{0}\" des Basiskonstruktors ist keine Klasse oder kein Schnittstellentyp.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Basiskonstruktoren müssen alle den gleichen Rückgabetyp aufweisen.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Das Basisverzeichnis zum Auflösen nicht absoluter Modulnamen.", + "Basic_Options_6172": "Standardoptionen", + "Binary_digit_expected_1177": "Es wurde eine Binärzahl erwartet.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Das Bindungselement \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Die blockbezogene Variable \"{0}\" wurde vor ihrer Deklaration verwendet.", + "Call_decorator_expression_90028": "Rufen Sie den Decoratorausdruck auf.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Eine Aufrufsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", + "Call_target_does_not_contain_any_signatures_2346": "Das Aufrufziel enthält keine Signaturen.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Der Zugriff auf \"{0}.{1}\" ist nicht möglich, da \"{0}\" ein Typ ist, aber kein Namespace. Wollten Sie den Typ der Eigenschaft \"{1}\" in \"{0}\" mit \"{0}[\"{1}\"]\" abrufen?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Ein Konstruktortyp \"{0}\" kann nicht einem Konstruktortyp \"{1}\" zugewiesen werden.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Ein abstrakter Konstruktortyp kann nicht einem nicht abstrakten Konstruktortyp zugewiesen werden.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine Konstante oder eine schreibgeschützte Eigenschaft handelt.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich nicht um eine Variable handelt.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Das Modul \"{0}\" kann nicht erweitert werden, weil es in eine Nicht-Modulentität aufgelöst wird.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Das Modul \"{0}\" kann nicht mit Wertexporten vergrößert werden, da es zu einer Entität aufgelöst wird, die kein Modul darstellt.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Module können nur mithilfe der Option \"{0}\" kompiliert werden, wenn die Kennzeichnung \"-module\" den Wert \"amd\" oder \"system\" aufweist.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Namespaces können nicht kompiliert werden, wenn das Flag \"-isolatedModules\" angegeben wird.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Eine Instanz der abstrakten Klasse kann nicht erstellt werden.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "\"{0}\" kann nicht exportiert werden. Nur lokale Deklarationen können aus einem Modul exportiert werden.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Eine Klasse \"{0}\" kann nicht erweitert werden. Der Klassenkonstruktor ist als privat markiert.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Eine Schnittstelle \"{0}\" kann nicht erweitert werden. Meinten Sie \"implements\"?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Im angegebenen Verzeichnis \"{0}\" wurde keine \"tsconfig.json\"-Datei gefunden.", + "Cannot_find_global_type_0_2318": "Der globale Typ \"{0}\" wurde nicht gefunden.", + "Cannot_find_global_value_0_2468": "Der globale Wert \"{0}\" wurde nicht gefunden.", + "Cannot_find_module_0_2307": "Das Modul \"{0}\" wurde nicht gefunden.", + "Cannot_find_name_0_2304": "Der Name \"{0}\" wurde nicht gefunden.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie den Instanzmember \"this.{0}\"?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie den statischen Member \"{1}.{0}\"?", + "Cannot_find_namespace_0_2503": "Der Namespace \"{0}\" wurde nicht gefunden.", + "Cannot_find_parameter_0_1225": "Der Parameter \"{0}\" wurde nicht gefunden.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Das gemeinsame Unterverzeichnis für die Eingabedateien wurde nicht gefunden.", + "Cannot_find_type_definition_file_for_0_2688": "Die Typdefinitionsdatei für \"{0}\" wurde nicht gefunden.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Typdeklarationsdateien können nicht importiert werden. Importieren Sie ggf. \"{0}\" anstelle von \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Die Variable \"{0}\" mit dem äußeren Bereich im gleichen Bereich wie die Deklaration \"{1}\" mit dem Blockbereich kann nicht initialisiert werden.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Ein Ausdruck, dessen Typ eine Aufrufsignatur fehlt, kann nicht aufgerufen werden. Der Typ \"{0}\" weist keine kompatiblen Aufrufsignaturen auf.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Ein Typ kann nicht erneut exportiert werden, wenn das Flag \"--isolatedModules\" angegeben ist.", + "Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}", + "Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.", + "Cannot_redeclare_exported_variable_0_2323": "Die exportierte Variable \"{0}\" kann nicht erneut deklariert werden.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Der Bezeichner \"{0}\" in der Catch-Klausel kann nicht erneut deklariert werden.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "JSX kann nur verwendet werden, wenn das Flag \"-jsx\" angegeben wird.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Es können keine imports-, exports- oder module-Erweiterungen verwendet werden, wenn \"-module\" den Wert \"none\" aufweist.", + "Cannot_use_namespace_0_as_a_type_2709": "Der Namespace \"{0}\" kann nicht als Typ verwendet werden.", + "Cannot_use_namespace_0_as_a_value_2708": "Der Namespace \"{0}\" kann nicht als Wert verwendet werden.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "\"new\" darf nicht mit einem Ausdruck verwendet werden, in dessen Typ eine Aufruf- oder Konstruktsignatur fehlt.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie durch mehrere Eingabedateien überschrieben würde.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie eine Eingabedatei überschreiben würde.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Die Variable der Catch-Klausel darf keine Typanmerkung aufweisen.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Die Variable der Catch-Klausel darf keinen Initialisierer aufweisen.", + "Change_0_to_1_90014": "Ändern Sie \"{0}\" in \"{1}\".", + "Change_extends_to_implements_90003": "\"extends\" in \"implements\" ändern", + "Change_spelling_to_0_90022": "Ändern Sie die Schreibweise in \"{0}\".", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Es wird überprüft, ob \"{0}\" das längste übereinstimmende Präfix für \"{1}\"–\"{2}\" ist.", + "Circular_definition_of_import_alias_0_2303": "Zirkuläre Definition des Importalias \"{0}\".", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Eine Zirkularität wurde beim Auflösen der Konfiguration erkannt: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Die Klasse \"{0}\" definiert die Instanzmember-Zugriffsmethode \"{1}\", die erweiterte Klasse \"{2}\" definiert diesen jedoch als Instanzmemberfunktion.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Die Klasse \"{0}\" definiert die Instanzmember-Zugriffsmethode \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmember-Zugriffsmethode.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Die Klasse \"{0}\" definiert die Instanzmemberfunktion \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Membereigenschaft.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Die Klasse \"{0}\" definiert die Instanzmembereigenschaft \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmemberfunktion.", + "Class_0_incorrectly_extends_base_class_1_2415": "Die Klasse \"{0}\" erweitert fälschlicherweise die Basisklasse \"{1}\".", + "Class_0_incorrectly_implements_interface_1_2420": "Die Klasse \"{0}\" implementiert fälschlicherweise die Schnittstelle \"{1}\".", + "Class_0_used_before_its_declaration_2449": "Klasse \"{0}\", die vor der Deklaration verwendet wurde.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Klassendeklarationen dürfen maximal ein \"@augments\"- oder \"@extends\"-Tag aufweisen.", + "Class_name_cannot_be_0_2414": "Der Klassenname darf nicht \"{0}\" sein.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Die statische Seite der Klasse \"{0}\" erweitert fälschlicherweise die statische Seite der Basisklasse \"{1}\".", + "Classes_can_only_extend_a_single_class_1174": "Klassen dürfen nur eine einzelne Klasse erweitern.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Klassen, die abstrakte Methoden enthalten, müssen als abstrakt markiert werden.", + "Command_line_Options_6171": "Befehlszeilenoptionen", + "Compilation_complete_Watching_for_file_changes_6042": "Die Kompilierung wurde abgeschlossen. Dateiänderungen werden überprüft.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Kompilieren Sie das dem Pfad zugewiesene Projekt zu dessen Konfigurationsdatei oder zu einem Ordner mit der Datei \"tsconfig.json\".", + "Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Aufzählung mit Membern mit Zeichenfolgenwerten nicht zulässig.", + "Concatenate_and_emit_output_to_single_file_6001": "Verketten und Ausgabe in einer Datei speichern.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "In Konflikt stehende Definitionen für \"{0}\" wurden unter \"{1}\" und \"{2}\" gefunden. Installieren Sie ggf. eine bestimmte Version dieser Bibliothek, um den Konflikt aufzulösen.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Eine Konstruktsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", + "Constructor_implementation_is_missing_2390": "Die Konstruktorimplementierung fehlt.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Der Konstruktor der Klasse \"{0}\" ist privat. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Der Konstruktor der Klasse \"{0}\" ist geschützt. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktoren für abgeleitete Klassen müssen einen Aufruf \"super\" enthalten.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.", + "Convert_function_0_to_class_95002": "Funktion \"{0}\" in Klasse konvertieren", + "Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse konvertieren", + "Convert_to_default_import_95013": "In Standardimport konvertieren", + "Corrupted_locale_file_0_6051": "Die Gebietsschemadatei \"{0}\" ist beschädigt.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Es wurde keine Deklarationsdatei für das Modul \"{0}\" gefunden. \"{1}\" weist implizit den Typ \"any\" auf.", + "Could_not_write_file_0_Colon_1_5033": "Die Datei \"{0}\" konnte nicht geschrieben werden. {1}.", + "DIRECTORY_6038": "VERZEICHNIS", + "Declaration_expected_1146": "Es wurde eine Deklaration erwartet.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Der Deklarationsname steht in Konflikt mit dem integrierten globalen Bezeichner \"{0}\".", + "Declaration_or_statement_expected_1128": "Es wurde eine Deklaration oder Anweisung erwartet.", + "Declare_method_0_90023": "Methode \"{0}\" deklarieren.", + "Declare_property_0_90016": "Eigenschaft \"{0}\" deklarieren.", + "Declare_static_method_0_90024": "Statische Methode \"{0}\" deklarieren.", + "Declare_static_property_0_90027": "Deklarieren Sie die statische Eigenschaft \"{0}\".", + "Decorators_are_not_valid_here_1206": "Decorators sind hier ungültig.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Decorators dürfen nicht auf mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen angewendet werden.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Der Standardexport des Moduls besitzt oder verwendet den privaten Namen \"{0}\".", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Veraltet] Verwenden Sie stattdessen \"--jsxFactory\". Geben Sie das Objekt an, das für \"createElement\" aufgerufen wurde, wenn das Ziel die JSX-Ausgabe \"react\" ist.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Veraltet] Verwenden Sie stattdessen \"--outFile\". Verketten und Ausgeben in eine einzige Datei", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Veraltet] Verwenden Sie stattdessen \"--skipLibCheck\". Überspringen Sie die Typüberprüfung der Standardbibliothek-Deklarationsdateien.", + "Digit_expected_1124": "Eine Ziffer wurde erwartet.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Das Verzeichnis \"{0}\" ist nicht vorhanden, Suchvorgänge darin werden übersprungen.", + "Disable_checking_for_this_file_90018": "Überprüfung für diese Datei deaktivieren.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Größenbeschränkungen für JavaScript-Projekte deaktivieren.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Deaktivieren Sie die strenge Überprüfung generischer Signaturen in Funktionstypen.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Verweise mit uneinheitlicher Groß-/Kleinschreibung auf die gleiche Datei nicht zulassen.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Fügen Sie keine Verweise mit dreifachen Schrägstrichen oder importierte Module zur Liste kompilierter Dateien hinzu.", + "Do_not_emit_comments_to_output_6009": "Kommentare nicht an die Ausgabe ausgeben.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Deklarationen für Code mit einer Anmerkung \"@internal\" nicht ausgeben.", + "Do_not_emit_outputs_6010": "Keine Ausgaben ausgeben.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Keine Ausgaben ausgeben, wenn Fehler gemeldet wurden.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Keine \"use strict\"-Direktiven in Modulausgabe ausgeben.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "const-Enumerationsdeklarationen im generierten Code nicht löschen.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Erstellen Sie keine benutzerdefinierten Hilfsfunktionen wie \"__extends\" in der kompilierten Ausgabe.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Beziehen Sie die Standardbibliotheksdatei (lib.d.ts) nicht ein.", + "Do_not_report_errors_on_unreachable_code_6077": "Fehler zu nicht erreichbarem Code nicht melden.", + "Do_not_report_errors_on_unused_labels_6074": "Fehler zu nicht verwendeten Bezeichnungen nicht melden.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Tatsächlichen Pfad von symbolischen Verknüpfungen nicht auflösen.", + "Do_not_truncate_error_messages_6165": "Kürzen Sie keine Fehlermeldungen.", + "Duplicate_declaration_0_2718": "Doppelte Deklaration \"{0}\".", + "Duplicate_function_implementation_2393": "Doppelte Funktionsimplementierung.", + "Duplicate_identifier_0_2300": "Doppelter Bezeichner \"{0}\".", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Doppelter Bezeichner \"{0}\". Der Compiler reserviert den Namen \"{1}\" im Bereich der obersten Ebene eines Moduls.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Doppelter Bezeichner \"{0}\". Der Compiler reserviert den Namen \"{1}\" im Bereich der obersten Ebene eines Moduls, das asynchrone Funktionen enthält.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Doppelter Bezeichner \"{0}\". Der Compiler verwendet die Deklaration \"{1}\", um asynchrone Funktionen zu unterstützen.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Doppelter Bezeichner \"arguments\". Der Compiler verwendet \"arguments\" zum Initialisieren der rest-Parameter.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Doppelter Bezeichner \"_newTarget\". Der Compiler verwendet die Variablendeklaration \"_newTarget\" zum Erfassen der Metaeigenschaftenreferenz \"new.target\".", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Doppelter Bezeichner \"_super\". Der Compiler verwendet \"_super\" zum Erfassen des Basisklassenverweises.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Doppelter Bezeichner \"_this\". Der Compiler verwendet die Variablendeklaration \"_this\" zum Erfassen des this-Verweises.", + "Duplicate_label_0_1114": "Doppelte Bezeichnung \"{0}\".", + "Duplicate_number_index_signature_2375": "Doppelte Zahlenindexsignatur.", + "Duplicate_string_index_signature_2374": "Doppelte Zeichenfolgen-Indexsignatur.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Der dynamische Import kann nicht verwendet werden, wenn ECMAScript 2015-Module das Ziel sind.", + "Dynamic_import_cannot_have_type_arguments_1326": "Der dynamische Import kann nicht über Typargumente verfügen.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Der dynamische Import benötigt einen Spezifizierer als Argument.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Der Spezifizierer des dynamischen Imports muss den Typ \"string\" aufweisen, hier ist er jedoch vom Typ \"{0}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Das Element weist implizit einen Typ \"any\" auf, weil der Indexausdruck nicht vom Typ \"number\" ist.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Das Element weist implizit einen Typ \"any\" auf, weil der Typ \"{0}\" keine Indexsignatur umfasst.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Geben Sie zu Beginn der Ausgabedateien eine UTF-8-Bytereihenfolge-Marke (BOM) aus.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Geben Sie eine einzelne Datei mit Quellzuordnungen anstelle einer separaten Datei aus.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Geben Sie die Quelle zusammen mit den Quellzuordnungen innerhalb einer einzelnen Datei aus; hierfür muss \"--inlineSourceMap\" oder \"--sourceMap\" festgelegt sein.", + "Enable_all_strict_type_checking_options_6180": "Aktivieren Sie alle strengen Typüberprüfungsoptionen.", + "Enable_strict_checking_of_function_types_6186": "Aktivieren Sie die strenge Überprüfung für Funktionstypen.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Aktivieren Sie die strenge Überprüfung der Eigenschafteninitialisierung in Klassen.", + "Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.", + "Enable_tracing_of_the_name_resolution_process_6085": "Ablaufverfolgung des Namensauflösungsvorgangs aktivieren.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Funktionen.", + "Enables_experimental_support_for_ES7_decorators_6065": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Decorators.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Ermöglicht experimentelle Unterstützung zum Ausgeben von Typmetadaten für Decorators.", + "Enum_0_used_before_its_declaration_2450": "Enumeration \"{0}\", die vor der Deklaration wurde.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Enumerationsdeklarationen müssen alle konstant oder nicht konstant sein.", + "Enum_member_expected_1132": "Ein Enumerationsmember wurde erwartet.", + "Enum_member_must_have_initializer_1061": "Ein Enumerationsmember muss einen Initialisierer aufweisen.", + "Enum_name_cannot_be_0_2431": "Der Enumerationsname darf nicht \"{0}\" sein.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Der Enumerationstyp \"{0}\" weist Member mit Initialisierern auf, die keine Literale sind.", + "Examples_Colon_0_6026": "Beispiele: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Übermäßige Stapeltiefe beim Vergleichen der Typen \"{0}\" und \"{1}\".", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} Typargumente erwartet; geben Sie diese mit einem @extends-Tag an.", + "Expected_0_arguments_but_got_1_2554": "{0} Argumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} Argumente wurden erwartet, empfangen wurden aber mindestens {1}.", + "Expected_0_type_arguments_but_got_1_2558": "{0} Typenargumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} Typargumente erwartet; geben Sie diese mit einem @extends-Tag an.", + "Expected_at_least_0_arguments_but_got_1_2555": "Mindestens {0} Argumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Mindestens {0} Argumente wurden erwartet, empfangen wurden aber mindestens {1}.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Das entsprechende schließende JSX-Tag wurde für \"{0}\" erwartet.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Für das JSX-Fragment wurde das entsprechende schließende Tag erwartet.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Der erwartete Typ des Felds \"{0}\" in der Datei \"package.json\" ist \"string\". Abgerufener Typ: \"{1}\".", + "Experimental_Options_6177": "Experimentelle Optionen", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Experimentelle Unterstützung für Decorator-Elemente ist ein Feature, das in zukünftigen Versionen Änderungen unterliegt. Legen Sie die Option \"-experimentalDecorators\" fest, um diese Warnung zu entfernen.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explizit angegebene Art der Modulauflösung: \"{0}\".", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Die Exportzuweisung darf nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"export default\" oder ein anderes Modulformat.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Die Exportzuweisung wird nicht unterstützt, wenn das Flag \"-module\" den Wert \"system\" aufweist.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Die Exportdeklaration verursacht einen Konflikt mit der exportierten Deklaration von \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Exportdeklarationen sind in einem Namespace unzulässig.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Die exportierte externe Pakettypisierungsdatei \"{0}\" ist kein Modul. Bitte wenden Sie sich an den Paketautor, um die Paketdefinition zu aktualisieren.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Exportierte externe Pakettypisierungen dürfen keine Verweise mit drei Schrägstrichen enthalten. Bitte wenden Sie sich an den Paketautor, um die Paketdefinition zu aktualisieren.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Der exportierte Typalias \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Die exportierte Variable \"{0}\" besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Die exportierte Variable \"{0}\" besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Die exportierte Variable \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exporte und Exportzuweisungen sind in Modulerweiterungen unzulässig.", + "Expression_expected_1109": "Es wurde ein Ausdruck erwartet.", + "Expression_or_comma_expected_1137": "Es wurde ein Ausdruck oder Komma erwartet.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Der Ausdruck wird in \"_super\" aufgelöst. Damit erfasst der Compiler den Basisklassenverweis.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Der Ausdruck wird in die Variablendeklaration \"{0}\" aufgelöst, die der Compiler verwendet, um asynchrone Funktionen zu unterstützen.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Der Ausdruck wird in die Variablendeklaration \"_newTarget\" aufgelöst, die der Compiler zum Erfassen der Metaeigenschaftenreferenz \"new.target\" verwendet.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Der Ausdruck wird in die Variablendeklaration \"_this\" aufgelöst, die der Compiler verwendet, um den this-Verweis zu erfassen.", + "Extract_constant_95006": "Konstante extrahieren", + "Extract_function_95005": "Funktion extrahieren", + "Extract_symbol_95003": "Symbol extrahieren", + "Extract_to_0_in_1_95004": "Als {0} nach {1} extrahieren", + "Extract_to_0_in_1_scope_95008": "Als {0} in {1}-Bereich extrahieren", + "Extract_to_0_in_enclosing_scope_95007": "Als {0} in einschließenden Bereich extrahieren", + "FILE_6035": "DATEI", + "FILE_OR_DIRECTORY_6040": "DATEI ODER VERZEICHNIS", + "Failed_to_parse_file_0_Colon_1_5014": "Fehler beim Analysieren der Datei \"{0}\": {1}.", + "Fallthrough_case_in_switch_7029": "FallThrough-Fall in switch-Anweisung.", + "File_0_does_not_exist_6096": "Die Datei \"{0}\" ist nicht vorhanden.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Die Datei \"{0}\" ist vorhanden – sie wird als Ergebnis der Namensauflösung verwendet.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Die Datei \"{0}\" hat eine nicht unterstützte Erweiterung und wird übersprungen.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Die Datei \"{0}\" weist eine nicht unterstützte Erweiterung auf. Die einzigen unterstützten Erweiterungen sind \"{1}\".", + "File_0_is_not_a_module_2306": "Die Datei \"{0}\" ist kein Modul.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Datei \"{0}\" befindet sich nicht unter \"rootDir\" \"{1}\". \"rootDir\" muss alle Quelldateien enthalten.", + "File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.", + "File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Der Dateiname \"{0}\" unterscheidet sich vom bereits enthaltenen Dateinamen \"{1}\" nur hinsichtlich der Groß-/Kleinschreibung.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Der Dateiname \"{0}\" weist eine Erweiterung \"{1}\" auf. Diese wird entfernt.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Die Dateispezifikation darf kein übergeordnetes Verzeichnis (\"..\") enthalten, das nach einem rekursiven Verzeichnisplatzhalter (\"**\") angegeben wird: \"{0}\".", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Die Dateispezifikation darf nicht mehrere rekursive Verzeichnisplatzhalter enthalten (\"**\"): \"{0}\".", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Die Dateispezifikation darf nicht mit einem rekursiven Verzeichnisplatzhalter (\"**\") enden: \"{0}\".", + "Found_package_json_at_0_6099": "\"package.json\" wurde unter \"{0}\" gefunden.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist. Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist. Module befinden sich automatisch im Strict-Modus.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Ein Funktionsausdruck ohne Rückgabetypanmerkung weist implizit einen {0}-Rückgabetyp auf.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Die Funktionsimplementierung fehlt oder folgt nicht unmittelbar auf die Deklaration.", + "Function_implementation_name_must_be_0_2389": "Der Name der Funktionsimplementierung muss \"{0}\" lauten.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Die Funktion weist implizit den Typ \"any\" auf, weil keine Rückgabetypanmerkung vorhanden ist und darauf direkt oder indirekt in einem ihrer Rückgabeausdrücke verwiesen wird.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Der Funktion fehlt die abschließende return-Anweisung, und der Rückgabetyp enthält nicht \"undefined\".", + "Function_overload_must_be_static_2387": "Die Funktionsüberladung muss statisch sein.", + "Function_overload_must_not_be_static_2388": "Die Funktionsüberladung darf nicht statisch sein.", + "Generates_corresponding_d_ts_file_6002": "Generiert die entsprechende .d.ts-Datei.", + "Generates_corresponding_map_file_6043": "Generiert die entsprechende MAP-Datei.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Der Generator weist implizit den Typ \"{0}\" auf, weil er keine Werte ausgibt. Sie können ggf. einen Rückgabetyp angeben.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generatoren sind in einem Umgebungskontext unzulässig.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Generatoren sind nur verfügbar, wenn das Ziel ECMAScript 2015 oder höher ist.", + "Generic_type_0_requires_1_type_argument_s_2314": "Der generische Typ \"{0}\" erfordert {1} Typargument(e).", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Der generische Typ \"{0}\" benötigt zwischen {1} und {2} Typargumente.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Generische Typinstanziierung ist übermäßig tief und möglicherweise unendlich.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Die Sichtbarkeit der Getter- und Setter-Zugriffsmethoden stimmt nicht überein.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Globale Modulexporte dürfen nur auf der obersten Ebene auftreten.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Globale Modulexporte dürfen nur in Deklarationsdateien auftreten.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Globale Modulexporte dürfen nur in Moduldateien auftreten.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Der globale Typ \"{0}\" muss eine Klassen- oder Schnittstellentyp sein.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Der globale Typ \"{0}\" muss {1} Typparameter aufweisen.", + "Hexadecimal_digit_expected_1125": "Es wurde eine hexadezimale Zahl erwartet.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Ein Bezeichner wird erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Module befinden sich automatisch im Strict-Modus.", + "Identifier_expected_1003": "Es wurde ein Bezeichner erwartet.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Bezeichner erwartet. \"__esModule\" ist als exportierter Marker für die Umwandlung von ECMAScript-Modulen reserviert.", + "Ignore_this_error_message_90019": "Diese Fehlermeldung ignorieren.", + "Implement_inherited_abstract_class_90007": "Geerbte abstrakte Klasse implementieren", + "Implement_interface_0_90006": "Schnittstelle \"{0}\" implementieren", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Die implements-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Import_0_from_module_1_90013": "Import von \"{0}\" aus Modul \"{1}\".", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Die Importzuweisung kann nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" oder ein anderes Modulformat.", + "Import_declaration_0_is_using_private_name_1_4000": "Die Importdeklaration \"{0}\" verwendet den privaten Namen \"{1}\".", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Die Importdeklaration verursacht einen Konflikt mit der lokalen Deklaration von \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Importdeklarationen in einem Namespace dürfen nicht auf ein Modul verweisen.", + "Import_emit_helpers_from_tslib_6139": "Ausgabehilfsprogramme aus \"tslib\" importieren.", + "Import_name_cannot_be_0_2438": "Der Importname darf nicht \"{0}\" sein.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Import- oder Exportdeklaration in einer Umgebungsmoduldeklaration dürfen nicht über den relativen Modulnamen auf ein Modul verweisen.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importe sind in Modulerweiterungen unzulässig. Verschieben Sie diese ggf. in das einschließende externe Modul.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "In Umgebungsenumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In einer Enumeration mit mehreren Deklarationen kann nur eine Deklaration einen Initialisierer für das erste Enumerationselement ausgeben.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "In const-Enumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", + "Index_signature_in_type_0_only_permits_reading_2542": "Die Indexsignatur in Typ \"{0}\" lässt nur Lesevorgänge zu.", + "Index_signature_is_missing_in_type_0_2329": "Die Indexsignatur fehlt im Typ \"{0}\".", + "Index_signatures_are_incompatible_2330": "Die Indexsignaturen sind nicht kompatibel.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Einzelne Deklarationen in der gemergten Deklaration \"{0}\" müssen alle exportiert oder alle lokal sein.", + "Infer_parameter_types_from_usage_95012": "Leiten Sie Parametertypen aus der Nutzung ab.", + "Infer_type_of_0_from_usage_95011": "Leiten Sie den Typ von \"{0}\" aus der Nutzung ab.", + "Initialize_property_0_in_the_constructor_90020": "Eigenschaft '{0}' im Konstruktor initialisieren.", + "Initialize_static_property_0_90021": "Statische Eigenschaft '{0}' initialisieren.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Der Initialisierer der Instanzmembervariablen \"{0}\" darf nicht auf den im Konstruktor deklarierten Bezeichner \"{1}\" verweisen.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Der Initialisierer des Parameters \"{0}\" darf nicht auf den anschließend deklarierten Bezeichner \"{1}\" verweisen.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Der Initialisierer stellt keinen Wert für dieses Bindungselement bereit, und das Bindungselement besitzt keinen Standardwert.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Initialisierer sind in Umgebungskontexten unzulässig.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialisiert ein TypeScript-Projekt und erstellt eine Datei \"tsconfig.json\".", + "Insert_command_line_options_and_files_from_a_file_6030": "Fügt Befehlszeilenoptionen und Dateien aus einer Datei ein.", + "Install_0_95014": "\"{0}\" installieren", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Die Schnittstelle \"{0}\" kann die Typen \"{1}\" und \"{2}\" nicht gleichzeitig erweitern.", + "Interface_0_incorrectly_extends_interface_1_2430": "Die Schnittstelle \"{0}\" erweitert fälschlicherweise die Schnittstelle \"{1}\".", + "Interface_declaration_cannot_have_implements_clause_1176": "Die Schnittstellendeklarationen darf keine implements-Klausel aufweisen.", + "Interface_name_cannot_be_0_2427": "Der Schnittstellenname darf nicht \"{0}\" sein.", + "Invalid_character_1127": "Ungültiges Zeichen.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Ungültiger Modulname in Augmentation. Das Modul \"{0}\" wird in ein nicht typisiertes Modul in \"{1}\" aufgelöst, das nicht augmentiert werden kann.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Ungültiger Modulname in der Erweiterung. Das Modul \"{0}\" wurde nicht gefunden.", + "Invalid_reference_directive_syntax_1084": "Ungültige Syntax der reference-Direktive.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Ungültige Verwendung von \"{0}\". Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Ungültige Verwendung von \"{0}\". Module befinden sich automatisch im Strict-Modus.", + "Invalid_use_of_0_in_strict_mode_1100": "Ungültige Verwendung von \"{0}\" im Strict-Modus.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Ungültiger Wert für \"jsxFactory\". \"{0}\" ist kein gültiger Bezeichner oder qualifizierter Name.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Ungültiger Wert für \"-reactNamespace\". \"{0}\" ist kein gültiger Bezeichner.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" entspricht nicht der Klausel \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" ist keiner Klassendeklaration zugeordnet.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Das JSDoc-Tag \"...\" wird möglicherweise nur im letzten Parameter einer Signatur angezeigt.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es gibt jedoch keinen Parameter dieses Namens.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Das JSDoc-Tag \"@typedef\" muss entweder eine Typanmerkung aufweisen, oder die Tags \"@property\" oder \"@member\" müssen darauf folgen.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc-Typen können nur innerhalb von Dokumentationskommentaren verwendet werden.", + "JSX_attribute_expected_17003": "Ein JSX-Attribut wurde erwartet.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX-Attributen darf nur ein nicht leeres expression-Objekt zugewiesen werden.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Das JSX-Element \"{0}\" weist kein entsprechendes schließendes Tag auf.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Der JSX-Elementattributtyp \"{0}\" darf kein Union-Typ sein.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Die JSX-Elementklasse unterstützt keine Attribute, weil sie keine Eigenschaft \"{0}\" aufweist.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Das JSX-Element enthält implizit den Typ \"any\", weil keine Schnittstelle \"JSX.{0}\" vorhanden ist.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Das JSX-Element enthält implizit den Typ \"any\", weil der globale Typ \"JSX.Element\" nicht vorhanden ist.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Der JSX-Elementtyp \"{0}\"weist keine Konstrukt- oder Aufrufsignaturen auf.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Der JSX-Elementtyp \"{0}\" ist keine Konstruktorfunktion für JSX-Elemente.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX-Elemente dürfen nicht mehrere Attribute mit dem gleichen Namen aufweisen.", + "JSX_expressions_must_have_one_parent_element_2657": "JSX-Ausdrücke müssen ein übergeordnetes Element aufweisen.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Das JSX-Fragment weist kein entsprechendes schließendes Tag auf.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Das JSX-Fragment wird bei Verwendung von --jsxFactory nicht unterstützt.", + "JSX_spread_child_must_be_an_array_type_2609": "Die untergeordnete JSX-Verteilung muss ein Arraytyp sein.", + "Jump_target_cannot_cross_function_boundary_1107": "Das Sprungziel darf die Funktionsgrenze nicht überschreiten.", + "KIND_6034": "ART", + "LOCATION_6037": "SPEICHERORT", + "Language_service_is_disabled_9004": "Der Sprachdienst ist deaktiviert.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Die linke Seite des Kommaoperators wird nicht verwendet besitzt keine Nebenwirkungen.", + "Line_break_not_permitted_here_1142": "Ein Zeilenumbruch ist hier unzulässig.", + "Line_terminator_not_permitted_before_arrow_1200": "Das Zeilenabschlusszeichen ist vor dem Pfeil unzulässig.", + "List_of_folders_to_include_type_definitions_from_6161": "Liste der Ordner, aus denen Typendefinitionen einbezogen werden sollen.", + "List_of_language_service_plugins_6181": "Liste der Sprachdienst-Plug-ins.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Liste der Stammordner, deren kombinierter Inhalt die Struktur des Projekts zur Laufzeit darstellt.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "\"{0}\" wird aus dem Stammverzeichnis \"{1}\" geladen. Speicherort des Kandidaten \"{2}\".", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Modul \"{0}\" wird aus dem Ordner \"node_modules\" geladen, die Zieldatei ist vom Typ \"{1}\".", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Modul wird als Datei/Ordner geladen, der Speicherort des Kandidatenmoduls ist \"{0}\", die Zieldatei ist vom Typ \"{1}\".", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Für das Gebietsschema ist das Format oder - erforderlich, z. B. \"{0}\" oder \"{1}\".", + "Longest_matching_prefix_for_0_is_1_6108": "Das längste übereinstimmende Präfix für \"{0}\" ist \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Die Suche erfolgt im Ordner \"node_modules\". Anfangsspeicherort \"{0}\".", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Legen Sie den super()-Aufruf als erste Anweisung im Konstruktor fest.", + "Member_0_implicitly_has_an_1_type_7008": "Der Member \"{0}\" weist implizit den Typ \"{1}\" auf.", + "Merge_conflict_marker_encountered_1185": "Mergekonfliktmarkierung", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Die gemergte Deklaration \"{0}\" darf keine Exportstandarddeklaration enthalten. Fügen Sie ggf. eine separate Deklaration \"export default {0}\" hinzu.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Die Metaeigenschaft \"{0}\" ist nur im Text einer Funktionsdeklaration, eines Funktionsausdrucks oder eines Konstruktors zulässig.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Die Methode \"{0}\" darf keine Implementierung besitzen, weil sie als abstrakt markiert ist.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Die Methode \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Die Methode \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Modifiers_cannot_appear_here_1184": "Modifizierer dürfen hier nicht enthalten sein.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Das Modul \"{0}\" hat bereits einen Member mit dem Namen \"{1}\" exportiert. Erwägen Sie, ihn explizit erneut zu exportieren, um die Mehrdeutigkeit zu vermeiden.", + "Module_0_has_no_default_export_1192": "Das Modul \"{0}\" weist keinen Standardexport auf.", + "Module_0_has_no_exported_member_1_2305": "Das Modul \"{0}\" weist keinen exportierten Member \"{1}\" auf.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Das Modul \"{0}\" wird durch eine lokale Deklaration mit dem gleichen Namen ausgeblendet.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Das Modul \"{0}\" wird in eine Nicht-Modulentität aufgelöst und darf nicht mithilfe dieses Konstrukts importiert werden.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Das Modul \"{0}\" verwendet \"export =\" und darf nicht mit \"export *\" verwendet werden.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Das Modul \"{0}\" wurde als in \"{1}\" deklariertes Umgebungsmodul aufgelöst, weil diese Datei nicht geändert wurde.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Das Modul \"{0}\" wurde als lokal deklariertes Umgebungsmodul in der Datei \"{1}\" aufgelöst.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Das Modul \"{0}\" wurde zu \"{1}\" aufgelöst, aber \"--jsx\" wurde nicht festgelegt.", + "Module_Resolution_Options_6174": "Modulauflösungsoptionen", + "Module_name_0_matched_pattern_1_6092": "Modulname \"{0}\", übereinstimmendes Muster \"{1}\".", + "Module_name_0_was_not_resolved_6090": "======== Der Modulname \"{0}\" wurde nicht aufgelöst. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Die Art der Modulauflösung wird nicht angegeben. \"{0}\" wird verwendet.", + "Module_resolution_using_rootDirs_has_failed_6111": "Fehler bei der Modulauflösung mithilfe von \"rootDirs\".", + "Multiple_constructor_implementations_are_not_allowed_2392": "Mehrere Konstruktorimplementierungen sind unzulässig.", + "NEWLINE_6061": "NEUE ZEILE", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Die benannte Eigenschaft \"{0}\" der Typen \"{1}\" und \"{2}\" ist nicht identisch.", + "Namespace_0_has_no_exported_member_1_2694": "Der Namespace \"{0}\" besitzt keinen exportierten Member \"{1}\".", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Kein Basiskonstruktor weist die angegebene Anzahl von Typargumenten auf.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "In der Konfigurationsdatei \"{0}\" wurden keine Eingaben gefunden. Als include-Pfade wurden \"{1}\", als exclude-Pfade wurden \"{2}\" angegeben.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Die nicht abstrakte Klasse \"{0}\" implementiert nicht den geerbten abstrakten Member \"{1}\" aus der Klasse \"{2}\".", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Der nicht abstrakte Ausdruck implementiert nicht den geerbten abstrakten Member \"{0}\" aus der Klasse \"{1}\".", + "Not_all_code_paths_return_a_value_7030": "Nicht alle Codepfade geben einen Wert zurück.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Der numerische Indextyp \"{0}\" kann dem Zeichenfolgen-Indextyp \"{1}\" nicht zugewiesen werden.", + "Object_is_possibly_null_2531": "Das Objekt ist möglicherweise \"NULL\".", + "Object_is_possibly_null_or_undefined_2533": "Das Objekt ist möglicherweise \"NULL\" oder \"nicht definiert\".", + "Object_is_possibly_undefined_2532": "Das Objekt ist möglicherweise \"nicht definiert\".", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Das Objektliteral kann nur bekannte Eigenschaften angeben, und \"{0}\" ist im Typ \"{1}\" nicht vorhanden.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Das Objektliteral gibt möglicherweise nur bekannte Eigenschaften an, \"{0}\" ist jedoch im Typ \"{1}\" nicht vorhanden. Wollten Sie \"{2}\" schreiben?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Die Eigenschaft \"{0}\" des Objektliterals weist implizit den Typ \"{1}\" auf.", + "Octal_digit_expected_1178": "Es wurde eine Oktalzahl erwartet.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Oktalliteraltypen müssen die Syntax \"ES2015\" verwenden. Verwenden Sie die Syntax \"{0}\".", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Oktalliterale sind in einem Mitgliederenumerationsinitialisierer nicht zulässig. Verwenden Sie die Syntax \"{0}\".", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Oktalliterale sind im Strict-Modus unzulässig.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Oktalliterale sind bei der Zielgruppenadressierung von ECMAScript 5 und höher nicht verfügbar. Verwenden Sie die Syntax \"{0}\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In einer for...in-Anweisung ist nur eine einzige Variablendeklaration zulässig.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In einer for...of-Anweisung ist nur eine einzige Variablendeklaration zulässig.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Nur eine void-Funktion kann mit dem Schlüsselwort \"new\" aufgerufen werden.", + "Only_ambient_modules_can_use_quoted_names_1035": "Nur Umgebungsmodule dürfen Namen in Anführungszeichen verwenden.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Nur die Module \"amd\" und \"system\" werden in Verbindung mit --{0} unterstützt.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Derzeit werden nur Bezeichner/qualifizierte Namen mit optionalen Typargumenten in den \"extends\"-Klauseln einer Klasse unterstützt.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Nur auf öffentliche und geschützte Methoden der Basisklasse kann über das Schlüsselwort \"super\" zugegriffen werden.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Der Operator \"{0}\" darf nicht auf die Typen \"{1}\" und \"{2}\" angewendet werden.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben werden.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Die Option \"{0}\" kann nur verwendet werden, wenn die Option \"-inlineSourceMap\" oder \"-sourceMap\" angegeben wird.", + "Option_0_cannot_be_specified_with_option_1_5053": "Die Option \"{0}\" darf nicht zusammen mit der Option \"{1}\" angegeben werden.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Die Option \"{0}\" darf nicht ohne die Option \"{1}\" angegeben werden.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Die Option \"{0}\" muss ein Zeichenfolgenarray als Wert aufweisen.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Die Option \"isolatedModules\" kann nur verwendet werden, wenn entweder die Option \"--module\" angegeben ist oder die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Die \"path\"-Option kann nicht ohne Angabe der \"-baseUrl\"-Option angegeben werden.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Die Option \"project\" darf nicht mit Quelldateien in einer Befehlszeile kombiniert werden.", + "Options_Colon_6027": "Optionen:", + "Output_directory_for_generated_declaration_files_6166": "Ausgabeverzeichnis für erstellte Deklarationsdateien.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Die Überladungssignatur ist nicht mit der Funktionsimplementierung kompatibel.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Überladungssignaturen müssen alle abstrakt oder nicht abstrakt sein.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Überladungssignaturen müssen alle umgebend oder nicht umgebend sein.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Überladungssignaturen müssen alle exportiert oder nicht exportiert sein.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Überladungssignaturen müssen alle optional oder erforderlich sein.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Überladungssignaturen müssen alle öffentlich, privat oder geschützt sein.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Auf den Parameter \"{0}\" darf in diesem Initialisierer nicht verwiesen werden.", + "Parameter_0_implicitly_has_an_1_type_7006": "Der Parameter \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Der Parameter \"{0}\" befindet sich nicht an der gleichen Position wie der Parameter \"{1}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Der Parameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Der Parameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Der Parameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Der Parameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Der Parameter \"{0}\" der Indexsignatur aus der exportierten Schnittstelle weist den Namen \"{1}\" aus dem privaten Modul \"{2}\" auf oder verwendet diesen.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Der Parameter \"{0}\" der Indexsignatur aus der exportierten Schnittstelle weist den privaten Namen \"{1}\" auf oder verwendet diesen.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Der Parameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Der Parameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Der Parameter darf kein Fragezeichen und keinen Initialisierer aufweisen.", + "Parameter_declaration_expected_1138": "Eine Parameterdeklaration wurde erwartet.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Der Parametertyp des öffentlichen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Der Parametertyp des öffentlichen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Im Strict-Modus analysieren und \"use strict\" für jede Quelldatei ausgeben.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Das Muster \"{0}\" darf höchstens ein Zeichen \"*\" aufweisen.", + "Prefix_0_with_an_underscore_90025": "Präfix \"{0}\" mit einem Unterstrich.", + "Print_names_of_files_part_of_the_compilation_6155": "Drucknamen des Dateiteils der Kompilierung.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Drucknamen des generierten Dateiteils der Kompilierung.", + "Print_the_compiler_s_version_6019": "Die Version des Compilers ausgeben.", + "Print_this_message_6017": "Diese Nachricht ausgeben.", + "Property_0_does_not_exist_on_const_enum_1_2479": "Die Eigenschaft \"{0}\" ist für die const-Enumeration \"{1}\" nicht vorhanden.", + "Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Die Eigenschaft \"{0}\" existiert nicht für Typ \"{1}\". Meinten Sie \"{2}\"?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Eigenschaft \"{0}\" weist widersprüchliche Deklarationen auf und ein Zugriff in Typ \"{1}\" ist nicht möglich.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem set-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann dem Typ \"{2}\" nicht zugewiesen werden.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Die Eigenschaft \"{0}\" ist deklariert, aber ihr Wert wird nie gelesen.", + "Property_0_is_incompatible_with_index_signature_2530": "Die Eigenschaft \"{0}\" ist nicht mit der Indexsignatur kompatibel.", + "Property_0_is_missing_in_type_1_2324": "Die Eigenschaft \"{0}\" fehlt im Typ \"{1}\".", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" optional, im Typ \"{2}\" aber erforderlich.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Die Eigenschaft \"{0}\" ist privat. Auf sie kann nur innerhalb der Klasse \"{1}\" zugegriffen werden.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" privat, im Typ \"{2}\" hingegen nicht.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Die Eigenschaft \"{0}\" ist geschützt. Auf sie kann nur über eine Instanz der Klasse \"{1}\" zugegriffen werden.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Die Eigenschaft \"{0}\" ist geschützt. Auf sie kann nur innerhalb der Klasse \"{1}\" und ihrer Unterklassen zugegriffen werden.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Die Eigenschaft \"{0}\" ist geschützt, Typ \"{1}\" ist aber keine von \"{2}\" abgeleitete Klasse.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" geschützt, im Typ \"{2}\" aber öffentlich.", + "Property_0_is_used_before_being_assigned_2565": "Die Eigenschaft \"{0}\" wird vor ihrer Zuweisung verwendet.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Die Eigenschaft \"{0}\" des JSX-Verteilungsattributs kann nicht der Zieleigenschaft zugewiesen werden.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Die Eigenschaft \"{0}\" des exportierten Klassenausdrucks ist unter Umständen nicht privat oder geschützt.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Die Eigenschaft \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Die Eigenschaft \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Die Eigenschaft \"{0}\" vom Typ \"{1}\" kann dem numerischen Indextyp \"{2}\" nicht zugewiesen werden.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Die Eigenschaft \"{0}\" vom Typ \"{1}\" kann dem Zeichenfolgen-Indextyp \"{2}\" nicht zugewiesen werden.", + "Property_assignment_expected_1136": "Die Zuweisung einer Eigenschaft wurde erwartet.", + "Property_destructuring_pattern_expected_1180": "Ein Eigenschaftendestrukturierungsmuster wurde erwartet.", + "Property_or_signature_expected_1131": "Eine Eigenschaft oder Signatur wurde erwartet.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Der Eigenschaftswert kann nur ein Zeichenfolgenliteral, ein numerisches Literal, \"true\", \"false\", \"NULL\", ein Objektliteral oder ein Arrayliteral sein.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Bieten Sie vollständige Unterstützung für Iterablen in \"for-of\", Verteilung und Destrukturierung mit dem Ziel \"ES5\" oder \"ES3\".", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Fehler für Ausdrücke und Deklarationen mit einem impliziten any-Typ auslösen.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.", + "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", + "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", + "Report_errors_in_js_files_8019": "Fehler in .js-Dateien melden.", + "Report_errors_on_unused_locals_6134": "Fehler für nicht verwendete lokale Variablen melden.", + "Report_errors_on_unused_parameters_6135": "Fehler für nicht verwendete Parameter melden.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Erforderliche Typparameter dürfen nicht auf optionale Typparameter folgen.", + "Resolution_for_module_0_was_found_in_cache_6147": "Die Auflösung für das Modul \"{0}\" wurde im Cache gefunden.", + "Resolving_from_node_modules_folder_6118": "Auflösen aus dem Ordner \"node_modules\"...", + "Resolving_module_0_from_1_6086": "======== Das Modul \"{0}\" aus \"{1}\" wird aufgelöst. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Der Modulname \"{0}\" relativ zur Basis-URL \"{1}\"–\"{2}\" wird aufgelöst.", + "Resolving_real_path_for_0_result_1_6130": "Der tatsächliche Pfad für \"{0}\" wird aufgelöst, Ergebnis \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. Das Stammverzeichnis ist \"{2}\". ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. Das Stammverzeichnis ist nicht festgelegt. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die nicht festgelegte Datei enthält. Das Stammverzeichnis ist \"{1}\". ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die nicht festgelegte Datei enthält. Das Stammverzeichnis ist nicht festgelegt. ========", + "Resolving_using_primary_search_paths_6117": "Auflösung mithilfe primärer Suchpfade...", + "Resolving_with_primary_search_path_0_6121": "Die Auflösung erfolgt mit dem primären Suchpfad \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Der rest-parameter \"{0}\" weist implizit einen Typ \"any[]\" auf.", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest-Typen dürfen nur aus object-Typen erstellt werden.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Der Rückgabetyp der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Der Rückgabetyp der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Der Rückgabetyp der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Der Rückgabetyp der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Der Rückgabetyp der Konstruktorsignatur muss dem Instanztyp der Klasse zugewiesen werden können.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Der Rückgabetyp der Indexsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Der Rückgabetyp der Indexsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Der Rückgabetyp der Methode aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Der Rückgabetyp der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Modulauflösungen aus \"{0}\" werden wiederverwendet, da Auflösungen aus dem alten Programm nicht geändert wurden.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Die Auflösung des Moduls \"{0}\" in die Datei \"{1}\" aus dem alten Programm wird wiederverwendet.", + "Rewrite_as_the_indexed_access_type_0_90026": "Als indizierten Zugriffstyp \"{0}\" neu schreiben.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Das Stammverzeichnis kann nicht ermittelt werden. Die primären Suchpfade werden übersprungen.", + "STRATEGY_6039": "STRATEGIE", + "Scoped_package_detected_looking_in_0_6182": "Bereichsbezogenes Paket erkannt. In \"{0}\" wird gesucht", + "Setters_cannot_return_a_value_2408": "Setter können keinen Wert zurückgeben.", + "Show_all_compiler_options_6169": "Alle Compileroptionen anzeigen.", + "Show_diagnostic_information_6149": "Diagnoseinformationen anzeigen.", + "Show_verbose_diagnostic_information_6150": "Ausführliche Diagnoseinformationen anzeigen.", + "Signature_0_must_be_a_type_predicate_1224": "Die Signatur \"{0}\" muss ein Typprädikat sein.", + "Skip_type_checking_of_declaration_files_6012": "Überspringen Sie die Typüberprüfung von Deklarationsdateien.", + "Source_Map_Options_6175": "Quellzuordnungsoptionen", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Eine spezialisierte Überladungssignatur kann keiner nicht spezialisierten Signatur zugewiesen werden.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Der Spezifizierer des dynamischen Imports darf kein Spread-Element sein.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript-Zielversion angeben: ES3 (Standard), ES5, ES2015, ES2016, ES2017 oder ESNEXT.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX-Codegenerierung angeben: \"preserve\", \"react-native\" oder \"react\".", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Geben Sie Bibliotheksdateien an, die in die Kompilierung eingeschlossen werden sollen: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Geben Sie die Codegenerierung für das Modul an: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" oder \"ESNext\".", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Geben Sie die Modulauflösungsstrategie an: \"node\" (Node.js) oder \"classic\" (TypeScript vor Version 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Geben Sie die JSX-Factoryfunktion an, die für eine react-JSX-Ausgabe verwendet werden soll, z. B. \"React.createElement\" oder \"h\".", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Geben Sie die Zeilenendesequenz an, die beim Ausgeben von Dateien verwendet werden soll: \"CRLF\" (DOS) oder \"LF\" (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Geben Sie den Speicherort an, an dem der Debugger TypeScript-Dateien ermitteln soll, anstatt Quellspeicherorte zu verwenden.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Geben Sie den Speicherort an, an dem der Debugger Zuordnungsdateien ermitteln soll, anstatt generierte Speicherorte zu verwenden.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Geben Sie das Stammverzeichnis der Eingabedateien an. Verwenden Sie diese Angabe, um die Ausgabeverzeichnisstruktur mithilfe von \"-outDir\" zu steuern.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Der Verteilungsoperator in new-Ausdrücken ist nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", + "Spread_types_may_only_be_created_from_object_types_2698": "Spread-Typen dürfen nur aus object-Typen erstellt werden.", + "Statement_expected_1129": "Eine Anweisung wurde erwartet.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Anweisungen sind in Umgebungskontexten unzulässig.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statische Member dürfen nicht auf Klassentypparameter verweisen.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Die statische Eigenschaft \"{0}\" steht in Konflikt mit der integrierten Eigenschaft \"Function.{0}\" der Konstruktorfunktion \"{1}\".", + "Strict_Type_Checking_Options_6173": "Strenge Typüberprüfungsoptionen", + "String_literal_expected_1141": "Ein Zeichenfolgenliteral wurde erwartet.", + "String_literal_with_double_quotes_expected_1327": "Ein Zeichenfolgenliteral mit doppelten Anführungszeichen wird erwartet.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Fehler und Nachrichten farbig und mit Kontext formatieren (experimentell).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Nachfolgende Variablendeklarationen müssen den gleichen Typ aufweisen. Die Variable \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Die Ersetzung \"{0}\" für das Muster \"{1}\" weist einen falschen Typ auf. Erwartet wurde \"string\", abgerufen wurde \"{2}\".", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Die Ersetzung \"{0}\" im Muster \"{1}\" darf höchstens ein Zeichen \"*\" aufweisen.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Die Ersetzung für das Muster \"{0}\" muss ein Array sein.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Ersetzungen für das Muster \"{0}\" dürfen kein leeres Array sein.", + "Successfully_created_a_tsconfig_json_file_6071": "Eine Datei \"tsconfig.json\" wurde erfolgreich erstellt.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Aufrufe von \"super\" sind außerhalb von Konstruktoren oder in geschachtelten Funktionen innerhalb von Konstruktoren unzulässig.", + "Suppress_excess_property_checks_for_object_literals_6072": "Übermäßige Eigenschaftenüberprüfungen für Objektliterale unterdrücken.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "noImplicitAny-Fehler für die Indizierung von Objekten unterdrücken, denen Indexsignaturen fehlen.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Der Symbol-Verweis verweist nicht auf das globale Symbolkonstruktorobjekt.", + "Syntax_Colon_0_6023": "Syntax: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Der Operator \"{0}\" darf nicht den Typ \"symbol\" angewendet werden.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Der Operator \"{0}\" ist für boolesche Typen unzulässig. Verwenden Sie stattdessen ggf. \"{1}\".", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Der Typ \"Object\" kann nur wenigen anderen Typen zugewiesen werden. Wollten Sie stattdessen den Typ \"any\" verwenden?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Auf das Objekt \"arguments\" darf in einer Pfeilfunktion in ES3 und ES5 nicht verwiesen werden. Verwenden Sie ggf. einen Standardfunktionsausdruck.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Auf das Objekt \"arguments\" darf in einer asynchronen Funktion oder Methode in ES3 und ES5 nicht verwiesen werden. Verwenden Sie ggf. eine Standardfunktion oder -methode.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Der Text einer \"if\"-Anweisung kann keine leere Anweisung sein.", + "The_character_set_of_the_input_files_6163": "Der Zeichensatz der Eingabedateien.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Der beinhaltende Funktions- oder Modulkörper ist zu groß für eine Ablaufsteuerungsanalyse.", + "The_current_host_does_not_support_the_0_option_5001": "Der aktuelle Host unterstützt die Option \"{0}\" nicht.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Der Ausdruck einer Exportzuweisung muss ein Bezeichner oder ein qualifizierter Name in einem Umgebungskontext sein.", + "The_files_list_in_config_file_0_is_empty_18002": "Die Liste \"files\" in der Konfigurationsdatei \"{0}\" ist leer.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Die linke Seite einer for...in-Anweisung darf kein Destrukturierungsmuster sein.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Die linke Seite einer for...in-Anweisung darf keine Typanmerkung verwenden.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Die linke Seite einer for...in-Anweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Die linke Seite einer for...in-Anweisung muss vom Typ \"string\" oder \"any\" sein.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Die linke Seite einer for...of-Anweisung darf keine Typanmerkung verwenden.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Die linke Seite einer for...of-Anweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Die linke Seite einer arithmetischen Operation muss den Typ \"any\" oder \"number\" aufweisen oder ein Enumerationstyp sein.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Die linke Seite eines Zuweisungsausdrucks muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Die linke Seite eines in-Ausdrucks muss vom Typ \"any\", \"string\", \"number\" oder \"symbol\" sein.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Die linke Seite eines instanceof-Ausdrucks muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Das beim Anzeigen von Meldungen für den Benutzer verwendete Gebietsschema (z. B. \"de-de\").", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Die maximale Abhängigkeitstiefe, die unter \"node_modules\" durchsucht und für die JavaScript-Dateien geladen werden sollen.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Der Operand eines delete-Operators darf keine schreibgeschützte Eigenschaft sein.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Der Operand eines delete-Operators muss eine Eigenschaftenreferenz sein.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Der Rückgabetyp eines JSX-Elementkonstruktors muss einen Objekttyp zurückgeben.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Der Rückgabetyp einer Parameter-Decorator-Funktion muss \"void\" oder \"any\" sein.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Der Rückgabetyp einer Eigenschaften-Decorator-Funktion muss \"void\" oder \"any\" sein.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Der Rückgabetyp einer asynchronen Funktion muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Der Rückgabetyp einer asynchronen Funktion oder Methode muss der globale Typ \"Promise\" sein.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "Die rechte Seite einer for...in-Anweisung muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Die rechte Seite einer arithmetischen Operation muss den Typ \"any\" oder \"number\" aufweisen oder ein Enumerationstyp sein.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Die rechte Seite eines in-Ausdrucks muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Die rechte Seite eines instanceof-Ausdrucks muss den Typ \"any\" oder einen Typ aufweisen, der dem Schnittstellentyp \"Function\" zugewiesen werden kann.", + "The_specified_path_does_not_exist_Colon_0_5058": "Der angegebene Pfad \"{0}\" ist nicht vorhanden.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Das Ziel einer Zuweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Das Ziel einer REST-Zuweisung für ein Objekt muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Der \"this\"-Kontext vom Typ \"{0}\" kann \"this\" vom Typ \"{1}\" der Methode nicht zugewiesen werden.", + "The_this_types_of_each_signature_are_incompatible_2685": "Die \"this\"-Typen jeder Signatur sind nicht kompatibel.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Das Typargument für den Typparameter \"{0}\" kann nicht aus der Syntax abgeleitet werden. Geben Sie die Typargumente ggf. explizit an.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Der von der \"next()\"-Methode eines Async-Iterators zurückgegebene Typ muss eine Zusage für einen Typ mit einer \"value\"-Eigenschaft sein.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Der von der Methode \"next()\" eines Iterators zurückgegebene Typ muss eine Eigenschaft \"value\" besitzen.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Die Variablendeklaration einer for...in-Anweisung darf keinen Initialisierer aufweisen.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Die Variablendeklaration einer for...of-Anweisung darf keinen Initialisierer aufweisen.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Die with-Anweisung wird nicht unterstützt. Alle Symbole in einem with-Block weisen den Typ \"any\" auf.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Diese Syntax erfordert ein importiertes Hilfsprogramm, aber das Modul \"{0}\" wurde nicht gefunden.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Diese Syntax erfordert ein importiertes Hilfsprogramm namens \"{1}\", aber das Modul \"{0}\" enthält keinen exportierten Member \"{1}\".", + "Trailing_comma_not_allowed_1009": "Ein nachgestelltes Komma ist unzulässig.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Jede Datei als separates Modul transpilieren (ähnlich wie bei \"ts.transpileModule\").", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Versuchen Sie \"npm install @types/{0}\", sofern vorhanden, oder fügen Sie eine neue Deklarationsdatei (.d.ts) hinzu, die \"declare module '{0}';\" enthält.", + "Trying_other_entries_in_rootDirs_6110": "Andere Einträge in \"rootDirs\" werden versucht.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Die Ersetzung \"{0}\" wird versucht. Speicherort des Kandidatenmoduls: \"{1}\".", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Der Tupeltyp \"{0}\" mit der Länge \"{1}\" kann dem Tupel mit der Länge \"{2}\" nicht zugewiesen werden.", + "Type_0_cannot_be_converted_to_type_1_2352": "Der Typ \"{0}\" kann nicht in den Typ \"{1}\" konvertiert werden.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Der Typ \"{0}\" kann nicht als Indextyp verwendet werden.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Der Typ \"{0}\" kann nicht zum Indizieren von Typ \"{1}\" verwendet werden.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Der Typ \"{0}\" erfüllt die Einschränkung \"{1}\" nicht.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Der Typ \"{0}\" weist keine übereinstimmende Indexsignatur für den Typ \"{1}\" auf.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Der Typ \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit Typ \"{1}\".", + "Type_0_has_no_property_1_2460": "Der Typ \"{0}\" besitzt keine Eigenschaft \"{1}\".", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Der Typ \"{0}\" verfügt über keine Eigenschaft \"{1}\" und keine Zeichenfolgen-Indexsignatur.", + "Type_0_is_not_a_constructor_function_type_2507": "Der Typ \"{0}\" ist kein Konstruktorfunktionstyp.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Der Typ \"{0}\" ist in ES5/ES3 kein gültiger Rückgabetyp einer asynchronen Funktion, weil er nicht auf einen Promise-kompatiblen Konstruktorwert verweist.", + "Type_0_is_not_an_array_type_2461": "Der Typ \"{0}\" ist kein Arraytyp.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Der Typ \"{0}\" ist kein Array- oder Zeichenfolgentyp.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ \"{0}\" ist kein Array-Typ oder Zeichenfolgentyp oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ \"{0}\" ist kein Array-Typ oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", + "Type_0_is_not_assignable_to_type_1_2322": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Typ \"{0}\" kann nicht zu Typ \"{1}\" zugewiesen werden. Es sind zwei verschiedene Typen mit diesem Namen vorhanden, diese sind jedoch nicht verwandt.", + "Type_0_is_not_comparable_to_type_1_2678": "Der Typ \"{0}\" kann nicht mit dem Typ \"{1}\" verglichen werden.", + "Type_0_is_not_generic_2315": "Der Typ \"{0}\" ist nicht generisch.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Der Typ \"{0}\" enthält keine Entsprechung für die Signatur \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Der Typ \"{0}\" verweist rekursiv auf sich selbst als ein Basistyp.", + "Type_alias_0_circularly_references_itself_2456": "Der Typalias \"{0}\" verweist zirkulär auf sich selbst.", + "Type_alias_name_cannot_be_0_2457": "Der Typaliasname darf nicht \"{0}\" sein.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Die Typanmerkung darf nicht für eine Konstruktordeklaration verwendet werden.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Der Typargumentkandidat \"{1}\" ist kein gültiges Typargument, weil er kein Obertyp des Kandidaten \"{0}\" ist.", + "Type_argument_expected_1140": "Ein Typargument wurde erwartet.", + "Type_argument_list_cannot_be_empty_1099": "Die Typargumentliste darf nicht leer sein.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Typdeklarationsdateien, die in die Kompilierung eingeschlossen werden sollen.", + "Type_expected_1110": "Es wurde ein Typ erwartet.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Auf den Typ wird direkt oder indirekt im Erfüllungsrückruf der eigenen \"then\"-Methode verwiesen.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Der Typ muss eine \"[Symbol.asyncIterator]()\"-Methode aufweisen, die einen Async-Iterator zurückgibt.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Der Typ muss über eine Methode \"[Symbol.iterator]()\" verfügen, die einen Iterator zurückgibt.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Der Typ des \"await\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" weist einen zirkulären Standard auf.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Der Typparameter \"{0}\" der exportierten Funktion besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Der Typparameter \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Der Typparameter \"{0}\" des exportierten Typalias enthält oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Der Typparameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Der Typparameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Der Typparameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_declaration_expected_1139": "Eine Typparameterdeklaration wurde erwartet.", + "Type_parameter_list_cannot_be_empty_1098": "Die Typparameterliste darf nicht leer sein.", + "Type_parameter_name_cannot_be_0_2368": "Der Name des Typparameters darf nicht \"{0}\" sein.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Typparameter dürfen nicht für eine Konstruktordeklaration verwendet werden.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Das Typprädikat \"{0}\" kann \"{1}\" nicht zugewiesen werden.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Die Typverweisdirektive \"{0}\" wurde nicht aufgelöst. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Die Typverweisdirektive \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. Primär: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typen weisen separate Deklarationen einer privaten Eigenschaft \"{0}\" auf.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Die Typen der Parameter \"{0}\" und \"{1}\" sind nicht kompatibel.", + "Types_of_property_0_are_incompatible_2326": "Die Typen der Eigenschaft \"{0}\" sind nicht kompatibel.", + "Unable_to_open_file_0_6050": "Die Datei \"{0}\" kann nicht geöffnet werden.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Die Signatur des Klassen-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Die Signatur des Methoden-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Die Signatur des Parameter-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Die Signatur des Eigenschaften-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unexpected_end_of_text_1126": "Unerwartetes Textende.", + "Unexpected_token_1012": "Unerwartetes Token.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Unerwartetes Token. Ein Konstruktor, eine Methode, eine Zugriffsmethode oder eine Eigenschaft wurde erwartet.", + "Unexpected_token_expected_1179": "Unerwartetes Token. \"{\" wurde erwartet.", + "Unknown_compiler_option_0_5023": "Unbekannte Compileroption \"{0}\".", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Unbekannte Option \"exclude\". Meinten Sie \"exclude\"?", + "Unknown_type_acquisition_option_0_17010": "Unbekannte Option zur Typerfassung: {0}.", + "Unreachable_code_detected_7027": "Es wurde unerreichbarer Code erkannt.", + "Unsupported_locale_0_6049": "Nicht unterstütztes Gebietsschema \"{0}\".", + "Unterminated_Unicode_escape_sequence_1199": "Nicht abgeschlossene Unicode-Escapesequenz.", + "Unterminated_quoted_string_in_response_file_0_6045": "Nicht abgeschlossene Zeichenfolge in Anführungszeichen in der Datei \"{0}\".", + "Unterminated_regular_expression_literal_1161": "Nicht abgeschlossenes reguläres Ausdrucksliteral.", + "Unterminated_string_literal_1002": "Nicht abgeschlossenes Zeichenfolgenliteral.", + "Unterminated_template_literal_1160": "Nicht abgeschlossenes Vorlagenliteral.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Nicht typisierte Funktionsaufrufe dürfen keine Typargumente annehmen.", + "Unused_label_7028": "Nicht verwendete Bezeichnung.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", + "VERSION_6036": "VERSION", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Der Wert des Typs \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit dem Typ \"{1}\". Wollten Sie ihn aufrufen?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Der Wert des Typs \"{0}\" kann nicht aufgerufen werden. Wollten Sie \"new\" einschließen?", + "Variable_0_implicitly_has_an_1_type_7005": "Die Variable \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Die Variable \"{0}\" weist an manchen Stellen implizit den Typ \"{1}\" auf, an denen der Typ nicht ermittelt werden kann.", + "Variable_0_is_used_before_being_assigned_2454": "Die Variable \"{0}\" wird vor ihrer Zuweisung verwendet.", + "Variable_declaration_expected_1134": "Eine Variablendeklaration wurde erwartet.", + "Variable_declaration_list_cannot_be_empty_1123": "Die Variablendeklarationsliste darf nicht leer sein.", + "Version_0_6029": "Version {0}", + "Watch_input_files_6005": "Eingabedateien überwachen.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Sie können keine Elemente umbenennen, die in der TypeScript-Standardbibliothek definiert sind.", + "You_cannot_rename_this_element_8000": "Sie können dieses Element nicht umbenennen.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" akzeptiert zu wenige Argumente, um hier als Decorator verwendet zu werden. Wollten Sie es zuerst aufrufen und \"@{0}()\" schreiben?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" ist zweimal angegeben. Das Attribut mit dem Namen \"{0}\" wird überschrieben.", + "_0_can_only_be_used_in_a_ts_file_8009": "\"{0}\" kann nur in einer TS-Datei verwendet werden.", + "_0_expected_1005": "\"{0}\" wurde erwartet.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "\"{0}\" weist implizit den Typ \"any\" auf, weil keine Rückgabetypanmerkung vorhanden ist und darauf direkt oder indirekt in einem der Rückgabeausdrücke des Objekts verwiesen wird.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "\"{0}\" weist implizit den Typ \"any\" auf, weil keine Typanmerkung vorhanden ist und darauf direkt oder indirekt im eigenen Initialisierer verwiesen wird.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" ist ein primitiver Typ, aber \"{1}\" ist ein Wrapperobjekt. Verwenden Sie vorzugsweise \"{0}\", wenn möglich.", + "_0_is_declared_but_its_value_is_never_read_6133": "\"{0}\" ist deklariert, aber der zugehörige Wert wird nie gelesen.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" ist keine gültige Metaeigenschaft für das Schlüsselwort \"{1}\". Meinten Sie \"{2}\"?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Auf \"{0}\" wird direkt oder indirekt im eigenen Basisausdruck verwiesen.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Auf \"{0}\" wird direkt oder indirekt in der eigenen Typanmerkung verwiesen.", + "_0_list_cannot_be_empty_1097": "Die {0}-Liste darf nicht leer sein.", + "_0_modifier_already_seen_1030": "Der {0}-Modifizierer ist bereits vorhanden.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Der Modifizierer \"{0}\" darf nicht für ein Klassenelement verwendet werden.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Der Modifizierer \"{0}\" darf nicht für eine Konstruktordeklaration verwendet werden.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Der Modifizierer \"{0}\" darf nicht für eine Dateneigenschaft verwendet werden.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Der Modifizierer \"{0}\" darf nicht für ein Modul- oder Namespaceelement verwendet werden.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Der Modifizierer \"{0}\" darf nicht für einen Parameter verwendet werden.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Der Modifizierer \"{0}\" darf nicht für einen Typmember verwendet werden.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Der Modifizierer \"{0}\" darf nicht für eine Indexsignatur verwendet werden.", + "_0_modifier_cannot_be_used_here_1042": "Der Modifizierer \"{0}\" kann hier nicht verwendet werden.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Der Modifizierer \"{0}\" kann nicht in einem Umgebungskontext verwendet werden.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Der Modifizierer \"{0}\" darf nicht mit dem Modifizierer \"{1}\" verwendet werden.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Der Modifizierer \"{0}\" darf nicht mit einer Klassendeklaration verwendet werden.", + "_0_modifier_must_precede_1_modifier_1029": "Der Modifizierer \"{0}\" muss dem Modifizierer \"{1}\" vorangestellt sein.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "\"{0}\" bezieht sich nur auf einen Typ, wird hier jedoch als Namespace verwendet.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "\"{0}\" bezieht sich nur auf einen Typ, wird aber hier als Wert verwendet.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "\"{0}\" bezieht sich auf eine globale UMD, die aktuelle Datei ist jedoch ein Modul. Ziehen Sie in Betracht, stattdessen einen Import hinzuzufügen.", + "_0_tag_already_specified_1223": "Das Tag \"{0}\" wurde bereits angegeben.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Das Tag \"{0}\" kann nicht unabhängig als ein JSDoc-Tag der obersten Ebene verwendet werden.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "\"{0}\" ohne Rückgabetypanmerkung weist implizit einen Rückgabetyp \"{1}\" auf.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Der Modifizierer \"abstract\" darf nur für eine Klassen-, Methoden- oder Eigenschaftendeklaration verwendet werden.", + "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.", + "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.", + "const_declarations_must_be_initialized_1155": "const-Deklarationen müssen initialisiert werden.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Der const-Enumerationsmemberinitialisierer wurde in einen unendlichen Wert ausgewertet.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Der const-Enumerationsmemberinitialisierer wurde in den unzulässigen Wert \"NaN\" ausgewertet.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "const-Enumerationen können nur in Eigenschaften- bzw. Indexzugriffsausdrücken oder auf der rechten Seite einer Importdeklaration oder Exportzuweisung verwendet werden.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "\"delete\" kann für einen Bezeichner im Strict-Modus nicht aufgerufen werden.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" kann nur in einer TS-Datei verwendet werden.", + "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" kann nur in einer TS-Datei verwendet werden.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Der Modifizierer \"export\" kann nicht auf Umgebungsmodule und Modulerweiterungen angewendet werden, da diese immer sichtbar sind.", + "extends_clause_already_seen_1172": "Die extends-Klausel ist bereits vorhanden.", + "extends_clause_must_precede_implements_clause_1173": "Die extends-Klausel muss der implements-Klausel vorangestellt sein.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Die \"extends\"-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Die \"extends\"-Klausel der exportierten Schnittstelle \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "file_6025": "Datei", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Die get- und set-Accessoren müssen den gleichen this-Typ aufweisen.", + "get_and_set_accessor_must_have_the_same_type_2380": "Die get- und set-Zugriffsmethoden müssen den gleichen Typ aufweisen.", + "implements_clause_already_seen_1175": "Die implements-Klausel ist bereits vorhanden.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "\"implements clauses\" kann nur in einer TS-Datei verwendet werden.", + "import_can_only_be_used_in_a_ts_file_8002": "\"import... =\" kann nur in einer TS-Datei verwendet werden.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "\"interface declarations\" kann nur in einer TS-Datei verwendet werden.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "let-Deklarationen können nur innerhalb eines Blocks deklariert werden.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "\"let\" darf nicht als Name in let- oder const-Deklarationen verwendet werden.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "\"module declarations\" kann nur in einer TS-Datei verwendet werden.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "\"new T[]\" kann nicht zum Erstellen eines Arrays verwendet werden. Verwenden Sie stattdessen \"new Array()\".", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Der new-Ausdruck, in dessen Ziel eine Konstruktsignatur fehlt, weist implizit einen Typ \"any\" auf.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Assertions, die nicht NULL sind, können nur in einer TS-Datei verwendet werden.", + "options_6024": "Optionen", + "or_expected_1144": "\"{\" oder \";\" wurde erwartet.", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" besitzt kein \"{0}\"-Feld.", + "package_json_has_0_field_1_that_references_2_6101": "\"package.json\" weist das {0}-Feld \"{1}\" auf, das auf \"{2}\" verweist.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" kann nur in einer TS-Datei verwendet werden.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Die Option \"paths\" wurde angegeben. Es wird nach einem Muster gesucht, das mit dem Modulnamen \"{0}\" übereinstimmt.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Der Modifizierer \"readonly\" darf nur für eine Eigenschaftendeklaration oder Indexsignatur verwendet werden.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Die Option \"rootDirs\" wurde festgelegt. Sie wird zum Auflösen des relativen Modulnamens \"{0}\" verwendet.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Auf \"super\" kann nur in einer abgeleiteten Klasse verwiesen werden.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Auf \"super\" kann nur in Membern abgeleiteter Klassen oder Objektliteralausdrücken verwiesen werden.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Auf \"super\" kann nicht in einem berechneten Eigenschaftennamen verwiesen werden.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Auf \"super\" kann nicht in Konstruktorargumenten verwiesen werden.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "\"super\" ist nur in Membern von Objektliteralausdrücken zulässig, wenn die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Vor dem Zugriff auf eine Eigenschaft von \"super\" im Konstruktor einer abgeleiteten Klasse muss \"super\" aufgerufen werden.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "\"super\" muss vor dem Zugreifen auf \"this\" im Konstruktor einer abgeleiteten Klasse aufgerufen werden.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Auf \"super\" muss eine Argumentliste oder Memberzugriff folgen.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Der Zugriff auf die super-Eigenschaft ist nur in einem Konstruktor, einer Memberfunktion oder einer Memberzugriffsmethode einer abgeleiteten Klasse zulässig.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Auf \"this\" kann nicht in einem berechneten Eigenschaftennamen verwiesen werden.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Auf \"this\" kann nicht in einem Modul- oder Namespacetext verwiesen werden.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Auf \"this\" kann nicht in einem statischen Eigenschafteninitialisierer verwiesen werden.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Auf \"this\" kann nicht in Konstruktorargumenten verwiesen werden.", + "this_cannot_be_referenced_in_current_location_2332": "Auf \"this\" kann am aktuellen Speicherort nicht verwiesen werden.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "\"this\" weist implizit den Typ \"any\" auf, weil keine Typanmerkung vorhanden ist.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "\"type aliases\" kann nur in einer TS-Datei verwendet werden.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Typargumente können nur in einer TS-Datei verwendet werden.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" kann nur in einer TS-Datei verwendet werden.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" kann nur in einer TS-Datei verwendet werden.", + "types_can_only_be_used_in_a_ts_file_8010": "\"types\" kann nur in einer TS-Datei verwendet werden.", + "unique_symbol_types_are_not_allowed_here_1335": "\"unique symbol\"-Typen sind hier nicht zulässig.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "\"unique symbol\"-Typen sind nur für Variablen in einer Variablenanweisung zulässig.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "\"unique symbol\"-Typen dürfen für eine Variablendeklaration mit einem Bindungsnamen nicht verwendet werden.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "with-Anweisungen sind in einem asynchronen Funktionsblock unzulässig.", + "with_statements_are_not_allowed_in_strict_mode_1101": "this-Anweisungen sind im Strict-Modus unzulässig.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "yield-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden." +} \ No newline at end of file diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg new file mode 100644 index 0000000000000..1cc79da620336 --- /dev/null +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -0,0 +1,5834 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..8f12067127703 --- /dev/null +++ b/lib/es/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Un modificador '{0}' no se puede usar con una declaración de importación.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Un modificador '{0}' no se puede usar con una declaración de interfaz.", + "A_0_parameter_must_be_the_first_parameter_2680": "El parámetro \"{0}\" debe ser el primer parámetro.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un parámetro de patrón de enlace no puede ser opcional en una signatura de implementación.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Una instrucción \"break\" solo se puede usar dentro de una iteración envolvente o en una instrucción switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Una instrucción \"break\" solo puede saltar a una etiqueta de una instrucción envolvente.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Una clase solo puede implementar un identificador o nombre completo con argumentos de tipo opcional.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Una declaración de clase sin el modificador \"default\" debe tener un nombre.", + "A_class_may_only_extend_another_class_2311": "Una clase solo puede extender otra clase.", + "A_class_may_only_implement_another_class_or_interface_2422": "Una clase solo puede implementar otra clase o interfaz.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un miembro de clase no puede tener la palabra clave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "No se admite una expresión de coma en un nombre de propiedad calculada.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nombre de propiedad calculada no puede hacer referencia a un parámetro de tipo desde su tipo contenedor.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nombre de propiedad calculada en una declaración de propiedad de clase debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nombre de propiedad calculada en una sobrecarga de método debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nombre de propiedad calculada en un literal de tipo debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nombre de propiedad calculada en un contexto de ambiente debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nombre de propiedad calculada en una interfaz debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nombre de propiedad calculada debe ser de tipo \"string\", \"number\", \"symbol\" o \"any\".", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nombre de propiedad calculada con el formato '{0}' debe ser de tipo \"symbol\".", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Solo se puede acceder a un miembro de enumeración const mediante un literal de cadena.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Un inicializador 'const' en un contexto de ambiente debe ser un literal de cadena o numérico.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un constructor no puede contener una llamada a \"super\" si su clase extiende \"null\".", + "A_constructor_cannot_have_a_this_parameter_2681": "Un constructor no puede tener un parámetro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Una instrucción \"continue\" solo se puede usar en una instrucción de iteración envolvente.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Una instrucción \"continue\" solo puede saltar a una etiqueta de una instrucción de iteración envolvente.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Un modificador \"declare\" no se puede usar en un contexto de ambiente.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Se necesita un modificador \"declare\" para una declaración de nivel superior de un archivo .d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un decorador solo puede modificar la implementación de un método, no una sobrecarga.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Una cláusula \"default\" no puede aparecer más de una vez en una instrucción \"switch\".", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Solo se puede usar una exportación predeterminada en un módulo de estilo ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "En este contexto no se permite una aserción de asignación definitiva \"!\".", + "A_destructuring_declaration_must_have_an_initializer_1182": "Una declaración de desestructuración debe tener un inicializador.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Una llamada de importación dinámica en ES5/ES3 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Una llamada de importación dinámica devuelven un valor \"Promise\". Asegúrese de que hay una declaración para \"Promise\" o incluya \"ES2015\" en la opción \"--lib\".", + "A_file_cannot_have_a_reference_to_itself_1006": "Un archivo no puede tener una referencia a sí mismo.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Solo se permite una instrucción \"for-await-of\" en una función o un generador de asincronía.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Una función que devuelve 'never' no puede tener un punto de conexión alcanzable.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Una función a la que se llama con la palabra clave 'new' no puede tener un tipo 'this' que sea 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Una función cuyo tipo declarado no es \"void\" o \"any\" debe devolver un valor.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un generador no puede tener una anotación de tipo \"void\".", + "A_get_accessor_cannot_have_parameters_1054": "Un descriptor de acceso \"get\" no puede tener parámetros.", + "A_get_accessor_must_return_a_value_2378": "Un descriptor de acceso \"get\" debe devolver un valor.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inicializador de miembro de una declaración enum no puede hacer referencia a los miembros que se declaran después de este, incluidos aquellos definidos en otras enumeraciones.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una clase mixin debe tener un constructor con un parámetro de REST sencillo del tipo \"any[]\".", + "A_module_cannot_have_multiple_default_exports_2528": "Un módulo no puede tener varias exportaciones predeterminadas.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una declaración de espacio de nombres no puede estar en un archivo distinto de una clase o función con la que se combina.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una declaración de espacio de nombres no se puede situar antes que una clase o función con la que se combina.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una declaración de espacio de nombres solo se permite en un espacio de nombres o en un módulo.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inicializador de parámetros solo se permite en una implementación de función o de constructor.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Una propiedad de parámetro no se puede declarar mediante un parámetro rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una propiedad de parámetro solo se permite en una implementación de constructor.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Una propiedad de parámetro podría no declararse mediante un patrón de enlace.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Una ruta de acceso en una opción \"extiende\" debe ser relativa o raíz, pero no '{0}'.", + "A_promise_must_have_a_then_method_1059": "Una promesa debe tener un método \"then\".", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una propiedad de una clase cuyo tipo sea \"unique symbol\" debe ser \"static\" y \"readonly\".", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una propiedad de una interfaz o un literal de tipo cuyo tipo sea \"unique symbol\" debe ser \"readonly\".", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un parámetro obligatorio no puede seguir a un parámetro opcional.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un elemento rest no puede contener un patrón de enlace.", + "A_rest_element_cannot_have_an_initializer_1186": "Un elemento rest no puede tener un inicializador.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un elemento rest debe ser el último en un patrón de desestructuración.", + "A_rest_parameter_cannot_be_optional_1047": "Un parámetro rest no puede ser opcional.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un parámetro rest no puede tener un inicializador.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un parámetro rest debe ser el último de una lista de parámetros.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un parámetro rest debe ser de un tipo de matriz.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Una instrucción \"return\" solo se puede usar en el cuerpo de una función.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Serie de entradas que reasigna las importaciones a ubicaciones de búsqueda relativas a \"baseUrl\".", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Un descriptor de acceso \"set\" no puede tener una anotación de tipo de valor devuelto.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Un descriptor de acceso \"set\" no puede tener un parámetro opcional.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Un descriptor de acceso \"set\" no puede tener un parámetro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Un descriptor de acceso \"set\" debe tener exactamente un parámetro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un parámetro de descriptor de acceso \"set\" no puede tener un inicializador.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Una signatura con una implementación no puede usar un tipo de literal de cadena.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Una llamada a \"super\" debe ser la primera instrucción del constructor cuando una clase contiene propiedades inicializadas o tiene propiedades de parámetro.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Una restricción de tipo basada en 'this' no es compatible con una restricción de tipo basada en un parámetro.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "El tipo \"this\" solo está disponible en un miembro no estático de una clase o interfaz.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Ya hay un archivo \"tsconfig.json\" definido en: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Una lista de elementos de tipo de tupla no puede estar vacía.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "No se admite una expresión de aserción de tipo en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Una propiedad de literal de tipo no puede tener un inicializador.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un predicado de tipo no puede hacer referencia a un parámetro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un predicado de tipo no puede hacer referencia al elemento '{0}' de un patrón de enlace.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "En las funciones y los métodos, un predicado de tipo solo se permite en la posición de tipo de valor devuelto.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "El tipo de un predicado de tipo debe poderse asignar al tipo de su parámetro.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Una variable cuyo tipo sea \"unique symbol\" debe ser \"const\".", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Una expresión \"yield\" solo se permite en un cuerpo de generador.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "No se puede acceder al método abstracto '{0}' de la clase '{1}' mediante una expresión super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Los métodos abstractos solo pueden aparecer en una clase abstracta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "No se puede acceder a la propiedad abstracta \"{0}\" de la clase \"{1}\" en el constructor.", + "Accessibility_modifier_already_seen_1028": "El modificador de accesibilidad ya se ha visto.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Los descriptores de acceso solo están disponibles cuando el destino es ECMAScript 5 y versiones posteriores.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", + "Add_0_to_existing_import_declaration_from_1_90015": "Agregue \"{0}\" a una declaración de importación existente desde \"{1}\".", + "Add_index_signature_for_property_0_90017": "Agregue una firma de índice para la propiedad \"{0}\".", + "Add_missing_super_call_90001": "Agregue la llamada a \"super()\" que falta.", + "Add_this_to_unresolved_variable_90008": "Agrega \"this.\" a una variable no resuelta.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Agregar un archivo tsconfig.json ayuda a organizar los proyectos que contienen archivos TypeScript y JavaScript. Más información en https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Comprobaciones adicionales", + "Advanced_Options_6178": "Opciones avanzadas", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas las declaraciones de '{0}' deben tener parámetros de tipo idénticos.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", + "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "No se permiten enumeraciones const de ambiente cuando se proporciona la marca \"--isolatedModules\".", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "La declaración de módulo de ambiente no puede especificar un nombre de módulo relativo.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Los módulos de ambiente no se pueden anidar en otros módulos o espacios de nombres.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un módulo AMD no puede tener varias asignaciones de nombre.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Un descriptor de acceso abstracto no puede tener una implementación.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Un descriptor de acceso no se puede declarar en un contexto de ambiente.", + "An_accessor_cannot_have_type_parameters_1094": "Un descriptor de acceso no puede tener parámetros de tipo.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una declaración de módulo de ambiente solo se permite en el nivel superior de un archivo.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmético debe ser de tipo \"any\", \"number\" o de tipo enum.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Una función o un método de asincronía en ES5/ES3 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Una función o un método asincrónico deben tener un tipo de valor devuelto válido que admita await.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Una función o un método asincrónicos deben devolver una \"promesa\". Asegúrese de que hay una declaración de \"promesa\" o incluya \"ES2015\" en la opción \"--lib\".", + "An_async_iterator_must_have_a_next_method_2519": "Un iterador de asincronía debe tener un método \"next()\".", + "An_enum_member_cannot_have_a_numeric_name_2452": "Un miembro de enumeración no puede tener un nombre numérico.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Una asignación de exportación solo se puede usar en un módulo.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Una asignación de exportación no se puede usar en un módulo con otros elementos exportados.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Una asignación de exportación no se puede usar en espacios de nombres.", + "An_export_assignment_cannot_have_modifiers_1120": "Una asignación de exportación no puede tener modificadores.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Una declaración de exportación solo se puede usar en un módulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Una declaración de exportación no puede tener modificadores.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Un valor de escape Unicode extendido debe estar entre 0x0 y 0x10FFFF, incluidos.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Una implementación no se puede declarar en contextos de ambiente.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Una declaración de importación solo se puede usar en un espacio de nombres o un módulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Una declaración de importación no puede tener modificadores.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Una ruta de acceso de importación no puede terminar con una extensión '{0}'. Puede importar '{1}' en su lugar.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argumento de expresión de índice debe ser de tipo \"string\", \"number\", \"symbol\" o \"any\".", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Una signatura de índice no puede tener un parámetro rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Una signatura de índice debe tener una anotación de tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Una signatura de índice debe tener exactamente un parámetro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parámetro de signatura de índice no puede tener un signo de interrogación.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parámetro de signatura de índice no puede tener un modificador de accesibilidad.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parámetro de signatura de índice no puede tener un inicializador.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parámetro de signatura de índice debe tener una anotación de tipo.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "El tipo de un parámetro de signatura de índice debe ser \"string\" o \"number\".", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Una interfaz solo puede extender un identificador o nombre completo con argumentos de tipo opcional.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Una interfaz solo puede extender una clase u otra interfaz.", + "An_interface_property_cannot_have_an_initializer_1246": "Una propiedad de interfaz no puede tener un inicializador.", + "An_iterator_must_have_a_next_method_2489": "Un iterador debe tener un método \"next()\".", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un literal de objeto no puede tener varios descriptores de acceso get o set con el mismo nombre.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Un literal de objeto no puede tener varias propiedades con el mismo nombre en modo strict.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un literal de objeto no puede tener una propiedad y un descriptor de acceso con el mismo nombre.", + "An_object_member_cannot_be_declared_optional_1162": "Un miembro de objeto no se puede declarar como opcional.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Una signatura de sobrecarga no se puede declarar como generador.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "No se admite una expresión unaria con el operador '{0}' en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "Annotate_with_type_from_JSDoc_95009": "Anotar con tipo de JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Anotar con tipos de JSDoc", + "Argument_expression_expected_1135": "Se esperaba una expresión de argumento.", + "Argument_for_0_option_must_be_Colon_1_6046": "El argumento para la opción '{0}' debe ser: {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "No se puede asignar un argumento de tipo '{0}' al parámetro de tipo '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "Se esperaba un patrón de desestructuración de elementos de matriz.", + "Asterisk_Slash_expected_1010": "Se esperaba \"*/\".", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Los aumentos del ámbito global solo pueden anidarse directamente en módulos externos o en declaraciones de módulos de ambiente.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Los aumentos del ámbito global deben tener el modificador 'declare', a menos que aparezcan en un contexto de ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "La detección automática de escritura está habilitada en el proyecto '{0}'. Se va a ejecutar un paso de resolución extra para el módulo '{1}' usando la ubicación de caché '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Las expresiones de clase base no pueden hacer referencia a parámetros de tipo de clase.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "El tipo de valor devuelto del constructor base '{0}' no es un tipo de clase o interfaz.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Todos los constructores base deben tener el mismo tipo de valor devuelto.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Directorio base para resolver nombres de módulos no absolutos.", + "Basic_Options_6172": "Opciones básicas", + "Binary_digit_expected_1177": "Se esperaba un dígito binario.", + "Binding_element_0_implicitly_has_an_1_type_7031": "El elemento de enlace '{0}' tiene un tipo '{1}' implícito.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable con ámbito de bloque '{0}' usada antes de su declaración.", + "Call_decorator_expression_90028": "Llame a la expresión decorador.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signatura de llamada, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", + "Call_target_does_not_contain_any_signatures_2346": "El destino de llamada no contiene signaturas.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "No se puede acceder a \"{0}.{1}\" porque \"{0}\" es un tipo, no un espacio de nombres. ¿Su intención era recuperar el tipo de la propiedad \"{1}\" en \"{0}\" con \"{0}[\"{1}\"]\"?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "No se puede asignar un tipo de constructor '{0}' a un tipo de constructor '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "No se puede asignar un tipo de constructor abstracto a uno no abstracto.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "No se puede asignar a '{0}' porque es una constante o una propiedad de solo lectura.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "No se puede asignar a '{0}' porque no es una variable.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "No se puede aumentar el módulo '{0}' porque se resuelve como una entidad que no es un módulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "No se puede aumentar el módulo \"{0}\" con exportaciones de valores porque se resuelve como una entidad que no es un módulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "No se pueden compilar los módulos con la opción '{0}' a no ser que la marca \"--module\" sea \"amd\" o \"system\".", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Los espacios de nombres no se pueden compilar si se proporciona la marca \"--isolatedModules\".", + "Cannot_create_an_instance_of_an_abstract_class_2511": "No se puede crear una instancia de una clase abstracta.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "No se puede exportar '{0}'. Solo se pueden exportar declaraciones locales desde un módulo.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "No se puede extender una clase '{0}'. El constructor de la clase está marcado como privado.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "No se puede extender una interfaz '{0}'. ¿Quiso decir 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "No se encuentra ningún archivo tsconfig.json en el directorio especificado: \"{0}\".", + "Cannot_find_global_type_0_2318": "No se encuentra el tipo '{0}' global.", + "Cannot_find_global_value_0_2468": "No se encuentra el valor '{0}' global.", + "Cannot_find_module_0_2307": "No se encuentra el módulo '{0}'.", + "Cannot_find_name_0_2304": "No se encuentra el nombre '{0}'.", + "Cannot_find_name_0_Did_you_mean_1_2552": "No se encuentra el nombre \"{0}\". ¿Quería decir \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "No se encuentra el nombre '{0}'. ¿Quería decir el miembro de instancia 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "No se encuentra el nombre '{0}'. ¿Quería decir el miembro estático '{1}.{0}'?", + "Cannot_find_namespace_0_2503": "No se encuentra el espacio de nombres '{0}'.", + "Cannot_find_parameter_0_1225": "No se encuentra el parámetro '{0}'.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "No se encuentra la ruta de acceso de subdirectorio común para los archivos de entrada.", + "Cannot_find_type_definition_file_for_0_2688": "No se puede encontrar el archivo de definición de tipo para '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "No se pueden importar archivos de declaración de tipos. Considere importar \"{0}\" en lugar de \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "No se puede inicializar la variable '{0}' de ámbito externo en el mismo ámbito que la declaración '{1}' con ámbito de bloque.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "No se puede invocar una expresión con un tipo sin signatura de llamada. El tipo '{0}' no tiene ninguna signatura de llamada compatible.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "No se puede volver a exportar un tipo si se proporciona la marca \"--isolatedModules\".", + "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "No se puede volver a declarar la variable '{0}' exportada.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "No se puede volver a declarar el identificador \"{0}\" en la cláusula catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "JSX no se puede usar si no se proporciona la marca \"--jsx\".", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "No se pueden usar importaciones, exportaciones o aumentos de módulos si el valor de \"--module\" es \"none\".", + "Cannot_use_namespace_0_as_a_type_2709": "No se puede utilizar el espacio de nombres '{0}' como un tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "No se puede utilizar el espacio de nombres '{0}' como un valor.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "No se puede usar \"new\" con una expresión cuyo tipo carece de una signatura de construcción o de llamada.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "No se puede escribir en el archivo '{0}' porque se sobrescribiría con varios archivos de entrada.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "No se puede escribir en el archivo '{0}' porque sobrescribiría el archivo de entrada.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "La variable de la cláusula catch no puede tener una anotación de tipo.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "La variable de la cláusula catch no puede tener un inicializador.", + "Change_0_to_1_90014": "Cambie \"{0}\" a \"{1}\".", + "Change_extends_to_implements_90003": "Cambiar \"extends\" por \"implements\".", + "Change_spelling_to_0_90022": "Cambiar la ortografía a \"{0}\".", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Comprobando si '{0}' es el prefijo coincidente más largo para '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definición circular del alias de importación '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Se detectó circularidad al resolver la configuración: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La clase '{0}' define el descriptor de acceso del miembro de instancia como '{1}', pero la clase extendida '{2}' lo define como función miembro de instancia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como descriptor de acceso de miembro de instancia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como propiedad de miembro de instancia.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La clase '{0}' define la propiedad de miembro de instancia como '{1}', pero la clase extendida '{2}' la define como función miembro de instancia.", + "Class_0_incorrectly_extends_base_class_1_2415": "La clase '{0}' extiende la clase base '{1}' de forma incorrecta.", + "Class_0_incorrectly_implements_interface_1_2420": "La clase '{0}' implementa la interfaz '{1}' de forma incorrecta.", + "Class_0_used_before_its_declaration_2449": "Se ha usado la clase \"{0}\" antes de declararla.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Las declaraciones de clase no pueden tener más de una etiqueta \"@augments\" o \"@extends\".", + "Class_name_cannot_be_0_2414": "El nombre de la clase no puede ser \"{0}\".", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "El lado estático de la clase '{0}' extiende el lado estático de la clase base '{1}' de forma incorrecta.", + "Classes_can_only_extend_a_single_class_1174": "Las clases solo pueden extender una clase única.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Las clases con métodos abstractos deben marcarse como abstractas.", + "Command_line_Options_6171": "Opciones de la línea de comandos", + "Compilation_complete_Watching_for_file_changes_6042": "Compilación completada. Supervisando los cambios del archivo.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".", + "Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "No se permiten valores calculados en una enumeración que tiene miembros con valores de cadena.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatenar y emitir la salida en un único archivo.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Se encontraron definiciones de '{0}' en conflicto en '{1}' y '{2}'. Puede instalar una versión específica de esta biblioteca para resolver el conflicto.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La signatura de construcción, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", + "Constructor_implementation_is_missing_2390": "Falta la implementación del constructor.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "El constructor de la clase '{0}' es privado y solo es accesible desde la declaración de la clase.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "El constructor de la clase '{0}' está protegido y solo es accesible desde la declaración de la clase.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Los constructores de las clases derivadas deben contener una llamada a \"super\".", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.", + "Convert_function_0_to_class_95002": "Convertir la función \"{0}\" en una clase", + "Convert_function_to_an_ES2015_class_95001": "Convertir la función en una clase ES2015", + "Convert_to_default_import_95013": "Convertir en importación predeterminada", + "Corrupted_locale_file_0_6051": "Archivo de configuración regional {0} dañado.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "No se encontró ningún archivo de declaración para el módulo '{0}'. '{1}' tiene un tipo \"any\" de forma implícita.", + "Could_not_write_file_0_Colon_1_5033": "No se puede escribir en el archivo \"{0}\": \"{1}\".", + "DIRECTORY_6038": "DIRECTORIO", + "Declaration_expected_1146": "Se esperaba una declaración.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Conflictos entre nombres de declaración con el identificador global '{0}' integrado.", + "Declaration_or_statement_expected_1128": "Se esperaba una declaración o una instrucción.", + "Declare_method_0_90023": "Declare el método \"{0}\".", + "Declare_property_0_90016": "Declare la propiedad \"{0}\".", + "Declare_static_method_0_90024": "Declare el método estático \"{0}\".", + "Declare_static_property_0_90027": "Declare la propiedad \"{0}\" estática.", + "Decorators_are_not_valid_here_1206": "Los elementos Decorator no son válidos aquí.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "No se pueden aplicar elementos Decorator a varios descriptores de acceso get o set con el mismo nombre.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "La exportación predeterminada del módulo tiene o usa el nombre privado '{0}'.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[En desuso] Use \"--jsxFactory\" en su lugar. Especifique el objeto invocado para createElement cuando el destino sea la emisión de JSX \"react\"", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[En desuso] Use \"--outFile\" en su lugar. Concatena y emite la salida en un solo archivo.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[En desuso] Use \"--skipLibCheck\" en su lugar. Omite la comprobación de tipos de los archivos de declaración de biblioteca predeterminados.", + "Digit_expected_1124": "Se esperaba un dígito.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "El directorio \"{0}\" no existe, se omitirán todas las búsquedas en él.", + "Disable_checking_for_this_file_90018": "Deshabilite la comprobación para este archivo.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Deshabilitar los límites de tamaño de proyectos de JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Deshabilite la comprobación estricta de firmas genéricas en tipos de función.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "No permitir referencias al mismo archivo con un uso incoherente de mayúsculas y minúsculas.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "No agregar módulos importados ni referencias con triple barra diagonal a la lista de archivos compilados.", + "Do_not_emit_comments_to_output_6009": "No emitir comentarios en la salida.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "No emitir declaraciones para el código que tiene una anotación \"@internal\".", + "Do_not_emit_outputs_6010": "No emitir salidas.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones auxiliares personalizadas como \"__extends\" en la salida compilada.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", + "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "No resolver la ruta de acceso real de los vínculos simbólicos.", + "Do_not_truncate_error_messages_6165": "No truncar los mensajes de error.", + "Duplicate_declaration_0_2718": "Declaración duplicada \"{0}\".", + "Duplicate_function_implementation_2393": "Implementación de función duplicada.", + "Duplicate_identifier_0_2300": "Identificador '{0}' duplicado.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificador '{0}' duplicado. El compilador se reserva el nombre '{1}' en el ámbito de nivel superior de un módulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Identificador '{0}' duplicado. El compilador reserva el nombre '{1}' en el ámbito de nivel superior de un módulo que contiene funciones asincrónicas.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificador '{0}' duplicado. El compilador usa la declaración '{1}' para admitir funciones asincrónicas.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificador \"arguments\" duplicado. El compilador usa \"arguments\" para inicializar parámetros rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificador duplicado \"_newTarget\". El compilador usa la declaración de variable \"_newTarget\" para capturar la referencia de la propiedad Meta \"new.target\".", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificador \"_super\" duplicado. El compilador usa \"_super\" para capturar una referencia de clase base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificador \"_this\" duplicado. El compilador usa la declaración de variable \"_this\" para capturar una referencia \"this\".", + "Duplicate_label_0_1114": "Etiqueta \"{0}\" duplicada.", + "Duplicate_number_index_signature_2375": "Signatura de índice de número duplicada.", + "Duplicate_string_index_signature_2374": "Signatura de índice de cadena duplicada.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "No se puede utilizar la importación dinámica cuando se destina a módulos ECMAScript 2015.", + "Dynamic_import_cannot_have_type_arguments_1326": "La importación dinámica no puede tener argumentos de tipo", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "La importación dinámica debe tener un especificador como argumento.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "El elemento tiene un tipo 'any' implícito porque la expresión de índice no es de tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "El elemento tiene un tipo \"any\" implícito porque el tipo '{0}' no tiene signatura de índice.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Emitir una marca BOM UTF-8 al principio de los archivos de salida.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir un solo archivo con mapas de origen en lugar de tener un archivo aparte.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir el origen junto a los mapas de origen en un solo archivo; requiere que se establezca \"--inlineSourceMap\" o \"--sourceMap\".", + "Enable_all_strict_type_checking_options_6180": "Habilitar todas las opciones de comprobación de tipos estricta.", + "Enable_strict_checking_of_function_types_6186": "Habilite la comprobación estricta de los tipos de función.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.", + "Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.", + "Enable_tracing_of_the_name_resolution_process_6085": "Habilitar seguimiento del proceso de resolución de nombres.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita la compatibilidad experimental con las funciones asincrónicas de ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Habilita la compatibilidad experimental con los elementos Decorator de ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita la compatibilidad experimental para emitir metadatos de tipo para los elementos Decorator.", + "Enum_0_used_before_its_declaration_2450": "Se ha usado la enumeración \"{0}\" antes de declararla.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones enum deben ser de tipo const o no const.", + "Enum_member_expected_1132": "Se esperaba un miembro de enumeración.", + "Enum_member_must_have_initializer_1061": "El miembro de enumeración debe tener un inicializador.", + "Enum_name_cannot_be_0_2431": "El nombre de la enumeración no puede ser \"{0}\".", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Tipo enum '{0}' tiene miembros con inicializadores que no son literales.", + "Examples_Colon_0_6026": "Ejemplos: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidad excesiva de la pila al comparar los tipos '{0}' y '{1}'.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Se esperaban argumentos de tipo {0}-{1}; proporciónelos con una etiqueta \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "Se esperaban {0} argumentos, pero se obtuvieron {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Se esperaban {0} argumentos, pero se obtuvieron {1} o más.", + "Expected_0_type_arguments_but_got_1_2558": "Se esperaban {0} argumentos de tipo, pero se obtuvieron {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Se esperaban argumentos de tipo {0}; proporciónelos con una etiqueta \"@extends\".", + "Expected_at_least_0_arguments_but_got_1_2555": "Se esperaban al menos {0} argumentos, pero se obtuvieron {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Se esperaban al menos {0} argumentos, pero se obtuvieron {1} o más.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Se esperaba la etiqueta de cierre JSX correspondiente de '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Se esperaba la etiqueta de cierre correspondiente para el fragmento de JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Se esperaba que el tipo del campo '{0}' en 'package.json' fuese 'string', pero se obtuvo '{1}'.", + "Experimental_Options_6177": "Opciones experimentales", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "La compatibilidad experimental con decoradores es una característica que está sujeta a cambios en una próxima versión. Establezca la opción 'experimentalDecorators' para quitar esta advertencia.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolución de módulo especificado de forma explícita: '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "No se puede usar una asignación de exportación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"export default\" u otro formato de módulo en su lugar.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "La asignación de exportación no es compatible cuando la marca \"--module\" es \"system\".", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La declaración de exportación está en conflicto con la declaración exportada de \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "No se permiten declaraciones de exportación en un espacio de nombres.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "El archivo '{0}' de escritura del paquete externo exportado no es un módulo. Póngase en contacto con el autor del paquete para actualizar la definición de este.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "El archivo de escritura del paquete externo exportado no puede contener referencias con tres barras diagonales. Póngase en contacto con el autor del paquete para actualizar la definición de este.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "El alias de tipo exportado '{0}' tiene o usa el nombre privado '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variable exportada '{0}' tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variable exportada '{0}' tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variable exportada '{0}' tiene o usa el nombre privado '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "En aumentos de módulos, no se admiten exportaciones ni asignaciones de exportación.", + "Expression_expected_1109": "Se esperaba una expresión.", + "Expression_or_comma_expected_1137": "Se esperaba una expresión o una coma.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "La expresión se resuelve en el valor \"_super\" que el compilador usa para capturar una referencia a la clase base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "La expresión se resuelve en la declaración de variable '{0}' que el compilador usa para admitir funciones asincrónicas.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "La expresión se resuelve en una declaración de variable \"_newTarget\" que el compilador usa para capturar la referencia de la propiedad Meta \"new.target\".", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "La expresión se resuelve en la declaración de variable \"_this\" que el compilador usa para capturar una referencia \"this\".", + "Extract_constant_95006": "Extraer la constante", + "Extract_function_95005": "Extraer la función", + "Extract_symbol_95003": "Extraer el símbolo", + "Extract_to_0_in_1_95004": "Extraer a {0} en {1}", + "Extract_to_0_in_1_scope_95008": "Extraer a {0} en el ámbito {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extraer a {0} en el ámbito de inclusión", + "FILE_6035": "ARCHIVO", + "FILE_OR_DIRECTORY_6040": "ARCHIVO O DIRECTORIO", + "Failed_to_parse_file_0_Colon_1_5014": "Error al analizar el archivo '{0}': {1}.", + "Fallthrough_case_in_switch_7029": "Caso de Fallthrough en instrucción switch.", + "File_0_does_not_exist_6096": "El archivo '{0}' no existe.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "El archivo '{0}' existe. Utilícelo como resultado de resolución de nombres.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "El archivo \"{0}\" tiene una extensión no admitida, así que se omitirá.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "La extensión del archivo '{0}' no es compatible. Las únicas extensiones compatibles son {1}.", + "File_0_is_not_a_module_2306": "El archivo '{0}' no es un módulo.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "El archivo '{0}' no está en \"rootDir\" '{1}'. Se espera que \"rootDir\" contenga todos los archivos de origen.", + "File_0_not_found_6053": "Archivo '{0}' no encontrado.", + "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "El nombre de archivo \"{0}\" es diferente del nombre de archivo \"{1}\" ya incluido solo en el uso de mayúsculas y minúsculas.", + "File_name_0_has_a_1_extension_stripping_it_6132": "El nombre de archivo \"{0}\" tiene una extensión \"{1}\" y se va a quitar.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La especificación del archivo no puede contener un directorio primario ('..') que aparezca después de un comodín de directorios recursivo ('**'): '{0}'.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "La especificación de archivo no puede contener varios comodines de directorio recursivo ('**'): '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La especificación de archivo no puede finalizar en un comodín de directorio recursivo ('**'): '{0}'.", + "Found_package_json_at_0_6099": "Se encontró 'package.json' en '{0}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'. Las definiciones de clase están en modo strict de forma automática.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'. Los módulos están en modo strict de forma automática.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "La expresión de función, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto '{0}'.", + "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_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.", + "Generates_corresponding_d_ts_file_6002": "Genera el archivo \".d.ts\" correspondiente.", + "Generates_corresponding_map_file_6043": "Genera el archivo \".map\" correspondiente.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "El generador tiene el tipo '{0}' implícitamente porque no produce ningún valor. Considere la posibilidad de proporcionar un tipo de valor devuelto.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Los generadores no se permiten en un contexto de ambiente.", + "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.", + "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.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Las exportaciones de módulos globales solo pueden aparecer en archivos de módulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "El tipo global '{0}' debe ser un tipo de clase o de interfaz.", + "Global_type_0_must_have_1_type_parameter_s_2317": "El tipo global '{0}' debe tener los siguientes parámetros de tipo: {1}.", + "Hexadecimal_digit_expected_1125": "Se esperaba un dígito hexadecimal.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Se esperaba un identificador. \"{0}\" es una palabra reservada en modo strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Las definiciones de clase están en modo strict automáticamente.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Los módulos están en modo strict automáticamente.", + "Identifier_expected_1003": "Se esperaba un identificador.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. \"__esModule\" está reservado como marcador exportado al transformar módulos ECMAScript.", + "Ignore_this_error_message_90019": "Ignore este mensaje de error.", + "Implement_inherited_abstract_class_90007": "Implementar clase abstracta heredada.", + "Implement_interface_0_90006": "Implementar interfaz \"{0}\".", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La cláusula implements de la clase '{0}' exportada tiene o usa el nombre privado '{1}'.", + "Import_0_from_module_1_90013": "Importar \"{0}\" desde el módulo \"{1}\".", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "No se puede usar una asignación de importación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" u otro formato de módulo en su lugar.", + "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", + "Import_emit_helpers_from_tslib_6139": "Importe elementos auxiliares de emisión de \"tslib\".", + "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "No se permiten importaciones en aumentos de módulos. Considere la posibilidad de moverlas al módulo externo envolvente.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones enum de ambiente, el inicializador de miembro debe ser una expresión constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "El inicializador de miembro de las declaraciones de enumeración \"const\" debe ser una expresión constante.", + "Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.", + "Index_signature_is_missing_in_type_0_2329": "Falta la signatura de índice en el tipo '{0}'.", + "Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Las declaraciones individuales de la declaración '{0}' combinada deben ser todas exportadas o todas locales.", + "Infer_parameter_types_from_usage_95012": "Infiera los tipos de parámetro del uso.", + "Infer_type_of_0_from_usage_95011": "Infiera el tipo de \"{0}\" del uso.", + "Initialize_property_0_in_the_constructor_90020": "Inicialice la propiedad \"{0}\" en el constructor.", + "Initialize_static_property_0_90021": "Inicialice la propiedad estática \"{0}\".", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "El inicializador de la variable miembro de instancia '{0}' no puede hacer referencia al identificador '{1}' declarado en el constructor.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "El inicializador del parámetro '{0}' no puede hacer referencia al identificador '{1}' declarado después.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "El inicializador no proporciona ningún valor para este elemento de enlace que, a su vez, no tiene un valor predeterminado.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "No se permiten inicializadores en los contextos de ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa un proyecto de TypeScript y crea un archivo tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserte opciones de la línea de comandos y archivos desde un archivo.", + "Install_0_95014": "Instalar \"{0}\"", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "La interfaz '{0}' no puede extender los tipos '{1}' y '{2}' simultáneamente.", + "Interface_0_incorrectly_extends_interface_1_2430": "La interfaz '{0}' extiende la interfaz '{1}' de forma incorrecta.", + "Interface_declaration_cannot_have_implements_clause_1176": "La declaración de interfaz no puede tener una cláusula \"implements\".", + "Interface_name_cannot_be_0_2427": "El nombre de la interfaz no puede ser \"{0}\".", + "Invalid_character_1127": "Carácter no válido.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nombre de módulo no válido en el aumento. El módulo '{0}' se resuelve como un módulo sin tipo en '{1}', que no se puede aumentar.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nombre de módulo no válido en un aumento, no se encuentra el módulo '{0}'.", + "Invalid_reference_directive_syntax_1084": "Sintaxis de la directiva \"reference\" no válida.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Uso no válido de '{0}'. Las definiciones de clase están en modo strict automáticamente.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso de '{0}' no válido. Los módulos están en modo strict automáticamente.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso no válido de '{0}' en modo strict.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor no válido para \"jsxFactory\". \"{0}\" no es un nombre calificado o un identificador válido.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor no válido para '--reactNamespace'. '{0}' no es un identificador válido.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La etiqueta \"@{0} {1}\" de JSDoc no coincide con la cláusula \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "La etiqueta \"@{0}\" de JSDoc no está asociada a una clase.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "\"...\" de JSDoc solo puede aparecer en el último parámetro de una signatura.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La etiqueta \"@param\" de JSDoc tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La etiqueta \"@typedef\" de JSDoc debe tener una anotación de tipo o ir seguida de las etiquetas \"@property\" o \"@member\".", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Los tipos JSDoc solo se pueden usar en los comentarios de la documentación.", + "JSX_attribute_expected_17003": "Se esperaba un atributo JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "A los atributos JSX se les debe asignar únicamente un elemento \"expression\" que no esté vacío.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "El elemento JSX '{0}' no tiene la etiqueta de cierre correspondiente.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "El tipo '{0}' de los atributos del elemento JSX no puede ser un tipo de unión.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La clase de elemento JSX no admite atributos porque no tiene una propiedad \"{0}\".", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "El elemento JSX tiene el tipo \"any\" implícitamente porque no existe ninguna interfaz \"JSX.{0}\".", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "El elemento JSX tiene el tipo \"any\" implícitamente porque no existe el tipo global \"JSX.Element\".", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "El tipo de elemento JSX '{0}' no tiene ninguna signatura de construcción ni de llamada.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "El tipo de elemento JSX '{0}' no es una función de constructor de los elementos JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Los elementos JSX no pueden tener varios atributos con el mismo nombre.", + "JSX_expressions_must_have_one_parent_element_2657": "Las expresiones JSX deben tener un elemento primario.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "El fragmento de JSX no tiene la etiqueta de cierre correspondiente.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "El fragmento de JSX no es compatible cuando se utiliza --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "El elemento secundario de propagación JSX debe ser de tipo matriz.", + "Jump_target_cannot_cross_function_boundary_1107": "Un destino de salto no puede atravesar el límite de función.", + "KIND_6034": "TIPO", + "LOCATION_6037": "UBICACIÓN", + "Language_service_is_disabled_9004": "El servicio de idioma está deshabilitado.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "La parte izquierda del operador de coma no se usa y no tiene efectos secundarios.", + "Line_break_not_permitted_here_1142": "No se permite el salto de línea aquí.", + "Line_terminator_not_permitted_before_arrow_1200": "No se permite usar un terminador de línea antes de una flecha.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista de carpetas de donde se deben incluir las definiciones de tipos.", + "List_of_language_service_plugins_6181": "Lista de complementos de servicio de lenguaje.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Lista de carpetas raíz cuyo contenido combinado representa la estructura del proyecto en tiempo de ejecución.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Cargando \"{0}\" del directorio raíz \"{1}\", ubicación candidata: \"{2}\"", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Se cargará el módulo \"{0}\" de la carpeta \"node_modules\", tipo de archivo de destino \"{1}\".", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Se cargará el módulo como archivo/carpeta, ubicación del módulo candidato \"{0}\", tipo de archivo de destino \"{1}\".", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "La configuración regional debe tener el formato o -. Por ejemplo, '{0}' o '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "El prefijo coincidente más largo para \"{0}\" es \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Buscando en la carpeta \"node_modules\", ubicación inicial: \"{0}\".", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Haga que la llamada a \"super()\" sea la primera instrucción del constructor.", + "Member_0_implicitly_has_an_1_type_7008": "El miembro '{0}' tiene un tipo '{1}' implícitamente.", + "Merge_conflict_marker_encountered_1185": "Se encontró un marcador de conflicto de combinación.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La declaración combinada '{0}' no puede incluir una declaración de exportación predeterminada. Considere la posibilidad de agregar una declaración \"export default {0}\" independiente en su lugar.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La propiedad Meta \"{0}\" solo se permite en el cuerpo de una declaración de función, una expresión de función o un constructor.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "El método '{0}' no puede tener ninguna implementación porque está marcado como abstracto.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "El método \"{0}\" de la interfaz exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "El método \"{0}\" de la interfaz exportada tiene o usa el nombre privado \"{1}\".", + "Modifiers_cannot_appear_here_1184": "Los modificadores no pueden aparecer aquí.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "El módulo {0} ya ha exportado un miembro denominado '{1}'. Considere la posibilidad de volver a exportarlo de forma explícita para resolver la ambigüedad.", + "Module_0_has_no_default_export_1192": "El módulo '{0}' no tiene ninguna exportación predeterminada.", + "Module_0_has_no_exported_member_1_2305": "El módulo '{0}' no tiene ningún miembro '{1}' exportado.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "El módulo \"{0}\" está oculto por una declaración local con el mismo nombre.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "El módulo '{0}' se resuelve en una entidad que no es un módulo y no se puede importar mediante esta construcción.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "El módulo '{0}' usa \"export =\" y no se puede usar con \"export *\".", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "El módulo '{0}' se resolvió como un módulo de ambiente declarado en '{1}', porque este archivo no se había modificado.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "El módulo '{0}' se resolvió como un módulo de ambiente declarado localmente en el archivo '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "El módulo '{0}' se resolvió en '{1}', pero \"--jsx\" no está establecido.", + "Module_Resolution_Options_6174": "Opciones de resolución de módulo", + "Module_name_0_matched_pattern_1_6092": "Nombre del módulo: '{0}', patrón coincidente: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== No se resolvió el nombre de módulo '{0}'. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== El nombre del módulo '{0}' se resolvió correctamente como '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "No se ha especificado el tipo de resolución del módulo, se usará '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "No se pudo resolver el módulo con \"rootDirs\".", + "Multiple_constructor_implementations_are_not_allowed_2392": "No se permiten varias implementaciones del constructor.", + "NEWLINE_6061": "NUEVA LÍNEA", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propiedad '{0}' con nombre de los tipos '{1}' y '{2}' no es idéntica en ambos.", + "Namespace_0_has_no_exported_member_1_2694": "El espacio de nombres '{0}' no tiene ningún miembro '{1}' exportado.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "No hay ningún constructor base con el número especificado de argumentos de tipo.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "No se encontraron entradas en el archivo de configuración '{0}'. Las rutas 'include' especificadas fueron '{1}' y las rutas 'exclude' fueron '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La clase '{0}' no abstracta no implementa el miembro abstracto heredado '{1}' de la clase '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Una expresión de clase no abstracta no implementa el miembro abstracto heredado '{0}' de la clase '{1}'.", + "Not_all_code_paths_return_a_value_7030": "No todas las rutas de acceso de código devuelven un valor.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "El tipo de índice numérico '{0}' no se puede asignar a un tipo de índice de cadena '{1}'.", + "Object_is_possibly_null_2531": "El objeto es posiblemente \"null\".", + "Object_is_possibly_null_or_undefined_2533": "El objeto es posiblemente \"null\" o \"undefined\".", + "Object_is_possibly_undefined_2532": "El objeto es posiblemente \"undefined\".", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "El literal de objeto solo puede especificar propiedades conocidas y '{0}' no existe en el tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "El literal de objeto solo puede especificar propiedades conocidas, pero \"{0}\" no existe en el tipo \"{1}\". ¿Quería escribir \"{2}\"?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propiedad '{0}' del literal de objeto tiene un tipo '{1}' implícitamente.", + "Octal_digit_expected_1178": "Se esperaba un dígito octal.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Los tipos de literales octales deben usar la sintaxis ES2015. Use la sintaxis \"{0}\".", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "No se permiten literales octales en el inicializador de miembros de enumeraciones. Use la sintaxis \"{0}\".", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Los literales octales no se permiten en modo strict.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Los literales octales no están disponibles cuando el destino es ECMAScript 5 y superior. Use la sintaxis \"{0}\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Solo se permite una declaración de variable en una instrucción \"for...in\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Solo se permite una declaración de variable en una instrucción \"for...of\".", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Solo se puede llamar a una función void con la palabra clave \"new\".", + "Only_ambient_modules_can_use_quoted_names_1035": "Solo los módulos de ambiente pueden usar nombres entrecomillados.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Solo los módulos \"amd\" y \"system\" se admiten con --{0}.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Actualmente, solo se admiten identificadores o nombres completos con argumentos de tipo opcional en la cláusula \"extends\" de una clase.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Solo es posible tener acceso a los métodos públicos y protegidos de la clase base mediante la palabra clave \"super\".", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "El operador '{0}' no se puede aplicar a los tipos '{1}' y '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "La opción '{0}' solo se puede especificar en el archivo 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "La opción '{0}' solo se puede usar cuando se proporciona '--inlineSourceMap' o '--sourceMap'.", + "Option_0_cannot_be_specified_with_option_1_5053": "La opción '{0}' no se puede especificar con la opción '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "La opción '{0}' no se puede especificar sin la opción '{1}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "La opción '{0}' debe tener una matriz de cadenas como valor.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "La opción \"isolatedModules\" solo se puede usar cuando se proporciona la opción \"--module\" o si la opción \"target\" es \"ES2015\" o una versión posterior.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "La opción 'paths' no se puede usar sin especificar la opción '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "La opción \"project\" no se puede combinar con archivos de origen en una línea de comandos.", + "Options_Colon_6027": "Opciones:", + "Output_directory_for_generated_declaration_files_6166": "Directorio de salida para los archivos de declaración generados.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signatura de sobrecarga no es compatible con la implementación de función.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Las signaturas de sobrecarga deben ser todas abstractas o no abstractas.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Las signaturas de sobrecarga deben ser todas de ambiente o de no ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Las signaturas de sobrecarga deben ser todas exportadas o no exportadas.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Las signaturas de sobrecarga deben ser todas opcionales u obligatorias.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Las signaturas de sobrecarga deben ser todas públicas, privadas o protegidas.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "No se puede hacer referencia al parámetro '{0}' en su inicializador.", + "Parameter_0_implicitly_has_an_1_type_7006": "El parámetro '{0}' tiene un tipo '{1}' implícitamente.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "El parámetro '{0}' no está en la misma posición que el parámetro '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "El parámetro '{0}' de la signatura de llamada de una interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "El parámetro '{0}' de la signatura de llamada de una interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "El parámetro '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "El parámetro '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "El parámetro '{0}' de la función exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "El parámetro '{0}' de la función exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "El parámetro '{0}' de la función exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "El parámetro \"{0}\" de la signatura de índice de la interfaz exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "El parámetro \"{0}\" de la signatura de índice de la interfaz exportada tiene o usa el nombre privado \"{1}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "El parámetro '{0}' del método de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "El parámetro '{0}' del método de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "El parámetro no puede tener un signo de interrogación y un inicializador.", + "Parameter_declaration_expected_1138": "Se espera una declaración de parámetros.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "El tipo de parámetro del establecedor público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "El tipo de parámetro del establecedor público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analiza en modo strict y emite \"use strict\" para cada archivo de código fuente.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "El patrón \"{0}\" puede tener un carácter '*' como máximo.", + "Prefix_0_with_an_underscore_90025": "Prefijo '{0}' con guion bajo.", + "Print_names_of_files_part_of_the_compilation_6155": "Imprimir los nombres de los archivos que forman parte de la compilación.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.", + "Print_the_compiler_s_version_6019": "Imprima la versión del compilador.", + "Print_this_message_6017": "Imprima este mensaje.", + "Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Quería decir \"{2}\"?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La propiedad \"{0}\" tiene declaraciones en conflicto y no está accesible en el tipo \"{1}\".", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso set le falta una anotación de tipo de parámetro.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar al tipo \"{2}\".", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La propiedad \"{0}\" se declara, pero su valor no se lee nunca.", + "Property_0_is_incompatible_with_index_signature_2530": "La propiedad '{0}' es incompatible con la signatura de índice.", + "Property_0_is_missing_in_type_1_2324": "Falta la propiedad '{0}' en el tipo '{1}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La propiedad '{0}' es opcional en el tipo '{1}', pero obligatoria en el tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La propiedad '{0}' es privada y solo se puede acceder a ella en la clase '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La propiedad '{0}' es privada en el tipo '{1}', pero no en el tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "La propiedad '{0}' está protegida y solo se puede acceder a ella a través de una instancia de la clase '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La propiedad '{0}' está protegida y solo se puede acceder a ella en la clase '{1}' y las subclases de esta.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La propiedad '{0}' está protegida, pero el tipo '{1}' no es una clase derivada de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La propiedad '{0}' está protegida en el tipo '{1}', pero es pública en el tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La propiedad \"{0}\" se usa antes de asignarla.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "La propiedad '{0}' del atributo spread de JSX no se puede asignar a la propiedad de destino.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "La propiedad \"{0}\" de la expresión de clase exportada no puede ser privada ni estar protegida.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La propiedad '{0}' de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La propiedad '{0}' de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "La propiedad '{0}' de tipo '{1}' no se puede asignar al tipo de índice numérico '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "La propiedad '{0}' de tipo '{1}' no se puede asignar al tipo de índice de cadena '{2}'.", + "Property_assignment_expected_1136": "Se esperaba una asignación de propiedad.", + "Property_destructuring_pattern_expected_1180": "Se esperaba un patrón de desestructuración de propiedad.", + "Property_or_signature_expected_1131": "Se esperaba una propiedad o una signatura.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "El valor de la propiedad puede ser solo un literal de cadena, literal numérico, 'true', 'false', 'null', literal de objeto o literal de matriz.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Proporcionar compatibilidad total con objetos iterables en \"for-of\", propagaciones y desestructuraciones cuando el destino es \"ES5\" o \"ES3\".", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "El método público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo externo {2}, pero no puede tener nombre.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "El método público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "El método público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo externo {2}, pero no puede tener nombre.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", + "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", + "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\".", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", + "Report_errors_in_js_files_8019": "Notifique los errores de los archivos .js.", + "Report_errors_on_unused_locals_6134": "Informe de errores sobre variables locales no usadas.", + "Report_errors_on_unused_parameters_6135": "Informe de errores sobre parámetros no usados.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Los parámetros de tipo requeridos pueden no seguir parámetros de tipo opcionales.", + "Resolution_for_module_0_was_found_in_cache_6147": "La resolución del módulo \"{0}\" se encontró en la memoria caché.", + "Resolving_from_node_modules_folder_6118": "Resolviendo desde la carpeta node_modules...", + "Resolving_module_0_from_1_6086": "======== Resolviendo el módulo '{0}' de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolviendo el nombre de módulo '{0}' relativo a la dirección URL base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Resolviendo la ruta de acceso real de \"{0}\", resultado: \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor: '{1}', directorio raíz: '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor: '{1}', directorio raíz no establecido. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor no establecido, directorio raíz: '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor no establecido, directorio raíz no establecido. ========", + "Resolving_using_primary_search_paths_6117": "Resolviendo con las rutas de búsqueda principales...", + "Resolving_with_primary_search_path_0_6121": "Resolviendo con la ruta de búsqueda principal \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "El parámetro rest '{0}' tiene un tipo \"any[]\" implícitamente.", + "Rest_types_may_only_be_created_from_object_types_2700": "Los tipos rest solo se pueden crear a partir de tipos de objeto.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "El tipo de valor devuelto de la signatura de llamada de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "El tipo de valor devuelto de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "El tipo de valor devuelto de la signatura de constructor de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "El tipo de valor devuelto de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "El tipo de valor devuelto de la signatura de constructor se debe poder asignar al tipo de instancia de la clase.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "El tipo de valor devuelto de la función exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "El tipo de valor devuelto de la función exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "El tipo de valor devuelto de la función exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "El tipo de valor devuelto de la signatura de índice de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "El tipo de valor devuelto de la signatura de índice de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "El tipo de valor devuelto del método de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "El tipo de valor devuelto del método de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo {2} externo, pero no se puede nombrar.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo {2} externo, pero no se puede nombrar.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre privado '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Las resoluciones de módulo cuyo origen es \"{0}\" se reutilizan, ya que las resoluciones no varían respecto al programa anterior.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Reutilizando la resolución del módulo \"{0}\" en el archivo \"{1}\" del programa anterior.", + "Rewrite_as_the_indexed_access_type_0_90026": "Reescribir como el tipo de acceso indexado \"{0}\".", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "No se puede determinar el directorio raíz, se omitirán las rutas de búsqueda principales.", + "STRATEGY_6039": "ESTRATEGIA", + "Scoped_package_detected_looking_in_0_6182": "Se detectó un paquete con ámbito al buscar en \"{0}\"", + "Setters_cannot_return_a_value_2408": "Los establecedores no pueden devolver un valor.", + "Show_all_compiler_options_6169": "Mostrar todas las opciones de compilador.", + "Show_diagnostic_information_6149": "Mostrar información de diagnóstico.", + "Show_verbose_diagnostic_information_6150": "Mostrar información de diagnóstico detallada.", + "Signature_0_must_be_a_type_predicate_1224": "La signatura '{0}' debe tener un predicado de tipo.", + "Skip_type_checking_of_declaration_files_6012": "Omita la comprobación de tipos de los archivos de declaración.", + "Source_Map_Options_6175": "Opciones de mapa de origen", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La signatura de sobrecarga especializada no se puede asignar a ninguna signatura no especializada.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "El especificador de importación dinámica no puede ser un elemento de propagación.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Especifique la versión de ECMAScript de destino: \"ES3\" (valor predeterminado), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\" o \"ESNEXT\".", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Especifique la generación de código JSX: \"preserve\", \"react-native\" o \"react\".", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Especifique archivos de biblioteca para incluirlos en la compilación: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Especifique la generación de código del módulo: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" o \"ESNext\".", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Especifique la estrategia de resolución de módulos: 'node' (Node.js) o 'classic' (TypeScript pre-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Especifique la función de generador JSX que se usará cuando el destino sea la emisión de JSX \"react\"; por ejemplo, \"React.createElement\" o \"h\".", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Especifique la secuencia de final de línea que debe usarse para emitir archivos: 'CRLF' (Dos) o 'LF' (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Especifique la ubicación donde el depurador debe colocar los archivos de TypeScript en lugar de sus ubicaciones de origen.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Especifique la ubicación donde el depurador debe colocar los archivos de asignaciones en lugar de las ubicaciones generadas.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique el directorio raíz de los archivos de entrada. Úselo para controlar la estructura del directorio de salida con --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "El operador spread de las expresiones \"new\" solo está disponible si el destino es ECMAScript 5 y versiones posteriores.", + "Spread_types_may_only_be_created_from_object_types_2698": "Los tipos spread solo se pueden crear a partir de tipos de objeto.", + "Statement_expected_1129": "Se esperaba una instrucción.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "No se permiten instrucciones en los contextos de ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "Los miembros estáticos no pueden hacer referencia a parámetros de tipo de clase.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La propiedad estática \"{0}\" está en conflicto con la propiedad integrada \"Function.{0}\" de la función de constructor \"{1}\".", + "Strict_Type_Checking_Options_6173": "Opciones de comprobación de tipos estricta", + "String_literal_expected_1141": "Se esperaba un literal de cadena.", + "String_literal_with_double_quotes_expected_1327": "Se esperaba un literal de cadena entre comillas dobles.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Use color y contexto para estilizar los errores y los mensajes (experimental).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Las declaraciones de variable subsiguientes deben tener el mismo tipo. La variable '{0}' debe ser de tipo '{1}', pero aquí tiene el tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "La sustitución '{0}' para el patrón '{1}' tiene un tipo incorrecto. Se esperaba 'string', pero se obtuvo '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La sustitución \"{0}\" del patrón \"{1}\" puede tener un carácter '*' como máximo.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Las sustituciones para el patrón '{0}' deben ser una matriz.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Las sustituciones para el patrón '{0}' no deben ser una matriz vacía.", + "Successfully_created_a_tsconfig_json_file_6071": "Archivo tsconfig.json creado correctamente.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "No se permiten llamadas a \"super\" fuera de los constructores o en funciones anidadas dentro de estos.", + "Suppress_excess_property_checks_for_object_literals_6072": "Suprima las comprobaciones de propiedades en exceso de los literales de objeto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Eliminar errores de noImplicitAny para los objetos de indexación a los que les falten firmas de índice.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "La referencia \"Symbol\" no hace referencia al objeto de constructor Symbol global.", + "Syntax_Colon_0_6023": "Sintaxis: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "El operador '{0}' no se puede aplicar al tipo \"symbol\".", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "No se permite usar el operador '{0}' para los tipos booleanos. Como alternativa, puede usar '{1}'.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "El tipo 'Object' se puede asignar a muy pocos tipos. ¿Se refería a usar el tipo 'any' en realidad?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "No se puede hacer referencia al objeto \"arguments\" en una función de flecha en ES3 ni ES5. Considere la posibilidad de usar una expresión de función estándar.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "No se puede hacer referencia al objeto \"arguments\" en una función o método asincrónico en ES3 ni ES5. Considere la posibilidad de usar un método o función estándar.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "El cuerpo de una instrucción \"if\" no puede ser la instrucción vacía.", + "The_character_set_of_the_input_files_6163": "Conjunto de caracteres de los archivos de entrada.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "El cuerpo de la función o del módulo contenedor es demasiado grande para realizar un análisis de flujo de control.", + "The_current_host_does_not_support_the_0_option_5001": "El host actual no admite la opción '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "La expresión de una asignación de exportación debe ser un identificador o un nombre completo en un contexto de ambiente.", + "The_files_list_in_config_file_0_is_empty_18002": "La lista de archivos del archivo de configuración '{0}' está vacía.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "El primer parámetro del método \"then\" de una promesa debe ser una devolución de llamada.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte izquierda de una instrucción \"for...in\" no puede ser un patrón de desestructuración.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La parte izquierda de una instrucción \"for...in\" no puede usar una anotación de tipo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La parte izquierda de una instrucción 'for...in' debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte izquierda de una instrucción \"for...in\" debe ser de tipo \"string\" o \"any\".", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La parte izquierda de una instrucción \"for...of\" no puede usar una anotación de tipo.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte izquierda de una instrucción 'for...of' debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La parte izquierda de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo enum.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte izquierda de una expresión de asignación debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La parte izquierda de una expresión \"in\" debe ser de tipo \"any\", \"string\", \"number\" o \"symbol\".", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte izquierda de una expresión \"instanceof\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Configuración regional utilizada para mostrar los mensajes al usuario (por ejemplo, \"es-es\")", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "La profundidad máxima de dependencia para buscar en node_modules y cargar los archivos de JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "El operando de un operador de eliminación no puede ser una propiedad de solo lectura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "El operando de un operador de eliminación debe ser una referencia de propiedad.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "El operando de un operador de incremento o decremento debe ser una variable o el acceso a una propiedad.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "El tipo de valor devuelto de un constructor de elemento JSX debe devolver un tipo de objeto.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "El tipo de valor devuelto de una función Decorator de parámetro debe ser \"void\" o \"any\".", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "El tipo de valor devuelto de una función Decorator de propiedad debe ser \"void\" o \"any\".", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "El tipo de valor devuelto de una función asincrónica debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "El tipo de valor devuelto de una función o un método asincrónicos debe ser el tipo Promise global.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "La parte derecha de una instrucción \"for...in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La parte derecha de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo enum.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte derecha de una expresión \"in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte derecha de una expresión \"instanceof\" debe ser de tipo \"any\" o un tipo que pueda asignarse al tipo de interfaz \"Function\".", + "The_specified_path_does_not_exist_Colon_0_5058": "La ruta de acceso especificada no existe: \"{0}\".", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "El destino de la asignación debe ser una variable o el acceso a una propiedad.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "El destino de una asignación de reposo de objetos debe ser una variable o un acceso a propiedad.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "El contexto 'this' de tipo '{0}' no se puede asignar al contexto 'this' de tipo '{1}' del método.", + "The_this_types_of_each_signature_are_incompatible_2685": "Los tipos 'this' de cada signatura son incompatibles.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "El argumento de tipo del parámetro de tipo '{0}' no se puede inferir del uso. Puede especificar los argumentos de tipo explícitamente.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "El tipo devuelto por el método \"next()\" de un iterador de asincronía debe ser una promesa para un tipo con una propiedad \"value\".", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "El tipo devuelto por el método \"next()\" de un iterador debe tener una propiedad \"value\".", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La declaración de variable de una instrucción \"for...in\" no puede tener un inicializador.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere una aplicación auxiliar importada, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", + "Trailing_comma_not_allowed_1009": "No se permite la coma final.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Pruebe \"npm install @types/{0}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\"", + "Trying_other_entries_in_rootDirs_6110": "Se probarán otras entradas de \"rootDirs\".", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Probando la sustitución '{0}', ubicación candidata para el módulo: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "El tipo de tupla '{0}' con longitud '{1}' no se pude asignar a la tupla con longitud '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "El tipo '{0}' no se puede convertir en el tipo '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "El tipo '{0}' no se puede usar como tipo de índice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "El tipo '{0}' no se puede usar para indexar el tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "El tipo '{0}' no cumple la restricción '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "El tipo '{0}' no tiene una signatura de índice correspondiente al tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "El tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\".", + "Type_0_has_no_property_1_2460": "El tipo '{0}' no tiene ninguna propiedad '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "El tipo '{0}' no tiene ninguna propiedad '{1}' ni ninguna signatura de índice de cadena.", + "Type_0_is_not_a_constructor_function_type_2507": "El tipo '{0}' no es un tipo de función de constructor.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "El tipo '{0}' no es un tipo de valor devuelto válido para una función asincrónica en ES5/ES3, porque no hace referencia a un valor de constructor compatible con promesas.", + "Type_0_is_not_an_array_type_2461": "'{0}' no es un tipo de matriz.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' no es un tipo de matriz o un tipo de cadena.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "El tipo \"{0}\" no es un tipo de matriz o un tipo de cadena o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "El tipo \"{0}\" no es un tipo de matriz o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_is_not_assignable_to_type_1_2322": "El tipo '{0}' no se puede asignar al tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "El tipo \"{0}\" no se puede asignar al tipo \"{1}\". Existen dos tipos distintos con este nombre, pero no están relacionados.", + "Type_0_is_not_comparable_to_type_1_2678": "El tipo '{0}' no se puede comparar con el tipo '{1}'.", + "Type_0_is_not_generic_2315": "El tipo '{0}' no es genérico.", + "Type_0_provides_no_match_for_the_signature_1_2658": "El tipo \"{0}\" no proporciona ninguna coincidencia para la signatura \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "El tipo '{0}' se hace referencia a sí mismo de forma recursiva como tipo base.", + "Type_alias_0_circularly_references_itself_2456": "El alias de tipo '{0}' se hace referencia a sí mismo de forma circular.", + "Type_alias_name_cannot_be_0_2457": "El nombre del alias de tipo no puede ser \"{0}\".", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Una anotación de tipo no puede aparecer en una declaración de constructor.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "El candidato de argumento de tipo '{1}' no es un argumento de tipo válido porque no es un supertipo del candidato '{0}'.", + "Type_argument_expected_1140": "Se esperaba un argumento de tipo.", + "Type_argument_list_cannot_be_empty_1099": "La lista de argumentos de tipo no puede estar vacía.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Archivos de declaración de tipos que se incluirán en la compilación.", + "Type_expected_1110": "Se esperaba un tipo.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Se hace referencia al tipo directa o indirectamente en la devolución de llamada de entrega de su propio método \"then\".", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "El tipo debe tener un método \"[Symbol.asyncIterator]()\" que devuelve un iterador de asincronía.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "El tipo debe tener un método \"[Symbol.iterator]()\" que devuelva un iterador.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "El tipo de operando \"await\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "El tipo de elementos iterados de un operando \"yield*\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "El tipo de operando \"yield\" en un generador asincrónico debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_parameter_0_has_a_circular_constraint_2313": "El parámetro de tipo '{0}' tiene una restricción circular.", + "Type_parameter_0_has_a_circular_default_2716": "El parámetro de tipo \"{0}\" tiene un valor circular predeterminado.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "El parámetro de tipo '{0}' de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "El parámetro de tipo '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "El parámetro de tipo '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "El parámetro de tipo '{0}' de la función exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "El parámetro de tipo '{0}' de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "El parámetro de tipo '{0}' del alias del tipo exportado tiene o usa un nombre privado '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "El parámetro de tipo '{0}' del método de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "El parámetro de tipo '{0}' del método público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "El parámetro de tipo '{0}' del método estático público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_declaration_expected_1139": "Se esperaba una declaración de parámetros de tipo.", + "Type_parameter_list_cannot_be_empty_1098": "La lista de parámetros de tipo no puede estar vacía.", + "Type_parameter_name_cannot_be_0_2368": "El nombre del parámetro de tipo no puede ser \"{0}\".", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Los parámetros de tipo no pueden aparecer en una declaración de constructor.", + "Type_predicate_0_is_not_assignable_to_1_1226": "El predicado de tipo '{0}' no se puede asignar a '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== No se resolvió la directiva de referencia de tipo '{0}'. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directiva de referencia de tipo '{0}' se resolvió correctamente como '{1}', principal: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Los tipos tienen declaraciones independientes de una propiedad '{0}' privada.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Los tipos de parámetros '{0}' y '{1}' no son compatibles.", + "Types_of_property_0_are_incompatible_2326": "Los tipos de propiedad '{0}' no son compatibles.", + "Unable_to_open_file_0_6050": "No se puede abrir el archivo '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "No se puede resolver la signatura de elemento Decorator de una clase cuando se llama como expresión.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "No se puede resolver la signatura de elemento Decorator de un método cuando se llama como expresión.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "No se puede resolver la signatura de elemento Decorator de un parámetro cuando se llama como expresión.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "No se puede resolver la signatura de elemento Decorator de una propiedad cuando se llama como expresión.", + "Unexpected_end_of_text_1126": "Final de texto inesperado.", + "Unexpected_token_1012": "Token inesperado.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Se esperaba un constructor, un método, un descriptor de acceso o una propiedad.", + "Unexpected_token_expected_1179": "Token inesperado. Se esperaba \"{\".", + "Unknown_compiler_option_0_5023": "Opción '{0}' del compilador desconocida.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opción 'excludes' desconocida. ¿Quería decir 'exclude'?", + "Unknown_type_acquisition_option_0_17010": "Opción '{0}' de adquisición de tipos desconocida.", + "Unreachable_code_detected_7027": "Se ha detectado código inaccesible.", + "Unsupported_locale_0_6049": "Configuración regional '{0}' no admitida.", + "Unterminated_Unicode_escape_sequence_1199": "Secuencia de escape Unicode sin terminar.", + "Unterminated_quoted_string_in_response_file_0_6045": "Cadena entrecomillada sin terminar en el archivo de respuesta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Literal de expresión regular sin terminar.", + "Unterminated_string_literal_1002": "Literal de cadena sin terminar.", + "Unterminated_template_literal_1160": "Literal de plantilla sin terminar.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Las llamadas a función sin tipo no pueden aceptar argumentos de tipo.", + "Unused_label_7028": "Etiqueta no usada.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", + "VERSION_6036": "VERSIÓN", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "El valor de tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\". ¿Realmente quiere llamarlo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "No se puede llamar a un valor de tipo '{0}'. ¿Pretendía incluir \"new\"?", + "Variable_0_implicitly_has_an_1_type_7005": "La variable '{0}' tiene un tipo '{1}' implícitamente.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variable '{0}' tiene implícitamente el tipo '{1}' en algunos sitios donde no se puede determinar su tipo.", + "Variable_0_is_used_before_being_assigned_2454": "La variable '{0}' se usa antes de asignarla.", + "Variable_declaration_expected_1134": "Se esperaba una declaración de variable.", + "Variable_declaration_list_cannot_be_empty_1123": "La lista de declaraciones de variable no puede estar vacía.", + "Version_0_6029": "Versión {0}", + "Watch_input_files_6005": "Inspeccionar archivos de entrada.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "No se puede cambiar el nombre de elementos definidos en la biblioteca TypeScript estándar.", + "You_cannot_rename_this_element_8000": "No se puede cambiar el nombre a este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" no acepta suficientes argumentos para utilizarse como decorador aquí. ¿Pretendía llamar primero y escribir \"@{0}()\"?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" se especifica dos veces. El atributo denominado \"{0}\" se sobrescribirá.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' solo se puede usar en un archivo .ts.", + "_0_expected_1005": "Se esperaba '{0}'.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' 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 este directa o indirectamente en una de sus expresiones return.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo y se hace referencia a este directa o indirectamente en su propio inicializador.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' es un elemento primitivo, pero '{1}' es un objeto contenedor. Use '{0}' preferentemente cuando sea posible.", + "_0_is_declared_but_its_value_is_never_read_6133": "Se declara \"{0}\", pero su valor no se lee nunca.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" no es una propiedad Meta válida para la palabra clave \"{1}\". ¿Pretendía usar \"{2}\"?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Se hace referencia a '{0}' directa o indirectamente en su propia expresión base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Se hace referencia a '{0}' directa o indirectamente en su propia anotación de tipo.", + "_0_list_cannot_be_empty_1097": "La lista '{0}' no puede estar vacía.", + "_0_modifier_already_seen_1030": "El modificador '{0}' ya se ha visto.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "El modificador '{0}' no puede aparecer en un elemento de clase.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "El modificador '{0}' no puede aparecer en una declaración de constructor.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "El modificador '{0}' no puede aparecer en una propiedad data.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "El modificador '{0}' no puede aparecer en un módulo o un elemento de espacio de nombres.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "El modificador '{0}' no puede aparecer en un parámetro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "El modificador '{0}' no puede aparecer en un miembro de tipo.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "El modificador '{0}' no puede aparecer en una signatura de índice.", + "_0_modifier_cannot_be_used_here_1042": "El modificador '{0}' no se puede usar aquí.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "El modificador '{0}' no se puede usar en un contexto de ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "El modificador '{0}' no se puede usar con el modificador '{1}'.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "El modificador '{0}' no se puede usar con una declaración de clase.", + "_0_modifier_must_precede_1_modifier_1029": "El modificador \"{0}\" debe preceder al modificador \"{1}\".", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' solo hace referencia a un tipo, pero aquí se usa como espacio de nombres.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' solo hace referencia a un tipo, pero aquí se usa como valor.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' hace referencia a un elemento UMD global, pero el archivo actual es un módulo. Puede agregar una importación en su lugar.", + "_0_tag_already_specified_1223": "La etiqueta '{0}' ya se ha especificado.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "La etiqueta '{0}' no se puede usar de forma independiente como etiqueta JSDoc de nivel superior.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}' carece de una anotación de tipo de valor devuelto, pero tiene un tipo de valor devuelto '{1}' implícitamente.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "El modificador 'abstract' solo puede aparecer en una declaración de propiedad, clase o método.", + "await_expression_is_only_allowed_within_an_async_function_1308": "La expresión \"await\" solo se permite en una función asincrónica.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Las expresiones \"await\" no se pueden usar en un inicializador de parámetros.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "La opción \"baseUrl\" está establecida en \"{0}\", se usará este valor para resolver el nombre de módulo no relativo \"{1}\".", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" solo se puede usar en una propiedad de literal de objeto dentro de una asignación de desestructuración.", + "case_or_default_expected_1130": "Se esperaba \"case\" o \"default\".", + "class_expressions_are_not_currently_supported_9003": "Actualmente, no se admiten las expresiones \"class\".", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Las declaraciones \"const\" solo se pueden declarar dentro de un bloque.", + "const_declarations_must_be_initialized_1155": "Las declaraciones \"const\" deben inicializarse.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor no finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor \"NaN\" no permitido.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación o una asignación de exportación.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "No se puede llamar a \"delete\" en un identificador en modo strict.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" solo se puede usar en un archivo .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" solo se puede usar en un archivo .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "El modificador 'export' no se puede aplicar a módulos de ambiente ni aumentos de módulos, porque siempre están visibles.", + "extends_clause_already_seen_1172": "La cláusula \"extends\" ya se ha visto.", + "extends_clause_must_precede_implements_clause_1173": "La cláusula \"extends\" debe preceder a la cláusula \"implements\".", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La cláusula \"extends\" de la clase \"{0}\" exportada tiene o usa el nombre privado \"{1}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La cláusula \"extends\" de la interfaz \"{0}\" exportada tiene o usa el nombre privado \"{1}\".", + "file_6025": "archivo", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Los descriptores de acceso 'get' y 'set' deben tener el mismo tipo 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Los descriptores de acceso \"get\" y \"set\" deben tener el mismo tipo.", + "implements_clause_already_seen_1175": "La cláusula \"implements\" ya se ha visto.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "\"implements clauses\" solo se puede usar en un archivo .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "\"import ... =\" solo se puede usar en un archivo .ts.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "\"interface declarations\" solo se puede usar en un archivo .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Las declaraciones \"let\" solo se pueden declarar dentro de un bloque.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "No se permite usar \"let\" como nombre en las declaraciones \"let\" o \"const\".", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "\"module declarations\" solo se puede usar en un archivo .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "\"new T[]\" no se puede usar para crear una matriz. Use \"new Array()\" en su lugar.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "La expresión \"new\", a cuyo destino le falta una signatura de construcción, tiene implícitamente un tipo \"any\".", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Las \"aserciones no nulas\" solo se pueden usar en un archivo .ts.", + "options_6024": "Opciones", + "or_expected_1144": "Se esperaba \"{\" o \";\".", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" no tiene un campo \"{0}\".", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' tiene el campo '{1}' de '{0}' que hace referencia a '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" solo se puede usar en un archivo .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Se ha especificado la opción 'paths'. Se buscará un patrón que coincida con el nombre de módulo '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "El modificador 'readonly' solo puede aparecer en una declaración de propiedad o una signatura de índice.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Se ha establecido la opción \"rootDirs\". Se usará para resolver el nombre de módulo relativo \"{0}\".", + "super_can_only_be_referenced_in_a_derived_class_2335": "Solo se puede hacer referencia a \"super\" en una clase derivada.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Solo se puede hacer referencia a 'super' en miembros de clases derivadas o expresiones de literal de objeto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "No se puede hacer referencia a \"super\" en un nombre de propiedad calculada.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "No se puede hacer referencia a \"super\" en argumentos de constructor.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' se permite únicamente en miembros de expresiones de literal de objeto cuando la opción 'target' es 'ES2015' o superior.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Debe llamarse a \"super\" antes de acceder a una propiedad de \"super\" en el constructor de una clase derivada.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Debe llamarse a 'super' antes de acceder a 'this' en el constructor de una clase derivada.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "\"super\" debe estar seguido de una lista de argumentos o un acceso a miembros.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "El acceso a la propiedad \"super\" se permite únicamente en un constructor, una función miembro o un descriptor de acceso de miembro de una clase derivada.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "No se puede hacer referencia a \"this\" en un nombre de propiedad calculada.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "No se puede hace referencia a \"this\" en el cuerpo de un módulo o de un espacio de nombres.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "No se puede hacer referencia a \"this\" en un inicializador de propiedad estática.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "No se puede hacer referencia a \"this\" en argumentos de constructor.", + "this_cannot_be_referenced_in_current_location_2332": "No se puede hacer referencia a \"this\" en la ubicación actual.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' tiene el tipo implícito 'any' porque no tiene una anotación de tipo.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "\"type aliases\" solo se puede usar en un archivo .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "\"type arguments\" solo se puede usar en un archivo .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" solo se puede usar en un archivo .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" solo se puede usar en un archivo .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "\"types\" solo se puede usar en un archivo .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Aquí no se permiten tipos \"unique symbol\".", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Los tipos \"unique symbol\" se permiten solo en variables en una instrucción de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Los tipos \"unique symbol\" no se pueden utilizar en una declaración de variable con un nombre de enlace.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "No se permiten instrucciones \"with\" en un bloque de funciones asincrónicas.", + "with_statements_are_not_allowed_in_strict_mode_1101": "No se permiten instrucciones \"with\" en modo strict.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Las expresiones \"yield\" no se pueden usar en un inicializador de parámetros." +} \ No newline at end of file diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..e3a3fea1e6bb7 --- /dev/null +++ b/lib/fr/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Impossible d'utiliser un modificateur '{0}' avec une déclaration d'importation.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Impossible d'utiliser un modificateur '{0}' avec une déclaration d'interface.", + "A_0_parameter_must_be_the_first_parameter_2680": "Un paramètre '{0}' doit être le premier paramètre.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un paramètre de modèle de liaison ne peut pas être facultatif dans une signature d'implémentation.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Une instruction 'break' peut être utilisée uniquement dans une itération englobante ou une instruction switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Une instruction 'break' peut accéder uniquement à une étiquette d'une instruction englobante.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Une classe peut uniquement implémenter un identificateur/nom qualifié avec des arguments de type facultatifs.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Une déclaration de classe sans modificateur 'default' doit porter un nom.", + "A_class_may_only_extend_another_class_2311": "Une classe peut uniquement étendre une autre classe.", + "A_class_may_only_implement_another_class_or_interface_2422": "Une classe peut uniquement implémenter une autre classe ou interface.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un membre de classe ne peut pas avoir le mot clé '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Une expression avec virgule n'est pas autorisée dans un nom de propriété calculée.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nom de propriété calculée ne peut pas référencer un paramètre de type à partir de son type conteneur.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nom de propriété calculée dans une déclaration de propriété de classe doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nom de propriété calculée dans une surcharge de méthode doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nom de propriété calculée dans un littéral de type doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nom de propriété calculée dans un contexte ambiant doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nom de propriété calculée dans une interface doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nom de propriété calculée doit être de type 'string', 'number', 'symbol' ou 'any'.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nom de propriété calculée de la forme '{0}' doit être de type 'symbol'.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Un membre d'enum const n'est accessible qu'à l'aide d'un littéral de chaîne.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Un initialiseur 'const' dans un contexte ambiant doit être un littéral de chaîne ou un littéral numérique.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un constructeur ne peut pas contenir d'appel de 'super' quand sa classe étend 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Un constructeur ne peut pas avoir un paramètre 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Une instruction 'continue' peut uniquement être utilisée dans une instruction d'itération englobante.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Une instruction 'continue' peut accéder uniquement à une étiquette d'une instruction d'itération englobante.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Impossible d'utiliser un modificateur 'declare' dans un contexte ambiant déjà défini.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Un modificateur 'declare' est obligatoire pour une déclaration de niveau supérieur dans un fichier .d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un élément décoratif peut uniquement décorer une implémentation de méthode, pas une surcharge.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Une clause 'default' ne peut pas figurer plusieurs fois dans une instruction 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Une exportation par défaut ne peut être utilisée que dans un module ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Une assertion d'affectation définie ' !' n'est pas autorisée dans ce contexte.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Une déclaration de déstructuration doit avoir un initialiseur.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Un appel d'importation dynamique en ES5/ES3 nécessite le constructeur 'Promise'. Vérifiez que vous avez une déclaration pour le constructeur 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Un appel d'importation dynamique retourne 'Promise'. Vérifiez que vous avez une déclaration pour 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "A_file_cannot_have_a_reference_to_itself_1006": "Un fichier ne peut pas contenir une référence à lui-même.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Une instruction 'for-await-of' est uniquement autorisée dans une fonction asynchrone ou un générateur asynchrone.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Une fonction qui retourne 'never' ne peut pas avoir de point de terminaison accessible.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Une fonction appelée avec le mot clé 'new' ne peut pas avoir un type 'this' dont la valeur est 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Une fonction dont le type déclaré n'est ni 'void', ni 'any', doit retourner une valeur.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un générateur ne peut pas avoir d'annotation de type 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Un accesseur 'get' ne peut pas avoir de paramètres.", + "A_get_accessor_must_return_a_value_2378": "Un accesseur 'get' doit retourner une valeur.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un initialiseur de membre dans une déclaration d'enum ne peut pas référencer des membres déclarés après lui, notamment des membres définis dans d'autres enums.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Une classe mixin doit avoir un constructeur avec un paramètre rest unique de type 'any[]'.", + "A_module_cannot_have_multiple_default_exports_2528": "Un module ne peut pas avoir plusieurs exportations par défaut.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Une déclaration d'espace de noms ne peut pas se trouver dans un autre fichier que celui d'une classe ou d'une fonction avec laquelle elle est fusionnée.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Une déclaration d'espace de noms ne peut pas se trouver avant une classe ou une fonction avec laquelle elle est fusionnée.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Une déclaration d'espace de noms est autorisée uniquement dans un espace de noms ou un module.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un initialiseur de paramètre est uniquement autorisé dans une implémentation de fonction ou de constructeur.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Impossible de déclarer une propriété de paramètre à l'aide d'un paramètre rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Une propriété de paramètre est uniquement autorisée dans une implémentation de constructeur.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Impossible de déclarer une propriété de paramètre à l'aide d'un modèle de liaison.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Un chemin dans une option 'extends' doit être relatif ou rooté, mais '{0}' n'est ni l'un ni l'autre.", + "A_promise_must_have_a_then_method_1059": "Une promesse doit avoir une méthode 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Une propriété d'une classe dont le type est un type 'symbole unique' doit être à la fois 'static' et 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Une propriété d'une interface ou d'un littéral de type dont le type est un type 'symbole unique' doit être 'readonly'.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un paramètre obligatoire ne peut pas suivre un paramètre optionnel.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un élément rest ne peut pas contenir de modèle de liaison.", + "A_rest_element_cannot_have_an_initializer_1186": "Un élément rest ne peut pas avoir d'initialiseur.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un élément rest doit être le dernier dans un modèle de déstructuration.", + "A_rest_parameter_cannot_be_optional_1047": "Un paramètre rest ne peut pas être facultatif.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un paramètre rest ne peut pas avoir d'initialiseur.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un paramètre rest doit être le dernier dans une liste de paramètres.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un paramètre rest doit être de type tableau.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Une instruction 'return' peut être utilisée uniquement dans un corps de fonction.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Série d'entrées qui remappent les importations aux emplacements de recherche en fonction de 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Un accesseur 'set' ne peut pas avoir d'annotation de type de retour.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Un accesseur 'set' ne peut pas avoir de paramètre optionnel.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Un accesseur 'set' ne peut pas avoir de paramètre rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Un accesseur 'set' doit avoir un seul paramètre.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un paramètre d'accesseur 'set' ne peut pas avoir d'initialiseur.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Une signature avec une implémentation ne peut pas utiliser de type de littéral de chaîne.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Un appel de 'super' doit être la première instruction du constructeur quand une classe contient des propriétés initialisées ou possède des propriétés de paramètre.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Une protection de type basée sur 'this' n'est pas compatible avec une protection de type basée sur des paramètres.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un type 'this' est disponible uniquement dans un membre non statique d'une classe ou d'une interface.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un fichier 'tsconfig.json' est déjà défini à l'emplacement '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Une liste d'éléments de type tuple ne peut pas être vide.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Une expression d'assertion de type n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Une propriété de littéral de type ne peut pas avoir d'initialiseur.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un prédicat de type ne peut pas référencer un paramètre rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un prédicat de type ne peut pas référencer un élément '{0}' dans un modèle de liaison.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un prédicat de type est autorisé uniquement dans une position de type de retour pour les fonctions et les méthodes.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Le type d'un prédicat de type doit être assignable au type de son paramètre.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Une variable dont le type est un type 'symbole unique' doit être 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Une expression 'yield' est autorisée uniquement dans le corps d'un générateur.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "La méthode abstraite '{0}' de la classe '{1}' n'est pas accessible au moyen de l'expression super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Les méthodes abstraites peuvent uniquement apparaître dans une classe abstraite.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "La propriété abstraite '{0}' de la classe '{1}' n'est pas accessible dans le constructeur.", + "Accessibility_modifier_already_seen_1028": "Modificateur d'accessibilité déjà rencontré.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Les accesseurs sont uniquement disponibles quand EcmaScript 5 ou version supérieure est ciblé.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", + "Add_0_to_existing_import_declaration_from_1_90015": "Ajoutez '{0}' à une déclaration d'importation existante à partir de \"{1}\".", + "Add_index_signature_for_property_0_90017": "Ajoutez une signature d'index pour la propriété '{0}'.", + "Add_missing_super_call_90001": "Ajoutez l'appel manquant à 'super()'.", + "Add_this_to_unresolved_variable_90008": "Ajoutez 'this.' à la variable non résolue.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "L'ajout d'un fichier tsconfig.json permet d'organiser les projets qui contiennent des fichiers TypeScript et JavaScript. En savoir plus sur https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Vérifications supplémentaires", + "Advanced_Options_6178": "Options avancées", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Toutes les déclarations de '{0}' doivent avoir des paramètres de type identiques.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", + "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Les enums const ambiants ne sont pas autorisés quand l'indicateur '--isolatedModules' est fourni.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Une déclaration de module ambiant ne peut pas spécifier un nom de module relatif.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Impossible d'imbriquer des modules ambiants dans d'autres modules ou espaces de noms.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un module AMD ne peut pas avoir plusieurs affectations de nom.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Un accesseur abstrait ne peut pas avoir d'implémentation.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Impossible de déclarer un accesseur dans un contexte ambiant.", + "An_accessor_cannot_have_type_parameters_1094": "Un accesseur ne peut pas avoir de paramètres de type.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Une déclaration de module ambiant est uniquement autorisée au niveau supérieur dans un fichier.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un opérande arithmétique doit être de type 'any', 'number' ou un type enum.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Une fonction ou méthode asynchrone en ES5/ES3 nécessite le constructeur 'Promise'. Vérifiez que vous avez une déclaration pour le constructeur 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Une fonction ou une méthode async doit avoir un type de retour valide pouvant être attendu.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Une fonction ou une méthode async doit retourner 'Promise'. Vérifiez que vous avez une déclaration pour 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.", + "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_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.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Une déclaration d'exportation peut uniquement être utilisée dans un module.", + "An_export_declaration_cannot_have_modifiers_1193": "Une déclaration d'exportation ne peut pas avoir de modificateurs.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Une valeur d'échappement Unicode étendue doit être comprise entre 0x0 et 0x10FFFF inclus.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Impossible de déclarer une implémentation dans des contextes ambiants.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Une déclaration d'importation peut uniquement être utilisée dans un espace de noms ou un module.", + "An_import_declaration_cannot_have_modifiers_1191": "Une déclaration d'importation ne peut pas avoir de modificateurs.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un chemin d'importation ne peut pas finir par une extension '{0}'. Importez '{1}' à la place.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argument d'expression d'index doit être de type 'string', 'number', 'symbol' ou 'any'.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Une signature d'index ne peut pas avoir de paramètre rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Une signature d'index doit avoir une annotation de type.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Une signature d'index doit avoir un seul paramètre.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un paramètre de signature d'index ne peut pas contenir de point d'interrogation.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un paramètre de signature d'index ne peut pas avoir de modificateur d'accessibilité.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un paramètre de signature d'index ne peut pas avoir d'initialiseur.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un paramètre de signature d'index doit avoir une annotation de type.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Le type d'un paramètre de signature d'index doit être 'string' ou 'number'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Une interface peut uniquement étendre un identificateur/nom qualifié avec des arguments de type facultatifs.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Une interface peut uniquement étendre une classe ou une autre interface.", + "An_interface_property_cannot_have_an_initializer_1246": "Une propriété d'interface ne peut pas avoir d'initialiseur.", + "An_iterator_must_have_a_next_method_2489": "Un itérateur doit comporter une méthode 'next()'.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un littéral d'objet ne peut pas avoir plusieurs accesseurs get/set portant le même nom.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Un littéral d'objet ne peut pas avoir plusieurs propriétés portant le même nom en mode strict.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un littéral d'objet ne peut pas avoir une propriété et un accesseur portant le même nom.", + "An_object_member_cannot_be_declared_optional_1162": "Impossible de déclarer un membre d'objet comme étant facultatif.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Une signature de surcharge ne peut pas être déclarée en tant que générateur.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Une expression unaire avec l'opérateur '{0}' n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "Annotate_with_type_from_JSDoc_95009": "Annoter avec le type de JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Annoter avec les types de JSDoc", + "Argument_expression_expected_1135": "Expression d'argument attendue.", + "Argument_for_0_option_must_be_Colon_1_6046": "L'argument de l'option '{0}' doit être {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argument de type '{0}' n'est pas attribuable au paramètre de type '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "Modèle de déstructuration d'élément de tableau attendu.", + "Asterisk_Slash_expected_1010": "'.' attendu.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Les augmentations de la portée globale ne peuvent être directement imbriquées que dans les modules externes ou les déclarations de modules ambiants.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Les augmentations de la portée globale doivent comporter un modificateur 'declare', sauf si elles apparaissent déjà dans un contexte ambiant.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "La détection automatique des typages est activée dans le projet '{0}'. Exécution de la passe de résolution supplémentaire pour le module '{1}' à l'aide de l'emplacement du cache '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Les expressions de classe de base ne peuvent pas référencer les paramètres de type de classe.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Le type de retour du constructeur de base '{0}' n'est pas un type de classe ou d'interface.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Les constructeurs de base doivent tous avoir le même type de retour.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Répertoire de base pour la résolution des noms de modules non absolus.", + "Basic_Options_6172": "Options de base", + "Binary_digit_expected_1177": "Chiffre binaire attendu.", + "Binding_element_0_implicitly_has_an_1_type_7031": "L'élément de liaison '{0}' possède implicitement un type '{1}'.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable de portée de bloc '{0}' utilisée avant sa déclaration.", + "Call_decorator_expression_90028": "Appelez l'expression de l'élément décoratif.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signature d'appel, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", + "Call_target_does_not_contain_any_signatures_2346": "La cible de l'appel ne contient aucune signature.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Impossible d'accéder à '{0}.{1}', car '{0}' est un type, mais pas un espace de noms. Voulez-vous plutôt récupérer le type de la propriété '{1}' dans '{0}' avec '{0}[\"{1}\"]' ?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Impossible d'assigner un type de constructeur '{0}' à un type de constructeur '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Impossible d'attribuer un type de constructeur abstrait à un type de constructeur non abstrait.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Impossible d'effectuer une assignation à '{0}', car il s'agit d'une constante ou d'une propriété en lecture seule.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Impossible d'effectuer une assignation à '{0}', car il ne s'agit pas d'une variable.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Impossible d'augmenter le module '{0}', car il se résout en une entité non-module.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Impossible d'augmenter le module '{0}' avec des exportations de valeurs, car il se résout en une entité non-module.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Impossible de compiler des modules à l'aide de l'option '{0}' tant que l'indicateur '--module' n'a pas la valeur 'amd' ou 'system'.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Impossible de compiler des espaces de noms quand l'indicateur '--isolatedModules' est fourni.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Impossible de créer une instance d'une classe abstraite.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Impossible d'exporter '{0}'. Seules les déclarations locales peuvent être exportées à partir d'un module.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Impossible d'étendre une classe '{0}'. Le constructeur de classe est marqué comme étant privé.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Impossible d'étendre une interface '{0}'. Vouliez-vous dire 'implements' ?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Le fichier tsconfig.json est introuvable dans le répertoire spécifié : '{0}'.", + "Cannot_find_global_type_0_2318": "Le type global '{0}' est introuvable.", + "Cannot_find_global_value_0_2468": "La valeur globale '{0}' est introuvable.", + "Cannot_find_module_0_2307": "Le module '{0}' est introuvable.", + "Cannot_find_name_0_2304": "Le nom '{0}' est introuvable.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Le nom '{0}' est introuvable. Est-ce qu'il ne s'agit pas plutôt de '{1}' ?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Le nom '{0}' est introuvable. Voulez-vous utiliser le membre d'instance 'this.{0}' ?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Le nom '{0}' est introuvable. Voulez-vous utiliser le membre statique '{1}.{0}' ?", + "Cannot_find_namespace_0_2503": "L'espace de noms '{0}' est introuvable.", + "Cannot_find_parameter_0_1225": "Paramètre '{0}' introuvable.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Impossible de trouver le chemin d'accès au sous-répertoire commun pour les fichiers d'entrée.", + "Cannot_find_type_definition_file_for_0_2688": "Le fichier de définition de type est introuvable pour '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Impossible d'importer les fichiers de déclaration de type. Importez '{0}' à la place de '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Impossible d'initialiser la variable de portée externe '{0}' dans la même portée que celle de la déclaration de portée de bloc '{1}'.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Impossible d'appeler une expression dont le type n'a pas de signature d'appel. Le type '{0}' n'a aucune signature d'appel compatible.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Impossible de réexporter un type quand l'indicateur '--isolatedModules' est spécifié.", + "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Impossible de redéclarer la variable exportée '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Impossible de redéclarer l'identificateur '{0}' dans la clause catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Impossible d'utiliser JSX, sauf si l'indicateur '--jsx' est fourni.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Impossible d'utiliser des importations, des exportations ou des augmentations de module quand '--module' a la valeur 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Impossible d'utiliser l'espace de noms '{0}' en tant que type.", + "Cannot_use_namespace_0_as_a_value_2708": "Impossible d'utiliser l'espace de noms '{0}' en tant que valeur.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Impossible d'utiliser 'new' avec une expression dont le type ne possède pas de signature d'appel ou de construction.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Impossible d'écrire le fichier '{0}', car il serait remplacé par plusieurs fichiers d'entrée.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Impossible d'écrire le fichier '{0}', car cela entraînerait le remplacement du fichier d'entrée.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Une variable de clause catch ne peut pas avoir d'annotation de type.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Une variable de clause catch ne peut pas avoir d'initialiseur.", + "Change_0_to_1_90014": "Changez '{0}' en '{1}'.", + "Change_extends_to_implements_90003": "Changez 'extends' en 'implements'.", + "Change_spelling_to_0_90022": "Changez l'orthographe en '{0}'.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Vérification en cours pour déterminer si '{0}' est le préfixe correspondant le plus long pour '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Définition circulaire de l'alias d'importation '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularité détectée durant la résolution de la configuration : {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La classe '{0}' définit l'accesseur de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La classe '{0}' définit la fonction de membre d'instance '{1}', mais la classe étendue '{2}' la définit comme accesseur de membre d'instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La classe '{0}' définit la fonction de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme propriété de membre d'instance.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' définit la propriété de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", + "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' étend de manière incorrecte la classe de base '{1}'.", + "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implémente de manière incorrecte l'interface '{1}'.", + "Class_0_used_before_its_declaration_2449": "Classe '{0}' utilisée avant sa déclaration.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Les déclarations de classes ne peuvent pas avoir plusieurs balises '@augments' ou '@extends'.", + "Class_name_cannot_be_0_2414": "Le nom de la classe ne peut pas être '{0}'.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Le côté statique de la classe '{0}' étend de manière incorrecte le côté statique de la classe de base '{1}'.", + "Classes_can_only_extend_a_single_class_1174": "Les classes ne peuvent étendre qu'une seule classe.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Les classes contenant des méthodes abstraites doivent être marquées comme étant abstraites.", + "Command_line_Options_6171": "Options de ligne de commande", + "Compilation_complete_Watching_for_file_changes_6042": "Fin de la compilation. Détection des changements apportés au fichier.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.", + "Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Les valeurs calculées ne sont pas autorisées dans un enum avec des membres ayant une valeur de chaîne.", + "Concatenate_and_emit_output_to_single_file_6001": "Concaténer la sortie et l'émettre vers un seul fichier.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Définitions en conflit pour '{0}' sur '{1}' et '{2}'. Installez une version spécifique de cette bibliothèque pour résoudre le conflit.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La signature de construction, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", + "Constructor_implementation_is_missing_2390": "L'implémentation de constructeur est manquante.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Le constructeur de la classe '{0}' est privé et uniquement accessible dans la déclaration de classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Le constructeur de la classe '{0}' est protégé et uniquement accessible dans la déclaration de classe.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Les constructeurs pour les classes dérivées doivent contenir un appel de 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Fichier conteneur non spécifié et répertoire racine impossible à déterminer. Recherche ignorée dans le dossier 'node_modules'.", + "Convert_function_0_to_class_95002": "Convertir la fonction '{0}' en classe", + "Convert_function_to_an_ES2015_class_95001": "Convertir la fonction en classe ES2015", + "Convert_to_default_import_95013": "Convertir en importation par défaut", + "Corrupted_locale_file_0_6051": "Fichier de paramètres régionaux endommagé : {0}.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Le fichier de déclaration du module '{0}' est introuvable. '{1}' a implicitement un type 'any'.", + "Could_not_write_file_0_Colon_1_5033": "Impossible d'écrire le fichier '{0}' : {1}.", + "DIRECTORY_6038": "RÉPERTOIRE", + "Declaration_expected_1146": "Déclaration attendue.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Le nom de la déclaration est en conflit avec l'identificateur global intégré '{0}'.", + "Declaration_or_statement_expected_1128": "Déclaration ou instruction attendue.", + "Declare_method_0_90023": "Déclarez la méthode '{0}'.", + "Declare_property_0_90016": "Déclarez la propriété '{0}'.", + "Declare_static_method_0_90024": "Déclarez la méthode statique '{0}'.", + "Declare_static_property_0_90027": "Déclarez la propriété statique '{0}'.", + "Decorators_are_not_valid_here_1206": "Les éléments décoratifs ne sont pas valides ici.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Impossible d'appliquer des éléments décoratifs à plusieurs accesseurs get/set du même nom.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'exportation par défaut du module a utilisé ou utilise le nom privé '{0}'.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Déconseillé] Utilisez '--jsxFactory' à la place. Permet de spécifier l'objet appelé pour createElement durant le ciblage de 'react' pour l'émission JSX", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Déconseillé] Utilisez '--outFile' à la place. Permet de concaténer et d'émettre la sortie vers un seul fichier", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Déconseillé] Utilisez '--skipLibCheck' à la place. Permet d'ignorer le contrôle de type des fichiers de déclaration de la bibliothèque par défaut.", + "Digit_expected_1124": "Chiffre attendu", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Le répertoire '{0}' n'existe pas. Toutes les recherches associées sont ignorées.", + "Disable_checking_for_this_file_90018": "Désactivez la vérification de ce fichier.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Désactivez les limitations de taille sur les projets JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Désactivez la vérification stricte des signatures génériques dans les types de fonction.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Interdisez les références dont la casse est incohérente dans le même fichier.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "N'ajoutez pas de références avec trois barres obliques, ni de modules importés à la liste des fichiers compilés.", + "Do_not_emit_comments_to_output_6009": "Ne pas émettre de commentaires dans la sortie.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "N'émettez pas de déclarations pour du code ayant une annotation '@internal'.", + "Do_not_emit_outputs_6010": "N'émettez pas de sorties.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "N'émettez pas de sortie si des erreurs sont signalées.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "N'émettez pas de directives 'use strict' dans une sortie de module.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "N'effacez pas les déclarations d'enum const dans le code généré.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Ne générez pas de fonctions d'assistance personnalisées comme '__extends' dans la sortie compilée.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "N'incluez pas le fichier bibliothèque par défaut (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Ne signalez pas les erreurs pour le code inaccessible.", + "Do_not_report_errors_on_unused_labels_6074": "Ne signalez pas les erreurs pour les étiquettes inutilisées.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Ne pas résoudre le chemin réel des liens symboliques.", + "Do_not_truncate_error_messages_6165": "Ne tronquez pas les messages d'erreur.", + "Duplicate_declaration_0_2718": "Déclaration '{0}' dupliquée.", + "Duplicate_function_implementation_2393": "Implémentation de fonction en double.", + "Duplicate_identifier_0_2300": "Identificateur '{0}' en double.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificateur '{0}' en double. Le compilateur réserve le nom '{1}' dans l'étendue de plus haut niveau d'un module.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Identificateur '{0}' en double. Le compilateur réserve le nom '{1}' dans la portée de plus haut niveau d'un module contenant des fonctions async.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificateur '{0}' en double. Le compilateur utilise la déclaration '{1}' pour prendre en charge les fonctions async.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificateur dupliqué 'arguments'. Le compilateur utilise 'arguments' pour initialiser les paramètres rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Dupliquez l'identificateur '_newTarget'. Le compilateur utilise la déclaration de variable '_newTarget' pour capturer la référence de méta-propriété 'new.target'.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificateur dupliqué '_super'. Le compilateur utilise '_super' pour capturer la référence de classe de base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificateur dupliqué '_this'. Le compilateur utilise la déclaration de variable '_this' pour capturer la référence 'this'.", + "Duplicate_label_0_1114": "Étiquette '{0}' en double.", + "Duplicate_number_index_signature_2375": "Signature d'index de nombre dupliquée.", + "Duplicate_string_index_signature_2374": "Signature d'index de chaîne dupliquée.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "L'importation dynamique ne peut pas être utilisée pour cibler des modules ECMAScript 2015.", + "Dynamic_import_cannot_have_type_arguments_1326": "L'importation dynamique ne peut pas avoir d'arguments de type", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "L'importation dynamique doit avoir un seul spécificateur comme argument.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'élément possède implicitement un type 'any', car l'expression d'index n'est pas de type 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'élément a implicitement un type 'any', car le type '{0}' n'a aucune signature d'index.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Émettez une marque d'ordre d'octet (BOM) UTF-8 au début des fichiers de sortie.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Émettez un seul fichier avec des mappages de sources au lieu d'avoir un fichier distinct.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Émettez la source aux côtés des mappages de sources dans un fichier unique. Nécessite la définition de '--inlineSourceMap' ou '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Activez toutes les options de contrôle de type strict.", + "Enable_strict_checking_of_function_types_6186": "Activez la vérification stricte des types de fonction.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.", + "Enable_strict_null_checks_6113": "Activez strict null checks.", + "Enable_tracing_of_the_name_resolution_process_6085": "Activez le traçage du processus de résolution de noms.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Active la prise en charge expérimentale des fonctions async ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Active la prise en charge expérimentale des éléments décoratifs ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Active la prise en charge expérimentale pour l'émission des métadonnées de type pour les éléments décoratifs.", + "Enum_0_used_before_its_declaration_2450": "Enum '{0}' utilisé avant sa déclaration.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Les déclarations d'enum doivent toutes être const ou non const.", + "Enum_member_expected_1132": "Membre enum attendu.", + "Enum_member_must_have_initializer_1061": "Un membre enum doit posséder un initialiseur.", + "Enum_name_cannot_be_0_2431": "Le nom d'enum ne peut pas être '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Le type enum '{0}' a des membres dont les initialiseurs ne sont pas des littéraux.", + "Examples_Colon_0_6026": "Exemples : {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profondeur excessive de la pile pour la comparaison des types '{0}' et '{1}'.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Arguments de type {0}-{1} attendus ; indiquez-les avec la balise '@extends'.", + "Expected_0_arguments_but_got_1_2554": "{0} arguments attendus, mais {1} reçus.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} arguments attendus, mais {1} ou plus reçus.", + "Expected_0_type_arguments_but_got_1_2558": "{0} arguments de type attendus, mais {1} reçus.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Arguments de type {0} attendus ; indiquez-les avec la balise '@extends'.", + "Expected_at_least_0_arguments_but_got_1_2555": "Au moins {0} arguments attendus, mais {1} reçus.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Au moins {0} arguments attendus, mais {1} ou plus reçus.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Balise de fermeture JSX correspondante attendue pour '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Balise de fermeture correspondante attendue pour le fragment JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Le type du champ '{0}' attendu dans 'package.json' est censé être 'string'. Obtention de '{1}'.", + "Experimental_Options_6177": "Options expérimentales", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "La prise en charge expérimentale des éléments décoratifs est une fonctionnalité (feature) susceptible d'être changée dans une future mise en production. Définissez l'option '--experimentalDecorators' pour supprimer cet avertissement.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Spécification explicite du genre de résolution de module : '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Vous ne pouvez pas utiliser l'assignation d'exportation pour cibler des modules ECMAScript. Utilisez 'export default' ou un autre format de module à la place.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assignation d'exportation n'est pas prise en charge quand l'indicateur '--module' est 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La déclaration d'exportation est en conflit avec la déclaration exportée de '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Les déclarations d'exportation ne sont pas autorisées dans un espace de noms.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Le fichier de typages du package externe exporté '{0}' n'est pas un module. Contactez l'auteur du package pour mettre à jour la définition du package.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Le fichier de typages du package externe exporté ne peut pas contenir de références avec trois barres obliques. Contactez l'auteur du package pour mettre à jour la définition du package.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "L'alias de type exporté '{0}' possède ou utilise le nom privé '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variable exportée '{0}' possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variable exportée '{0}' possède ou utilise le nom '{1}' du module privé '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variable exportée '{0}' possède ou utilise le nom privé '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Les exportations et les assignations d'exportation ne sont pas autorisées dans les augmentations de module.", + "Expression_expected_1109": "Expression attendue.", + "Expression_or_comma_expected_1137": "Expression ou virgule attendue.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Expression résolue en '_super' et utilisée par le compilateur pour capturer la référence de classe de base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "L'expression correspond à la déclaration de variable '{0}' que le compilateur utilise pour prendre en charge les fonctions async.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "L'expression génère une déclaration de variable '_newTarget' que le compilateur utilise pour capturer la référence de méta-propriété 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Expression résolue en déclaration de variable '_this' et utilisée par le compilateur pour capturer la référence 'this'.", + "Extract_constant_95006": "Extraire la constante", + "Extract_function_95005": "Extraire la fonction", + "Extract_symbol_95003": "Extraire le symbole", + "Extract_to_0_in_1_95004": "Extraire vers {0} dans {1}", + "Extract_to_0_in_1_scope_95008": "Extraire vers {0} dans la portée {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extraire vers {0} dans la portée englobante", + "FILE_6035": "FICHIER", + "FILE_OR_DIRECTORY_6040": "FICHIER OU RÉPERTOIRE", + "Failed_to_parse_file_0_Colon_1_5014": "Échec de l'analyse du fichier '{0}' : {1}.", + "Fallthrough_case_in_switch_7029": "Case avec fallthrough dans une instruction switch.", + "File_0_does_not_exist_6096": "Le fichier '{0}' n'existe pas.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Le fichier '{0}' existe. Utilisez-le comme résultat pour la résolution de noms.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Le fichier '{0}' a une extension non prise en charge. Il est ignoré.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Le fichier '{0}' possède une extension non prise en charge. Les seules extensions prises en charge sont {1}.", + "File_0_is_not_a_module_2306": "Le fichier '{0}' n'est pas un module.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Le fichier '{0}' ne se trouve pas sous 'rootDir' '{1}'. 'rootDir' est supposé contenir tous les fichiers sources.", + "File_0_not_found_6053": "Fichier '{0}' introuvable.", + "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Le nom de fichier '{0}' diffère du nom de fichier '{1}' déjà inclus uniquement par la casse.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Le nom de fichier '{0}' a une extension '{1}'. Suppression de l'extension.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La spécification de fichier ne peut pas contenir un répertoire parent ('..') après un caractère générique de répertoire récursif ('**') : '{0}'.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Une spécification de fichier ne peut pas contenir plusieurs caractères génériques de répertoires récursifs ('**') : '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Une spécification de fichier ne peut pas se terminer par un caractère générique de répertoire récursif ('**') : '{0}'.", + "Found_package_json_at_0_6099": "'package.json' trouvé sur '{0}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'. Les définitions de classe sont automatiquement en mode strict.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'. Les modules sont automatiquement en mode strict.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "L'expression de fonction, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "L'implémentation de fonction est manquante ou ne suit pas immédiatement la déclaration.", + "Function_implementation_name_must_be_0_2389": "Le nom de l'implémentation de fonction doit être '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La fonction possède implicitement le type de retour 'any', car elle n'a pas d'annotation de type de retour, et est référencée directement ou indirectement dans l'une de ses expressions de retour.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "La fonction n'a pas d'instruction return de fin, et le type de retour n'inclut pas 'undefined'.", + "Function_overload_must_be_static_2387": "La surcharge de fonction doit être statique.", + "Function_overload_must_not_be_static_2388": "La surcharge de fonction ne doit pas être statique.", + "Generates_corresponding_d_ts_file_6002": "Génère le fichier '.d.ts' correspondant.", + "Generates_corresponding_map_file_6043": "Génère le fichier '.map' correspondant.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Le générateur a implicitement le type '{0}', car il ne produit aucune valeur. Fournissez plutôt un type de retour.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Les générateurs ne sont pas autorisés dans un contexte ambiant.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Les générateurs sont disponibles uniquement quand ECMAScript 2015 ou version supérieure est ciblé.", + "Generic_type_0_requires_1_type_argument_s_2314": "Le type générique '{0}' exige {1} argument(s) de type.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Le type générique '{0}' nécessite entre {1} et {2} arguments de type.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "L'instanciation du type générique est trop profonde et éventuellement infinie.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Les accesseurs getter et setter ne sont pas en accord sur la visibilité.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Les exportations de modules globaux ne peuvent apparaître qu'au niveau supérieur.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Les exportations de modules globaux ne peuvent apparaître que dans les fichiers de déclaration.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Les exportations de modules globaux ne peuvent apparaître que dans les fichiers de module.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Le type global '{0}' doit être un type de classe ou d'interface.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Le type global '{0}' doit avoir {1} paramètre(s) de type.", + "Hexadecimal_digit_expected_1125": "Chiffre hexadécimal attendu.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Identificateur attendu. '{0}' est un mot réservé en mode strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les définitions de classe sont automatiquement en mode strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les modules sont automatiquement en mode strict.", + "Identifier_expected_1003": "Identificateur attendu.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificateur attendu. '__esModule' est réservé en tant que marqueur exporté durant la transformation des modules ECMAScript.", + "Ignore_this_error_message_90019": "Ignorez ce message d'erreur.", + "Implement_inherited_abstract_class_90007": "Implémentez la classe abstraite héritée.", + "Implement_interface_0_90006": "Implémentez l'interface '{0}'.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clause implements de la classe exportée '{0}' possède ou utilise le nom privé '{1}'.", + "Import_0_from_module_1_90013": "Importez '{0}' à partir du module \"{1}\".", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Vous ne pouvez pas utiliser l'assignation d'importation pour cibler des modules ECMAScript. Utilisez plutôt 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' ou un autre format de module.", + "Import_declaration_0_is_using_private_name_1_4000": "La déclaration d'importation '{0}' utilise le nom privé '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La déclaration d'importation est en conflit avec la déclaration locale de '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Les déclarations d'importation dans un espace de noms ne peuvent pas référencer un module.", + "Import_emit_helpers_from_tslib_6139": "Importer l'assistance à l'émission à partir de 'tslib'.", + "Import_name_cannot_be_0_2438": "Le nom d'importation ne peut pas être '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Une déclaration d'importation ou d'exportation dans une déclaration de module ambiant ne peut référencer un module au moyen d'un nom de module relatif.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Les importations ne sont pas autorisées dans les augmentations de module. Déplacez-les vers le module externe englobant.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Dans les déclarations d'enums ambiants, l'initialiseur de membre doit être une expression constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Dans un enum avec plusieurs déclarations, seule une déclaration peut omettre un initialiseur pour son premier élément d'enum.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Dans les déclarations d'enum 'const', l'initialiseur de membre doit être une expression constante.", + "Index_signature_in_type_0_only_permits_reading_2542": "La signature d'index du type '{0}' autorise uniquement la lecture.", + "Index_signature_is_missing_in_type_0_2329": "Signature d'index manquante dans le type '{0}'.", + "Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Les déclarations individuelles de la déclaration fusionnée '{0}' doivent toutes être exportées ou locales.", + "Infer_parameter_types_from_usage_95012": "Déduisez les types des paramètres à partir de l'utilisation.", + "Infer_type_of_0_from_usage_95011": "Déduisez le type de '{0}' à partir de l'utilisation.", + "Initialize_property_0_in_the_constructor_90020": "Initialisez la propriété '{0}' dans le constructeur.", + "Initialize_static_property_0_90021": "Initialisez la propriété statique '{0}'.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'initialiseur de la variable membre d'instance '{0}' ne peut pas référencer l'identificateur '{1}' déclaré dans le constructeur.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'initialiseur du paramètre '{0}' ne peut pas référencer l'identificateur '{1}' déclaré après lui.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'initialiseur ne fournit aucune valeur pour cet élément de liaison, et ce dernier n'a pas de valeur par défaut.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Les initialiseurs ne sont pas autorisés dans les contextes ambiants.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialise un projet TypeScript et crée un fichier tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Insérer les options de ligne de commande et les fichiers à partir d'un fichier texte.", + "Install_0_95014": "Installer '{0}'", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "L'interface '{0}' ne peut pas étendre simultanément les types '{1}' et '{2}'.", + "Interface_0_incorrectly_extends_interface_1_2430": "L'interface '{0}' étend de manière incorrecte l'interface '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "Une déclaration d'interface ne peut pas avoir de clause 'implements'.", + "Interface_name_cannot_be_0_2427": "Le nom de l'interface ne peut pas être '{0}'.", + "Invalid_character_1127": "Caractère non valide.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nom de module non valide dans l'augmentation. Le module '{0}' est résolu en module non typé à l'emplacement '{1}', ce qui empêche toute augmentation.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nom de module non valide dans l'augmentation. Le module '{0}' est introuvable.", + "Invalid_reference_directive_syntax_1084": "Syntaxe de directive 'reference' non valide.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Utilisation non valide de '{0}'. Les définitions de classe sont automatiquement en mode strict.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Utilisation non valide de '{0}'. Les modules sont automatiquement en mode strict.", + "Invalid_use_of_0_in_strict_mode_1100": "Utilisation non valide de '{0}' en mode strict.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valeur non valide pour 'jsxFactory'. '{0}' n'est pas un identificateur valide ou un nom qualifié.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valeur non valide pour '--reactNamespace'. '{0}' n'est pas un identificateur valide.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La balise JSDoc '@{0} {1}' ne correspond pas à la clause 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "La balise JSDoc '@{0}' n'est pas attachée à une classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' peut apparaître uniquement dans le dernier paramètre d'une signature.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La balise JSDoc '@typedef' doit avoir une annotation de type ou être suivie des balises '@property' ou '@member'.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Les types JSDoc peuvent uniquement être utilisés dans les commentaires de la documentation.", + "JSX_attribute_expected_17003": "Attribut JSX attendu.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Les attributs JSX doivent uniquement être attribués à une 'expression' non vide.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "L'élément JSX '{0}' n'a pas de balise de fermeture correspondante.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Le type '{0}' des attributs de l'élément JSX ne peut pas être un type union.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe de l'élément JSX ne prend pas en charge les attributs, car elle n'a pas de propriété '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "L'élément JSX a implicitement le type 'any', car il n'existe aucune interface 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "L'élément JSX a implicitement le type 'any', car le type global 'JSX.Element' n'existe pas.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Le type '{0}' de l'élément JSX n'a pas de signatures de construction ou d'appel.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Le type '{0}' de l'élément JSX n'est pas une fonction constructeur pour les éléments JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Les éléments JSX ne peuvent pas avoir plusieurs attributs du même nom.", + "JSX_expressions_must_have_one_parent_element_2657": "Les expressions JSX doivent avoir un élément parent.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Le fragment JSX n'a pas de balise de fermeture correspondante.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Le fragment JSX n'est pas pris en charge quand --jsxFactory est utilisé", + "JSX_spread_child_must_be_an_array_type_2609": "L'enfant spread JSX doit être un type de tableau.", + "Jump_target_cannot_cross_function_boundary_1107": "La cible du saut ne peut pas traverser une limite de fonction.", + "KIND_6034": "GENRE", + "LOCATION_6037": "EMPLACEMENT", + "Language_service_is_disabled_9004": "Le service de langage est désactivé.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Le côté gauche de l'opérateur virgule n'est pas utilisé, et n'a aucun effet secondaire.", + "Line_break_not_permitted_here_1142": "Saut de ligne non autorisé ici.", + "Line_terminator_not_permitted_before_arrow_1200": "Marque de fin de ligne non autorisée devant une flèche.", + "List_of_folders_to_include_type_definitions_from_6161": "Liste des dossiers à partir desquels inclure les définitions de type.", + "List_of_language_service_plugins_6181": "Liste des plug-ins de service de langage.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Liste des dossiers racines dont le contenu combiné représente la structure du projet au moment de l'exécution.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Chargement de '{0}' à partir du répertoire racine '{1}', emplacement candidat '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Chargement du module '{0}' à partir du dossier 'node_modules'. Type du fichier cible '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Chargement du module en tant que fichier/dossier. Emplacement du module candidat '{0}'. Type de fichier cible '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Les paramètres régionaux doivent être sous la forme ou -. Par exemple, '{0}' ou '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "Le préfixe correspondant le plus long pour '{0}' est '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Recherche dans le dossier 'node_modules', emplacement initial '{0}'.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Faites de l'appel à 'super()' la première instruction du constructeur.", + "Member_0_implicitly_has_an_1_type_7008": "Le membre '{0}' possède implicitement un type '{1}'.", + "Merge_conflict_marker_encountered_1185": "Marqueur de conflit de fusion rencontré.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La déclaration fusionnée '{0}' ne peut pas inclure de déclaration d'exportation par défaut. Ajoutez plutôt une déclaration 'export default {0}' distincte.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La méta-propriété '{0}' n'est autorisée que dans le corps d'une déclaration de fonction, d'une expression de fonction ou d'un constructeur.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "La méthode '{0}' ne peut pas avoir d'implémentation, car elle est marquée comme étant abstraite.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "La méthode '{0}' de l'interface exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "La méthode '{0}' de l'interface exportée comporte ou utilise le nom privé '{1}'.", + "Modifiers_cannot_appear_here_1184": "Les modificateurs ne peuvent pas apparaître ici.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Le module {0} a déjà exporté un membre nommé '{1}'. Effectuez une réexportation explicite pour lever l'ambiguïté.", + "Module_0_has_no_default_export_1192": "Le module '{0}' n'a pas d'exportation par défaut.", + "Module_0_has_no_exported_member_1_2305": "Le module '{0}' n'a aucun membre exporté '{1}'.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Le module '{0}' est masqué par une déclaration locale portant le même nom.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Le module '{0}' se résout en une entité non-module et ne peut pas être importé à l'aide de cette construction.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Le module '{0}' utilise 'export =' et ne peut pas être utilisé avec 'export *'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Le module '{0}' a été résolu en tant que module ambiant déclaré dans '{1}', car ce fichier n'a pas été modifié.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Le module '{0}' a été résolu en tant que module ambiant déclaré localement dans le fichier '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Le module '{0}' a été résolu en '{1}' mais '--jsx' n'est pas défini.", + "Module_Resolution_Options_6174": "Options de résolution du module", + "Module_name_0_matched_pattern_1_6092": "Nom de module '{0}', modèle correspondant '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Le nom de module '{0}' n'a pas été résolu. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.", + "NEWLINE_6061": "NOUVELLE LIGNE", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propriété nommée '{0}' des types '{1}' et '{2}' n'est pas identique.", + "Namespace_0_has_no_exported_member_1_2694": "L'espace de noms '{0}' n'a aucun membre exporté '{1}'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Aucun constructeur de base n'a le nombre spécifié d'arguments de type.", + "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.", + "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}'.", + "Object_is_possibly_null_2531": "L'objet a peut-être la valeur 'null'.", + "Object_is_possibly_null_or_undefined_2533": "L'objet a peut-être la valeur 'null' ou 'undefined'.", + "Object_is_possibly_undefined_2532": "L'objet a peut-être la valeur 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Un littéral d'objet peut uniquement spécifier des propriétés connues, et '{0}' n'existe pas dans le type '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Un littéral d'objet peut uniquement spécifier des propriétés connues, mais '{0}' n'existe pas dans le type '{1}'. Est-ce que vous avez voulu écrire '{2}' ?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propriété '{0}' du littéral d'objet possède implicitement un type '{1}'.", + "Octal_digit_expected_1178": "Chiffre octal attendu.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Les types de littéral octal doivent utiliser la syntaxe ES2015. Utilisez la syntaxe '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Les littéraux octaux ne sont pas autorisés dans l'initialiseur des membres d'énumérations. Utilisez la syntaxe '{0}'.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Les littéraux octaux ne sont pas autorisés en mode strict.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Les littéraux octaux ne sont pas disponibles lorsque vous ciblez ECMAScript 5 et ultérieur. Utilisez la syntaxe '{0}'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Une seule déclaration de variable est autorisée dans une instruction 'for...in'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Seule une déclaration de variable unique est autorisée dans une instruction 'for...of'.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Seule une fonction void peut être appelée avec le mot clé 'new'.", + "Only_ambient_modules_can_use_quoted_names_1035": "Seuls les modules ambiants peuvent utiliser des noms entre guillemets.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Seuls les modules 'amd' et 'system' sont pris en charge avec --{0}.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Seuls les identificateurs/noms qualifiés avec des arguments de type facultatifs sont pris en charge dans une clause 'extends' de classe.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Seules les méthodes publiques et protégées de la classe de base sont accessibles par le biais du mot clé 'super'.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Impossible d'appliquer l'opérateur '{0}' aux types '{1}' et '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "L'option '{0}' ne peut être spécifiée que dans le fichier 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "L'option '{0}' peut être utilisée uniquement quand l'option '--inlineSourceMap' ou l'option '--sourceMap' est spécifiée.", + "Option_0_cannot_be_specified_with_option_1_5053": "Impossible de spécifier l'option '{0}' avec l'option '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Impossible de spécifier l'option '{0}' sans spécifier l'option '{1}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "L'option '{0}' doit avoir un tableau de chaînes en tant que valeur.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'option 'isolatedModules' peut être utilisée seulement quand l'option '--module' est spécifiée, ou quand l'option 'target' a la valeur 'ES2015' ou une version supérieure.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Impossible d'utiliser l'option 'paths' sans spécifier l'option '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Impossible d'associer l'option 'project' à des fichiers sources sur une ligne de commande.", + "Options_Colon_6027": "Options :", + "Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "La signature de surcharge n'est pas compatible avec l'implémentation de fonction.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Les signatures de surcharge doivent toutes être exportées ou non exportées.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Les signatures de surcharge doivent toutes être facultatives ou requises.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Les signatures de surcharge doivent toutes être publiques, privées ou protégées.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Le paramètre '{0}' ne peut pas être référencé dans son initialiseur.", + "Parameter_0_implicitly_has_an_1_type_7006": "Le paramètre '{0}' possède implicitement un type '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Le paramètre '{0}' n'est pas à la même position que le paramètre '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Le paramètre '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Le paramètre '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Le paramètre '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Le paramètre '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Le paramètre '{0}' de la signature d'index de l'interface exportée a ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Le paramètre '{0}' de la signature d'index de l'interface exportée a ou utilise le nom privé '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Le paramètre '{0}' de la méthode de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Le paramètre '{0}' de la méthode de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Un paramètre ne peut pas contenir de point d'interrogation et d'initialiseur.", + "Parameter_declaration_expected_1138": "Déclaration de paramètre attendue.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analyser en mode strict et émettre \"use strict\" pour chaque fichier source.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Le modèle '{0}' ne peut avoir qu'un seul caractère '*' au maximum.", + "Prefix_0_with_an_underscore_90025": "Préfixez '{0}' avec un trait de soulignement.", + "Print_names_of_files_part_of_the_compilation_6155": "Imprimez les noms des fichiers faisant partie de la compilation.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.", + "Print_the_compiler_s_version_6019": "Affichez la version du compilateur.", + "Print_this_message_6017": "Imprimez ce message.", + "Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propriété '{0}' n'existe pas sur le type '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La propriété '{0}' a des déclarations en conflit et est inaccessible dans le type '{1}'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propriété '{0}' a implicitement le type 'any', car son accesseur set ne dispose pas d'une annotation de type de paramètre.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propriété '{0}' du type '{1}' ne peut pas être assignée au type '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La propriété '{0}' est déclarée mais sa valeur n'est jamais lue.", + "Property_0_is_incompatible_with_index_signature_2530": "La propriété '{0}' est incompatible avec la signature d'index.", + "Property_0_is_missing_in_type_1_2324": "La propriété '{0}' est manquante dans le type '{1}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La propriété '{0}' est facultative dans le type '{1}', mais obligatoire dans le type '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La propriété '{0}' est privée et uniquement accessible dans la classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La propriété '{0}' est privée dans le type '{1}', mais pas dans le type '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "La propriété '{0}' est protégée et uniquement accessible par le biais d'une instance de la classe '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La propriété '{0}' est protégée et uniquement accessible dans la classe '{1}' et ses sous-classes.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La propriété '{0}' est protégée, mais le type '{1}' n'est pas une classe dérivée de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La propriété '{0}' est protégée dans le type '{1}', mais publique dans le type '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La propriété '{0}' est utilisée avant d'être assignée.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Impossible d'assigner la propriété '{0}' de l'attribut spread JSX à la propriété cible.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "La propriété '{0}' de l'expression de classe exportée ne peut pas être privée ou protégée.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La propriété '{0}' de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La propriété '{0}' de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Impossible d'assigner la propriété '{0}' de type '{1}' au type d'index numérique '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Impossible d'assigner la propriété '{0}' de type '{1}' au type d'index de chaîne '{2}'.", + "Property_assignment_expected_1136": "Assignation de propriété attendue.", + "Property_destructuring_pattern_expected_1180": "Modèle de déstructuration de propriété attendu.", + "Property_or_signature_expected_1131": "Propriété ou signature attendue.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "La valeur de la propriété peut être uniquement un littéral de chaîne, un littéral numérique, 'true', 'false', 'null', un littéral d'objet ou un littéral de tableau.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Fournissez une prise en charge complète des éléments pouvant faire l'objet d'une itération dans 'for-of', de l'opérateur spread et de la déstructuration durant le ciblage d''ES5' ou 'ES3'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module externe {2} mais ne peut pas être nommée.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom privé '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La propriété publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La propriété publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La propriété publique '{0}' de la classe exportée possède ou utilise le type privé '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module externe {2} mais ne peut pas être nommée.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom privé '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le type privé '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", + "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", + "Remove_declaration_for_Colon_0_90004": "Supprimez la déclaration pour : '{0}'.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", + "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", + "Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.", + "Report_errors_on_unused_parameters_6135": "Signaler les erreurs sur les paramètres inutilisés.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Les paramètres de type obligatoires ne peuvent pas être placés à la suite des paramètres de type optionnels.", + "Resolution_for_module_0_was_found_in_cache_6147": "La résolution du module '{0}' a été trouvée dans le cache.", + "Resolving_from_node_modules_folder_6118": "Résolution à partir du dossier node_modules...", + "Resolving_module_0_from_1_6086": "======== Résolution du module '{0}' à partir de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Résolution du nom de module '{0}' par rapport à l'URL de base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Résolution du chemin réel pour '{0}', résultat '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}', répertoire racine '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}', répertoire racine non défini. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Résolution de la directive de référence de type '{0}', fichier conteneur non défini, répertoire racine '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Résolution de la directive de référence de type '{0}', fichier conteneur non défini, répertoire racine non défini. ========", + "Resolving_using_primary_search_paths_6117": "Résolution à l'aide des chemins de recherche primaires...", + "Resolving_with_primary_search_path_0_6121": "Résolution à l'aide du chemin de recherche primaire '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Le paramètre rest '{0}' possède implicitement un type 'any[]'.", + "Rest_types_may_only_be_created_from_object_types_2700": "Vous ne pouvez créer des types Rest qu'à partir de types d'objet.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Le type de retour de la signature d'appel de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Le type de retour de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Le type de retour de la signature de constructeur de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Le type de retour de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Le type de retour de la signature de constructeur doit pouvoir être assigné au type d'instance de la classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Le type de retour de la fonction exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Le type de retour de la fonction exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Le type de retour de la fonction exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Le type de retour de la signature d'index de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Le type de retour de la signature d'index de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Le type de retour de la méthode de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Le type de retour de la méthode de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Réutilisation des résolutions de module provenant de '{0}', car les résolutions sont inchangées par rapport à l'ancien programme.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Réutilisation de la résolution du module '{0}' dans le fichier '{1}' à partir de l'ancien programme.", + "Rewrite_as_the_indexed_access_type_0_90026": "Réécrire en tant que type d'accès indexé '{0}'.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Impossible de déterminer le répertoire racine, chemins de recherche primaires ignorés.", + "STRATEGY_6039": "STRATÉGIE", + "Scoped_package_detected_looking_in_0_6182": "Package de portée détecté. Recherche dans '{0}'", + "Setters_cannot_return_a_value_2408": "Les méthodes setter ne peuvent pas retourner de valeur.", + "Show_all_compiler_options_6169": "Affichez toutes les options du compilateur.", + "Show_diagnostic_information_6149": "Affichez les informations de diagnostic.", + "Show_verbose_diagnostic_information_6150": "Affichez les informations de diagnostic détaillées.", + "Signature_0_must_be_a_type_predicate_1224": "La signature '{0}' doit être un prédicat de type.", + "Skip_type_checking_of_declaration_files_6012": "Ignorer le contrôle de type des fichiers de déclaration.", + "Source_Map_Options_6175": "Options de mappage de source", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La signature de surcharge spécialisée n'est assignable à aucune signature non spécialisée.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Le spécificateur de l'importation dynamique ne peut pas être un élément spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Spécifiez la version cible d'ECMAScript : 'ES3' (par défaut), 'ES5', 'ES2015', 'ES2016', 'ES2017' ou 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Spécifiez la génération de code JSX : 'preserve', 'react-native' ou 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Spécifiez les fichiers bibliothèques à inclure dans la compilation : ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Spécifiez la génération de code du module : 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' ou 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Spécifiez la stratégie de résolution de module : 'node' (Node.js) ou 'classic' (version de TypeScript antérieure à 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Spécifiez la fonction de fabrique JSX à utiliser pour le ciblage d'une émission JSX 'react', par exemple 'React.createElement' ou 'h'.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Spécifiez la séquence de fin de ligne à utiliser durant l'émission des fichiers : 'CRLF' (Dos) ou 'LF' (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Spécifiez l'emplacement dans lequel le débogueur doit localiser les fichiers TypeScript au lieu des emplacements sources.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Spécifiez l'emplacement dans lequel le débogueur doit localiser les fichiers de mappage au lieu des emplacements générés.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Spécifiez le répertoire racine des fichiers d'entrée. Contrôlez la structure des répertoires de sortie avec --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'opérateur spread dans les expressions 'new' est disponible uniquement quand ECMAScript 5 ou version supérieure est ciblé.", + "Spread_types_may_only_be_created_from_object_types_2698": "Vous ne pouvez créer des types Spread qu'à partir de types d'objet.", + "Statement_expected_1129": "Instruction attendue.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Les instructions ne sont pas autorisées dans les contextes ambiants.", + "Static_members_cannot_reference_class_type_parameters_2302": "Les membres statiques ne peuvent pas référencer des paramètres de type de classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La propriété statique '{0}' est en conflit avec la propriété intégrée 'Function.{0}' de la fonction constructeur '{1}'.", + "Strict_Type_Checking_Options_6173": "Options de contrôle de type strict", + "String_literal_expected_1141": "Littéral de chaîne attendu.", + "String_literal_with_double_quotes_expected_1327": "Littéral de chaîne avec guillemets doubles attendu.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylisez les erreurs et les messages avec de la couleur et du contexte (expérimental).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Les déclarations de variable ultérieures doivent avoir le même type. La variable '{0}' doit être de type '{1}', mais elle a ici le type '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Le type de la substitution '{0}' du modèle '{1}' est incorrect. Attente de 'string'. Obtention de '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La substitution '{0}' dans le modèle '{1}' ne peut avoir qu'un seul caractère '*' au maximum.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Les substitutions du modèle '{0}' doivent correspondre à un tableau.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Les substitutions du modèle '{0}' ne doivent pas correspondre à un tableau vide.", + "Successfully_created_a_tsconfig_json_file_6071": "Un fichier tsconfig.json a été créé.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Les appels de 'super' ne sont pas autorisés hors des constructeurs ou dans des fonctions imbriquées dans des constructeurs.", + "Suppress_excess_property_checks_for_object_literals_6072": "Supprimez les vérifications des propriétés en trop pour les littéraux d'objet.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Supprimer les erreurs noImplicitAny pour les objets d'indexation auxquels il manque des signatures d'index.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "La référence 'Symbol' ne fait pas référence à l'objet constructeur Symbol global.", + "Syntax_Colon_0_6023": "Syntaxe : {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Impossible d'appliquer l'opérateur '{0}' au type 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "L'opérateur '{0}' n'est pas autorisé pour les types booléens. Utilisez '{1}' à la place.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Le type 'Object' peut être assigné à très peu d'autres types. Souhaitez-vous utiliser le type 'any' à la place ?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Impossible de référencer l'objet 'arguments' dans une fonction arrow dans ES3 et ES5. Utilisez plutôt une expression de fonction standard.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Les objets 'arguments' ne peuvent pas être référencés dans une fonction ou méthode async en ES3 et ES5. Utilisez une fonction ou méthode standard.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Le corps d'une instruction 'if' ne peut pas être l'instruction vide.", + "The_character_set_of_the_input_files_6163": "Jeu de caractères des fichiers d'entrée.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Le corps de la fonction ou du module conteneur est trop grand pour l'analyse du flux de contrôle.", + "The_current_host_does_not_support_the_0_option_5001": "L'hôte actuel ne prend pas en charge l'option '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "L'expression d'une assignation d'exportation doit être un identificateur ou un nom qualifié dans un contexte ambiant.", + "The_files_list_in_config_file_0_is_empty_18002": "La liste 'files' du fichier config '{0}' est vide.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Le premier paramètre de la méthode 'then' d'une promesse doit être un rappel.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Le type global 'JSX.{0}' ne peut pas avoir plusieurs propriétés.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La partie gauche d'une instruction 'for...in' ne peut pas être un modèle de déstructuration.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La partie gauche d'une instruction 'for...in' ne peut pas utiliser d'annotation de type.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La partie gauche d'une instruction 'for...in' doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La partie gauche d'une instruction 'for...in' doit être de type 'string' ou 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La partie gauche d'une instruction 'for...of' ne peut pas utiliser d'annotation de type.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La partie gauche d'une instruction 'for...of' doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La partie gauche d'une opération arithmétique doit être de type 'any', 'number' ou un type enum.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La partie gauche d'une expression d'assignation doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La partie gauche d'une expression 'in' doit être de type 'any', 'string', 'number' ou 'symbol'.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La partie gauche d'une expression 'instanceof' doit être de type 'any', un type d'objet ou un paramètre de type.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Paramètres régionaux utilisés pour afficher les messages à l'utilisateur (exemple : 'fr-fr')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondeur de dépendance maximale pour la recherche sous node_modules et le chargement de fichiers JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'opérande d'un opérateur delete ne peut pas être une propriété en lecture seule.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'opérande d'un opérateur delete doit être une référence de propriété.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être un accès à une variable ou une propriété.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Le type de retour d'un constructeur d'éléments JSX doit retourner un type d'objet.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Le type de retour d'une fonction d'élément décoratif de paramètre doit être 'void' ou 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Le type de retour d'une fonction d'élément décoratif de propriété doit être 'void' ou 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Le type de retour d'une fonction asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Le type de retour d'une fonction ou d'une méthode async doit être le type Promise global.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "La partie droite d'une instruction 'for...in' doit être de type 'any', un type d'objet ou un paramètre de type.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La partie droite d'une opération arithmétique doit être de type 'any', 'number' ou un type enum.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La partie droite d'une expression 'in' doit être de type 'any', un type d'objet ou un paramètre de type.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La partie droite d'une expression 'instanceof' doit être de type 'any' ou d'un type pouvant être assigné au type d'interface 'Function'.", + "The_specified_path_does_not_exist_Colon_0_5058": "Le chemin spécifié n'existe pas : '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "La cible d'une assignation doit être un accès à une variable ou une propriété.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La cible de l'assignation du reste d'un objet doit être un accès à une variable ou une propriété.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Le contexte 'this' de type '{0}' n'est pas assignable au contexte 'this' de type '{1}' de la méthode.", + "The_this_types_of_each_signature_are_incompatible_2685": "Les types 'this' de chaque signature sont incompatibles.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "L'argument de type pour le paramètre de type '{0}' ne peut pas être déduit à partir de l'utilisation. Spécifiez plutôt les arguments de type de manière explicite.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Le type retourné par la méthode 'next()' d'un itérateur asynchrone doit être une promesse pour un type ayant une propriété 'value'.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Le type retourné par la méthode 'next()' d'un itérateur doit avoir une propriété 'value'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La déclaration de variable d'une instruction 'for...in' ne peut pas avoir d'initialiseur.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La déclaration de variable d'une instruction 'for...of' ne peut pas avoir d'initialiseur.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'instruction 'with' n'est pas prise en charge. Tous les symboles d'un bloc 'with' ont le type 'any'.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Cette syntaxe nécessite une application d'assistance importée, mais le module '{0}' est introuvable.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Cette syntaxe nécessite une application d'assistance importée nommée '{1}', mais le module '{0}' ne compte aucun membre exporté '{1}'.", + "Trailing_comma_not_allowed_1009": "Virgule de fin non autorisée.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilez chaque fichier sous forme de module distinct (semblable à 'ts.transpileModule').", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Essayez 'npm install @types/{0}' s'il existe, ou ajoutez un nouveau fichier de déclaration (.d.ts) contenant 'declare module '{0}';'", + "Trying_other_entries_in_rootDirs_6110": "Essai avec d'autres entrées dans 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Essai avec la substitution '{0}', emplacement de module candidat : '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Le type tuple '{0}' de longueur '{1}' ne peut pas être assigné à un tuple de longueur '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "Impossible de convertir le type '{0}' en type '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Impossible d'utiliser le type '{0}' comme type d'index.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Le type '{0}' ne peut pas être utilisé pour indexer le type '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Le type '{0}' ne satisfait pas la contrainte '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Le type '{0}' n'a aucune signature d'index correspondant au type '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Le type '{0}' n'a aucune propriété en commun avec le type '{1}'.", + "Type_0_has_no_property_1_2460": "Le type '{0}' n'a pas de propriété '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Le type '{0}' n'a pas de propriété '{1}' ni de signature d'index de chaîne.", + "Type_0_is_not_a_constructor_function_type_2507": "Le type '{0}' n'est pas un type de fonction constructeur.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Le type '{0}' n'est pas un type de retour de fonction async valide en ES5/ES3, car il ne référence pas une valeur de constructeur compatible avec une promesse.", + "Type_0_is_not_an_array_type_2461": "Le type '{0}' n'est pas un type de tableau.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Le type '{0}' n'est pas un type de tableau ou un type de chaîne.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Le type '{0}' n'est pas un type tableau ou un type chaîne, ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Le type '{0}' n'est pas un type tableau ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_is_not_assignable_to_type_1_2322": "Impossible d'assigner le type '{0}' au type '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Le type '{0}' ne peut pas être assigné au type '{1}'. Il existe deux types distincts portant ce nom, mais ils ne sont pas liés.", + "Type_0_is_not_comparable_to_type_1_2678": "Le type '{0}' n'est pas comparable au type '{1}'.", + "Type_0_is_not_generic_2315": "Le type '{0}' n'est pas générique.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Le type '{0}' ne fournit aucune correspondance pour la signature '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Le type '{0}' fait référence à lui-même de manière récursive en tant que type de base.", + "Type_alias_0_circularly_references_itself_2456": "L'alias de type '{0}' fait référence à lui-même de manière circulaire.", + "Type_alias_name_cannot_be_0_2457": "Le nom de l'alias de type ne peut pas être '{0}'.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Une annotation de type ne peut pas apparaître sur une déclaration de constructeur.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Le candidat de l'argument de type '{1}' n'est pas un argument de type valide, car il ne s'agit pas d'un supertype du candidat '{0}'.", + "Type_argument_expected_1140": "Argument de type attendu.", + "Type_argument_list_cannot_be_empty_1099": "La liste des arguments de type ne peut pas être vide.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Fichiers de déclaration de type à inclure dans la compilation.", + "Type_expected_1110": "Type attendu.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Le type est directement ou indirectement référencé dans le rappel d'exécution de sa propre méthode 'then'.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Le type doit comporter une méthode '[Symbol.asyncIterator]()' qui retourne un itérateur asynchrone.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Le type doit comporter une méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Le type d'un opérande 'await' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Le type des éléments itérés d'un opérande 'yield*' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Le type d'un opérande 'yield' dans un générateur asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_parameter_0_has_a_circular_constraint_2313": "Le paramètre de type '{0}' possède une contrainte circulaire.", + "Type_parameter_0_has_a_circular_default_2716": "Le paramètre de type '{0}' a une valeur par défaut circulaire.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Le paramètre de type '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Le paramètre de type '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Le paramètre de type '{0}' de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Le paramètre de type '{0}' de la fonction exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Le paramètre de type '{0}' de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Le paramètre de type '{0}' de l'alias du type exporté contient ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Le paramètre de type '{0}' de la méthode de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Le paramètre de type '{0}' de la méthode publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Le paramètre de type '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_declaration_expected_1139": "Déclaration du paramètre de type attendue.", + "Type_parameter_list_cannot_be_empty_1098": "La liste des paramètres de type ne peut pas être vide.", + "Type_parameter_name_cannot_be_0_2368": "Le nom du paramètre de type ne peut pas être '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Les paramètres de type ne peuvent pas apparaître sur une déclaration de constructeur.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Impossible d'assigner le prédicat de type '{0}' à '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== La directive de référence de type '{0}' n'a pas été résolue. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directive de référence de type '{0}' a été correctement résolue en '{1}', primaire : {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Les types ont des déclarations distinctes d'une propriété privée '{0}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Les types des paramètres '{0}' et '{1}' sont incompatibles.", + "Types_of_property_0_are_incompatible_2326": "Les types de la propriété '{0}' sont incompatibles.", + "Unable_to_open_file_0_6050": "Impossible d'ouvrir le fichier '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Impossible de résoudre la signature d'un élément décoratif de classe quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Impossible de résoudre la signature d'un élément décoratif de méthode quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Impossible de résoudre la signature d'un élément décoratif de paramètre quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Impossible de résoudre la signature d'un élément décoratif de propriété quand il est appelé en tant qu'expression.", + "Unexpected_end_of_text_1126": "Fin de texte inattendue.", + "Unexpected_token_1012": "Jeton inattendu.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Jeton inattendu. Un constructeur, une méthode, un accesseur ou une propriété est attendu.", + "Unexpected_token_expected_1179": "Jeton inattendu. '{' est attendu.", + "Unknown_compiler_option_0_5023": "Option de compilateur '{0}' inconnue.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Option 'excludes' inconnue. Voulez-vous utiliser 'exclude' ?", + "Unknown_type_acquisition_option_0_17010": "Option d'acquisition de type inconnue '{0}'.", + "Unreachable_code_detected_7027": "Code inatteignable détecté.", + "Unsupported_locale_0_6049": "Paramètres régionaux non pris en charge : '{0}'.", + "Unterminated_Unicode_escape_sequence_1199": "Séquence d'échappement Unicode inachevée.", + "Unterminated_quoted_string_in_response_file_0_6045": "Chaîne entre guillemets inachevée dans le fichier réponse '{0}'.", + "Unterminated_regular_expression_literal_1161": "Littéral d'expression régulière inachevé.", + "Unterminated_string_literal_1002": "Littéral de chaîne inachevé.", + "Unterminated_template_literal_1160": "Littéral de modèle inachevé.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Les appels de fonctions non typées ne peuvent pas accepter d'arguments de type.", + "Unused_label_7028": "Étiquette inutilisée.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", + "VERSION_6036": "VERSION", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "La valeur de type '{0}' n'a aucune propriété en commun avec le type '{1}'. Voulez-vous vraiment l'appeler ?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "La valeur de type '{0}' ne peut pas être appelée. Voulez-vous inclure 'new' ?", + "Variable_0_implicitly_has_an_1_type_7005": "La variable '{0}' possède implicitement un type '{1}'.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variable '{0}' a implicitement le type '{1}' dans certains emplacements où son type ne peut pas être déterminé.", + "Variable_0_is_used_before_being_assigned_2454": "La variable '{0}' est utilisée avant d'être assignée.", + "Variable_declaration_expected_1134": "Déclaration de variable attendue.", + "Variable_declaration_list_cannot_be_empty_1123": "La liste des déclarations de variable ne peut pas être vide.", + "Version_0_6029": "Version {0}", + "Watch_input_files_6005": "Fichiers d'entrée d'espion.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Vous ne pouvez pas renommer des éléments définis dans la bibliothèque TypeScript standard.", + "You_cannot_rename_this_element_8000": "Vous ne pouvez pas renommer cet élément.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accepte trop peu d'arguments pour pouvoir être utilisé ici en tant qu'élément décoratif. Voulez-vous vraiment l'appeler d'abord et écrire '@{0}()' ?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' spécifié deux fois. L'attribut nommé '{0}' va être remplacé.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' peut uniquement être utilisé dans un fichier .ts.", + "_0_expected_1005": "'{0}' attendu.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' possède implicitement le type de retour 'any', car il n'a pas d'annotation de type de retour, et est référencé directement ou indirectement dans l'une de ses expressions de retour.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' a implicitement le type 'any', car il n'a pas d'annotation de type et est référencé directement ou indirectement dans son propre initialiseur.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' est une primitive, mais '{1}' est un objet wrapper. Si possible, utilisez '{0}' de préférence.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' est déclaré mais sa valeur n'est jamais lue.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' n'est pas une métapropriété valide pour le mot clé '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' est référencé directement ou indirectement dans sa propre expression de base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' est référencé directement ou indirectement dans sa propre annotation de type.", + "_0_list_cannot_be_empty_1097": "La liste '{0}' ne peut pas être vide.", + "_0_modifier_already_seen_1030": "Modificateur '{0}' déjà rencontré.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Le modificateur '{0}' ne peut pas apparaître dans un élément de classe.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Le modificateur '{0}' ne peut pas apparaître sur une déclaration de constructeur.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Le modificateur '{0}' ne peut pas apparaître dans une propriété de données.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Le modificateur '{0}' ne peut pas apparaître dans un élément de module ou d'espace de noms.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Le modificateur '{0}' ne peut pas apparaître dans un paramètre.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Le modificateur '{0}' ne peut pas apparaître dans un membre de type.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Le modificateur '{0}' ne peut pas apparaître dans une signature d'index.", + "_0_modifier_cannot_be_used_here_1042": "Impossible d'utiliser le modificateur '{0}' ici.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Impossible d'utiliser le modificateur '{0}' dans un contexte ambiant.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Impossible d'utiliser les modificateurs '{0}' et '{1}' ensemble.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Impossible d'utiliser le modificateur '{0}' avec une déclaration de classe.", + "_0_modifier_must_precede_1_modifier_1029": "Le modificateur '{0}' doit précéder le modificateur '{1}'.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' référence uniquement un type mais s'utilise en tant qu'espace de noms ici.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' fait uniquement référence à un type mais s'utilise en tant que valeur ici.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' fait référence à une variable globale UMD, mais le fichier actuel est un module. Ajoutez une importation à la place.", + "_0_tag_already_specified_1223": "La balise '{0}' est déjà spécifiée.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Impossible d'utiliser la balise '{0}' de manière indépendante en tant que balise JSDoc de niveau supérieur.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Le modificateur 'abstract' peut apparaître uniquement dans une déclaration de classe, de méthode ou de propriété.", + "await_expression_is_only_allowed_within_an_async_function_1308": "L'expression 'await' est autorisée uniquement dans une fonction async.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Impossible d'utiliser des expressions 'await' dans un initialiseur de paramètre.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "L'option 'baseUrl' a la valeur '{0}'. Utilisation de cette valeur pour la résolution du nom de module non relatif '{1}'.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' ne peut être utilisé que dans une propriété de littéral d'objet au sein d'une affectation par déstructuration.", + "case_or_default_expected_1130": "'case' ou 'default' attendu.", + "class_expressions_are_not_currently_supported_9003": "Les expressions 'class' ne sont actuellement pas prises en charge.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Les déclarations 'const' ne peuvent être déclarées que dans un bloc.", + "const_declarations_must_be_initialized_1155": "Les déclarations 'const' doivent être initialisées.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'initialiseur de membre enum 'const' donne une valeur non finie.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'initialiseur de membre enum 'const' donne une valeur non autorisée 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation ou d'une assignation d'exportation.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' ne peut pas être appelé dans un identificateur en mode strict.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Les déclarations 'enum' peuvent uniquement être utilisées dans un fichier .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' peut uniquement être utilisé dans un fichier .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Impossible d'appliquer le modificateur 'export' aux modules ambients et aux augmentations de module, car ils sont toujours visibles.", + "extends_clause_already_seen_1172": "Clause 'extends' déjà rencontrée.", + "extends_clause_must_precede_implements_clause_1173": "La clause 'extends' doit précéder la clause 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La clause 'extends' de la classe exportée '{0}' comporte ou utilise le nom privé '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La clause 'extends' de l'interface exportée '{0}' comporte ou utilise le nom privé '{1}'.", + "file_6025": "fichier", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Les accesseurs 'get' et 'set' doivent avoir le même type 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Les accesseurs 'get' et 'set' doivent avoir le même type.", + "implements_clause_already_seen_1175": "Clause 'implements' déjà rencontrée.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Les clauses 'implements' peuvent uniquement être utilisées dans un fichier .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' peut uniquement être utilisé dans un fichier .ts.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Les 'déclarations d'interface' peuvent uniquement être utilisées dans un fichier .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Les déclarations 'let' ne peuvent être déclarées que dans un bloc.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' ne peut pas être utilisé comme nom dans les déclarations 'let' ou 'const'.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Les 'déclarations de module' peuvent uniquement être utilisées dans un fichier .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Impossible d'utiliser 'new T[]' pour créer un tableau. Utilisez 'new Array()' à la place.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "L'expression 'new', dont la cible ne dispose pas d'une signature de construction, possède implicitement un type 'any'.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Les 'assertions non null' peuvent uniquement être utilisées dans un fichier .ts.", + "options_6024": "options", + "or_expected_1144": "'{' ou ';' attendu.", + "package_json_does_not_have_a_0_field_6100": "'package.json' n'a aucun champ '{0}'.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' a un champ '{0}' '{1}' qui fait référence à '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Les 'modificateurs de paramètre' peuvent uniquement être utilisés dans un fichier .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "L'option 'paths' est spécifiée. Recherche d'un modèle correspondant au nom de module '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Le modificateur 'readonly' peut apparaître uniquement dans une déclaration de propriété ou une signature d'index.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'option 'rootDirs' est définie. Utilisation de celle-ci pour la résolution du nom de module relatif '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' ne peut être référencé que dans une classe dérivée.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' ne peut être référencé que dans les membres des classes dérivées ou les expressions littérales d'objet.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Impossible de référencer 'super' dans un nom de propriété calculée.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Impossible de référencer 'super' dans des arguments de constructeur.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' est uniquement autorisé dans les membres des expressions littérales d'objet quand l'option 'target' a la valeur 'ES2015' ou une valeur supérieure.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "'super' doit être appelé avant d'accéder à une propriété de 'super' dans le constructeur d'une classe dérivée.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "'super' doit être appelé avant d'accéder à 'this' dans le constructeur d'une classe dérivée.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' doit être suivi d'une liste d'arguments ou d'un accès au membre.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "L'accès aux propriétés 'super' est autorisé uniquement dans un constructeur, une fonction membre ou un accesseur membre d'une classe dérivée.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Impossible de référencer 'this' dans un nom de propriété calculée.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Impossible de référencer 'this' dans le corps d'un module ou d'un espace de noms.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Impossible de référencer 'this' dans un initialiseur de propriété statique.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Impossible de référencer 'this' dans des arguments de constructeur.", + "this_cannot_be_referenced_in_current_location_2332": "Impossible de référencer 'this' dans l'emplacement actuel.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' possède implicitement le type 'any', car il n'a pas d'annotation de type.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Les 'alias de type' peuvent uniquement être utilisés dans un fichier .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Les 'arguments de type' peuvent uniquement être utilisés dans un fichier .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Les 'expressions d'assertion de type' peuvent uniquement être utilisées dans un fichier .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Les 'déclarations de paramètre de type' peuvent uniquement être utilisées dans un fichier .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "Les 'types' peuvent uniquement être utilisés dans un fichier .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Les types 'symbole unique' ne sont pas autorisés ici.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Les types 'symbole unique' sont uniquement autorisés sur les variables d'une déclaration de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Les types 'symbole unique' ne peuvent pas être utilisés dans une déclaration de variable avec un nom de liaison.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Les instructions 'with' ne sont pas autorisées dans un bloc de fonctions async.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Les instructions 'with' ne sont pas autorisées en mode strict.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Impossible d'utiliser des expressions 'yield' dans un initialiseur de paramètre." +} \ No newline at end of file diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..a9fffd5450d9e --- /dev/null +++ b/lib/it/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Non è possibile usare un modificatore '{0}' con una dichiarazione di importazione.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Non è possibile usare un modificatore '{0}' con una dichiarazione di interfaccia.", + "A_0_parameter_must_be_the_first_parameter_2680": "Il primo parametro deve essere '{0}'.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un parametro del criterio di binding non può essere facoltativo in una firma di implementazione.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Un'istruzione 'break' può essere usata solo all'interno di un'iterazione di inclusione o di un'istruzione switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Un'istruzione 'break' può solo passare a un'etichetta di un'istruzione di inclusione.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Una classe può implementare solo un identificatore/nome qualificato con argomenti tipo facoltativi.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "È necessario assegnare un nome a una dichiarazione di classe senza modificatore 'default'.", + "A_class_may_only_extend_another_class_2311": "Una classe può estendere solo un'altra classe.", + "A_class_may_only_implement_another_class_or_interface_2422": "Una classe può implementare solo un'altra classe o interfaccia.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un membro di classe non può contenere la parola chiave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Non sono consentite espressioni con virgole in un nome di proprietà calcolato.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nome di proprietà calcolato non può fare riferimento a un parametro di tipo dal tipo che lo contiene.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nome di proprietà calcolato in una dichiarazione di proprietà di classe deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nome di proprietà calcolato in un overload di metodo deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nome di proprietà calcolato in un valore letterale di tipo deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nome di proprietà calcolato in un contesto di ambiente deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nome di proprietà calcolato in un'interfaccia deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nome di proprietà calcolato deve essere di tipo 'string', 'number', 'symbol' o 'any'.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nome di proprietà calcolato in formato '{0}' deve essere di tipo 'symbol'.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "È possibile accedere a un membro di enumerazione const solo tramite un valore letterale stringa.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Un inizializzatore 'const' in un contesto di ambiente deve essere un valore letterale numerico o stringa.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un costruttore non può contenere una chiamata 'super' quando la relativa classe estende 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Un costruttore non può contenere un parametro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Un'istruzione 'continue' può essere usata solo all'interno di un'istruzione di iterazione di inclusione.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Un'istruzione 'continue' può solo passare a un'etichetta di un'istruzione di iterazione di inclusione.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Non è possibile usare un modificatore 'declare' in un contesto già di ambiente.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Un modificatore 'declare' è obbligatorio per una dichiarazione di primo livello in un file con estensione d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un elemento Decorator può solo decorare un'implementazione del metodo e non un overload.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Una clausola 'default' non può essere specificata più volte in un'istruzione 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "È possibile usare un'esportazione predefinita solo in un modulo di tipo ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "In questo contesto non sono consentite asserzioni di assegnazione definite '!'.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Una dichiarazione di destrutturazione deve includere un inizializzatore.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Con una chiamata di importazione dinamica in ES5/ES3 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Una chiamata di importazione dinamica restituisce un elemento 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "A_file_cannot_have_a_reference_to_itself_1006": "Un file non può contenere un riferimento a se stesso.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Un'istruzione 'for-await-of' è consentita solo in una funzione asincrona o un generatore asincrono.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Una funzione che restituisce 'never' non può includere un punto finale raggiungibile.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Una funzione chiamata con la parola chiave 'new' non può contenere un tipo 'this' con valore 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Una funzione il cui tipo dichiarato non è 'void' né 'any' deve restituire un valore.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un generatore non può contenere un'annotazione di tipo 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Una funzione di accesso 'get' non può contenere parametri.", + "A_get_accessor_must_return_a_value_2378": "Una funzione di accesso 'get' deve restituire un valore.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inizializzatore di membro in una dichiarazione di enumerazione non può fare riferimento a membri dichiarati successivamente, inclusi quelli definiti in altre enumerazioni.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una classe mixin deve includere un costruttore con un unico parametro REST di tipo 'any[]'.", + "A_module_cannot_have_multiple_default_exports_2528": "Un modulo non può includere più esportazioni predefinite.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una dichiarazione di spazio dei nomi non può essere presente in un file diverso rispetto a una classe o funzione con cui è stato eseguito il merge.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una dichiarazione di spazio dei nomi non può essere specificata prima di una classe o funzione con cui è stato eseguito il merge.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una dichiarazione di spazio dei nomi è consentita solo in uno spazio dei nomi o in un modulo.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inizializzatore di parametro è consentito solo in un'implementazione di funzione o costruttore.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Non è possibile dichiarare una proprietà di parametro usando un parametro REST.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una proprietà di parametro è consentita solo in un'implementazione di costruttore.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Non è possibile dichiarare una proprietà di parametro con un modello di associazione.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Un percorso in un'opzione 'extends' deve essere relativo o completo, ma '{0}' non lo è.", + "A_promise_must_have_a_then_method_1059": "Una promessa deve contenere un metodo 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una proprietà di una classe il cui tipo è un tipo 'unique symbol' deve essere sia 'static' che 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una proprietà di un'interfaccia o di un valore letterale di tipo il cui tipo è un tipo 'unique symbol' deve essere 'readonly'.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un parametro obbligatorio non può seguire un parametro facoltativo.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un elemento rest non può contenere un criterio di binding.", + "A_rest_element_cannot_have_an_initializer_1186": "Un elemento rest non può includere un inizializzatore.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un elemento rest deve essere l'ultimo di un criterio di destrutturazione.", + "A_rest_parameter_cannot_be_optional_1047": "Un parametro rest non può essere facoltativo.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un parametro rest non può contenere un inizializzatore.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un parametro rest deve essere l'ultimo di un elenco di parametri.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un parametro rest deve essere di un tipo di matrice.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Un'istruzione 'return' può essere usata solo all'interno di un corpo di funzione.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Serie di voci che ripetono il mapping delle importazioni a percorsi di ricerca relativi al valore di 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Una funzione di accesso 'set' non può contenere un'annotazione di tipo restituito.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Una funzione di accesso 'set' non può contenere un parametro facoltativo.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Una funzione di accesso 'set' non può contenere il parametro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Una funzione di accesso 'set' deve contenere un solo parametro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un parametro della funzione di accesso 'set' non può contenere un inizializzatore.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Una firma con un'implementazione non può usare un tipo di valore letterale stringa.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Una chiamata 'super' deve essere la prima istruzione del costruttore quando una classe contiene proprietà inizializzate o proprietà di parametri.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Un guard di tipo basato su 'this' non è compatibile con uno basato su parametri.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un tipo 'this' è disponibile solo in un membro non statico di una classe o di interfaccia.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un file 'tsconfig.json' è già definito in: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "L'elenco degli elementi di tipo tupla non può essere vuoto.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione di asserzione tipi. Provare a racchiudere l'espressione tra parentesi.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Una proprietà di valore letterale di tipo non può contenere un inizializzatore.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un predicato di tipo non può fare riferimento a un parametro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un predicato di tipo non può fare riferimento all'elemento '{0}' in un criterio di binding.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un predicato di tipo è consentito solo nella posizione del tipo restituito per le funzioni e i metodi.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Il tipo di un predicato di tipo deve essere assegnabile al tipo del relativo parametro.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Una variabile il cui tipo è un tipo 'unique symbol' deve essere 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Un'espressione 'yield' è consentita solo nel corpo di un generatore.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Non è possibile accedere al metodo astratto '{0}' nella classe '{1}' tramite l'espressione super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "I metodi astratti possono essere inclusi solo in una classe astratta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Non è possibile accedere alla proprietà astratta '{0}' nella classe '{1}' nel costruttore.", + "Accessibility_modifier_already_seen_1028": "Il modificatore di accessibilità è già presente.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Le funzioni di accesso sono disponibili solo se destinate a ECMAScript 5 e versioni successive.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", + "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\".", + "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'.", + "Add_missing_super_call_90001": "Aggiunge la chiamata mancante a 'super()'.", + "Add_this_to_unresolved_variable_90008": "Aggiungi 'this.' alla variabile non risolta.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Aggiungere un file tsconfig.json per organizzare più facilmente progetti che contengono sia file TypeScript che JavaScript. Per altre informazioni, vedere https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Controlli aggiuntivi", + "Advanced_Options_6178": "Opzioni avanzate", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Tutte le dichiarazioni di '{0}' devono contenere modificatori identici.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tutte le dichiarazioni di '{0}' devono contenere parametri di tipo identici.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Tutte le dichiarazioni di un metodo astratto devono essere consecutive.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.", + "Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Le enumerazioni const di ambiente non sono consentite quando viene specificato il flag '--isolatedModules'.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Non è possibile specificare il nome di modulo relativo nella dichiarazione di modulo di ambiente.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "I moduli di ambiente non possono essere annidati in altri moduli o spazi dei nomi.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un modulo AMD non può includere più assegnazioni di nome.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Una funzione di accesso astratta non può contenere un'implementazione.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Non è possibile dichiarare una funzione di accesso in un contesto di ambiente.", + "An_accessor_cannot_have_type_parameters_1094": "Una funzione di accesso non può contenere parametri di tipo.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una dichiarazione di modulo di ambiente è consentita solo al primo livello in un file.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmetico deve essere di tipo 'any', 'number' o un tipo di enum.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Con una funzione o un metodo asincrono in ES5/ES3 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Una funzione o un metodo asincrono deve includere un tipo restituito awaitable valido.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Un metodo o una funzione asincrona deve restituire un elemento 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", + "An_async_iterator_must_have_a_next_method_2519": "Un iteratore asincrono deve contenere un metodo 'next()'.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Il nome di un membro enum non può essere numerico.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "È possibile usare un'assegnazione di esportazione solo in un modulo.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Non è possibile usare un'assegnazione di esportazione in un modulo con altri elementi esportati.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Non è possibile usare un'assegnazione di esportazione in uno spazio dei nomi.", + "An_export_assignment_cannot_have_modifiers_1120": "Un'assegnazione di esportazione non può contenere modificatori.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "È possibile usare una dichiarazione di esportazione solo in un modulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Una dichiarazione di esportazione non può contenere modificatori.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Un valore di escape Unicode avanzato deve essere compreso tra 0x0 e 0x10FFFF inclusi.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Non è possibile dichiarare un'implementazione in contesti di ambiente.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "È possibile usare una dichiarazione di importazione solo in uno spazio dei nomi o in un modulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Una dichiarazione di importazione non può contenere modificatori.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un percorso di importazione non può terminare con l'estensione '{0}'. In alternativa, provare a importare '{1}'.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argomento di espressione di indice deve essere di tipo 'string', 'number', 'symbol' o 'any'.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Una firma dell'indice non può contenere un parametro rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Una firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Una firma dell'indice deve contenere un solo parametro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parametro della firma dell'indice non può contenere un punto interrogativo.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parametro della firma dell'indice non può contenere un modificatore di accessibilità.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parametro della firma dell'indice non può contenere un inizializzatore.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parametro della firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Il tipo di un parametro della firma dell'indice deve essere 'string' o 'number'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Un'interfaccia può estendere solo un identificatore/nome qualificato con argomenti tipo facoltativi.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Un'interfaccia può estendere solo una classe o un'altra interfaccia.", + "An_interface_property_cannot_have_an_initializer_1246": "Una proprietà di interfaccia non può contenere un inizializzatore.", + "An_iterator_must_have_a_next_method_2489": "Un iteratore deve contenere un metodo 'next()'.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un valore letterale di oggetto non può contenere più funzioni di accesso get/set con lo stesso nome.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Un valore letterale di oggetto non può contenere più proprietà con lo stesso nome in modalità strict.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un valore letterale di oggetto non può contenere proprietà e funzioni di accesso con lo stesso nome.", + "An_object_member_cannot_be_declared_optional_1162": "Un membro di oggetto non può essere dichiarato come facoltativo.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Non è possibile dichiarare come generatore una firma di overload.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione unaria con l'operatore '{0}'. Provare a racchiudere l'espressione tra parentesi.", + "Annotate_with_type_from_JSDoc_95009": "Annota con tipo di JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Annota con tipi di JSDoc", + "Argument_expression_expected_1135": "È prevista l'espressione di argomento.", + "Argument_for_0_option_must_be_Colon_1_6046": "L'argomento per l'opzione '{0}' deve essere {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argomento di tipo '{0}' non è assegnabile al parametro di tipo '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "È previsto il criterio di destrutturazione dell'elemento della matrice.", + "Asterisk_Slash_expected_1010": "È previsto '*/'.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Gli aumenti per l'ambito globale possono solo essere direttamente annidati in dichiarazioni di modulo di ambiente o moduli esterni.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Gli aumenti per l'ambito globale devono contenere il modificatore 'declare', a meno che non siano già presenti in un contesto di ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Il rilevamento automatico per le defizioni di tipi è abilitato nel progetto '{0}'. Verrà eseguito il passaggio di risoluzione aggiuntivo per il modulo '{1}' usando il percorso della cache '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Le espressioni di classi di base non possono fare riferimento a parametri di tipo classe.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Il tipo restituito '{0}' del costruttore di base non è un tipo di classe o di interfaccia.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Il tipo restituito deve essere identico per tutti i costruttori di base.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Directory di base per risolvere i nomi di modulo non assoluti.", + "Basic_Options_6172": "Opzioni di base", + "Binary_digit_expected_1177": "È prevista una cifra binaria.", + "Binding_element_0_implicitly_has_an_1_type_7031": "L'elemento di binding '{0}' contiene implicitamente un tipo '{1}'.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "La variabile con ambito blocco '{0}' è stata usata prima di essere stata dichiarata.", + "Call_decorator_expression_90028": "Chiama l'espressione Decorator.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La firma di chiamata, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", + "Call_target_does_not_contain_any_signatures_2346": "La destinazione della chiamata non contiene alcuna firma.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Non è possibile accedere a '{0}.{1}' perché '{0}' è un tipo ma non uno spazio dei nomi. Si intendeva recuperare il tipo della proprietà '{1}' in '{0}' con '{0}[\"{1}\"]'?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Non è possibile assegnare un tipo di costruttore '{0}' a un tipo di costruttore '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Non è possibile assegnare un tipo di costruttore astratto a un tipo di costruttore non astratto.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Non è possibile assegnare a '{0}' perché è una costante o una proprietà di sola lettura.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Non è possibile assegnare a '{0}' perché non è una variabile.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Non è possibile aumentare il modulo '{0}' perché viene risolto in un'entità non modulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Non è possibile aumentare il modulo '{0}' con le esportazioni dei valori perché viene risolto in un'entità non modulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Non è possibile compilare moduli con l'opzione '{0}' a meno che il flag '--module' non sia impostato su 'amd' o 'system'.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Non è possibile compilare spazi dei nomi se non viene specificato il flag '--isolatedModules'.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Non è possibile creare un'istanza di una classe astratta.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Non è possibile esportare '{0}'. Da un modulo è possibile esportare solo dichiarazioni locali.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Non è possibile estendere una classe '{0}'. Il costruttore di classe è contrassegnato come privato.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Non è possibile estendere un'interfaccia '{0}'. Si intendeva usare 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Non è stato trovato alcun file tsconfig.json nella directory specificata '{0}'.", + "Cannot_find_global_type_0_2318": "Il tipo globale '{0}' non è stato trovato.", + "Cannot_find_global_value_0_2468": "Il valore globale '{0}' non è stato trovato.", + "Cannot_find_module_0_2307": "Il modulo '{0}' non è stato trovato.", + "Cannot_find_name_0_2304": "Il nome '{0}' non è stato trovato.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Il nome '{0}' non è stato trovato. Si intendeva '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Il nome '{0}' non è stato trovato. Si intendeva il membro di istanza 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Il nome '{0}' non è stato trovato. Si intendeva il membro statico '{1}.{0}'?", + "Cannot_find_namespace_0_2503": "Lo spazio dei nomi '{0}' non è stato trovato.", + "Cannot_find_parameter_0_1225": "Il parametro '{0}' non è stato trovato.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Il percorso della sottodirectory comune per i file di input non è stato trovato.", + "Cannot_find_type_definition_file_for_0_2688": "Il file di definizione del tipo per '{0}' non è stato trovato.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Non è possibile importare file di dichiarazione di tipo. Provare a importare '{0}' invece di '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Non è possibile inizializzare la variabile con ambito esterna '{0}' nello stesso ambito della dichiarazione con ambito del blocco '{1}'.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Non è possibile richiamare un'espressione al cui tipo manca una firma di chiamata. Per il tipo '{0}' non esistono firme di chiamata compatibili.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Non è possibile riesportare un tipo quando è stato specificato il flag '--isolatedModules'.", + "Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Non è possibile dichiarare di nuovo la variabile esportata '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Non è possibile dichiarare di nuovo l'identificatore '{0}' nella clausola catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Non è possibile usare JSX a meno che non sia specificato il flag '--jsx'.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Non è possibile usare importazioni, esportazioni o aumenti del modulo quando il valore di '--module' è 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Non è possibile usare lo spazio dei nomi '{0}' come tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "Non è possibile usare lo spazio dei nomi '{0}' come valore.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Non è possibile usare 'new' con un'espressione al cui tipo manca una firma del costrutto o di chiamata.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Non è possibile scrivere il file '{0}' perché verrebbe sovrascritto da più file di input.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Non è possibile scrivere il file '{0}' perché sovrascriverebbe il file di input.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "La variabile della clausola catch non può contenere un'annotazione di tipo.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "La variabile della clausola catch non può contenere un inizializzatore.", + "Change_0_to_1_90014": "Cambia '{0}' in '{1}'.", + "Change_extends_to_implements_90003": "Cambia 'extends' in 'implements'.", + "Change_spelling_to_0_90022": "Modificare l'ortografia in '{0}'.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verrà verificato se '{0}' è il prefisso di corrispondenza più lungo per '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definizione circolare dell'alias di importazione '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "È stata rilevata una circolarità durante la risoluzione della configurazione: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La classe '{0}' definisce '{1}' come funzione di accesso di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La classe '{0}' definisce '{1}' come funzione di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di accesso di membro di istanza.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La classe '{0}' definisce '{1}' come funzione di membro di istanza, mentre la classe estesa '{2}' la definisce come proprietà di membro di istanza.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' definisce '{1}' come proprietà di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", + "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' estende in modo errato la classe di base '{1}'.", + "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implementa in modo errato l'interfaccia '{1}'.", + "Class_0_used_before_its_declaration_2449": "La classe '{0}' è stata usata prima di essere stata dichiarata.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Le dichiarazioni di classe non possono contenere più di un tag `@augments` o `@extends`.", + "Class_name_cannot_be_0_2414": "Il nome della classe non può essere '{0}'.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Il lato statico '{0}' della classe estende in modo errato il lato statico '{1}' della classe di base.", + "Classes_can_only_extend_a_single_class_1174": "Le classi possono estendere solo un'unica classe.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Le classi che contengono metodi astratti devono essere contrassegnate come astratte.", + "Command_line_Options_6171": "Opzioni della riga di comando", + "Compilation_complete_Watching_for_file_changes_6042": "Compilazione completata. Verranno individuate le modifiche ai file.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto di cui è stato specificato il percorso del file di configurazione o di una cartella contenente un file 'tsconfig.json'.", + "Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "In un'enumerazione con membri con valore stringa non sono consentiti valori calcolati.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatena e crea l'output in un singolo file.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "In '{1}' e '{2}' sono state trovate definizioni in conflitto per '{0}'. Per risolvere il conflitto, provare a installare una versione specifica di questa libreria.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La firma del costrutto, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", + "Constructor_implementation_is_missing_2390": "Manca l'implementazione di costruttore.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Il costruttore della classe '{0}' è privato e accessibile solo all'interno della dichiarazione di classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Il costruttore della classe '{0}' è protetto e accessibile solo all'interno della dichiarazione di classe.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "I costruttori di classi derivate devono contenere una chiamata 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.", + "Convert_function_0_to_class_95002": "Converti la funzione '{0}' in classe", + "Convert_function_to_an_ES2015_class_95001": "Converti la funzione in una classe ES2015", + "Convert_to_default_import_95013": "Converti nell'importazione predefinita", + "Corrupted_locale_file_0_6051": "Il file delle impostazioni locali {0} è danneggiato.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Non è stato trovato alcun file di dichiarazione per il modulo '{0}'. A '{1}' è assegnato implicitamente un tipo 'any'.", + "Could_not_write_file_0_Colon_1_5033": "Non è stato possibile scrivere il file '{0}': {1}.", + "DIRECTORY_6038": "DIRECTORY", + "Declaration_expected_1146": "È prevista la dichiarazione.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Il nome della dichiarazione è in conflitto con l'identificatore globale predefinito '{0}'.", + "Declaration_or_statement_expected_1128": "È prevista la dichiarazione o l'istruzione.", + "Declare_method_0_90023": "Dichiarare il metodo '{0}'.", + "Declare_property_0_90016": "Dichiarare la proprietà '{0}'.", + "Declare_static_method_0_90024": "Dichiarare il metodo statico '{0}'.", + "Declare_static_property_0_90027": "Dichiarare la proprietà statica '{0}'.", + "Decorators_are_not_valid_here_1206": "In questo punto le espressioni Decorator non sono valide.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Non è possibile applicare le espressioni Decorator a più funzioni di accesso get/set con lo stesso nome.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'esportazione predefinita del modulo contiene o usa il nome privato '{0}'.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Deprecata] In alternativa, usare '--jsxFactory'. Specifica l'oggetto richiamato per createElement quando la destinazione è la creazione JSX 'react'", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Deprecata] In alternativa, usare '--outFile'. Concatena e crea l'output in un singolo file", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Deprecata] In alternativa, usare '--skipLibCheck'. Ignora il controllo del tipo dei file di dichiarazione delle librerie predefinite.", + "Digit_expected_1124": "È prevista la cifra.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "La directory '{0}' non esiste. Tutte le ricerche che la interessano verranno ignorate.", + "Disable_checking_for_this_file_90018": "Disabilita la verifica per questo file.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Disabilita le dimensioni relative alle dimensioni per i progetti JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Disabilitare il controllo tassativo delle firme generiche nei tipi funzione.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Non consente riferimenti allo stesso file in cui le maiuscole/minuscole vengono usate in modo incoerente.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Non aggiunge riferimenti con tripla barra (////) o moduli importati all'elenco di file compilati.", + "Do_not_emit_comments_to_output_6009": "Non crea commenti nell'output.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Non crea dichiarazioni per codice che contiene un'annotazione '@internal'.", + "Do_not_emit_outputs_6010": "Non crea output.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Non crea output se sono stati restituiti errori.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Non crea direttive 'use strict' nell'output del modulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Non cancella le dichiarazioni enum const nel codice generato.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Non genera funzioni di supporto personalizzate, come '__extends', nell'output compilato.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Non include il file di libreria predefinito (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Non segnala gli errori in caso di codice non raggiungibile.", + "Do_not_report_errors_on_unused_labels_6074": "Non segnala gli errori in caso di etichette non usate.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Non risolvere il percorso reale di collegamenti simbolici.", + "Do_not_truncate_error_messages_6165": "Non tronca i messaggi di errore.", + "Duplicate_declaration_0_2718": "La dichiarazione '{0}' è duplicata.", + "Duplicate_function_implementation_2393": "Implementazione di funzione duplicata.", + "Duplicate_identifier_0_2300": "Identificatore '{0}' duplicato.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificatore '{0}' duplicato. Il compilatore riserva il nome '{1}' nell'ambito di primo livello di un modulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "L'identificatore '{0}' è duplicato. Il compilatore riserva il nome '{1}' nell'ambito di primo livello di un modulo che contiene funzioni asincrone.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificatore '{0}' duplicato. Il compilatore usa la dichiarazione '{1}' per supportare le funzioni asincrone.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificatore 'arguments' duplicato. Il compilatore usa 'arguments' per inizializzare i parametri rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificatore '_newTarget' duplicato. Il compilatore usa la dichiarazione di variabile '_newTarget' per acquisire il riferimento alla metaproprietà 'new.target'.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificatore '_super' duplicato. Il compilatore usa '_super' per acquisire il riferimento della classe di base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificatore '_this' duplicato. Il compilatore usa la dichiarazione di variabile '_this' per acquisire il riferimento 'this'.", + "Duplicate_label_0_1114": "Etichetta '{0}' duplicata.", + "Duplicate_number_index_signature_2375": "La firma dell'indice di tipo number è duplicata.", + "Duplicate_string_index_signature_2374": "La firma dell'indice di tipo string è duplicata.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Non è possibile usare l'importazione dinamica quando come destinazione si impostano moduli ECMAScript 2015.", + "Dynamic_import_cannot_have_type_arguments_1326": "Nell'importazione dinamica non possono essere presenti argomenti tipo", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Come argomento dell'importazione dinamica si può indicare un solo identificatore.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "L'identificatore dell'importazione dinamica deve essere di tipo 'string', ma il tipo specificato qui è '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'elemento contiene implicitamente un tipo 'any' perché l'espressione di indice non è di tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'elemento contiene implicitamente un tipo 'any' perché al tipo '{0}' non è assegnata alcuna firma dell'indice.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Crea un BOM (Byte Order Mark) UTF-8 all'inizio dei file di output.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping d origine invece di file separati.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente alle mappe di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.", + "Enable_strict_checking_of_function_types_6186": "Abilitare il controllo tassativo dei tipi funzione.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Abilita il controllo tassativo dell'inizializzazione delle proprietà nelle classi.", + "Enable_strict_null_checks_6113": "Abilita i controlli strict Null.", + "Enable_tracing_of_the_name_resolution_process_6085": "Abilita la traccia del processo di risoluzione dei nomi.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Abilita il supporto sperimentale per le funzioni asincrone di ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Abilita il supporto sperimentale per le espressioni Decorator di ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Abilita il supporto sperimentale per la creazione dei metadati dei tipi per le espressioni Decorator.", + "Enum_0_used_before_its_declaration_2450": "L'enumerazione '{0}' è stata usata prima di essere stata dichiarata.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Le dichiarazioni enum devono essere tutte const o tutte non const.", + "Enum_member_expected_1132": "È previsto il membro enum.", + "Enum_member_must_have_initializer_1061": "Il membro enum deve contenere l'inizializzatore.", + "Enum_name_cannot_be_0_2431": "Il nome dell'enumerazione non può essere '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Il tipo di enumerazione '{0}' contiene membri i cui inizializzatori non sono valori letterali.", + "Examples_Colon_0_6026": "Esempi: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "La profondità dello stack per il confronto dei tipi '{0}' e '{1}' è eccessiva.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Sono previsti argomento tipo {0}-{1}. Per specificarli, usare un tag '@extends'.", + "Expected_0_arguments_but_got_1_2554": "Sono previsti {0} argomenti, ma ne sono stati ottenuti {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Sono previsti {0} argomenti, ma ne sono stati ottenuti più di {1}.", + "Expected_0_type_arguments_but_got_1_2558": "Sono previsti {0} argomenti tipo, ma ne sono stati ottenuti {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Sono previsti argomento tipo {0}. Per specificarli, usare un tag '@extends'.", + "Expected_at_least_0_arguments_but_got_1_2555": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti più di {1}.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "È previsto il tag di chiusura JSX corrispondente per '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "È previsto il tag di chiusura corrispondente per il frammento JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Il tipo previsto del campo '{0}' in 'package.json' è 'string', ma è stato ottenuto '{1}'.", + "Experimental_Options_6177": "Opzioni sperimentali", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Il supporto sperimentale per gli elementi Decorator è una funzionalità soggetta a modifica nelle prossime versioni. Per rimuovere questo avviso, impostare l'opzione 'experimentalDecorators'.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Il tipo di risoluzione del modulo '{0}' è stato specificato in modo esplicito.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Non è possibile usare l'assegnazione di esportazione se destinata a moduli ECMAScript. Provare a usare 'export default' o un altro formato di modulo.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assegnazione dell'esportazione non è supportata quando il valore del flag '--module' è 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La dichiarazione di esportazione è in conflitto con la dichiarazione esportata di '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Le dichiarazioni di esportazione non sono consentite in uno spazio dei nomi.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Il file delle definizioni di tipi di pacchetto esterno esportate '{0}' non è un modulo. Contattare l'autore del pacchetto per aggiornare la definizione del pacchetto.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Il file delle definizioni di tipi di pacchetto esterno esportate non può contenere riferimenti con ///. Contattare l'autore del pacchetto per aggiornare la definizione del pacchetto.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "L'alias di tipo esportato '{0}' contiene o usa il nome privato '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variabile esportata '{0}' contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variabile esportata '{0}' contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variabile esportata '{0}' contiene o usa il nome privato '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Le esportazioni e le assegnazioni di esportazioni non sono consentite negli aumenti del modulo.", + "Expression_expected_1109": "È prevista l'espressione.", + "Expression_or_comma_expected_1137": "È prevista l'espressione o la virgola.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "L'espressione viene risolta in '_super', che è usato dal compilatore per acquisire il riferimento della classe di base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "L'espressione viene risolta nella dichiarazione di variabile '{0}', che è usata dal compilatore per supportare le funzioni asincrone.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "L'espressione viene risolta nella dichiarazione di variabile '_newTarget', che è usata dal compilatore per acquisire il riferimento alla metaproprietà 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "L'espressione viene risolta nella dichiarazione di variabile '_this', che è usata dal compilatore per acquisire il riferimento 'this'.", + "Extract_constant_95006": "Estrarre la costante", + "Extract_function_95005": "Estrarre la funzione", + "Extract_symbol_95003": "Estrarre il simbolo", + "Extract_to_0_in_1_95004": "Estrarre in {0} in {1}", + "Extract_to_0_in_1_scope_95008": "Estrarre in {0} nell'ambito {1}", + "Extract_to_0_in_enclosing_scope_95007": "Estrarre in {0} nell'ambito che lo contiene", + "FILE_6035": "FILE", + "FILE_OR_DIRECTORY_6040": "FILE O DIRECTORY", + "Failed_to_parse_file_0_Colon_1_5014": "Non è stato possibile analizzare il file '{0}': {1}.", + "Fallthrough_case_in_switch_7029": "Caso di fallthrough in switch.", + "File_0_does_not_exist_6096": "Il file '{0}' non esiste.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Il file '{0}' esiste. Usarlo come risultato per la risoluzione dei nomi.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "L'estensione del file '{0}' non è supportata. Il file verrà ignorato.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "L'estensione del file '{0}' non è supportata. Le uniche estensioni supportate sono {1}.", + "File_0_is_not_a_module_2306": "Il file '{0}' non è un modulo.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Il file '{0}' non si trova in 'rootDir' '{1}'. 'rootDir' deve contenere tutti i file di origine.", + "File_0_not_found_6053": "Il file '{0}' non è stato trovato.", + "File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Il nome file '{0}' differisce da quello già incluso '{1}' solo per l'uso di maiuscole/minuscole.", + "File_name_0_has_a_1_extension_stripping_it_6132": "L'estensione del nome file '{0}' è '{1}' e verrà rimossa.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La specifica del file non può contenere una directory padre ('..') inserita dopo un carattere jolly ('**') di directory ricorsiva: '{0}'.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "La specifica del file non può contenere più caratteri jolly ('**') di directory ricorsiva: '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La specifica del file non può terminare con caratteri jolly ('**') di directory ricorsiva: '{0}'.", + "Found_package_json_at_0_6099": "Il file 'package.json' è stato trovato in '{0}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'. Le definizioni di classe sono impostate automaticamente nella modalità strict.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'. I moduli sono impostati automaticamente nella modalità strict.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "L'espressione di funzione, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "L'implementazione di funzione manca o non segue immediatamente la dichiarazione.", + "Function_implementation_name_must_be_0_2389": "Il nome dell'implementazione di funzione deve essere '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La funzione contiene implicitamente il tipo restituito 'any', perché non contiene un'annotazione di tipo restituito e viene usata come riferimento diretto o indiretto in una delle relative espressioni restituite.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Nella funzione manca l'istruzione return finale e il tipo restituito non include 'undefined'.", + "Function_overload_must_be_static_2387": "L'overload della funzione deve essere statico.", + "Function_overload_must_not_be_static_2388": "L'overload della funzione non deve essere statico.", + "Generates_corresponding_d_ts_file_6002": "Genera il file '.d.ts' corrispondente.", + "Generates_corresponding_map_file_6043": "Genera il file '.map' corrispondente.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Il tipo del generatore è implicitamente '{0}' perché non contiene alcun valore. Provare a specificare un tipo restituito.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "I generatori non sono consentiti in un contesto di ambiente.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "I generatori sono disponibili solo se destinati a ECMAScript 2015 o versioni successive.", + "Generic_type_0_requires_1_type_argument_s_2314": "Il tipo generico '{0}' richiede {1} argomento/i di tipo.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Il tipo generico '{0}' richiede tra {1} e {2} argomenti tipo.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creazione di un'istanza di tipo generico presenta troppi livelli ed è probabilmente infinita.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Le funzioni di accesso getter e setter non concordano nella visibilità.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Le esportazioni di moduli globali possono essere usate solo al primo livello.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Le esportazioni di moduli globali possono essere usate solo in file di dichiarazione.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Le esportazioni di moduli globali possono essere usate solo in file di modulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Il tipo globale '{0}' deve un tipo di classe o di interfaccia.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Il tipo globale '{0}' deve contenere {1} parametro/i di tipo.", + "Hexadecimal_digit_expected_1125": "È prevista la cifra esadecimale.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. Le definizioni di classe sono automaticamente impostate sulla modalità strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. I moduli vengono impostati automaticamente in modalità strict.", + "Identifier_expected_1003": "È previsto l'identificatore.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "È previsto un identificatore. '__esModule' è riservato come marcatore esportato durante la trasformazione di moduli ECMAScript.", + "Ignore_this_error_message_90019": "Ignora questo messaggio di errore.", + "Implement_inherited_abstract_class_90007": "Implementa la classe astratta ereditata.", + "Implement_interface_0_90006": "Implementa l'interfaccia '{0}'.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clausola implements della classe esportata '{0}' contiene o usa il nome privato '{1}'.", + "Import_0_from_module_1_90013": "Importa '{0}' dal modulo \"{1}\".", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Non è possibile usare l'assegnazione di importazione se destinata a moduli ECMAScript. Provare a usare 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' o un altro formato di modulo.", + "Import_declaration_0_is_using_private_name_1_4000": "La dichiarazione di importazione '{0}' usa il nome privato '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La dichiarazione di importazione è in conflitto con la dichiarazione locale di '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Le dichiarazioni di importazione in uno spazio dei nomi non possono far riferimento a un modulo.", + "Import_emit_helpers_from_tslib_6139": "Importa gli helper di creazione da 'tslib'.", + "Import_name_cannot_be_0_2438": "Il nome dell'importazione non può essere '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La dichiarazione di importazione o esportazione in una dichiarazione di modulo di ambiente non può fare riferimento al modulo tramite il nome di modulo relativo.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Le importazioni non sono consentite negli aumenti di modulo. Provare a spostarle nel modulo esterno di inclusione.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni enum dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento enum.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Nelle dichiarazioni enum 'const' l'inizializzatore di membro deve essere un'espressione costante.", + "Index_signature_in_type_0_only_permits_reading_2542": "La firma dell'indice nel tipo '{0}' consente solo la lettura.", + "Index_signature_is_missing_in_type_0_2329": "Nel tipo '{0}' manca la firma dell'indice.", + "Index_signatures_are_incompatible_2330": "Le firme dell'indice sono incompatibili.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Le singole dichiarazioni della dichiarazione sottoposta a merge '{0}' devono essere tutte esportate o tutte locali.", + "Infer_parameter_types_from_usage_95012": "Deriva i tipi di parametro dall'utilizzo.", + "Infer_type_of_0_from_usage_95011": "Deriva il tipo di '{0}' dall'utilizzo.", + "Initialize_property_0_in_the_constructor_90020": "Inizializza la proprietà '{0}' nel costruttore.", + "Initialize_static_property_0_90021": "Inizializza la proprietà statica '{0}'.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'inizializzatore della variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'inizializzatore del parametro '{0}' non può fare riferimento all'identificatore '{1}' dichiarato dopo di esso.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'inizializzatore non fornisce alcun valore per questo elemento di binding e per quest'ultimo non è disponibile un valore predefinito.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Gli inizializzatori non sono consentiti in contesti di ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inizializza un progetto TypeScript e crea un file tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserisce i file e le opzioni della riga di comando da un file.", + "Install_0_95014": "Installa '{0}'", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "L'interfaccia '{0}' non può estendere simultaneamente i tipi '{1}' e '{2}'.", + "Interface_0_incorrectly_extends_interface_1_2430": "L'interfaccia '{0}' estende in modo errato l'interfaccia '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "La dichiarazione di interfaccia non può avere una clausola 'implements'.", + "Interface_name_cannot_be_0_2427": "Il nome dell'interfaccia non può essere '{0}'.", + "Invalid_character_1127": "Carattere non valido.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' viene risolto in un modulo non tipizzato in '{1}', che non può essere aumentato.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' non è stato trovato.", + "Invalid_reference_directive_syntax_1084": "La sintassi della direttiva 'reference' non è valida.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Uso non valido di '{0}'. Le definizioni di classe sono automaticamente impostate sulla modalità strict.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso non valido di '{0}'. I moduli vengono impostati automaticamente in modalità strict.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso non valido di '{0}' in modalità strict.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Il valore non è valido per 'jsxFactory'. '{0}' non è un identificatore o un nome qualificato valido.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Il valore di '--reactNamespace' non è valido. '{0}' non è un identificatore valido", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Il tag '@{0} {1}' di JSDoc non corrisponde alla clausola 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Il tag '@{0}' di JSDoc non è collegato a una classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' può essere presente solo nell'ultimo parametro di una firma.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Il tag '@typedef' di JSDoc deve contenere un'annotazione di tipo o essere seguito dal tag '@property' o '@member'.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "I tipi JSDoc possono essere usati solo nei commenti della documentazione.", + "JSX_attribute_expected_17003": "È previsto l'attributo JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Agli attributi JSX deve essere assegnato solo un elemento 'expression' non vuoto.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Per l'elemento JSX '{0}' non esiste alcun tag di chiusura corrispondente.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Il tipo '{0}' degli attributi dell'elemento JSX potrebbe non essere un tipo di unione.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe dell'elemento JSX non supporta gli attributi perché non contiene una proprietà '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "L'elemento JSX contiene implicitamente il tipo 'any' perché non esiste alcuna interfaccia 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "L'elemento JSX contiene implicitamente il tipo 'any' perché il tipo globale 'JSX.Element' non esiste.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Il tipo '{0}' dell'elemento JSX non contiene firme di costrutto o chiamata.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Il tipo '{0}' dell'elemento JSX non è una funzione del costruttore per elementi JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Gli elementi JSX non possono contenere più attributi con lo stesso nome.", + "JSX_expressions_must_have_one_parent_element_2657": "Le espressioni JSX devono contenere un solo elemento padre.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Per il frammento JSX non esiste alcun tag di chiusura corrispondente.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "Il frammento JSX non è supportato quando si usa --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "L'elemento figlio dell'attributo spread JSX deve essere un tipo di matrice.", + "Jump_target_cannot_cross_function_boundary_1107": "La destinazione di collegamento non può oltrepassare il limite della funzione.", + "KIND_6034": "TIPOLOGIA", + "LOCATION_6037": "PERCORSO", + "Language_service_is_disabled_9004": "Il servizio di linguaggio è disabilitato.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Il lato sinistro dell'operatore virgola non è usato e non ha effetti collaterali.", + "Line_break_not_permitted_here_1142": "L'interruzione di riga non è consentita in questo punto.", + "Line_terminator_not_permitted_before_arrow_1200": "Il terminatore di riga non è consentito prima di arrow.", + "List_of_folders_to_include_type_definitions_from_6161": "Elenco di cartelle da cui includere le definizioni di tipo.", + "List_of_language_service_plugins_6181": "Elenco dei plug-in dei servizi di linguaggio.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Elenco delle cartelle radice il cui contenuto combinato rappresenta la struttura del progetto in fase di esecuzione.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Verrà eseguito il caricamento di '{0}' dalla directory radice '{1}'. Percorso candidato: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Verrà eseguito il caricamento del modulo '{0}' dalla cartella 'node_modules'. Tipo di file di destinazione: '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Verrà eseguito il caricamento del modulo come file/cartella. Percorso candidato del modulo: '{0}'. Tipo di file di destinazione: '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Le impostazioni locali devono essere nel formato o -, ad esempio, '{0}' o '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "Il prefisso di corrispondenza più lungo per '{0}' è '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Verrà eseguita la ricerca nella cartella 'node_modules'. Percorso iniziale: '{0}'.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Imposta la chiamata a 'super()' come prima istruzione nel costruttore.", + "Member_0_implicitly_has_an_1_type_7008": "Il membro '{0}' contiene implicitamente un tipo '{1}'.", + "Merge_conflict_marker_encountered_1185": "È stato rilevato un indicatore di conflitti di merge.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La dichiarazione '{0}' sottoposta a merge non può includere una dichiarazione di esportazione predefinita. Provare ad aggiungere una dichiarazione 'export default {0}' distinta.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La metaproprietà '{0}' è consentita solo nel corpo di una dichiarazione di funzione, di un'espressione di funzione o di un costruttore.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Il metodo '{0}' non può includere un'implementazione perché è contrassegnato come astratto.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Il metodo '{0}' dell'interfaccia esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Il metodo '{0}' dell'interfaccia esportata ha o usa il nome privato '{1}'.", + "Modifiers_cannot_appear_here_1184": "In questo punto non è possibile usare modificatori.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Il modulo {0} ha già esportato un membro denominato '{1}'. Per risolvere l'ambiguità, provare a esportarlo di nuovo in modo esplicito.", + "Module_0_has_no_default_export_1192": "Per il modulo '{0}' non esistono esportazioni predefinite.", + "Module_0_has_no_exported_member_1_2305": "Il modulo '{0}' non contiene un membro esportato '{1}'.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Il modulo '{0}' è nascosto da una dichiarazione locale con lo stesso nome.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Il modulo '{0}' viene risolto in un'entità non modulo e non può essere importato con questo costrutto.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Il modulo '{0}' usa 'export =' e non può essere usato con 'export *'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Il modulo '{0}' è stato risolto come modulo di ambiente dichiarato in '{1}' dal momento che questo file non è stato modificato.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Il modulo '{0}' è stato risolto come modulo di ambiente dichiarato in locale nel file '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Il modulo '{0}' è stato risolto in '{1}', ma '--jsx' non è impostato.", + "Module_Resolution_Options_6174": "Opzioni di risoluzione moduli", + "Module_name_0_matched_pattern_1_6092": "Nome del modulo: '{0}'. Criterio corrispondente: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Il nome del modulo '{0}' non è stato risolto. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Il nome del modulo '{0}' è stato risolto in '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Il tipo di risoluzione del modulo non è specificato. Verrà usato '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "La risoluzione del modulo con 'rootDirs' non è riuscita.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Non è possibile usare più implementazioni di costruttore.", + "NEWLINE_6061": "NUOVA RIGA", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Le proprietà denominate '{0}' dei tipi '{1}' e '{2}' non sono identiche.", + "Namespace_0_has_no_exported_member_1_2694": "Lo spazio dei nomi '{0}' non contiene un membro esportato '{1}'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Nessun costruttore di base contiene il numero specificato di argomenti tipo.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Non sono stati trovati input nel file config '{0}'. Percorsi 'include' specificati: '{1}'. Percorsi 'exclude' specificati: '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non astratta '{0}' non implementa il membro astratto ereditato '{1}' della classe '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'espressione di classe non astratta non implementa il membro astratto ereditato '{0}' dalla classe '{1}'.", + "Not_all_code_paths_return_a_value_7030": "Non tutti i percorsi del codice restituiscono un valore.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Il tipo di indice numerico '{0}' non è assegnabile al tipo di indice stringa '{1}'.", + "Object_is_possibly_null_2531": "L'oggetto è probabilmente 'null'.", + "Object_is_possibly_null_or_undefined_2533": "L'oggetto è probabilmente 'null' o 'undefined'.", + "Object_is_possibly_undefined_2532": "L'oggetto è probabilmente 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Il valore letterale di oggetto può specificare solo proprietà note e '{0}' non esiste nel tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Il valore letterale dell'oggetto può specificare solo proprietà note, ma '{0}' non esiste nel tipo '{1}'. Si intendeva scrivere '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La proprietà '{0}' del valore letterale di oggetto contiene implicitamente un tipo '{1}'.", + "Octal_digit_expected_1178": "È prevista la cifra ottale.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "I tipi di valori letterali ottali devono usare la sintassi ES2015. Usare la sintassi '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "I valori letterali ottali non sono consentiti nell'inizializzatore di membri di enumerazioni. Usare la sintassi '{0}'.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "I valori letterali ottali non sono consentiti in modalità strict.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "I valori letterali ottali non sono disponibili quando la destinazione è ECMAScript 5 e versioni successive. Usare la sintassi '{0}'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In un'istruzione 'for...in' è consentita solo una singola dichiarazione di variabile.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In un'istruzione 'for...of' è consentita solo una singola dichiarazione di variabile.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Con la parola chiave 'new' può essere chiamata solo una funzione void.", + "Only_ambient_modules_can_use_quoted_names_1035": "I nomi delimitati si possono usare solo nei moduli di ambiente.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Unitamente a --{0} sono supportati solo i moduli 'amd' e 'system'.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Nella clausola 'extends' di una classe sono attualmente supportati solo identificatori/nomi qualificati con argomenti tipo facoltativi.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Con la parola chiave 'super' è possibile accedere solo ai metodi pubblico e protetto della classe di base.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Non è possibile applicare l'operatore '{0}' ai tipi '{1}' e '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "L'opzione '{0}' può essere specificata solo nel file 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "L'opzione '{0}' può essere usata solo quando si specifica l'opzione '--inlineSourceMap' o '--sourceMap'.", + "Option_0_cannot_be_specified_with_option_1_5053": "Non è possibile specificare l'opzione '{0}' insieme all'opzione '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Non è possibile specificare l'opzione '{0}' senza l'opzione '{1}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Il valore dell'opzione '{0}' deve essere una matrice di stringhe.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'opzione 'isolatedModules' può essere usata solo quando si specifica l'opzione '--module' oppure il valore dell'opzione 'target' è 'ES2015' o maggiore.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Non è possibile usare l'opzione 'paths' senza specificare l'opzione '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Non è possibile combinare l'opzione 'project' con file di origine in una riga di comando.", + "Options_Colon_6027": "Opzioni:", + "Output_directory_for_generated_declaration_files_6166": "Directory di output per i file di dichiarazione generati.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "La firma di overload non è compatibile con l'implementazione di funzione.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Le firme di overload devono essere tutte astratte o tutte non astratte.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Le firme di overload devono essere tutte di ambiente o non di ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Le firme di overload devono essere tutte esportate o tutte non esportate.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Le firme di overload devono essere tutte facoltative o obbligatorie.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Le firme di overload devono essere tutte pubbliche, private o protette.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Non è possibile fare riferimento al parametro '{0}' nel relativo inizializzatore.", + "Parameter_0_implicitly_has_an_1_type_7006": "Il parametro '{0}' contiene implicitamente un tipo '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Il parametro '{0}' non si trova nella stessa posizione del parametro '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Il parametro '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Il parametro '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Il parametro '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Il parametro '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Il parametro '{0}' della funzione esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Il parametro '{0}' della funzione esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Il parametro '{0}' della funzione esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Il parametro '{0}' della firma dell'indice dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Il parametro '{0}' della firma dell'indice dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Il parametro '{0}' del metodo dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Il parametro '{0}' del metodo dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Il parametro non può contenere il punto interrogativo e l'inizializzatore.", + "Parameter_declaration_expected_1138": "È prevista la dichiarazione di parametro.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Il tipo di parametro del setter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Il tipo di parametro del setter pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Esegue l'analisi in modalità strict e crea la direttiva \"use strict\" per ogni file di origine.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Il criterio '{0}' deve contenere al massimo un carattere '*'.", + "Prefix_0_with_an_underscore_90025": "Anteporre un carattere di sottolineatura a '{0}'.", + "Print_names_of_files_part_of_the_compilation_6155": "Stampa i nomi dei file che fanno parte della compilazione.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.", + "Print_the_compiler_s_version_6019": "Stampa la versione del compilatore.", + "Print_this_message_6017": "Stampa questo messaggio.", + "Property_0_does_not_exist_on_const_enum_1_2479": "La proprietà '{0}' non esiste nell'enumerazione 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva '{2}'?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La proprietà '{0}' include dichiarazioni in conflitto ed è inaccessibile nel tipo '{1}'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso set manca un'annotazione di tipo di parametro.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La proprietà '{0}' nel tipo '{1}' non è assegnabile al tipo '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La proprietà '{0}' è dichiarata, ma il suo valore non viene mai letto.", + "Property_0_is_incompatible_with_index_signature_2530": "La proprietà '{0}' non è compatibile con la firma dell'indice.", + "Property_0_is_missing_in_type_1_2324": "Nel tipo '{1}' manca la proprietà '{0}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La proprietà '{0}' è facoltativa nel tipo '{1}', ma obbligatoria nel tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La proprietà '{0}' è privata e accessibile solo all'interno della classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La proprietà '{0}' è privata nel tipo '{1}', ma non nel tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "La proprietà '{0}' è protetta e accessibile solo tramite un'istanza della classe '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La proprietà '{0}' è protetta e accessibile solo all'interno della classe '{1}' e delle relative sottoclassi.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La proprietà '{0}' è protetta, ma il tipo '{1}' non è una classe derivata da '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La proprietà '{0}' è protetta nel tipo '{1}', ma è pubblica non nel tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La proprietà '{0}' viene usata prima dell'assegnazione.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "La proprietà '{0}' dell'attributo spread JSX non è assegnabile alla proprietà di destinazione.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "La proprietà '{0}' dell'espressione di classe esportata potrebbe essere non privata o protetta.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La proprietà '{0}' dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La proprietà '{0}' dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "La proprietà '{0}' del tipo '{1}' non è assegnabile a un tipo di indice numerico '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "La proprietà '{0}' del tipo '{1}' non è assegnabile a un tipo di indice stringa '{2}'.", + "Property_assignment_expected_1136": "È prevista l'assegnazione di proprietà.", + "Property_destructuring_pattern_expected_1180": "È previsto il criterio di destrutturazione della proprietà.", + "Property_or_signature_expected_1131": "È prevista la proprietà o la firma.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Il valore della proprietà può essere solo un valore letterale stringa, un valore letterale numerico, 'true', 'false', 'null', un valore letterale di oggetto o un valore letterale di matrice.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Fornisce supporto completo per elementi iterabili in 'for-of', spread e destrutturazione quando la destinazione è 'ES5' o 'ES3'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome privato '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Il metodo statico pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Il metodo statico pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Il metodo statico pubblico '{0}' della classe esportata ha o usa il nome privato '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Genera un errore in caso di espressioni o dichiarazioni con tipo 'any' implicito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.", + "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", + "Remove_declaration_for_Colon_0_90004": "Rimuovi la dichiarazione per {0}.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", + "Report_errors_in_js_files_8019": "Segnala gli errori presenti nei file con estensione js.", + "Report_errors_on_unused_locals_6134": "Segnala errori relativi a variabili locali non usate.", + "Report_errors_on_unused_parameters_6135": "Segnala errori relativi a parametri non usati.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "I parametri di tipo obbligatori potrebbero non seguire i parametri di tipo facoltativi.", + "Resolution_for_module_0_was_found_in_cache_6147": "La risoluzione per il modulo '{0}' non è stata trovata nella cache.", + "Resolving_from_node_modules_folder_6118": "Risoluzione dalla cartella node_modules...", + "Resolving_module_0_from_1_6086": "======== Risoluzione del modulo '{0}' da '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Verrà eseguita la risoluzione del nome del modulo '{0}' relativo all'URL di base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Risoluzione del percorso reale per '{0}'. Risultato: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}' con directory radice '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}' e directory radice non impostata. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file non impostato con directory radice '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file non impostato con directory radice non impostata. ========", + "Resolving_using_primary_search_paths_6117": "Risoluzione con percorsi di ricerca primaria...", + "Resolving_with_primary_search_path_0_6121": "La risoluzione verrà eseguita con il percorso di ricerca primaria '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Il parametro rest '{0}' contiene implicitamente un tipo 'any[]'.", + "Rest_types_may_only_be_created_from_object_types_2700": "È possibile creare tipi rest solo da tipi di oggetto.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Il tipo restituito della firma di chiamata dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Il tipo restituito della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Il tipo restituito della firma del costruttore dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Il tipo restituito della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Il tipo restituito della firma del costruttore deve essere assegnabile al tipo di istanza della classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Il tipo restituito della funzione esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Il tipo restituito della funzione esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Il tipo restituito della funzione esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Il tipo restituito della firma dell'indice dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Il tipo restituito della firma dell'indice dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Il tipo restituito del metodo dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Il tipo restituito del metodo dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2}, ma non può essere rinominato.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno '{2}', ma non può essere rinominato.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome privato '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Le risoluzioni dei moduli con origine in '{0}' verranno riutilizzate perché sono invariate rispetto al vecchio programma.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "La risoluzione del modulo '{0}' del vecchio programma verrà riutilizzata nel file '{1}'.", + "Rewrite_as_the_indexed_access_type_0_90026": "Riscrivere come tipo di accesso indicizzato '{0}'.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Non è possibile determinare la directory radice. I percorsi di ricerca primaria verranno ignorati.", + "STRATEGY_6039": "STRATEGIA", + "Scoped_package_detected_looking_in_0_6182": "Il pacchetto con ambito è stato rilevato. Verrà eseguita una ricerca in '{0}'", + "Setters_cannot_return_a_value_2408": "I setter non possono restituire un valore.", + "Show_all_compiler_options_6169": "Mostra tutte le opzioni del compilatore.", + "Show_diagnostic_information_6149": "Mostra le informazioni di diagnostica.", + "Show_verbose_diagnostic_information_6150": "Mostra le informazioni di diagnostica dettagliate.", + "Signature_0_must_be_a_type_predicate_1224": "La firma '{0}' deve essere un predicato di tipo.", + "Skip_type_checking_of_declaration_files_6012": "Ignora il controllo del tipo dei file di dichiarazione.", + "Source_Map_Options_6175": "Opzioni per mapping di origine", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La firma di overload specializzata non è assegnabile a una firma non specializzata.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "L'identificatore dell'importazione dinamica non può essere l'elemento spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Specifica la versione di destinazione di ECMAScript: 'ES3' (predefinita), 'ES5', 'ES2015', 'ES2016', 'ES2017' o 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Specifica la generazione del codice JSX: 'preserve', 'react-native' o 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Specifica i file di libreria da includere nella compilazione: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Consente di specificare il tipo di generazione del codice del modulo, ovvero 'none', commonjs', 'amd', 'system', 'umd', 'es2015' o 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Specifica la strategia di risoluzione del modulo: 'node' (Node.js) o 'classic' (TypeScript prima della versione 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Consente di specificare la funzione della factory JSX da usare quando la destinazione è la creazione JSX 'react', ad esempio 'React.createElement' o 'h'.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Specifica la sequenza di fine riga da usare per la creazione dei file, ovvero 'CRLF' (in DOS) o 'LF' (in UNIX).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Specifica il percorso in cui il debugger deve trovare i file TypeScript invece dei percorsi di origine.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Specifica il percorso in cui il debugger deve trovare i file map invece dei percorsi generati.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Specifica la directory radice dei file di input. Usare per controllare la struttura della directory di output con --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'operatore Spread in espressioni 'new' è disponibile solo se destinato a ECMAScript 5 e versioni successive.", + "Spread_types_may_only_be_created_from_object_types_2698": "È possibile creare tipi spread solo da tipi di oggetto.", + "Statement_expected_1129": "È prevista l'istruzione.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Le istruzioni non sono consentite in contesti di ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "I membri statici non possono fare riferimento a parametri di tipo classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La proprietà statica '{0}' è in conflitto con la proprietà predefinita 'Function.{0}' della funzione del costruttore '{1}'.", + "Strict_Type_Checking_Options_6173": "Opzioni per controlli del tipo strict", + "String_literal_expected_1141": "È previsto un valore letterale stringa.", + "String_literal_with_double_quotes_expected_1327": "È previsto un valore letterale stringa con virgolette doppie.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Applica stili a errori e messaggi usando colore e contesto (sperimentale).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Le dichiarazioni di proprietà successive devono essere dello stesso tipo. La proprietà '{0}' deve essere di tipo '{1}', ma qui è di tipo '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Le dichiarazioni di variabili successive devono essere dello stesso tipo. La variabile '{0}' deve essere di tipo '{1}', mentre è di tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Il tipo della sostituzione '{0}' per il criterio '{1}' non è corretto. È previsto 'string', ma è stato ottenuto '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La sostituzione '{0}' nel criterio '{1}' può contenere al massimo un carattere '*'.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Le sostituzioni per il criterio '{0}' devono essere una matrice.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Le sostituzioni per il criterio '{0}' non devono essere una matrice vuota.", + "Successfully_created_a_tsconfig_json_file_6071": "La creazione di un file tsconfig.json è riuscita.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Le chiamate super non sono consentite all'esterno di costruttori o nelle funzioni annidate all'interno di costruttori.", + "Suppress_excess_property_checks_for_object_literals_6072": "Elimina i controlli delle proprietà in eccesso per i valori letterali di oggetto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Non visualizza gli errori noImplicitAny per gli oggetti di indicizzazione in cui mancano le firme dell'indice.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Il riferimento 'Symbol' non fa riferimento all'oggetto costruttore Symbol globale.", + "Syntax_Colon_0_6023": "Sintassi: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Non è possibile applicare l'operatore '{0}' al tipo 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "L'operatore '{0}' non è consentito per i tipi booleani. Provare a usare '{1}'.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Il tipo 'Object' può essere assegnato a un numero molto limitato di altri tipi. Si intendeva usare il tipo 'any'?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Non è possibile fare riferimento all'oggetto 'arguments' in una funzione arrow in ES3 e ES5. Provare a usare un'espressione di funzione standard.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Non è possibile fare riferimento all'oggetto 'arguments' in un metodo o una funzione asincrona in ES3 e ES5. Provare a usare un metodo o una funzione standard.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Il corpo di un'istruzione 'if' non può essere l'istruzione vuota.", + "The_character_set_of_the_input_files_6163": "Set di caratteri dei file di input.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Il corpo del modulo o la funzione che contiene è troppo grande per l'analisi del flusso di controllo.", + "The_current_host_does_not_support_the_0_option_5001": "L'host corrente non supporta l'opzione '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "L'espressione di un'assegnazione di esportazione deve essere un identificatore o un nome completo in un contesto di ambiente.", + "The_files_list_in_config_file_0_is_empty_18002": "L'elenco 'files' nel file config '{0}' è vuoto.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Il primo parametro del metodo 'then' di una promessa deve essere un callback.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Il tipo globale 'JSX.{0}' non può contenere più di una proprietà.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte sinistra di un'espressione 'for...in' non può essere un criterio di destrutturazione.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Nella parte sinistra di un'espressione 'for...in' non è possibile usare un'annotazione di tipo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La parte sinistra di un'istruzione 'for...in' deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte sinistra di un'espressione 'for...in' deve essere di tipo 'string' o 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Nella parte sinistra di un'espressione 'for...of' non è possibile usare un'annotazione di tipo.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte sinistra di un'istruzione 'for...of' deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La parte sinistra di un'operazione aritmetica deve essere di tipo 'any', 'number' o un tipo di enumerazione.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte sinistra di un'espressione di assegnazione deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La parte sinistra di un'espressione 'in' deve essere di tipo 'any', 'string', 'number' o 'symbol'.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte sinistra di un'espressione 'instanceof' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Impostazioni locali usate per la visualizzazione di messaggi all'utente, ad esempio 'it-it'", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondità massima delle dipendenze per la ricerca in node_modules e il caricamento dei file JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'operando di un operatore delete non può essere una proprietà di sola lettura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'operando di un operatore delete deve essere un riferimento a proprietà.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'operando di un operatore di incremento o decremento deve essere una variabile o un accesso a proprietà.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Il tipo restituito di un costruttore di elementi JSX deve restituire un tipo di oggetto.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Il tipo restituito di una funzione di espressione Decorator del parametro deve essere 'void' o 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Il tipo restituito di una funzione di espressione Decorator della proprietà deve essere 'void' o 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Il tipo restituito di una funzione asincrona deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Il tipo restituito di un metodo o una funzione asincrona deve essere il tipo globale Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "La parte destra di un'istruzione 'for...in' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La parte destra di un'operazione aritmetica deve essere di tipo 'any', 'number' o un tipo di enumerazione.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte destra di un'espressione 'in' deve essere di tipo 'any' oppure deve essere un tipo di oggetto o un parametro di tipo.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte destra di un'espressione 'instanceof' deve essere di tipo 'any' o di un tipo assegnabile al tipo di interfaccia 'Function'.", + "The_specified_path_does_not_exist_Colon_0_5058": "Il percorso specificato non esiste: '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "La destinazione di un'assegnazione deve essere una variabile o un accesso a proprietà.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La destinazione di un'assegnazione rimanente dell'oggetto deve essere una variabile o un accesso a proprietà.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Il contesto 'this' del tipo '{0}' non è assegnabile a quello 'this' di tipo '{1}' del metodo.", + "The_this_types_of_each_signature_are_incompatible_2685": "I tipi 'this' delle singole firme non sono compatibili.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Non è possibile dedurre l'argomento tipo per il parametro di tipo '{0}' dall'utilizzo. Provare a specificare gli argomenti tipo in modo esplicito.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Il tipo restituito dal metodo 'next()' di un iteratore asincrono deve essere una promessa per un tipo con una proprietà 'value'.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Il tipo restituito dal metodo 'next()' di un iteratore deve contenere una proprietà 'value'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La dichiarazione di variabile di un'istruzione 'for...in' non può contenere un inizializzatore.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La dichiarazione di variabile di un'istruzione 'for...of' non può contenere un inizializzatore.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'istruzione 'with' non è supportata. Il tipo di tutti i simboli in un blocco 'with' è 'any'.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Con questa sintassi è richiesto un helper importato, ma il modulo '{0}' non è stato trovato.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Con questa sintassi è richiesto un helper importato denominato '{1}', ma il modulo '{0}' non contiene alcun membro esportato '{1}'.", + "Trailing_comma_not_allowed_1009": "La virgola finale non è consentita.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Esegue il transpile di ogni file in un modulo separato (simile a 'ts.transpileModule').", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Provare con `npm install @types/{0}` se esiste oppure aggiungere un nuovo file di dichiarazione con estensione d.ts contenente `declare module '{0}';`", + "Trying_other_entries_in_rootDirs_6110": "Verrà effettuato un tentativo con altre voci in 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Verrà effettuato un tentativo con la sostituzione '{0}'. Percorso candidato del modulo: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Non è possibile assegnare il tipo di tupla '{0}' la cui lunghezza è '{1}' alla tupla la cui lunghezza è '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "Non è possibile convertire il tipo '{0}' nel tipo '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Non è possibile usare il tipo '{0}' come tipo di indice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Non è possibile usare il tipo '{0}' per indicizzare il tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Il tipo '{0}' non soddisfa il vincolo '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Nel tipo '{0}' non esiste alcuna firma dell'indice corrispondente per il tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Il tipo '{0}' non ha proprietà in comune con il tipo '{1}'.", + "Type_0_has_no_property_1_2460": "Il tipo '{0}' non contiene la proprietà '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Il tipo '{0}' non contiene la proprietà '{1}' né la firma dell'indice di tipo stringa.", + "Type_0_is_not_a_constructor_function_type_2507": "Il tipo '{0}' non è un tipo di funzione del costruttore.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Il tipo '{0}' non è un tipo restituito di funzione asincrona valido in ES5/ES3 perché non fa riferimento a un valore di costruttore compatibile con Promise.", + "Type_0_is_not_an_array_type_2461": "Il tipo '{0}' non è un tipo matrice.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Il tipo '{0}' non è un tipo matrice o stringa.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Il tipo '{0}' non è un tipo matrice o stringa oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Il tipo '{0}' non è un tipo matrice oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_is_not_assignable_to_type_1_2322": "Il tipo '{0}' non è assegnabile al tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Il tipo '{0}' non è assegnabile al tipo '{1}'. Sono presenti due tipi diversi con questo nome, che però non sono correlati.", + "Type_0_is_not_comparable_to_type_1_2678": "Il tipo '{0}' non è confrontabile con il tipo '{1}'.", + "Type_0_is_not_generic_2315": "Il tipo '{0}' non è generico.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Il tipo '{0}' non fornisce corrispondenze per la firma '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Il tipo '{0}' fa riferimento a se stesso in modo ricorsivo come tipo di base.", + "Type_alias_0_circularly_references_itself_2456": "L'alias di tipo '{0}' contiene un riferimento circolare a se stesso.", + "Type_alias_name_cannot_be_0_2457": "Il nome dell'alias di tipo non può essere '{0}'.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "L'annotazione di tipo non può essere inclusa in una dichiarazione di costruttore.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Il candidato '{1}' non è un argomento tipo valido perché non è un supertipo del candidato '{0}'.", + "Type_argument_expected_1140": "È previsto l'argomento tipo.", + "Type_argument_list_cannot_be_empty_1099": "L'elenco degli argomenti tipo non può essere vuoto.", + "Type_declaration_files_to_be_included_in_compilation_6124": "File della dichiarazione di tipo da includere nella compilazione.", + "Type_expected_1110": "È previsto il tipo.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Il tipo viene usato come riferimento diretto o indiretto nel callback di fulfillment del relativo metodo 'then'.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Il tipo deve contenere un metodo '[Symbol.asyncIterator]()' che restituisce un iteratore asincrono.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Il tipo deve contenere un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Il tipo dell'operando 'await' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Il tipo di elementi iterati di un operando 'yield*' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Il tipo dell'operando 'yield' in un generatore asincrono deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_parameter_0_has_a_circular_constraint_2313": "Il parametro di tipo '{0}' contiene un vincolo circolare.", + "Type_parameter_0_has_a_circular_default_2716": "Il parametro di tipo '{0}' contiene un'impostazione predefinita circolare.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Il parametro di tipo '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Il parametro di tipo '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Il parametro di tipo '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Il parametro di tipo '{0}' della funzione esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Il parametro di tipo '{0}' dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Il parametro di tipo '{0}' dell'alias di tipo esportato contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Il parametro di tipo '{0}' del metodo dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Il parametro di tipo '{0}' del metodo pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Il parametro di tipo '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_declaration_expected_1139": "È prevista la dichiarazione di parametro di tipo.", + "Type_parameter_list_cannot_be_empty_1098": "L'elenco dei parametri di tipo non può essere vuoto.", + "Type_parameter_name_cannot_be_0_2368": "Il nome del parametro di tipo non può essere '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "I parametri di tipo non possono essere inclusi in una dichiarazione di costruttore.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Il predicato di tipo '{0}' non è assegnabile a '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== La direttiva '{0}' del riferimento al tipo non è stata risolta. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La direttiva '{0}' del riferimento al tipo è stata risolta in '{1}'. Primaria: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "I tipi contengono dichiarazioni separate di una proprietà privata '{0}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "I tipi dei parametri '{0}' e '{1}' sono incompatibili.", + "Types_of_property_0_are_incompatible_2326": "I tipi della proprietà '{0}' sono incompatibili.", + "Unable_to_open_file_0_6050": "Non è possibile aprire il file '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Non è possibile risolvere la firma dell'espressione Decorator della classe quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Non è possibile risolvere la firma dell'espressione Decorator del metodo quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Non è possibile risolvere la firma dell'espressione Decorator del parametro quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Non è possibile risolvere la firma dell'espressione Decorator della proprietà quando è chiamata come espressione.", + "Unexpected_end_of_text_1126": "Fine del testo imprevista.", + "Unexpected_token_1012": "Token imprevisto.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token imprevisto. È previsto un costruttore, un metodo, una funzione di accesso o una proprietà.", + "Unexpected_token_expected_1179": "Token imprevisto. È previsto '{'.", + "Unknown_compiler_option_0_5023": "Opzione del compilatore sconosciuta: '{0}'.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "L'opzione 'excludes' è sconosciuta. Si intendeva 'exclude'?", + "Unknown_type_acquisition_option_0_17010": "L'opzione '{0}' relativa all'acquisizione del tipo è sconosciuta.", + "Unreachable_code_detected_7027": "È stato rilevato codice non raggiungibile.", + "Unsupported_locale_0_6049": "Impostazioni locali non supportate: '{0}'.", + "Unterminated_Unicode_escape_sequence_1199": "Sequenza di escape Unicode senza terminazione.", + "Unterminated_quoted_string_in_response_file_0_6045": "Stringa tra virgolette senza terminazione nel file di risposta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Valore letterale di espressione regolare senza terminazione.", + "Unterminated_string_literal_1002": "Valore letterale stringa senza terminazione.", + "Unterminated_template_literal_1160": "Valore letterale di modello senza terminazione.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Le chiamate di funzione non tipizzate potrebbero non accettare argomenti tipo.", + "Unused_label_7028": "Etichetta non usata.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", + "VERSION_6036": "VERSIONE", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Il valore di tipo '{0}' non ha proprietà in comune con il tipo '{1}'. Si intendeva chiamarlo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Il valore di tipo '{0}' non è chiamabile. Si intendeva includere 'new'?", + "Variable_0_implicitly_has_an_1_type_7005": "La variabile '{0}' contiene implicitamente un tipo '{1}'.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variabile '{0}' contiene implicitamente il tipo '{1}' in alcune posizioni in cui non è possibile determinarne il tipo.", + "Variable_0_is_used_before_being_assigned_2454": "La variabile '{0}' viene usata prima dell'assegnazione.", + "Variable_declaration_expected_1134": "È prevista la dichiarazione di variabile.", + "Variable_declaration_list_cannot_be_empty_1123": "L'elenco delle dichiarazioni di variabile non può essere vuoto.", + "Version_0_6029": "Versione {0}", + "Watch_input_files_6005": "Controlla i file di input.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Non è possibile rinominare elementi definiti nella libreria TypeScript standard.", + "You_cannot_rename_this_element_8000": "Non è possibile rinominare questo elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accetta un numero troppo ridotto di argomenti da usare come espressione Decorator in questo punto. Si intendeva chiamarlo prima e scrivere '@{0}()'?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Gli attributi '{0}' sono stati specificati due volte. L'attributo denominato '{0}' verrà sovrascritto.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' può essere usato solo in un file con estensione ts.", + "_0_expected_1005": "È previsto '{0}'.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' contiene implicitamente il tipo restituito 'any', perché non contiene un'annotazione di tipo restituito e viene usato come riferimento diretto o indiretto in una delle relative espressioni restituite.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' contiene implicitamente il tipo 'any', perché non contiene un'annotazione di tipo e viene usato come riferimento diretto o indiretto nel relativo inizializzatore.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' è una primitiva, ma '{1}' è un oggetto wrapper. Quando possibile, preferire '{0}'.", + "_0_is_declared_but_its_value_is_never_read_6133": "L'elemento '{0}' è dichiarato, ma il suo valore non viene mai letto.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' non è una metaproprietà valida per la parola chiave '{1}'. Si intendeva '{2}'?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' viene usato come riferimento diretto o indiretto nella relativa espressione di base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' viene usato come riferimento diretto o indiretto nella relativa annotazione di tipo.", + "_0_list_cannot_be_empty_1097": "L'elenco '{0}' non può essere vuoto.", + "_0_modifier_already_seen_1030": "Il modificatore '{0}' è già presente.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Il modificatore '{0}' non può essere incluso in un elemento classe.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Il modificatore '{0}' non può essere incluso in una dichiarazione di costruttore.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Il modificatore '{0}' non può essere incluso in una proprietà Data.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Il modificatore '{0}' non può essere incluso in un elemento modulo o spazio dei nomi.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Il modificatore '{0}' non può essere incluso in un parametro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Il modificatore '{0}' non può essere incluso in un membro di tipo.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Il modificatore '{0}' non può essere incluso in una firma dell'indice.", + "_0_modifier_cannot_be_used_here_1042": "Non è possibile usare il modificatore '{0}' in questo punto.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Non è possibile usare il modificatore '{0}' in un contesto di ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Non è possibile usare il modificatore '{0}' con il modificatore '{1}'.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Non è possibile usare il modificatore '{0}' con una dichiarazione di classe.", + "_0_modifier_must_precede_1_modifier_1029": "Il modificatore '{0}' deve precedere il modificatore '{1}'.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come spazio dei nomi.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come valore.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' fa riferimento a un istruzione globale UMD, ma il file corrente è un modulo. Provare ad aggiungere un'importazione.", + "_0_tag_already_specified_1223": "Il tag '{0}' è già specificato.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Non è possibile usare in modo indipendente il tag '{0}' come tag JSDoc di primo livello.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Il modificatore 'abstract' può essere incluso solo in una dichiarazione di classe, metodo o proprietà.", + "await_expression_is_only_allowed_within_an_async_function_1308": "L'espressione 'await' è consentita solo in una funzione asincrona.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Non è possibile usare le espressioni 'await' in un inizializzatore di parametri.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "L'opzione 'baseUrl' è impostata su '{0}'. Verrà usato questo valore per risolvere il nome del modulo non relativo '{1}'.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "È possibile usare '=' solo in una proprietà di valore letterale di oggetto all'interno di un'assegnazione di destrutturazione.", + "case_or_default_expected_1130": "È previsto 'case' o 'default'.", + "class_expressions_are_not_currently_supported_9003": "Le espressioni 'class' non sono attualmente supportate.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Le dichiarazioni 'const' possono essere dichiarate solo all'interno di un blocco.", + "const_declarations_must_be_initialized_1155": "Le dichiarazioni 'const' devono essere inizializzate.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'inizializzatore di membro enum 'const' è stato valutato come valore non finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'inizializzatore di membro enum 'const' è stato valutato come valore non consentito 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione o di una dichiarazione di importazione.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Non è possibile chiamare 'delete' su un identificatore in modalità strict.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' può essere usato solo in un file con estensione ts.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' può essere usato solo in un file con estensione ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Non è possibile applicare il modificatore 'export' a moduli di ambiente e aumenti di modulo perché sono sempre visibili.", + "extends_clause_already_seen_1172": "La clausola 'extends' è già presente.", + "extends_clause_must_precede_implements_clause_1173": "La clausola 'extends' deve precedere la clausola 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La clausola 'extends' della classe esportata '{0}' contiene o usa il nome privato '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La clausola 'extends' dell'interfaccia esportata '{0}' contiene o usa il nome privato '{1}'.", + "file_6025": "file", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Le funzioni di accesso 'get e 'set' devono essere dello stesso tipo 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Le funzioni di accesso 'get e 'set' devono essere dello stesso tipo.", + "implements_clause_already_seen_1175": "La clausola 'implements' è già presente.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' può essere usato solo in un file con estensione ts.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' può essere usato solo in un file con estensione ts.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' può essere usato solo in un file con estensione ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Le dichiarazioni 'let' possono essere dichiarate solo all'interno di un blocco.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Non è consentito usare 'let' come nome in dichiarazioni 'let' o 'const'.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' può essere usato solo in un file con estensione ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Non è possibile usare 'new T[]' per creare una matrice. Usare 'new Array()'.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "L'espressione 'new', nella cui destinazione manca una firma del costrutto, contiene implicitamente un tipo 'any'.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' può essere usato solo in un file con estensione ts.", + "options_6024": "opzioni", + "or_expected_1144": "È previsto '{' o ';'.", + "package_json_does_not_have_a_0_field_6100": "Il file 'package.json' non contiene un campo '{0}'.", + "package_json_has_0_field_1_that_references_2_6101": "Il file 'package.json' contiene il campo '{1}' di '{0}' che fa riferimento a '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' può essere usato solo in un file con estensione ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "È specificata l'opzione 'paths'. Verrà cercato un criterio per la corrispondenza con il nome del modulo '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Il modificatore 'readonly' può essere incluso solo in una dichiarazione di proprietà o una firma dell'indice.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'opzione 'rootDirs' è impostata e verrà usata per risolvere il nome del modulo relativo '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "È possibile fare riferimento a 'super' solo in una classe derivata.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "È possibile fare riferimento a 'super' solo in membri di classi derivate o espressioni letterali di oggetto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Non è possibile fare riferimento a 'super' in un nome di proprietà calcolato.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Non è possibile fare riferimento a 'super' in argomenti del costruttore.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' è consentito solo in membri di espressioni letterali di oggetto quando il valore dell'opzione 'target' è 'ES2015' o superiore.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "È necessario chiamare 'super' prima di accedere a una proprietà di 'super' nel costruttore di una classe derivata.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "È necessario chiamare 'super' prima di accedere a 'this' nel costruttore di una classe derivata.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' deve essere seguito da un elenco di argomento o da un accesso membro.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "L'accesso alla proprietà 'super' è consentito solo in un costruttore, in una funzione membro o in una funzione di accesso di membro di una classe derivata.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Non è possibile fare riferimento a 'this' in un nome di proprietà calcolato.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Non è possibile fare riferimento a 'this' nel corpo di un modulo o di uno spazio dei nomi.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Non è possibile fare riferimento a 'this' in un inizializzatore di proprietà statica.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Non è possibile fare riferimento a 'this' in argomenti del costruttore.", + "this_cannot_be_referenced_in_current_location_2332": "Non è possibile fare riferimento a 'this' nella posizione corrente.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' contiene implicitamente il tipo 'any' perché non include un'annotazione di tipo.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' può essere usato solo in un file con estensione ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' può essere usato solo in un file con estensione ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' può essere usato solo in un file con estensione ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' può essere usato solo in un file con estensione ts.", + "types_can_only_be_used_in_a_ts_file_8010": "'types' può essere usato solo in un file con estensione ts.", + "unique_symbol_types_are_not_allowed_here_1335": "I tipi 'unique symbol' non sono consentiti in questo punto.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "I tipi 'unique symbol' sono consentiti solo nelle variabili in un'istruzione di variabile.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Non è possibile usare i tipi 'unique symbol' in una dichiarazione di variabile con nome di binding.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Le istruzioni 'with' non sono consentite in un blocco di funzione asincrona.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Le istruzioni 'with' non sono consentite in modalità strict.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Non è possibile usare le espressioni 'yield' in un inizializzatore di parametri." +} \ No newline at end of file diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..45d39e6d00b3b --- /dev/null +++ b/lib/ja/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "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_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}' キーワードを指定することはできません。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "コンマ式は計算されたプロパティ名では使用できません。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算されたプロパティ名は、型パラメーターをそれを含む型から参照することはできません。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "クラス プロパティ宣言内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "メソッド オーバーロード内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型リテラル内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境コンテキスト内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "インターフェイス内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算されたプロパティ名は 'string' 型、'number' 型、'symbol' 型、または 'any' 型のいずれかでなければなりません。", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "形式 '{0}' の計算されたプロパティ名は 'symbol' 型でなければなりません。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 列挙型メンバーは、文字列リテラルを使用してのみアクセスできます。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "環境コンテキスト内の 'const' 初期化子は文字列リテラルか数値リテラルにする必要があります。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "コンストラクターのクラスが 'null' を拡張する場合、そのコンストラクターに 'super' の呼び出しを含めることはできません。", + "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_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_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' コンストラクターの宣言があることを確認するか、`--lib` オプションに 'ES2015' を組み込んでください。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "動的インポート呼び出しは 'Promise' を返します。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることをご確認ください。", + "A_file_cannot_have_a_reference_to_itself_1006": "ファイルにそれ自体への参照を含めることはできません。", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "'for-await-of' ステートメントは、非同期関数または非同期ジェネレーターの中でのみ使用できます。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never' を返す関数には、到達可能なエンド ポイントがありません。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'new' キーワードで呼び出される関数に、'void' である 'this' 型を使用することはできません。", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "宣言された型が 'void' でも 'any' でもない関数は値を返す必要があります。", + "A_generator_cannot_have_a_void_type_annotation_2505": "ジェネレーターに 'void' 型の注釈を指定することはできません。", + "A_get_accessor_cannot_have_parameters_1054": "'get' アクセサーにパラメーターを指定することはできません。", + "A_get_accessor_must_return_a_value_2378": "'get' アクセサーは値を返す必要があります。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "enum 宣言のメンバー初期化子は、他の enum で定義されたメンバーを含め、その後で宣言されたメンバーを参照できません。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin クラスには、型 'any[]' の単一の rest パラメーターを持つコンストラクターが必要です。", + "A_module_cannot_have_multiple_default_exports_2528": "モジュールに複数の既定のエクスポートを含めることはできません。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "名前空間宣言は、それとマージするクラスや関数と異なるファイルに配置できません。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "名前空間宣言は、それとマージするクラスや関数より前に配置できません。", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "名前空間宣言は、名前空間かモジュールでのみ使用できます。", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "パラメーター初期化子は、関数またはコンストラクターの実装でのみ指定できます。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "パラメーター プロパティは、rest パラメーターを使用して宣言することはできません。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "パラメーター プロパティは、コンストラクターの実装でのみ指定できます。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "パラメーター プロパティは、バインド パターンを使用して宣言することはできません。", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'拡張' オプション内のパスは相対パスまたはルート パスである必要がありますが、'{0}' の場合は、その必要はありません。", + "A_promise_must_have_a_then_method_1059": "Promise には 'then' メソッドが必要です。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型が '一意のシンボル' 型のクラスのプロパティは、'static' と 'readonly' の両方である必要があります。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型が '一意のシンボル' 型のインターフェイスまたは型リテラルのプロパティは、'readonly' である必要があります。", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必須パラメーターを省略可能なパラメーターの後に指定することはできません。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 要素にバインド パターンを含めることはできません。", + "A_rest_element_cannot_have_an_initializer_1186": "rest 要素に初期化子を指定することはできません。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 要素は非構造化パターンの最後に指定する必要があります。", + "A_rest_parameter_cannot_be_optional_1047": "rest パラメーターを省略可能にすることはできません。", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest パラメーターに初期化子を指定することはできません。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest パラメーターはパラメーター リストの最後に指定する必要があります。", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest パラメーターは配列型でなければなりません。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' ステートメントは、関数本体でのみ使用できます。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "'baseUrl' の相対的な場所を検索するためにインポートを再マップする一連のエントリ。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' アクセサーに、戻り値の型の注釈を指定することはできません。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' アクセサーに、省略可能パラメーターを指定することはできません。", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' アクセサーに rest パラメーターを指定することはできません。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' アクセサーにはパラメーターを 1 つだけ指定しなければなりません。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' アクセサーのパラメーターに初期化子を含めることはできません。", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "実装のシグネチャには文字列リテラル型は使用できません。", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "'super' の呼び出しは、初期化されたプロパティまたはパラメーターのプロパティがクラスに含まれている場合、コンストラクターの最初のステートメントでなければなりません。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'this' ベース型のガードはパラメーター ベース型のガードとは互換性がありません。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 型はクラスまたはインターフェイスの静的でないメンバーでのみ使用できます。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' ファイルは既に '{0}' で定義されています。", + "A_tuple_type_element_list_cannot_be_empty_1122": "タプル型の要素リストを空にすることはできません。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "累乗式の左辺で型アサーション式を使用することはできません。式を括弧で囲むことを検討してください。", + "A_type_literal_property_cannot_have_an_initializer_1247": "型リテラル プロパティに初期化子を使用することはできません。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "型の述語は rest パラメーターを参照できません。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "型の述語は、バインド パターン内の要素 '{0}' を参照できません。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "型の述語は、関数およびメソッドの戻り値の型の位置でのみ使用できます。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "type 述語の型はそのパラメーターの型に割り当て可能である必要があります。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型が '一意のシンボル' 型の変数は、'const' である必要があります。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 式は、ジェネレーター本文でのみ使用できます。", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "クラス '{1}' の抽象メソッド '{0}' には super 式を介してアクセスできません。", + "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": "アクセシビリティ修飾子は既に存在します。", + "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_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加します。", + "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加します。", + "Add_this_to_unresolved_variable_90008": "'this.' を未解決の変数に追加します。", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "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_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", + "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", + "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_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "環境コンテキストではアクセサーは宣言できません。", + "An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "アンビエント モジュール宣言は、ファイルの最上位にのみ使用できます。", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "算術オペランドは 'any' 型、'number' 型、列挙型のいずれかでなければなりません。", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 の非同期の関数またはメソッドには、'Promise' コンストラクターが必要です。'Promise' コンストラクターの宣言があることを確認するか、`--lib` オプションに 'ES2015' を組み込んでください。", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同期関数または非同期メソッドには、有効で待機可能な戻り値の型を指定する必要があります。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同期関数またはメソッドは 'Promise' を返す必要があります。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることを確認してください。", + "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", + "An_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_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 の間 (両端を含む) でなければなりません。", + "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_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": "インデックス シグネチャに rest パラメーターを指定することはできません。", + "An_index_signature_must_have_a_type_annotation_1021": "インデックス シグネチャには型の注釈が必要です。", + "An_index_signature_must_have_exactly_one_parameter_1096": "インデックス シグネチャには、パラメーターを 1 つだけ指定しなければなりません。", + "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_initializer_1020": "インデックス シグネチャのパラメーターに初期化子を指定することはできません。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "インデックス シグネチャのパラメーターには型の注釈が必要です。", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "インデックス シグネチャのパラメーターの型は 'string' または 'number' でなければなりません。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "インターフェイスが拡張するのは、オプションの型引数が指定された識別子/完全修飾名のみです。", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "インターフェイスで拡張できるのは、クラスまたは他のインターフェイスのみです。", + "An_interface_property_cannot_have_an_initializer_1246": "インターフェイス プロパティに初期化子を使用することはできません。", + "An_iterator_must_have_a_next_method_2489": "反復子には 'next()' メソッドが必要です。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "オブジェクト リテラルに同じ名前の複数の get/set アクセサーを指定することはできません。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "厳格モードでは、オブジェクト リテラルに同じ名前の複数のプロパティを指定することはできません。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "オブジェクト リテラルには、同じ名前のプロパティおよびアクセサーを指定することはできません。", + "An_object_member_cannot_be_declared_optional_1162": "オブジェクト メンバーを省略可能として宣言することはできません。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "オーバーロード シグネチャをジェネレーターとして宣言することはできません。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "累乗式の左辺で '{0}' 演算子を含む単項式を使用することはできません。式を括弧で囲むことを検討してください。", + "Annotate_with_type_from_JSDoc_95009": "JSDoc の型で注釈を付けます", + "Annotate_with_types_from_JSDoc_95010": "JSDoc の型で注釈を付けます", + "Argument_expression_expected_1135": "引数式が必要です。", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' オプションの引数は {1} である必要があります。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "型 '{0}' の引数を型 '{1}' のパラメーターに割り当てることはできません。", + "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' 修飾子を使用する必要があります。", + "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}' は、クラス型またはインターフェイス型ではありません。", + "Base_constructors_must_all_have_the_same_return_type_2510": "既定コンストラクターの戻り値の型は、すべて同じである必要があります。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "相対モジュール名を解決するためのベース ディレクトリ。", + "Basic_Options_6172": "基本オプション", + "Binary_digit_expected_1177": "2 進の数字が必要です。", + "Binding_element_0_implicitly_has_an_1_type_7031": "バインド要素 '{0}' には暗黙的に '{1}' 型が含まれます。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "ブロック スコープの変数 '{0}' が、宣言の前に使用されています。", + "Call_decorator_expression_90028": "デコレーター式を呼び出します。", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "戻り値の型の注釈がない呼び出しシグネチャの戻り値の型は、暗黙的に 'any' になります。", + "Call_target_does_not_contain_any_signatures_2346": "呼び出しターゲットにシグネチャが含まれていません。", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}.{1}' にアクセスできません。'{0}' は型で、名前空間ではありません。'{0}[\"{1}\"]' で '{0}' のプロパティ '{1}' の型を取得するつもりでしたか?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' コンストラクター型を '{1}' コンストラクター型に割り当てることができません。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "抽象コンストラクター型を非抽象コンストラクター型に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "定数または読み取り専用プロパティであるため、'{0}' に割り当てられません。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "変数ではないため、'{0}' に割り当てられません。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "モジュール '{0}' は、モジュール以外のエンティティに解決するので拡張できません。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "モジュール '{0}' は、モジュール以外のエンティティに解決するため、値のエクスポートで拡張できません。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' フラグが 'amd' か 'system' でない限り、オプション '{0}' を使用してモジュールをコンパイルできません。", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "'--isolatedModules' フラグが指定されていると、名前空間をコンパイルできません。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "抽象クラスのインスタンスは作成できません。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}' をエクスポートできません。モジュールからエクスポートできるのはローカル宣言のみです。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "クラス '{0}' を拡張できません。Class コンストラクターがプライベートに設定されています。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "インターフェイス '{0}' を拡張できません。'implements' ですか?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "指定されたディレクトリに tsconfig.json ファイルが見つかりません: '{0}'。", + "Cannot_find_global_type_0_2318": "グローバル型 '{0}' が見つかりません。", + "Cannot_find_global_value_0_2468": "グローバル値 '{0}' が見つかりません。", + "Cannot_find_module_0_2307": "モジュール '{0}' が見つかりません。", + "Cannot_find_name_0_2304": "名前 '{0}' が見つかりません。", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' という名前は見つかりません。'{1}' ですか?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "名前 '{0}' が見つかりません。インスタンス メンバー 'this.{0}' ですか?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "名前 '{0}' が見つかりません。静的メンバー '{1}.{0}' ですか?", + "Cannot_find_namespace_0_2503": "名前空間 '{0}' が見つかりません。", + "Cannot_find_parameter_0_1225": "パラメーター '{0}' が見つかりません。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "入力ファイルの共通サブディレクトリ パスが見つかりません。", + "Cannot_find_type_definition_file_for_0_2688": "'{0}' の型定義ファイルが見つかりません。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "型宣言ファイルをインポートできません。'{1}' の代わりに '{0}' をインポートすることを検討してください。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "ブロック スコープ宣言 '{1}' と同じスコープ内の外部スコープ変数 '{0}' を初期化できません。", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "型に呼び出しシグネチャがない式を呼び出すことはできません。型 '{0}' には互換性のある呼び出しシグネチャがありません。", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "0'--isolatedModules' フラグが指定されている場合、型を再エクスポートできません。", + "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", + "Cannot_redeclare_exported_variable_0_2323": "エクスポートされた変数 '{0}' を再び宣言できません。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "catch 句で識別子 '{0}' を再宣言することはできません。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' フラグが指定されていないと、JSX を使用できません。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module' が 'none' である場合、インポート、エクスポート、モジュール拡張は使用できません。", + "Cannot_use_namespace_0_as_a_type_2709": "名前空間 '{0}' を型として使用することはできません。", + "Cannot_use_namespace_0_as_a_value_2708": "名前空間 '{0}' を値として使用することはできません。", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "呼び出しシグネチャまたはコンストラクト シグネチャがない型が含まれる式では 'new' は使用できません。", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "複数の入力ファイルで上書きされることになるため、ファイル '{0}' を書き込めません。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "入力ファイルを上書きすることになるため、ファイル '{0}' を書き込めません。", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "catch 句の変数に型の注釈を指定することはできません。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "catch 句の変数に初期化子を指定することはできません。", + "Change_0_to_1_90014": "'{0}' を '{1}' に変更します。", + "Change_extends_to_implements_90003": "'extends' を 'implements' に変更します。", + "Change_spelling_to_0_90022": "スペルを '{0}' に変更してください。", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' が '{1}' - '{2}' の最長一致のプレフィックスであるかを確認しています。", + "Circular_definition_of_import_alias_0_2303": "インポート エイリアス '{0}' の循環定義です。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "構成: {0} の解決中に循環が検出されました", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "クラス '{0}' で定義されたインスタンス メンバー アクセサー '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "クラス '{0}' で定義されたインスタンス メンバー関数 '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー アクセサーとして定義されています。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "クラス '{0}' で定義されたインスタンス メンバー関数 '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー プロパティとして定義されています。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "クラス '{0}' で定義されたインスタンス メンバー プロパティ '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", + "Class_0_incorrectly_extends_base_class_1_2415": "クラス '{0}' は基底クラス '{1}' を正しく拡張していません。", + "Class_0_incorrectly_implements_interface_1_2420": "クラス '{0}' はインターフェイス '{1}' を正しく実装していません。", + "Class_0_used_before_its_declaration_2449": "クラス '{0}' は宣言の前に使用されました。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "クラス宣言で複数の '@augments' または `@extends` タグを使用することはできません。", + "Class_name_cannot_be_0_2414": "クラス名を '{0}' にすることはできません。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "クラス側の静的な '{0}' が基底クラス側の静的な '{1}' を正しく拡張していません。", + "Classes_can_only_extend_a_single_class_1174": "クラスで拡張できるクラスは 1 つのみです。", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "抽象メソッドを含むクラスは abstract に指定する必要があります。", + "Command_line_Options_6171": "コマンド ライン オプション", + "Compilation_complete_Watching_for_file_changes_6042": "コンパイルが完了しました。ファイルの変更を監視しています。", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", + "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", + "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙では使用できません。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙では、計算値は許可されません。", + "Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{0}' の定義が '{1}' および '{2}' で競合しています。競合を解決するには、このライブラリの特定バージョンのインストールをご検討ください。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "戻り値の型の注釈がないコンストラクト シグネチャの戻り値の型は、暗黙的に 'any' になります。", + "Constructor_implementation_is_missing_2390": "コンストラクターの実装がありません。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "クラス '{0}' のコンストラクターはプライベートであり、クラス宣言内でのみアクセス可能です。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "クラス '{0}' のコンストラクターは保護されており、クラス宣言内でのみアクセス可能です。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生クラスのコンストラクターには 'super' の呼び出しを含める必要があります。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", + "Convert_function_0_to_class_95002": "関数 '{0}' をクラスに変換します", + "Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します", + "Convert_to_default_import_95013": "既定のインポートに変換する", + "Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "モジュール '{0}' の宣言ファイルが見つかりませんでした。'{1}' は暗黙的に 'any' 型になります。", + "Could_not_write_file_0_Colon_1_5033": "ファイル '{0}' を書き込めませんでした: '{1}'。", + "DIRECTORY_6038": "ディレクトリ", + "Declaration_expected_1146": "宣言が必要です。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣言名が組み込みのグローバル識別子 '{0}' と競合しています。", + "Declaration_or_statement_expected_1128": "宣言またはステートメントが必要です。", + "Declare_method_0_90023": "メソッド '{0}' を宣言します。", + "Declare_property_0_90016": "プロパティ '{0}' を宣言します。", + "Declare_static_method_0_90024": "静的メソッド '{0}' を宣言します。", + "Declare_static_property_0_90027": "静的プロパティ '{0}' を宣言します。", + "Decorators_are_not_valid_here_1206": "デコレーターはここでは無効です。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "デコレーターを同じ名前の複数の get/set アクセサーに適用することはできません。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "モジュールの既定エクスポートがプライベート名 '{0}' を使用しています。", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[非推奨] 代わりに '--jsxFactory' を使います。'react' JSX 発行を対象とするときに、createElement に対して呼び出されたオブジェクトを指定します", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[非推奨] 代わりに '--outFile' を使います。出力を連結して 1 つのファイルを生成します", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[非推奨] 代わりに '--skipLibCheck' を使います。既定のライブラリ宣言ファイルの型チェックをスキップします。", + "Digit_expected_1124": "数値が必要です", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "ディレクトリ '{0}' は存在していません。ディレクトリ内のすべての参照をスキップしています。", + "Disable_checking_for_this_file_90018": "このファイルのチェックを無効にします。", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript プロジェクトのサイズ制限を無効にします。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "関数型の汎用シグネチャに対する厳密なチェックを無効にします。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "同じファイルへの大文字小文字の異なる参照を許可しない。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "トリプルスラッシュの参照やインポートしたモジュールをコンパイルされたファイルのリストに追加しないでください。", + "Do_not_emit_comments_to_output_6009": "コメントを出力しないでください。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' の注釈を含むコードの宣言を生成しないでください。", + "Do_not_emit_outputs_6010": "出力しないでください。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "エラーが報告される場合は、出力しないでください。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "モジュール出力で 'use strict' ディレクティブを生成しません。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "生成されたコード内で const enum 宣言を消去しないでください。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "コンパイルされた出力で '__extends' などのカスタム ヘルパー関数を生成しないでください。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "既定のライブラリ ファイル (lib.d.ts) を含めないでください。", + "Do_not_report_errors_on_unreachable_code_6077": "到達できないコードに関するエラーを報告しない。", + "Do_not_report_errors_on_unused_labels_6074": "未使用のラベルに関するエラーを報告しない。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "symlink の実際のパスを解決しません。", + "Do_not_truncate_error_messages_6165": "エラー メッセージを切り捨てないでください。", + "Duplicate_declaration_0_2718": "宣言 '{0}' が重複しています。", + "Duplicate_function_implementation_2393": "関数の実装が重複しています。", + "Duplicate_identifier_0_2300": "識別子 '{0}' が重複しています。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "識別子 '{0}' が重複しています。コンパイラは、モジュールの最上位のスコープに名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "識別子 '{0}' が重複しています。コンパイラは非同期関数を含むモジュールの最上位のスコープに名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "識別子 '{0}' が重複しています。コンパイラは宣言 '{1}' を使用して非同期関数をサポートします。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "識別子 'arguments' が重複しています。コンパイラは 'arguments' を使用して rest パラメーターを初期化します。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "識別子 '_newTarget' が重複しています。コンパイラは変数宣言 '_newTarget' を使用して、'new.target' メタプロパティの参照をキャプチャします。", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "識別子 '_super' が重複しています。コンパイラは '_super' を使用して基底クラスの参照をキャプチャします。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "識別子 '_this' が重複しています。コンパイラは変数宣言 '_this' を使用して '_this' の参照をキャプチャします。", + "Duplicate_label_0_1114": "ラベル '{0}' が重複しています。", + "Duplicate_number_index_signature_2375": "number インデックス シグネチャが重複しています。", + "Duplicate_string_index_signature_2374": "string インデックス シグネチャが重複しています。", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 モジュールを対象とする場合、動的インポートを使用することはできません。", + "Dynamic_import_cannot_have_type_arguments_1326": "動的インポートには型引数を指定することはできません", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動的インポートには、引数として 1 つの指定子を指定する必要があります。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動的インポートの指定子の型は 'string' である必要がありますが、ここでは型 '{0}' が指定されています。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "インデックス式が型 'number' ではないため、要素に 'any' 型が暗黙的に指定されます。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "型 '{0}' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "出力ファイルの最初に UTF-8 バイト順マーク(BOM) を生成します。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", + "Enable_all_strict_type_checking_options_6180": "strict 型チェックのオプションをすべて有効にします。", + "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", + "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", + "Enable_tracing_of_the_name_resolution_process_6085": "名前解決の処理のトレースを有効にします。", + "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 非同期関数用の実験的なサポートを有効にします。", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 デコレーター用の実験的なサポートを有効にします。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "デコレーター用の型メタデータを発行するための実験的なサポートを有効にします。", + "Enum_0_used_before_its_declaration_2450": "列挙型 '{0}' は宣言の前に使用されました。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "enum 宣言は、すべてが定数、またはすべてが非定数でなければなりません。", + "Enum_member_expected_1132": "列挙型メンバーが必要です。", + "Enum_member_must_have_initializer_1061": "列挙メンバーには初期化子が必要です。", + "Enum_name_cannot_be_0_2431": "列挙型の名前を '{0}' にすることはできません。", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "列挙型 '{0}' に、リテラルではない初期化子を持つメンバーがあります。", + "Examples_Colon_0_6026": "例: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "型 '{0}' と '{1}' を比較するスタックが深すぎます。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} 型の引数が必要です。'@extends' タグで指定してください。", + "Expected_0_arguments_but_got_1_2554": "{0} 個の引数が必要ですが、{1} 個指定されました。", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} 個の引数が必要ですが、{1} 個以上指定されました。", + "Expected_0_type_arguments_but_got_1_2558": "{0} 個の型引数が必要ですが、{1} 個が指定されました。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} 型の引数が必要です。'@extends' タグで指定してください。", + "Expected_at_least_0_arguments_but_got_1_2555": "最低でも {0} 個の引数が必要ですが、{1} 個指定されました。", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "最低でも {0} 個の引数が必要ですが、{1} 個以上指定されました。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' の対応する JSX 終了タグが必要です。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX フラグメントの対応する終了タグが必要です。", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "'package.json' の '{0}' フィールドの型は 'string' であるべきですが、'{1}' を取得しました。", + "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_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}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "エクスポートされた外部パッケージの型指定のファイルにトリプルスラッシュ参照を含めることはできません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "エクスポートされた型のエイリアス '{0}' にプライベート名 '{1}' が付いているか、その名前を使用しています。", + "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": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。", + "Expression_expected_1109": "式が必要です。", + "Expression_or_comma_expected_1137": "式またはコンマが必要です。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "式は、コンパイラが非同期関数をサポートするために使用する変数宣言 '{0}' に解決されます。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "式は、コンパイラが 'new.target' メタプロパティの参照をキャプチャするために使用する変数宣言 '_newTarget' に解決されます。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "式は、コンパイラが 'this' の参照をキャプチャするために使用する変数宣言 '_this' に解決されます。", + "Extract_constant_95006": "定数の抽出", + "Extract_function_95005": "関数の抽出", + "Extract_symbol_95003": "シンボルの抽出", + "Extract_to_0_in_1_95004": "{1} 内の {0} に抽出する", + "Extract_to_0_in_1_scope_95008": "{1} スコープ内の {0} に抽出する", + "Extract_to_0_in_enclosing_scope_95007": "外側のスコープ内の {0} に抽出する", + "FILE_6035": "ファイル", + "FILE_OR_DIRECTORY_6040": "ファイルまたはディレクトリ", + "Failed_to_parse_file_0_Colon_1_5014": "ファイル '{0}' を解析できませんでした。{1}。", + "Fallthrough_case_in_switch_7029": "switch に case のフォールスルーがあります。", + "File_0_does_not_exist_6096": "ファイル '{0}' が存在しません。", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "ファイル '{0}' が存在します。名前解決の結果として使用します。", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "ファイル '{0}' にはサポートされていない拡張機能があるため、スキップしています。", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "ファイル '{0}' はサポートされていない拡張子を含んでいます。サポートされている拡張子は {1} のみです。", + "File_0_is_not_a_module_2306": "ファイル '{0}' はモジュールではありません。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "ファイル '{0}' が 'rootDir' '{1}' の下にありません。'rootDir' にすべてにソース ファイルが含まれている必要があります。", + "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", + "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "ファイル名 '{0}' は、既に含まれているファイル名 '{1}' と大文字と小文字の指定だけが異なります。", + "File_name_0_has_a_1_extension_stripping_it_6132": "ファイル名 '{0}' に '{1}' 拡張子が使われています - 削除しています。", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "ファイルの指定で再帰ディレクトリのワイルドカード ('**') の後に親ディレクトリ ('..') を指定することはできません: '{0}'。", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "ファイルの指定に複数の再帰的なディレクトリのワイルドカード ('**') を含めることはできません: '{0}'。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "ファイルの指定の末尾を再帰的なディレクトリのワイルドカード ('**') にすることはできません: '{0}'。", + "Found_package_json_at_0_6099": "'{0}' で 'package.json' が見つかりました。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。クラス定義は自動的に厳格モードになります。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。モジュールは自動的に厳格モードになります。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "戻り値の型の注釈がない関数式の戻り値の型は、暗黙的に '{0}' になります。", + "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": "関数は、戻り値の型の注釈がなく、いずれかの return 式で直接的にまたは間接的に参照されているため、戻り値の型は暗黙的に 'any' になります。", + "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": "関数のオーバーロードは静的にはできせん。", + "Generates_corresponding_d_ts_file_6002": "対応する '.d.ts' ファイルを生成します。", + "Generates_corresponding_map_file_6043": "対応する '.map' ファイルを生成します。", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "ジェネレーターは値を生成しないため、暗黙的に型 '{0}' になります。戻り値の型を指定することを検討してください。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "ジェネレーターは環境コンテキストでは使用できません。", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "ジェネレーターは、ECMAScript 2015 以上を対象にする場合のみ使用できます。", + "Generic_type_0_requires_1_type_argument_s_2314": "ジェネリック型 '{0}' には {1} 個の型引数が必要です。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "ジェネリック型 '{0}' には、{1} 個から {2} 個までの型引数が必要です。", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "ジェネリック型のインスタンス化は非常に深く、無限である可能性があります。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "ゲッターおよびセッターで表示が許可されていません。", + "Global_module_exports_may_only_appear_at_top_level_1316": "グローバル モジュールのエクスポートは最上位レベルにのみ出現可能です。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "グローバル モジュールのエクスポートは宣言ファイルにのみ出現可能です。", + "Global_module_exports_may_only_appear_in_module_files_1314": "グローバル モジュールのエクスポートはモジュール ファイルにのみ出現可能です。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "グローバル型 '{0}' はクラス型またはインターフェイス型でなければなりません。", + "Global_type_0_must_have_1_type_parameter_s_2317": "グローバル型 '{0}' には {1} 個の型パラメーターが必要です。", + "Hexadecimal_digit_expected_1125": "16 進の数字が必要です。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "識別子が必要です。'{0}' は厳格モードの予約語です。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "識別子が必要です。'{0}' は厳格モードの予約語です。クラス定義は自動的に厳格モードになります。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "識別子が必要です。'{0}' は、厳格モードの予約語です。モジュールは自動的に厳格モードになります。", + "Identifier_expected_1003": "識別子が必要です。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "識別子が必要です。'__esModule' は、ECMAScript モジュールを変換するときのエクスポート済みマーカーとして予約されています。", + "Ignore_this_error_message_90019": "このエラー メッセージを無視します。", + "Implement_inherited_abstract_class_90007": "継承抽象クラスを実装します。", + "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_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": "名前空間内のインポート宣言は、モジュールを参照できません。", + "Import_emit_helpers_from_tslib_6139": "生成ヘルパーを 'tslib' からインポートします。", + "Import_name_cannot_be_0_2438": "インポート名を '{0}' にすることはできません。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "アンビエント モジュール宣言内のインポート宣言またはエクスポート宣言は、相対モジュール名を通してモジュールを参照することはできません。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "インポートはモジュールの拡張では許可されていません。外側の外部モジュールに移動することを検討してください。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 列挙型の宣言で、メンバー初期化子は定数式でなければなりません。", + "Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。", + "Index_signature_is_missing_in_type_0_2329": "型 '{0}' のインデックス シグネチャがありません。", + "Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "マージされた宣言 '{0}' の個々の宣言はすべてエクスポートされるか、すべてローカルであるかのどちらかである必要があります。", + "Infer_parameter_types_from_usage_95012": "使用状況からパラメーターの型を推論します。", + "Infer_type_of_0_from_usage_95011": "使用状況から型 '{0}' を推論します。", + "Initialize_property_0_in_the_constructor_90020": "コンストラクターのプロパティ '{0}' を初期化します。", + "Initialize_static_property_0_90021": "静的プロパティ '{0}' を初期化します。", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "インスタンス メンバー変数 '{0}' の初期化子はコンストラクターで宣言された識別子 '{1}' を参照できません。", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "パラメーター '{0}' の初期化子はその後で宣言された識別子 '{1}' を参照できません。", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初期化子にこのバインド要素の値が提示されていません。またバインド要素に既定値がありません。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "初期化子は環境コンテキストでは使用できません。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript プロジェクトを初期化して、tsconfig.json ファイルを作成します。", + "Insert_command_line_options_and_files_from_a_file_6030": "コマンド ライン オプションとファイルをファイルから挿入します。", + "Install_0_95014": "'{0}' のインストール", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "インターフェイス '{0}' で型 '{1}' と型 '{2}' を同時には拡張できません。", + "Interface_0_incorrectly_extends_interface_1_2430": "インターフェイス '{0}' はインターフェイス '{1}' を正しく拡張していません。", + "Interface_declaration_cannot_have_implements_clause_1176": "インターフェイス宣言に 'implements' 句を指定することはできません。", + "Interface_name_cannot_be_0_2427": "インターフェイス名を '{0}' にすることはできません。", + "Invalid_character_1127": "無効な文字です。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "拡張のモジュール名が無効です。モジュール '{0}' は '{1}' の型指定のないモジュールに解決されるため、拡張されません。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "拡張のモジュール名が無効です。モジュール '{0}' が見つかりません。", + "Invalid_reference_directive_syntax_1084": "無効な 'reference' ディレクティブ構文です。", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "'{0}' の使用が無効です。クラス定義は自動的に厳格モードになります。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' の使用方法が無効です。モジュールは自動的に厳格モードになります。", + "Invalid_use_of_0_in_strict_mode_1100": "厳格モードでは '{0}' の使用は無効です。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' の値が無効です。'{0}' が有効な識別子または修飾名ではありません。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' の値が無効です。'{0}' は有効な識別子ではありません。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' が 'extends {2}' 句と一致しません。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' はクラスにアタッチされていません。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' は、シグネチャの最後のパラメーターにのみ使用できます。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' タグの名前は '{0}' ですが、その名前のパラメーターはありません。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' タグには、型の注釈を指定するか、後に '@property' タグや '@member' タグを付ける必要があります。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc の種類は、ドキュメント コメント内でのみ使用できます。", + "JSX_attribute_expected_17003": "JSX 属性が必要です。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 属性は、空ではない '式' にのみ割り当てる必要があります。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 要素 '{0}' には対応する終了タグがありません。", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 要素属性の型 '{0}' は共用体型ではありません。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 要素クラスは '{0}' プロパティを含まないため、属性をサポートしません。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "インターフェイス 'JSX.{0}' が存在しないため、暗黙的に JSX 要素の型は 'any' になります。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "グローバル型 'JSX.Element' が存在しないため、JSX 要素は暗黙的に型 'any' になります。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 要素型 '{0}' にはコンストラクトも呼び出しシグネチャも含まれていません。", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 要素型 '{0}' は JSX 要素のコンストラクター関数ではありません。", + "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_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません", + "JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。", + "Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。", + "KIND_6034": "種類", + "LOCATION_6037": "場所", + "Language_service_is_disabled_9004": "言語サービスが無効になっています。", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "コンマ演算子の左側が使用されていないため、副作用はありません。", + "Line_break_not_permitted_here_1142": "ここで改行することはできません。", + "Line_terminator_not_permitted_before_arrow_1200": "行の終端記号をアローの前で使用することはできません。", + "List_of_folders_to_include_type_definitions_from_6161": "含める型定義の元のフォルダーの一覧。", + "List_of_language_service_plugins_6181": "言語サービス プラグインの一覧。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "結合されたコンテンツがランタイムでのプロジェクトの構成を表すルート フォルダーの一覧。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "ルート ディレクトリ '{1}' から '{0}' を読み込んでいます。候補の場所は '{2}' です。", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' フォルダーからモジュール '{0}' を読み込んでいます。対象のファイルの種類は '{1}' です。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "ファイル / フォルダーとしてモジュールを読み込んでいます。候補のモジュールの場所は '{0}'、対象のファイルの種類は '{1}' です。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "ロケールは または - の形式で指定する必要があります (例: '{0}'、'{1}')。", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}' の一致する最長プレフィックスは '{1}' です。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' フォルダーを検索しています。最初の場所は '{0}' です。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにします。", + "Member_0_implicitly_has_an_1_type_7008": "メンバー '{0}' の型は暗黙的に '{1}' になります。", + "Merge_conflict_marker_encountered_1185": "マージ競合マーカーが検出されました。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "マージされた宣言 '{0}' に既定のエクスポート宣言を含めることはできません。代わりに、'export default {0}' 宣言を別個に追加することを検討してください。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "メタプロパティ '{0}' は、関数の宣言の本文、関数の式、またはコンストラクターでのみ許可されています。", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "メソッド '{0}' は abstract に指定されているため、実装を含めることができません。", + "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": "ここで修飾子を使用することはできません。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "モジュール {0} は既に '{1}' という名前のメンバーをエクスポートしています。あいまいさを解決するため、明示的にもう一度エクスポートすることを検討してください。", + "Module_0_has_no_default_export_1192": "モジュール '{0}' に既定エクスポートがありません。", + "Module_0_has_no_exported_member_1_2305": "モジュール '{0}' にエクスポートされたメンバー '{1}' がありません。", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "モジュール '{0}' は同じ名前のローカル宣言によって非表示になっています。", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "モジュール '{0}' はモジュール以外のエンティティに解決されるため、このコンストラクトを使用してインポートできません。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "モジュール '{0}' には 'export =' が使用されているため、'export *' は併用できません。", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "このファイルが変更されなかったため、モジュール '{0}' は '{1}' で宣言されたアンビエント モジュールとして解決されました。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "モジュール '{0}' は、ファイル '{1}' のローカルで宣言されたアンビエント モジュールとして解決されました。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "モジュール '{0}' は '{1}' に解決されましたが、'--jsx' が設定されていません。", + "Module_Resolution_Options_6174": "モジュール解決のオプション", + "Module_name_0_matched_pattern_1_6092": "モジュール名 '{0}'、照合されたパターン '{1}'。", + "Module_name_0_was_not_resolved_6090": "======== モジュール名 '{0}' が解決されませんでした。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。", + "Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。", + "NEWLINE_6061": "改行", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' 型および '{2}' 型の名前付きプロパティ '{0}' が一致しません。", + "Namespace_0_has_no_exported_member_1_2694": "名前空間 '{0}' にエクスポートされたメンバー '{1}' がありません。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "指定した数の型引数を持つ基底コンストラクターは存在しません。", + "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}' はクラス '{2}' からの継承抽象メンバー '{1}' を実装しません。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象クラスの式はクラス '{1}' からの継承抽象メンバー '{0}' を実装しません。", + "Not_all_code_paths_return_a_value_7030": "一部のコード パスは値を返しません。", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "数値インデックス型 '{0}' を文字列インデックス型 '{1}' に割り当てることはできません。", + "Object_is_possibly_null_2531": "オブジェクトは 'null' である可能性があります。", + "Object_is_possibly_null_or_undefined_2533": "オブジェクトは 'null' か 'undefined' である可能性があります。", + "Object_is_possibly_undefined_2532": "オブジェクトは 'undefined' である可能性があります。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "オブジェクト リテラルは既知のプロパティのみ指定できます。'{0}' は型 '{1}' に存在しません。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "オブジェクト リテラルで指定できるのは既知のプロパティのみですが、'{0}' は型 '{1}' に存在しません。書こうとしたのは '{2}' ですか?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "オブジェクト リテラルのプロパティ '{0}' の型は暗黙的に '{1}' になります。", + "Octal_digit_expected_1178": "8 進の数字が必要です。", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "8 進数のリテラル型には、ES2015 構文を使用する必要があります。構文 '{0}' を使用してください。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8 進数のリテラルは、列挙メンバーの初期化子では許可されていません。構文 '{0}' を使用してください。", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "厳格モードでは Octal リテラルは使用できません。", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 以降を対象にする場合、8 進数のリテラルは使用できません。構文 '{0}' を使用してください。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' ステートメントで使用できる変数宣言は 1 つのみです。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' ステートメントで使用できる変数宣言は 1 つのみです。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' キーワードを指定して呼び出せるのは void 関数のみです。", + "Only_ambient_modules_can_use_quoted_names_1035": "引用符付きの名前を使用できるのはアンビエント モジュールのみです。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} と共にサポートされるのは 'amd' モジュールと 'system' モジュールのみです。", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "クラス 'extends' 句で現在サポートされているのは、オプションの型引数が指定された ID/完全修飾名のみです。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' キーワードを使用してアクセスできるのは、基底クラスのパブリック メソッドと保護されたメソッドのみです。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "演算子 '{0}' を型 '{1}' および '{2}' に適用することはできません。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "オプション '{0}' は 'tsconfig.json' ファイルにのみ指定できます。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "オプション '{0} を使用できるのは、オプション '--inlineSourceMap' またはオプション '--sourceMap' のいずれかを指定した場合のみです。", + "Option_0_cannot_be_specified_with_option_1_5053": "オプション '{0}' をオプション '{1}' とともに指定することはできません。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "オプション '{1}' を指定せずに、オプション '{0}' を指定することはできません。", + "Option_0_should_have_array_of_strings_as_a_value_6103": "オプション '{0}' には、値として文字列の配列を指定する必要があります。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "オプション 'isolatedModules' は、オプション '--module' が指定されているか、オプション 'target' が 'ES2015' 以上であるかのいずれかの場合でのみ使用できます。", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "オプション 'paths' は、'--baseUrl' オプションを指定せずに使用できません。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "オプション 'project' をコマンド ライン上でソース ファイルと一緒に指定することはできません。", + "Options_Colon_6027": "オプション:", + "Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "オーバーロード シグネチャは関数の実装に対応していません。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "オーバーロードのシグネチャはすべてがエクスポート済みであるか、またはエクスポート済みでない必要があります。", + "Overload_signatures_must_all_be_optional_or_required_2386": "オーバーロードのシグネチャは、すべて省略可能であるか、すべて必須であるかのどちらかである必要があります。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "オーバーロードのシグネチャはすべて、public、private、または protected でなければなりません。", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "パラメーター '{0}' はその初期化子内では参照できません。", + "Parameter_0_implicitly_has_an_1_type_7006": "パラメーター '{0}' の型は暗黙的に '{1}' になります。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "パラメーター '{0}' がパラメーター '{1}' と同じ位置にありません。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' がプライベート名 '{1}' を使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "エクスポートされた関数のパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "エクスポートされた関数のパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "エクスポートされた関数のパラメーター '{0}' がプライベート名 '{1}' を使用しています。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート モジュール '{2}' の名前 '{1}' が指定されているか使用されています。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート名 '{1}' が指定されているか使用されています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' がプライベート名 '{1}' を使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' がプライベート名 '{1}' を使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "パラメーターに疑問符および初期化子を指定することはできません。", + "Parameter_declaration_expected_1138": "パラメーター宣言が必要です。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート名 '{1}' を使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート名 '{1}' を使用しています。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "厳格モードで解析してソース ファイルごとに \"use strict\" を生成します。", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "パターン '{0}' に使用できる '*' 文字は最大で 1 つです。", + "Prefix_0_with_an_underscore_90025": "アンダースコアを含むプレフィックス '{0}'。", + "Print_names_of_files_part_of_the_compilation_6155": "コンパイルの一環としてファイルの名前を書き出します。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。", + "Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。", + "Print_this_message_6017": "このメッセージを表示します。", + "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙 '{1}' に存在しません。", + "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "プロパティ '{0}' は型 '{1}' に存在していません。'{2}' ですか?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "プロパティ '{0}' には競合する宣言があり、型 '{1}' ではアクセスできません。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。set アクセサーにはパラメーター型の注釈がないためです。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "型 '{1}' のプロパティ '{0}' を型 '{2}' に割り当てることはできません。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "プロパティ '{0}' が宣言されていますが、その値が読み取られることはありません。", + "Property_0_is_incompatible_with_index_signature_2530": "プロパティ '{0}' はインデックス シグネチャと互換性がありません。", + "Property_0_is_missing_in_type_1_2324": "型 '{1}' にプロパティ '{0}' がありません。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "プロパティ '{0}' は型 '{1}' では省略可能ですが、型 '{2}' では必須です。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "プロパティ '{0}' はプライベートで、クラス '{1}' 内でのみアクセスできます。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "プロパティ '{0}' は型 '{1}' ではプライベートですが、型 '{2}' ではプライベートではありません。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "プロパティ '{0}' は保護されているため、クラス '{1}' のインスタンス経由でのみアクセスできます。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "プロパティ '{0}' は保護されているため、クラス '{1}' とそのサブクラス内でのみアクセスできます。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "プロパティ '{0}' は保護されていますが、型 '{1}' は '{2}' から派生したクラスではありません。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "プロパティ '{0}' は型 '{1}' では保護されていますが、型 '{2}' ではパブリックです。", + "Property_0_is_used_before_being_assigned_2565": "プロパティ '{0}' は割り当てられる前に使用されています。", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX のスプレッド属性のプロパティ '{0}' をターゲット プロパティに割り当てることはできません。", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "エクスポートされたクラスの式のプロパティ '{0}' が private または protected でない可能性があります。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "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_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'、オブジェクト リテラルまたは配列リテラルのみ使用できます。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'for-of' の iterable、spread、'ES5' や 'ES3' をターゲットとする場合は destructuring に対してフル サポートを提供します。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "エクスポートされたクラスのパブリック メソッド '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "エクスポートされたクラスのパブリック メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "エクスポートされたクラスのパブリック メソッド '{0}' がプライベート名 '{1}' を使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "エクスポートされたクラスのパブリック プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート名 '{1}' を使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "エクスポートされたクラスのパブリック静的メソッド '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート名 '{1}' を使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート名 '{1}' を使用しています。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", + "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", + "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除します: {0}。", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", + "Report_errors_in_js_files_8019": ".js ファイルのエラーを報告します。", + "Report_errors_on_unused_locals_6134": "使用されていないローカルに関するエラーを報告します。", + "Report_errors_on_unused_parameters_6135": "使用されていないパラメーターに関するエラーを報告します。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。", + "Resolution_for_module_0_was_found_in_cache_6147": "モジュール '{0}' の解決がキャッシュに見つかりました。", + "Resolving_from_node_modules_folder_6118": "node_modules フォルダーから解決しています...", + "Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。", + "Resolving_real_path_for_0_result_1_6130": "'{0}' の実際のパスを解決しています。結果は '{1}' です。", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイル '{1}'、ルート ディレクトリ '{2}'。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイル '{1}'、ルート ディレクトリは未設定。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイルは未設定、ルート ディレクトリ '{1}'。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイルは未設定、ルート ディレクトリは未設定。========", + "Resolving_using_primary_search_paths_6117": "プライマリ検索パスを使用して解決しています...", + "Resolving_with_primary_search_path_0_6121": "プライマリ検索パス '{0}' で解決しています。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest パラメーター '{0}' の型は暗黙的に 'any[]' になります。", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 型はオブジェクトの種類からのみ作成できます。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "コンストラクター シグネチャの戻り値の型は、クラスのインスタンス型に割り当て可能でなければなりません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "エクスポートされた関数の戻り値の型が外部モジュール {1} の名前 '{0}' を使用していますが、名前を指定することはできません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "エクスポートされた関数の戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "エクスポートされた関数の戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "エクスポートされたクラスのパブリック メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を使用していますが、名前を指定することはできません。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "'{0}' で生成されたモジュール解決は、前のプログラムから変更されていないため、再利用しています。", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "前のプログラムを再利用して、モジュール '{0}' をファイル '{1}' に解決しています。", + "Rewrite_as_the_indexed_access_type_0_90026": "インデックス化されたアクセスの種類 '{0}' として書き換えます。", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "ルート ディレクトリを決定できません。プライマリ検索パスをスキップします。", + "STRATEGY_6039": "戦略", + "Scoped_package_detected_looking_in_0_6182": "'{0}' 内を検索して、スコープ パッケージが検出されました", + "Setters_cannot_return_a_value_2408": "セッターは値を返せません。", + "Show_all_compiler_options_6169": "コンパイラ オプションをすべて表示します。", + "Show_diagnostic_information_6149": "診断情報を表示します。", + "Show_verbose_diagnostic_information_6150": "詳細な診断情報を表示します。", + "Signature_0_must_be_a_type_predicate_1224": "シグネチャ '{0}' は型の述語である必要があります。", + "Skip_type_checking_of_declaration_files_6012": "宣言ファイルの型チェックをスキップします。", + "Source_Map_Options_6175": "ソース マップ オプション", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "特殊化されたオーバーロード シグネチャは、特殊化されていないシグネチャに割り当てることはできません。", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "動的インポートの指定子にはスプレッド要素を指定できません。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript のターゲット バージョンを指定します: 'ES3' (既定)、'ES5'、'ES2015'、'ES2016'、'ES2017'、'ESNEXT'。", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX コード生成を指定します: 'preserve'、'react-native'、'react'。", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "コンパイルに含めるライブラリ ファイルを指定します: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "モジュール コード生成を指定します: 'none'、'commonjs'、'amd'、'system'、'umd'、'es2015'、'ESNext'。", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "モジュールの解決方法を指定します: 'node' (Node.js) または 'classic' (TypeScript pre-1.6)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'react' JSX 発行 ('React.createElement' や 'h') などを対象とするときに使用する JSX ファクトリ関数を指定します。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "ファイルの生成時に使用する行シーケンスの末尾を指定します: 'CRLF' (dos) または 'LF' (unix)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "デバッガーがソースの場所の代わりに TypeScript ファイルを検索する必要のある場所を指定します。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "デバッガーが、生成された場所の代わりにマップ ファイルを検索する必要のある場所を指定します。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "入力ファイルのルート ディレクトリを指定します。--outDir とともに、出力ディレクトリ構造の制御に使用します。", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 式のスプレッド演算子は ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 型はオブジェクトの種類からのみ作成できます。", + "Statement_expected_1129": "ステートメントが必要です。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "ステートメントは環境コンテキストでは使用できません。", + "Static_members_cannot_reference_class_type_parameters_2302": "静的メンバーはクラスの型パラメーターを参照できません。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "静的プロパティ '{0}' がコンストラクター関数 '{1}' のビルトイン プロパティ 'Function.{0}' と競合しています。", + "Strict_Type_Checking_Options_6173": "Strict 型チェック オプション", + "String_literal_expected_1141": "文字列リテラルが必要です。", + "String_literal_with_double_quotes_expected_1327": "二重引用符を含む文字列リテラルが必要です。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "色とコンテキストを使用してエラーとメッセージにスタイルを適用します (試験的)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後続の変数宣言は同じ型でなければなりません。変数 '{0}' の型は '{1}' である必要がありますが、'{2}' になっています。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "パターン '{1}' の代入 '{0}' の型が正しくありません。必要な型は 'string' ですが、'{2}' を取得しました。", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "パターン '{1}' の代入 '{0}' に使用できる '*' 文字は最大 1 つです。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "パターン '{0}' への代入は配列でなければなりません。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "パターン '{0}' への代入を空の配列にすることはできません。", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json ファイルが正常に作成されました。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "super の呼び出しは、コンストラクターの外部、またはコンストラクター内の入れ子になった関数では使用できません。", + "Suppress_excess_property_checks_for_object_literals_6072": "オブジェクト リテラルの過剰なプロパティ確認を抑制します。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "インデックス シグニチャのないオブジェクトにインデックスを作成するため、noImplicitAny エラーを抑制します。", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'Symbol' 参照は、グローバル シンボル コンストラクター オブジェクトを参照しません。", + "Syntax_Colon_0_6023": "構文: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 演算子を 'symbol' 型に適用することはできません。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' 演算子はブール型には使用できません。代わりに '{1}' を使用してください。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 型を割り当てることができるその他の型はごく少数です。代わりの候補には 'any' 型があります。", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "'arguments' オブジェクトは、ES3 および ES5 のアロー関数で参照することはできません。標準の関数式の使用を考慮してください。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "'arguments' オブジェクトは、ES3 および ES5 の非同期関数またはメソッドで参照することはできません。標準の関数またはメソッドを使用することを検討してください。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' ステートメントの本文を空のステートメントにすることはできません。", + "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_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' ステートメントの左側を非構造化パターンにすることはできません。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' ステートメントの左側で型の注釈を使用することはできません。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' ステートメントの左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' ステートメントの左側の型は 'string' または 'any' でなければなりません。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' ステートメントの左側で型の注釈を使用することはできません。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' ステートメントの左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "算術演算の左辺には、'any' 型、'number' 型、または列挙型を指定してください。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "代入式の左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' 式の左辺の型は 'any'、'string'、'number'、または 'symbol' でなければなりません。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 式の左辺には、'any' 型、オブジェクト型、または型パラメーターを指定してください。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "ユーザーにメッセージを表示するときに使用するロケール (例: 'en-us')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules の下を検索して JavaScript ファイルを読み込む依存関係の最大深度です。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "delete 演算子のオペランドを読み取り専用のプロパティにすることはできません。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "delete 演算子のオペランドはプロパティ参照でなければなりません。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "インクリメントまたはデクリメント演算子のオペランドは、変数またはプロパティ アクセスである必要があります。", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 要素コンストラクターの戻り値の型は、オブジェクト型を返す必要があります。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "パラメーター デコレーター関数の戻り値の型は、'void' か 'any' である必要があります。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "プロパティ デコレーター関数の戻り値の型は、'void' か 'any' である必要があります。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "非同期関数の戻り値の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "非同期関数または非同期メソッドの戻り値の型は、グローバル Promise 型である必要があります。", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "for...in' ステートメントの右辺には、'any' 型、オブジェクト型、または型パラメーターを指定してください。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "算術演算の右辺には、'any' 型、'number' 型、または列挙型を指定してください。", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 式の右辺は、'any' 型、オブジェクト型、型パラメーターでなければなりません。", + "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_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}' の型引数を使用法から推論することはできません。型引数を明示的に指定してください。", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "非同期反復子の 'next()' メソッドから返される型は、'value' プロパティを持つ型の Promise でなければなりません。", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "反復子の 'next()' メソッドによって返される型には 'value' プロパティが必要です。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' ステートメントの変数宣言に初期化子を指定することはできません。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' ステートメントの変数宣言に初期化子を指定することはできません。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ステートメントはサポートされていません。'with' ブロック内のすべてのシンボルの型は 'any' になります。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "この構文にはインポートされたヘルパーが必要ですが、モジュール '{0}' が見つかりません。", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "この構文には '{1}' という名前のインポートされたヘルパーが必要ですが、モジュール '{0}' にエクスポートされたメンバー '{1}' がありません。", + "Trailing_comma_not_allowed_1009": "末尾にコンマは使用できません。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "個々のモジュールとして各ファイルをトランスパイルします ('ts.transpileModule' に類似)。", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "`npm install @types/{0}` を試すか (存在する場合)、`declare module '{0}';` を含む新しい宣言 (.d.ts) ファイルを追加してください", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs' の他のエントリを試しています。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "代入 '{0}' を試しています。候補のモジュールの場所: '{1}'。", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "長さが '{1}' のタプル型 '{0}' を長さが '{2}' のタプルに割り当てることはできません。", + "Type_0_cannot_be_converted_to_type_1_2352": "型 '{0}' を型 '{1}' に変換できません。", + "Type_0_cannot_be_used_as_an_index_type_2538": "型 '{0}' はインデックスの型として使用できません。", + "Type_0_cannot_be_used_to_index_type_1_2536": "型 '{0}' はインデックスの種類 '{1}' に使用できません。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "型 '{0}' は制約 '{1}' を満たしていません。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "型 '{0}' には型 '{1}' と一致するインデックス シグネチャがありません。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "型 '{0}' には型 '{1}' と共通のプロパティがありません。", + "Type_0_has_no_property_1_2460": "型 '{0}' にプロパティ '{1}' がありません。", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "型 '{0}' にプロパティ '{1}' および string インデックス シグネチャがありません。", + "Type_0_is_not_a_constructor_function_type_2507": "型 '{0}' はコンストラクター関数型ではありません。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "型 '{0}' は Promise と互換性のあるコンストラクター値を参照しないため、ES5/ES3 において有効な非同期関数の戻り値の型ではありません。", + "Type_0_is_not_an_array_type_2461": "型 '{0}' は配列型ではありません。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "型 '{0}' は配列型でも文字列型でもありません。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "型 '{0}' は、配列型でも文字列型でもないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "型 '{0}' は、配列型ではないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", + "Type_0_is_not_assignable_to_type_1_2322": "型 '{0}' を型 '{1}' に割り当てることはできません。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "型 '{0}' は型 '{1}' に割り当てられません。同じ名前で 2 つの異なる型が存在しますが、これは関連していません。", + "Type_0_is_not_comparable_to_type_1_2678": "型 '{0}' は型 '{1}' と比較できません。", + "Type_0_is_not_generic_2315": "型 '{0}' はジェネリックではありません。", + "Type_0_provides_no_match_for_the_signature_1_2658": "型 '{0}' にはシグネチャ '{1}' に一致するものがありません。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "型 '{0}' が、基本型としてそれ自体を再帰的に参照しています。", + "Type_alias_0_circularly_references_itself_2456": "型のエイリアス '{0}' が自身を循環参照しています。", + "Type_alias_name_cannot_be_0_2457": "型のエイリアス名を '{0}' にすることはできません。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "型の注釈はコンストラクター宣言では使用できません。", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "型引数の候補 '{1}' は、候補 '{0}' のスーパータイプではないため、有効な型引数ではありません。", + "Type_argument_expected_1140": "型引数が必要です。", + "Type_argument_list_cannot_be_empty_1099": "型引数リストを空にすることはできません。", + "Type_declaration_files_to_be_included_in_compilation_6124": "コンパイルに含む型宣言ファイル。", + "Type_expected_1110": "型が必要です。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "型は、それ自身の 'then' メソッドのフルフィルメント コールバック内で直接または間接的に参照されます。", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "型には、非同期反復子を返す '[Symbol.asyncIterator]()' メソッドが必要です。", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "型には、反復子を返す '[Symbol.iterator]()' メソッドが必要です。", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' オペランドの反復要素の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同期ジェネレーター内の 'yield' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_parameter_0_has_a_circular_constraint_2313": "型パラメーター '{0}' に循環制約があります。", + "Type_parameter_0_has_a_circular_default_2716": "型パラメーター '{0}' に循環既定値があります。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "エクスポートされたインターフェイスの呼び出しシグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "エクスポートされたインターフェイスのコンストラクター シグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "エクスポートされたクラスの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "エクスポートされた関数の型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "エクスポートされたインターフェイスの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "エクスポートした型のエイリアスの型パラメーター '{0}' にプライベート名 '{1}' が指定されているか、これを使用しています。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "エクスポートされたインターフェイスのメソッドの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "エクスポートされたクラスのパブリック メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "エクスポートされたクラスのパブリック静的メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_declaration_expected_1139": "型パラメーターの宣言が必要です。", + "Type_parameter_list_cannot_be_empty_1098": "型パラメーター リストを空にすることはできません。", + "Type_parameter_name_cannot_be_0_2368": "型パラメーター名を '{0}' にすることはできません。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "型パラメーターはコンストラクター宣言では使用できません。", + "Type_predicate_0_is_not_assignable_to_1_1226": "型の述語 '{0}' を '{1}' に割り当てることはできません。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 型参照ディレクティブ '{0}' が解決されませんでした。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 型参照ディレクティブ '{0}' が正常に '{1}' に解決されました。プライマリ: {2}。========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "複数の型に、プライベート プロパティ '{0}' の異なる宣言が含まれています。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "パラメーター '{0}' および '{1}' は型に互換性がありません。", + "Types_of_property_0_are_incompatible_2326": "プロパティ '{0}' の型に互換性がありません。", + "Unable_to_open_file_0_6050": "ファイル '{0}' を開くことができません。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "式として呼び出される場合、クラス デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "式として呼び出される場合、メソッド デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "式として呼び出される場合、パラメーター デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "式として呼び出される場合、プロパティ デコレーターのシグネチャを解決できません。", + "Unexpected_end_of_text_1126": "予期しないテキストの末尾です。", + "Unexpected_token_1012": "予期しないトークンです。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "予期しないトークンです。コンストラクター、メソッド、アクセサー、またはプロパティが必要です。", + "Unexpected_token_expected_1179": "予期しないトークンです。'{' が必要です。", + "Unknown_compiler_option_0_5023": "コンパイラ オプション '{0}' が不明です。", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "不明なオプション 'excludes' です。'exclude' ですか?", + "Unknown_type_acquisition_option_0_17010": "不明な型の取得オプション '{0}'。", + "Unreachable_code_detected_7027": "到達できないコードが検出されました。", + "Unsupported_locale_0_6049": "ロケール '{0}' はサポートされていません。", + "Unterminated_Unicode_escape_sequence_1199": "未終了の Unicode エスケープ シーケンスです。", + "Unterminated_quoted_string_in_response_file_0_6045": "応答ファイル '{0}' の文字列の終了引用符がありません。", + "Unterminated_regular_expression_literal_1161": "未終了の正規表現リテラルです。", + "Unterminated_string_literal_1002": "未終了の文字列リテラルです。", + "Unterminated_template_literal_1160": "未終了のテンプレート リテラルです。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "型指定のない関数の呼び出しで型引数を使用することはできません。", + "Unused_label_7028": "未使用のラベル。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", + "VERSION_6036": "バージョン", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "型 '{0}' の値には、型 '{1}' と共通のプロパティがありません。呼び出しますか?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "型 '{0}' の値は呼び出せません。'new' を含めますか?", + "Variable_0_implicitly_has_an_1_type_7005": "変数 '{0}' の型は暗黙的に '{1}' になります。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "変数 '{0}' は、型を決定できない一部の場所では、暗黙のうちに '{1}' 型になります。", + "Variable_0_is_used_before_being_assigned_2454": "変数 '{0}' は割り当てられる前に使用されています。", + "Variable_declaration_expected_1134": "変数の宣言が必要です。", + "Variable_declaration_list_cannot_be_empty_1123": "変数宣言リストを空にすることはできません。", + "Version_0_6029": "バージョン {0}", + "Watch_input_files_6005": "入力ファイルを監視します。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "標準の TypeScript ライブラリで定義された要素の名前を変更することはできません。", + "You_cannot_rename_this_element_8000": "この要素の名前を変更することはできません。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' は受け入れる引数が少なすぎるので、ここでデコレーターとして使用することができません。最初にこれを呼び出してから、'@{0}()' を書き込むつもりでしたか?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' は 2 回指定されています。'{0}' という名前の属性は上書きされます。", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' を使用できるのは .ts ファイル内のみです。", + "_0_expected_1005": "'{0}' が必要です。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' は、戻り値の型の注釈がなく、いずれかの return 式で直接的にまたは間接的に参照されているため、戻り値の型は暗黙的に 'any' になります。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' には型の注釈がなく、直接または間接的に初期化子で参照されているため、暗黙的に 'any' 型が含まれています。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' はプリミティブですが、'{1}' はラッパー オブジェクトです。できれば '{0}' をご使用ください。", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' が宣言されていますが、その値が読み取られることはありません。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' はキーワード '{1}' に関するメタプロパティとして無効です。候補: '{2}'。", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' はそれ自身のベース式内で直接または間接的に参照されます。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' はそれ自身の型の注釈内で直接または間接的に参照されます。", + "_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_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' 修飾子は、クラス宣言、メソッド宣言、またはプロパティ宣言のみに使用できます。", + "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": "'=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。", + "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' 列挙型は、プロパティまたはインデックスのアクセス式、あるいはインポート宣言またはエクスポート割り当ての右辺にのみ使用できます。", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 宣言' を使用できるのは .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' 修飾子を適用することはできません。", + "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}' を使用しています。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "エクスポートされたインターフェイス '{0}' の 'extends' 句がプライベート名 '{1}' を使用しています。", + "file_6025": "ファイル", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' アクセサーおよび 'set' アクセサーには、同じ 'this' 型が必要です。", + "get_and_set_accessor_must_have_the_same_type_2380": "'get' アクセサーと 'set' アクセサーは同じ型でなければなりません。", + "implements_clause_already_seen_1175": "'implements' 句は既に存在します。", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements 句' を使用できるのは .ts ファイル内のみです。", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' を使用できるのは .ts ファイル内のみです。", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'インターフェイス宣言' を使用できるのは .ts ファイル内のみです。", + "let_declarations_can_only_be_declared_inside_a_block_1157": "'let' 宣言は、ブロック内でのみ宣言できます。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' は、'let' 宣言または 'const' 宣言で名前として使用することはできません。", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'モジュール宣言' を使用できるのは .ts ファイル内のみです。", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "'new T[]' は配列の作成に使用できません。代わりに 'new Array()' を使用してください。", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "ターゲットにコンストラクト シグネチャがない 'new' 式の型は、暗黙的に 'any' になります。", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'null 以外のアサーション' を使用できるのは .ts ファイル内のみです。", + "options_6024": "オプション", + "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": "'パラメーター修飾子' を使用できるのは .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' 修飾子はプロパティ宣言またはインデックス シグネチャのみに使用できます。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' オプションが設定され、このオプションを使用して相対モジュール名 '{0}' を解決します。", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' は、派生クラスでのみ参照できます。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' は、派生クラスのメンバーまたはオブジェクトのリテラル式のメンバーでのみ参照されます。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' は、計算されたプロパティ名では参照できません。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' はコンストラクター引数では参照できません。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "オプション 'target' が 'ES2015' 以降の場合、'super' はオブジェクトのリテラル式のメンバーでのみ使用できます。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "派生クラスのコンストラクター内の 'super' のプロパティにアクセスする前に、'super' を呼び出す必要があります。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "派生クラスのコンストラクター内の 'this' にアクセスする前に、'super' を呼び出す必要があります。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' の後には、引数リストまたはメンバー アクセスが必要です。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' プロパティ アクセスはコンストラクター、メンバー関数、または派生クラスのメンバー アクセサーでのみ許可されます。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' は、計算されたプロパティ名では参照できません。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' はモジュール本体内または名前空間本体内では参照できません。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' は、静的プロパティ初期化子では参照できません。", + "this_cannot_be_referenced_in_constructor_arguments_2333": "'this' はコンストラクター引数では参照できません。", + "this_cannot_be_referenced_in_current_location_2332": "'this' は現在の場所では参照できません。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' は型として注釈を持たないため、暗黙的に型 'any' になります。", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'型のエイリアス' を使用できるのは .ts ファイル内のみです。", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'型引数' を使用できるのは .ts ファイル内のみです。", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'型アサーション式' を使用できるのは、.ts ファイル内のみです。", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'型パラメーター宣言' を使用できるのは .ts ファイル内のみです。", + "types_can_only_be_used_in_a_ts_file_8010": "'型' を使用できるのは .ts ファイル内のみです。", + "unique_symbol_types_are_not_allowed_here_1335": "'一意のシンボル' 型はここでは許可されていません。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'一意のシンボル' 型は変数ステートメントの変数でのみ許可されています。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'一意のシンボル' 型は、バインディング名を持つ変数の宣言では使用できません。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 式は、非同期関数ブロックでは使用できません。", + "with_statements_are_not_allowed_in_strict_mode_1101": "厳格モードでは 'with' ステートメントは使用できません。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 式は、パラメーター初期化子では使用できません。" +} \ No newline at end of file diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..1da5977910679 --- /dev/null +++ b/lib/ko/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "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_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}' 키워드를 사용할 수 없습니다.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "쉼표 식은 컴퓨팅된 속성 이름에 사용할 수 없습니다.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "계산된 속성 이름에서는 포함하는 형식의 형식 매개 변수를 참조할 수 없습니다.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "클래스 속성 선언의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "메서드 오버로드의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "리터럴 형식의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "앰비언트 컨텍스트의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "인터페이스의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "계산된 속성 이름은 'string', 'number', 'symbol' 또는 'any' 형식이어야 합니다.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "'{0}' 양식의 계산된 속성 이름은 'symbol' 형식이어야 합니다.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 열거형 멤버는 문자열 리터럴을 통해서만 액세스할 수 있습니다.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "앰비언트 컨텍스트의 'const' 이니셜라이저는 문자열 또는 숫자 리터럴이어야 합니다.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "생성자는 해당 클래스가 'null'을 확장하는 경우 'super' 호출을 포함할 수 없습니다.", + "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": "'declare' 한정자는 .d.ts 파일의 최상위 선언에 필요합니다.", + "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_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' 생성자에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "동적 가져오기 호출은 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_file_cannot_have_a_reference_to_itself_1006": "파일은 자신에 대한 참조를 포함할 수 없습니다.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "'for-await-of' 식은 비동기 함수 또는 비동기 생성기 내에서만 사용할 수 있습니다.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never'를 반환하는 함수에는 연결 가능한 끝점이 있을 수 없습니다.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'new' 키워드로 호출한 함수에는 'void'인 'this' 형식을 사용할 수 없습니다.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "선언된 형식이 'void'도 'any'도 아닌 함수는 값을 반환해야 합니다.", + "A_generator_cannot_have_a_void_type_annotation_2505": "생성기에는 'void' 형식 주석을 사용할 수 없습니다.", + "A_get_accessor_cannot_have_parameters_1054": "'get' 접근자에는 매개 변수를 사용할 수 없습니다.", + "A_get_accessor_must_return_a_value_2378": "'get' 접근자는 값을 반환해야 합니다.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "열거형 선언의 멤버 이니셜라이저는 그 뒤에 선언된 멤버와 다른 열거형에 정의된 멤버를 참조할 수 없습니다.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 클래스에는 'any[]' 형식의 rest 매개 변수 하나를 사용하는 생성자가 있어야 합니다.", + "A_module_cannot_have_multiple_default_exports_2528": "모듈에는 기본 내보내기가 여러 개 있을 수 없습니다.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수와 다른 파일에 있을 수 없습니다,", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수 앞에 있을 수 없습니다.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "네임스페이스 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "매개 변수 이니셜라이저는 함수 또는 생성자 구현에서만 허용됩니다.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "rest 매개 변수를 사용하여 매개 변수 속성을 선언할 수 없습니다.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "매개 변수 속성은 생성자 구현에서만 허용됩니다.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "바인딩 패턴을 사용하여 매개 변수 속성을 선언할 수 없습니다.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'extends' 옵션의 경로는 상대 경로이거나 루트 경로여야 하지만 '{0}'은(는) 아닙니다.", + "A_promise_must_have_a_then_method_1059": "프라미스에는 'then' 메서드가 있어야 합니다.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "형식이 '고유 기호' 형식인 클래스의 속성은 'static'과 'readonly' 둘 다여야 합니다.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "형식이 '고유 기호' 형식인 인터페이스 또는 형식 리터럴의 속성은 'readonly'여야 합니다.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "필수 매개 변수는 선택적 매개 변수 뒤에 올 수 없습니다.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 요소에는 바인딩 패턴이 포함될 수 없습니다.", + "A_rest_element_cannot_have_an_initializer_1186": "rest 요소에는 이니셜라이저를 사용할 수 없습니다.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 요소는 배열 구조 파괴 패턴의 마지막 요소여야 합니다.", + "A_rest_parameter_cannot_be_optional_1047": "rest 매개 변수는 선택 사항이 될 수 없습니다.", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' 접근자에는 선택적 매개 변수를 사용할 수 없습니다.", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' 접근자에는 rest 매개 변수를 사용할 수 없습니다.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' 접근자에는 매개 변수를 하나만 사용해야 합니다.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' 접근자 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "구현이 있는 서명에는 문자열 리터럴 형식을 사용할 수 없습니다.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "클래스에 초기화된 속성이 있거나 매개 변수 속성이 있으면 'super' 호출이 생성자에서 첫 번째 문이어야 합니다.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'this' 기반 형식 가드는 매개 변수 기반 형식 가드와 호환되지 않습니다.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 형식은 클래스 또는 인터페이스의 비정적 멤버에서만 사용할 수 있습니다.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 파일이 이미 '{0}'에 정의되어 있습니다.", + "A_tuple_type_element_list_cannot_be_empty_1122": "튜플 형식 요소 목록은 비워 둘 수 없습니다.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "지수 식의 왼쪽에는 type assertion expression을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "A_type_literal_property_cannot_have_an_initializer_1247": "형식 리터럴 속성에는 이니셜라이저를 사용할 수 없습니다.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "형식 조건자는 rest 매개 변수를 참조할 수 없습니다.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "형식 조건자는 바인딩 패턴에서 '{0}' 요소를 참조할 수 없습니다.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "형식 조건자는 함수 및 메서드의 반환 형식 위치에서만 사용할 수 있습니다.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "형식 조건자의 형식을 해당 매개 변수의 형식에 할당할 수 있어야 합니다.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "형식이 '고유한 기호' 형식인 변수는 'const'여야 합니다.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 식은 생성기 본문에서만 사용할 수 있습니다.", + "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": "액세스 가능성 한정자가 이미 있습니다.", + "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_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처를 추가합니다.", + "Add_missing_super_call_90001": "누락된 'super()' 호출을 추가하세요.", + "Add_this_to_unresolved_variable_90008": "확인되지 않은 변수에 'this.'을 추가하세요.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "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_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", + "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", + "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_abstract_accessor_cannot_have_an_implementation_1318": "추상 접근자는 구현이 있을 수 없습니다.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "접근자는 앰비언트 컨텍스트에서 선언될 수 없습니다.", + "An_accessor_cannot_have_type_parameters_1094": "접근자에는 형식 매개 변수를 사용할 수 없습니다.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "앰비언트 모듈 선언은 파일의 최상위에서만 사용할 수 있습니다.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "산술 피연산자는 'any', 'number' 또는 열거형 형식이어야 합니다.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3의 비동기 함수 또는 메서드에 'Promise' 생성자가 필요합니다. 'Promise' 생성자에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "비동기 함수 또는 메서드에는 유효한 대기 가능 반환 형식이 있어야 합니다.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "비동기 함수 또는 메서드는 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "An_async_iterator_must_have_a_next_method_2519": "비동기 반복기에는 'next()' 메서드가 있어야 합니다.", + "An_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_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": "확장된 유니코드 이스케이프 값은 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_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": "인덱스 시그니처에는 rest 매개 변수를 사용할 수 없습니다.", + "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_initializer_1020": "인덱스 시그니처 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "인덱스 시그니처 매개 변수에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "인덱스 시그니처 매개 변수 형식은 'string' 또는 'number'여야 합니다.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "인터페이스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 확장할 수 있습니다.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "인터페이스는 클래스 또는 다른 인터페이스만 확장할 수 있습니다.", + "An_interface_property_cannot_have_an_initializer_1246": "인터페이스 속성에는 이니셜라이저를 사용할 수 없습니다.", + "An_iterator_must_have_a_next_method_2489": "반복기에는 'next()' 메서드가 있어야 합니다.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "개체 리터럴에 이름이 같은 여러 개의 get/set 접근자를 사용할 수 없습니다.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "strict 모드에서는 개체 리터럴에 이름이 같은 여러 개의 속성을 사용할 수 없습니다.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "개체 리터럴에 이름이 같은 속성과 접근자를 사용할 수 없습니다.", + "An_object_member_cannot_be_declared_optional_1162": "개체 멤버는 선택적으로 선언될 수 없습니다.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "오버로드 시그니처는 생성기로 선언할 수 없습니다.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "지수 식의 왼쪽에는 '{0}' 연산자가 있는 단항 식을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "Annotate_with_type_from_JSDoc_95009": "JSDoc의 형식을 사용하여 주석 추가", + "Annotate_with_types_from_JSDoc_95010": "JSDoc의 형식을 사용하여 주석 추가", + "Argument_expression_expected_1135": "인수 식이 필요합니다.", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 옵션의 인수는 {1}이어야(여야) 합니다.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "'{0}' 형식의 인수는 '{1}' 형식의 매개 변수에 할당될 수 없습니다.", + "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' 한정자를 포함해야 합니다.", + "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}'은(는) 클래스 또는 인터페이스 형식이 아닙니다.", + "Base_constructors_must_all_have_the_same_return_type_2510": "기본 생성자는 모두 반환 형식이 같아야 합니다.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "비추상 모듈 이름을 확인할 기본 디렉터리입니다.", + "Basic_Options_6172": "기본 옵션", + "Binary_digit_expected_1177": "이진수가 있어야 합니다.", + "Binding_element_0_implicitly_has_an_1_type_7031": "바인딩 요소 '{0}'에 암시적으로 '{1}' 형식이 있습니다.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "선언 전에 사용된 블록 범위 변수 '{0}'입니다.", + "Call_decorator_expression_90028": "decorator 식을 호출합니다.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "반환 형식 주석이 없는 호출 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "Call_target_does_not_contain_any_signatures_2346": "호출 대상에 시그니처가 포함되어 있지 않습니다.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}'이(가) 네임스페이스가 아니라 형식이므로 '{0}.{1}'에 액세스할 수 없습니다. '{0}'에서 '{0}[\"{1}\"]'과(와) 함께 '{1}' 속성의 형식을 검색하려고 했나요?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' 생성자 형식을 '{1}' 생성자 형식에 할당할 수 없습니다.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "추상 생성자 형식을 비추상 생성자 형식에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "상수 또는 읽기 전용 속성이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "변수가 아니므로 '{0}'에 할당할 수 없습니다.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "'{0}' 모듈은 모듈이 아닌 엔터티로 확인되므로 확대할 수 없습니다.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "모듈이 아닌 엔터티로 확인되기 때문에 값 내보내기로 모듈 '{0}'을(를) 확대할 수 없습니다.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' 플래그가 'amd' 또는 'system'이 아닌 경우 '{0}' 옵션을 사용하여 모듈을 컴파일할 수 없습니다.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "'--isolatedModules' 플래그가 제공된 경우 네임스페이스를 컴파일할 수 없습니다.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "추상 클래스의 인스턴스를 만들 수 없습니다.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}'을(를) 내보낼 수 없습니다. 지역 선언만 모듈에서 내보낼 수 있습니다.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "'{0}' 클래스를 확장할 수 없습니다. 클래스 생성자가 private로 표시되어 있습니다.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "인터페이스 '{0}'을(를) 확장할 수 없습니다. 'implements'를 확장하시겠습니까?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "지정된 디렉터리에서 tsconfig.json 파일을 찾을 수 없습니다. '{0}'.", + "Cannot_find_global_type_0_2318": "전역 형식 '{0}'을(를) 찾을 수 없습니다.", + "Cannot_find_global_value_0_2468": "전역 값 '{0}'을(를) 찾을 수 없습니다.", + "Cannot_find_module_0_2307": "'{0}' 모듈을 찾을 수 없습니다.", + "Cannot_find_name_0_2304": "'{0}' 이름을 찾을 수 없습니다.", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' 이름을 찾을 수 없습니다. '{1}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "'{0}' 이름을 찾을 수 없습니다. 인스턴스 멤버 'this.{0}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "'{0}' 이름을 찾을 수 없습니다. 정적 멤버 '{1}.{0}'을(를) 사용하시겠습니까?", + "Cannot_find_namespace_0_2503": "'{0}' 네임스페이스를 찾을 수 없습니다.", + "Cannot_find_parameter_0_1225": "'{0}' 매개 변수를 찾을 수 없습니다.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "입력 파일의 공용 하위 디렉터리 경로를 찾을 수 없습니다.", + "Cannot_find_type_definition_file_for_0_2688": "'{0}'에 대한 형식 정의 파일을 찾을 수 없습니다.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "형식 선언 파일을 가져올 수 없습니다. '{1}' 대신 '{0}'을(를) 가져오세요.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "블록 범위 선언 '{1}'과(와) 동일한 범위 내에서 외부 범위 변수 '{0}'을(를) 초기화할 수 없습니다.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "형식에 호출 시그니처가 없는 식을 호출할 수 없습니다. '{0}' 형식에 호환되는 호출 시그니처가 없습니다.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", + "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_redeclare_exported_variable_0_2323": "내보낸 변수 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "catch 절에서 식별자 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' 플래그를 제공하지 않으면 JSX를 사용할 수 없습니다.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module'이 'none'인 경우 가져오기, 내보내기 또는 모듈 확대를 사용할 수 없습니다.", + "Cannot_use_namespace_0_as_a_type_2709": "'{0}' 네임스페이스를 형식으로 사용할 수 없습니다.", + "Cannot_use_namespace_0_as_a_value_2708": "'{0}' 네임스페이스를 값으로 사용할 수 없습니다.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "형식에 호출 또는 구문 시그니처가 없는 식에는 'new'를 사용할 수 없습니다.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "'{0}' 파일은 여러 입력 파일로 덮어쓰이므로 쓸 수 없습니다.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "'{0}' 파일은 입력 파일을 덮어쓰므로 쓸 수 없습니다.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 절 변수에 형식 주석을 사용할 수 없습니다.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 절 변수에 이니셜라이저를 사용할 수 없습니다.", + "Change_0_to_1_90014": "'{0}'을(를) '{1}'(으)로 변경합니다.", + "Change_extends_to_implements_90003": "'extends'를 'implements'로 변경하세요.", + "Change_spelling_to_0_90022": "철자를 '{0}'(으)로 변경하세요.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}'이(가) '{1}' - '{2}'에 대해 일치하는 가장 긴 접두사인지 확인하는 중입니다.", + "Circular_definition_of_import_alias_0_2303": "가져오기 별칭 '{0}'의 순환 정의입니다.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "구성을 확인하는 동안 순환이 검색되었습니다. {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "'{0}' 클래스는 인스턴스 멤버 접근자 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 접근자를 인스턴스 멤버 함수로 정의합니다.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "'{0}' 클래스가 인스턴스 멤버 함수 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 함수를 인스턴스 멤버 접근자로 정의합니다.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "'{0}' 클래스가 인스턴스 멤버 함수 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 함수를 인스턴스 멤버 속성으로 정의합니다.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' 클래스가 인스턴스 멤버 속성 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 속성을 인스턴스 멤버 함수로 정의합니다.", + "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' 클래스가 기본 클래스 '{1}'을(를) 잘못 확장합니다.", + "Class_0_incorrectly_implements_interface_1_2420": "'{0}' 클래스가 '{1}' 인터페이스를 잘못 구현합니다.", + "Class_0_used_before_its_declaration_2449": "선언 전에 사용된 '{0}' 클래스입니다.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "클래스 선언은 '@augments' 또는 `@extends` 태그를 둘 이상 가질 수 없습니다.", + "Class_name_cannot_be_0_2414": "클래스 이름은 '{0}'일 수 없습니다.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "클래스 정적 측면 '{0}'이(가) 기본 클래스 정적 측면 '{1}'을(를) 잘못 확장합니다.", + "Classes_can_only_extend_a_single_class_1174": "클래스는 단일 클래스만 확장할 수 있습니다.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "추상 메서드를 포함하는 클래스는 abstract로 표시되어 있어야 합니다.", + "Command_line_Options_6171": "명령줄 옵션", + "Compilation_complete_Watching_for_file_changes_6042": "컴파일이 완료되었습니다. 파일이 변경되었는지 확인하는 중입니다.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", + "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", + "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{1}' 및 '{2}'에서 '{0}'에 대한 정의가 충돌하고 있습니다. 이 라이브러리의 특정 버전을 설치하여 충돌을 해결하세요.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "반환 형식 주석이 없는 구문 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "Constructor_implementation_is_missing_2390": "생성자 구현이 없습니다.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "'{0}' 클래스의 생성자는 private이며 클래스 선언 내에서만 액세스할 수 있습니다.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' 클래스의 생성자는 protected이며 클래스 선언 내에서만 액세스할 수 있습니다.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "파생 클래스의 생성자는 'super' 호출을 포함해야 합니다.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", + "Convert_function_0_to_class_95002": "'{0}' 함수를 클래스로 변환", + "Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환", + "Convert_to_default_import_95013": "기본 가져오기로 변환", + "Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "모듈 '{0}'에 대한 선언 파일을 찾을 수 없습니다. '{1}'에는 암시적으로 'any' 형식이 포함됩니다.", + "Could_not_write_file_0_Colon_1_5033": "'{0}' 파일을 쓸 수 없습니다. '{1}'.", + "DIRECTORY_6038": "디렉터리", + "Declaration_expected_1146": "선언이 필요합니다.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "선언 이름이 기본 제공 전역 ID '{0}'과(와) 충돌합니다.", + "Declaration_or_statement_expected_1128": "선언 또는 문이 필요합니다.", + "Declare_method_0_90023": "'{0}' 메서드를 선언합니다.", + "Declare_property_0_90016": "'{0}' 속성을 선언합니다.", + "Declare_static_method_0_90024": "'{0}' 정적 메서드를 선언합니다.", + "Declare_static_property_0_90027": "정적 속성 '{0}'을(를) 선언합니다.", + "Decorators_are_not_valid_here_1206": "데코레이터는 여기에 사용할 수 없습니다.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "동일한 이름의 여러 get/set 접근자에 데코레이터를 적용할 수 없습니다.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[사용되지 않음] 대신 '--jsxFactory'를 사용합니다. 'react' JSX 내보내기를 대상으로 할 경우 createElement에 대해 호출되는 개체를 지정합니다.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[사용되지 않음] 대신 '--outFile'을 사용합니다. 출력을 연결하고 단일 파일로 내보냅니다.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[사용되지 않음] 대신 '--skipLibCheck'를 사용합니다. 기본 라이브러리 선언 파일의 형식 검사를 건너뜁니다.", + "Digit_expected_1124": "숫자가 필요합니다.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' 디렉터리가 없으므로 이 디렉터리에서 모든 조회를 건너뜁니다.", + "Disable_checking_for_this_file_90018": "이 파일 확인을 사용하지 않도록 설정합니다.", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript 프로젝트에 대한 크기 제한을 사용하지 않도록 설정합니다.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "함수 형식의 제네릭 시그니처에 대한 엄격한 검사를 사용하지 않도록 설정합니다.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "동일한 파일에 대해 대/소문자를 일관되지 않게 사용한 참조를 허용하지 않습니다.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "컴파일된 파일 목록에 삼중 슬래시 참조 또는 가져온 모듈을 추가하지 않습니다.", + "Do_not_emit_comments_to_output_6009": "주석을 출력에 내보내지 마세요.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' 주석이 있는 코드에 대한 선언을 내보내지 마세요.", + "Do_not_emit_outputs_6010": "출력을 내보내지 않습니다.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "오류가 보고되면 출력을 내보내지 않습니다.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "'use strict' 지시문을 모듈 출력에 내보내지 마세요.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "생성된 코드에서 const 열거형 선언을 지우지 마세요.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "컴파일된 출력에서 '__extends'와 같은 사용자 지정 도우미 함수를 생성하지 않습니다.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "기본 라이브러리 파일(lib.d.ts)을 포함하지 않습니다.", + "Do_not_report_errors_on_unreachable_code_6077": "접근할 수 없는 코드에 대한 오류를 보고하지 않습니다.", + "Do_not_report_errors_on_unused_labels_6074": "사용되지 않는 레이블에 대한 오류를 보고하지 않습니다.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "symlink의 실제 경로를 확인하지 마세요.", + "Do_not_truncate_error_messages_6165": "오류 메시지를 자르지 않습니다.", + "Duplicate_declaration_0_2718": "'{0}' 선언이 중복되었습니다.", + "Duplicate_function_implementation_2393": "중복된 함수 구현입니다.", + "Duplicate_identifier_0_2300": "'{0}' 식별자가 중복되었습니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "'{0}' 식별자가 중복되었습니다. 컴파일러는 모듈의 최상위 범위에 이름 '{1}'을(를) 예약합니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "'{0}' 식별자가 중복되었습니다. 컴파일러는 비동기 함수를 포함하는 모듈의 최상위 범위에 '{1}' 이름을 예약합니다.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "중복 식별자 '{0}'입니다. 컴파일러는 '{1}' 선언을 사용하여 비동기 함수를 지원합니다.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "중복 식별자 'arguments'입니다. 컴파일러는 'arguments'를 사용해서 rest 매개 변수를 초기화합니다.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "'_newTarget' 식별자가 중복되었습니다. 컴파일러는 변수 선언 '_newTarget'을 사용하여 'new.target' 메타 속성 참조를 캡처합니다.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "중복 식별자 '_super'입니다. 컴파일러는 '_super'를 사용해서 기본 클래스 참조를 캡처합니다.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "중복 식별자 '_this'입니다. 컴파일러는 변수 선언 '_this'를 사용해서 'this' 참조를 캡처합니다.", + "Duplicate_label_0_1114": "중복된 레이블 '{0}'입니다.", + "Duplicate_number_index_signature_2375": "중복 숫자 인덱스 시그니처입니다.", + "Duplicate_string_index_signature_2374": "중복 문자열 인덱스 시그니처입니다.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 모듈을 대상을 지정할 때에는 동적 가져오기를 사용할 수 없습니다.", + "Dynamic_import_cannot_have_type_arguments_1326": "동적 가져오기에는 형식 인수를 사용할 수 없습니다.", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "동적 가져오기에는 지정자 하나를 인수로 사용해야 합니다.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에는 '{0}' 형식이 있습니다.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "'{0}' 형식에 인덱스 시그니처가 없으므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "출력 파일의 시작에서 UTF-8 BOM(바이트 순서 표시)을 내보냅니다.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "별도의 파일을 사용하는 대신 소스 맵과 함께 단일 파일을 내보냅니다.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.", + "Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.", + "Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용합니다.", + "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", + "Enable_tracing_of_the_name_resolution_process_6085": "이름 확인 프로세스 추적을 사용하도록 설정하세요.", + "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 비동기 함수에 대해 실험적 지원을 사용합니다.", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 데코레이터에 대해 실험적 지원을 사용합니다.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "데코레이터에 대한 형식 메타데이터를 내보내기 위해 실험적 지원을 사용합니다.", + "Enum_0_used_before_its_declaration_2450": "선언 전에 사용된 '{0}' 열거형입니다.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "열거형 선언은 모두 const 또는 비const여야 합니다.", + "Enum_member_expected_1132": "열거형 멤버가 필요합니다.", + "Enum_member_must_have_initializer_1061": "열거형 멤버에는 이니셜라이저가 있어야 합니다.", + "Enum_name_cannot_be_0_2431": "열거형 이름은 '{0}'일 수 없습니다.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "열거형 형식 '{0}'에 리터럴이 아닌 이니셜라이저를 사용하는 멤버가 있습니다.", + "Examples_Colon_0_6026": "예: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "'{0}' 및 '{1}' 형식을 비교하는 스택 깊이가 과도합니다.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "'@extends' 태그로 제공하는 예상되는 {0}-{1} 형식 인수입니다.", + "Expected_0_arguments_but_got_1_2554": "{0}개의 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0}개의 인수가 필요한데 {1}개 이상을 가져왔습니다.", + "Expected_0_type_arguments_but_got_1_2558": "{0}개의 형식 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "'@extends' 태그로 제공하는 예상되는 {0} 형식 인수입니다.", + "Expected_at_least_0_arguments_but_got_1_2555": "최소 {0}개의 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "최소 {0}개의 인수가 필요한데 {1}개 이상을 가져왔습니다.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}'에 해당하는 JSX 닫는 태그가 필요합니다.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX 조각에 닫는 태그가 필요합니다.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "'package.json'의 '{0}' 필드에 'string' 형식이 필요한데 '{1}'을(를) 얻었습니다.", + "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_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}'은(는) 모듈이 아닙니다. 패키지 작성자에게 문의하여 패키지 정의를 업데이트하세요.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "내보낸 외부 패키지 입력 항목 파일에는 삼중 슬래시 참조가 포함될 수 없습니다. 패키지 작성자에게 문의하여 패키지 정의를 업데이트하세요.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "내보낸 형식 별칭 '{0}'은(는) '{1}' 전용 이름을 포함하거나 사용 중입니다.", + "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": "내보내기 및 할당 내보내기는 모듈 확대에서 허용되지 않습니다.", + "Expression_expected_1109": "식이 필요합니다.", + "Expression_or_comma_expected_1137": "식 또는 쉼표가 필요합니다.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "컴파일러가 기본 클래스 참조를 캡처하기 위해 사용하는 '_super'로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "컴파일러가 비동기 함수를 지원하기 위해 사용하는 변수 선언 '{0}'(으)로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "컴파일러가 'new.target' 메타 속성 참조를 캡처하기 위해 사용하는 변수 선언 '_newTarget'으로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "컴파일러가 'this' 참조를 캡처하기 위해 사용하는 변수 선언 '_this'로 식이 확인됩니다.", + "Extract_constant_95006": "상수 추출", + "Extract_function_95005": "함수 추출", + "Extract_symbol_95003": "기호 추출", + "Extract_to_0_in_1_95004": "{1}의 {0}(으)로 추출", + "Extract_to_0_in_1_scope_95008": "{1} 범위의 {0}(으)로 추출", + "Extract_to_0_in_enclosing_scope_95007": "바깥쪽 범위의 {0}(으)로 추출", + "FILE_6035": "파일", + "FILE_OR_DIRECTORY_6040": "파일 또는 디렉터리", + "Failed_to_parse_file_0_Colon_1_5014": "'{0}' 파일 구문 분석 실패: {1}.", + "Fallthrough_case_in_switch_7029": "switch에 Fallthrough case가 있습니다.", + "File_0_does_not_exist_6096": "'{0}' 파일이 없습니다.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "'{0}' 파일이 있습니다. 이 파일을 이름 확인 결과로 사용하세요.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' 파일은 확장명이 지원되지 않으므로 건너뜁니다.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' 파일의 확장명이 지원되지 않습니다. 지원되는 확장명은 {1}뿐입니다.", + "File_0_is_not_a_module_2306": "'{0}' 파일은 모듈이 아닙니다.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' 파일이 'rootDir' '{1}' 아래에 있지 않습니다. 'rootDir'에는 모든 소스 파일이 포함되어 있어야 합니다.", + "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", + "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' 파일 이름은 이미 포함된 '{1}' 파일 이름과 대/소문자만 다릅니다.", + "File_name_0_has_a_1_extension_stripping_it_6132": "파일 이름 '{0}'에 '{1}' 확장명이 있어 제거하는 중입니다.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "파일 사양은 재귀 디렉터리 와일드카드('**') 뒤에 나타나는 부모 디렉터리('..')를 포함할 수 없습니다. '{0}'.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "파일 사양은 여러 개의 재귀 디렉터리 와일드카드('**')를 포함할 수 없습니다. '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "파일 사양은 재귀 디렉터리 와일드카드('**')로 끝날 수 없습니다. '{0}'.", + "Found_package_json_at_0_6099": "'{0}'에서 'package.json'을 찾았습니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "반환 형식 주석이 없는 함수 식에는 암시적으로 '{0}' 반환 형식이 포함됩니다.", + "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": "함수에 끝 return 문이 없으며 반환 형식에 'undefined'가 포함되지 않습니다.", + "Function_overload_must_be_static_2387": "함수 오버로드는 정적이어야 합니다.", + "Function_overload_must_not_be_static_2388": "함수 오버로드는 정적이 아니어야 합니다.", + "Generates_corresponding_d_ts_file_6002": "해당 '.d.ts' 파일을 생성합니다.", + "Generates_corresponding_map_file_6043": "해당 '.map' 파일을 생성합니다.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "생성기는 값을 생성하지 않으므로 암시적으로 '{0}' 형식입니다. 반환 형식을 제공하세요.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "생성기는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "생성기는 ECMAScript 2015 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Generic_type_0_requires_1_type_argument_s_2314": "'{0}' 제네릭 형식에 {1} 형식 인수가 필요합니다.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "제네릭 형식 '{0}'에 {1} 및 {2} 사이의 형식 인수가 필요합니다.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "제네릭 형식 인스턴스화는 깊이가 매우 깊으며 무한할 수도 있습니다.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Getter 및 Setter 접근자의 표시 유형이 다릅니다.", + "Global_module_exports_may_only_appear_at_top_level_1316": "전역 모듈 내보내기는 최상위 수준에만 나올 수 있습니다.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "전역 모듈 내보내기는 선언 파일에만 나올 수 있습니다.", + "Global_module_exports_may_only_appear_in_module_files_1314": "전역 모듈 내보내기는 모듈 파일에만 나올 수 있습니다.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "전역 형식 '{0}'은 클래스 또는 인터페이스 형식이어야 합니다.", + "Global_type_0_must_have_1_type_parameter_s_2317": "전역 형식 '{0}'에는 {1} 형식 매개 변수를 사용해야 합니다.", + "Hexadecimal_digit_expected_1125": "16진수가 필요합니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Identifier_expected_1003": "식별자가 필요합니다.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "식별자가 필요합니다. '__esModule'은 ECMAScript 모듈을 변환할 때 내보낸 표식으로 예약되어 있습니다.", + "Ignore_this_error_message_90019": "이 오류 메시지를 무시합니다.", + "Implement_inherited_abstract_class_90007": "상속된 추상 클래스를 구현하세요.", + "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_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": "네임스페이스의 가져오기 선언은 모듈을 참조할 수 없습니다.", + "Import_emit_helpers_from_tslib_6139": "'tslib'에서 내보내기 도우미를 가져오세요.", + "Import_name_cannot_be_0_2438": "가져오기 이름은 '{0}'일 수 없습니다.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "앰비언트 모듈 선언의 가져오기 또는 내보내기 선언은 상대적 모듈 이름을 통해 모듈을 참조할 수 없습니다.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "가져오기는 모듈 확대에서 허용되지 않습니다. 내보내기를 바깥쪽 외부 모듈로 이동하세요.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "앰비언트 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "다중 선언이 포함된 열거형에서는 하나의 선언만 첫 번째 열거형 요소에 대한 이니셜라이저를 생략할 수 있습니다.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", + "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' 형식의 인덱스 시그니처는 읽기만 허용됩니다.", + "Index_signature_is_missing_in_type_0_2329": "'{0}' 형식에 인덱스 시그니처가 없습니다.", + "Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "병합된 선언 '{0}'의 개별 선언은 모두 내보내 졌거나 모두 로컬이어야 합니다.", + "Infer_parameter_types_from_usage_95012": "사용량에서 매개 변수 형식을 유추합니다.", + "Infer_type_of_0_from_usage_95011": "사용량에서 '{0}'의 형식을 유추합니다.", + "Initialize_property_0_in_the_constructor_90020": "생성자에서 속성 '{0}'을(를) 초기화합니다.", + "Initialize_static_property_0_90021": "정적 속성 '{0}'을(를) 초기화합니다.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "인스턴스 멤버 변수 '{0}'의 이니셜라이저는 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "매개 변수 '{0}'의 이니셜라이저는 그 다음에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "이니셜라이저는 이 바인딩 요소에 대한 값을 제공하지 않으며 바인딩 요소에는 기본값이 없습니다.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "앰비언트 컨텍스트에서는 이니셜라이저가 허용되지 않습니다.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript 프로젝트를 초기화하고 tsconfig.json 파일을 만듭니다.", + "Insert_command_line_options_and_files_from_a_file_6030": "파일에서 명령줄 옵션 및 파일을 삽입합니다.", + "Install_0_95014": "'{0}' 설치", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "'{0}' 인터페이스는 '{1}' 및 '{2}' 형식을 동시에 확장할 수 없습니다.", + "Interface_0_incorrectly_extends_interface_1_2430": "'{0}' 인터페이스가 '{1}' 인터페이스를 잘못 확장합니다.", + "Interface_declaration_cannot_have_implements_clause_1176": "인터페이스 선언에는 'implements' 절을 사용할 수 없습니다.", + "Interface_name_cannot_be_0_2427": "인터페이스 이름은 '{0}'일 수 없습니다.", + "Invalid_character_1127": "잘못된 문자입니다.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "확대의 모듈 이름이 잘못되었습니다. '{1}'에서 '{0}' 모듈이 형식화되지 않은 모듈로 확인되어 확대할 수 없습니다.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "확대의 모듈 이름이 잘못되었습니다. '{0}' 모듈을 찾을 수 없습니다.", + "Invalid_reference_directive_syntax_1084": "'reference' 지시문 구문이 잘못되었습니다.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "'{0}'을(를) 잘못 사용했습니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}'을(를) 잘못 사용했습니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Invalid_use_of_0_in_strict_mode_1100": "strict 모드에서 '{0}'을(를) 잘못 사용했습니다.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory'에 대한 값이 잘못되었습니다. '{0}'이(가) 올바른 식별자 또는 정규화된 이름이 아닙니다.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace'의 값이 잘못되었습니다. '{0}'은(는) 올바른 식별자가 아닙니다.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}'이(가) 'extends {2}' 절과 일치하지 않습니다.", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}'이(가) 클래스에 연결되어 있지 않습니다.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...'은 시그니처의 마지막 매개 변수에만 나타날 수 있습니다.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 태그의 이름이 '{0}'인데 해당 이름의 매개 변수가 없습니다.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 태그는 형식 주석을 포함하거나, '@property' 또는 '@member' 태그 앞에 와야 합니다.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 유형은 문서 주석 내에서만 사용될 수 있습니다.", + "JSX_attribute_expected_17003": "JSX 특성이 필요합니다.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 특성에는 비어 있지 않은 '식'만 할당할 수 있습니다.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 요소 '{0}'에 닫는 태그가 없습니다.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 요소 특성 형식 '{0}'은(는) 공용 구조체 형식일 수 없습니다.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 요소 클래스는 '{0}' 속성이 없으므로 특성을 지원하지 않습니다.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "'JSX.{0}' 인터페이스가 없으므로 JSX 요소는 암시적으로 'any' 형식입니다.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "전역 형식 'JSX.Element'가 없으므로 JSX 요소는 암시적으로 'any' 형식입니다.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 요소 형식 '{0}'에 구문 또는 호출 시그니처가 없습니다.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 요소 형식 '{0}'은(는) JSX 요소에 대한 생성자 함수가 아닙니다.", + "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_jsxFactory_17016": "JSX 조각은 --jsxFactory를 사용하는 경우 지원되지 않습니다.", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 분배 자식은 배열 형식이어야 합니다.", + "Jump_target_cannot_cross_function_boundary_1107": "점프 대상은 함수 경계를 벗어날 수 없습니다.", + "KIND_6034": "KIND", + "LOCATION_6037": "위치", + "Language_service_is_disabled_9004": "언어 서비스를 사용할 수 없습니다.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "쉼표 연산자의 왼쪽은 사용되지 않으며 이로 인해 의도하지 않은 결과가 발생하지 않습니다.", + "Line_break_not_permitted_here_1142": "여기서는 줄 바꿈이 허용되지 않습니다.", + "Line_terminator_not_permitted_before_arrow_1200": "줄 마침 표시는 화살표 앞에 사용할 수 없습니다.", + "List_of_folders_to_include_type_definitions_from_6161": "포함할 형식 정의가 있는 폴더의 목록입니다.", + "List_of_language_service_plugins_6181": "언어 서비스 플러그 인의 목록입니다.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "런타임에 프로젝트의 구조를 나타내는 결합된 콘텐츠가 있는 루트 폴더의 목록입니다.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "루트 디렉터리 '{1}'에서 '{0}'을(를) 로드하고 있습니다. 후보 위치: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' 폴더에서 '{0}' 모듈을 로드하고 있습니다. 대상 파일 형식은 '{1}'입니다.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "모듈을 파일/폴더로 로드하고 있습니다. 후보 모듈 위치: '{0}', 대상 파일 형식: '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "로캘이 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}'에 대해 일치하는 가장 긴 접두사는 '{1}'입니다.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' 폴더에서 찾고 있습니다. 초기 위치: '{0}'.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출하세요.", + "Member_0_implicitly_has_an_1_type_7008": "'{0}' 멤버에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Merge_conflict_marker_encountered_1185": "병합 충돌 표식을 발견했습니다.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "병합된 선언 '{0}'에는 기본 내보내기 선언을 포함할 수 없습니다. 대신 별도의 'export default {0}' 선언을 추가하세요.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "메타 속성 '{0}'은(는) 함수 선언, 함수 식 또는 생성기의 본문에서만 사용할 수 있습니다.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "'{0}' 메서드는 abstract로 표시되어 있으므로 구현이 있을 수 없습니다.", + "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": "한정자를 여기에 표시할 수 없습니다.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} 모듈에서 '{1}'(이)라는 멤버를 이미 내보냈습니다. 모호성을 해결하려면 명시적으로 다시 내보내는 것이 좋습니다.", + "Module_0_has_no_default_export_1192": "모듈 '{0}'에는 기본 내보내기가 없습니다.", + "Module_0_has_no_exported_member_1_2305": "'{0}' 모듈에 내보낸 멤버 '{1}'이(가) 없습니다.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' 모듈은 이름이 같은 로컬 선언으로 숨겨집니다.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "모듈 '{0}'은(는) 모듈이 아닌 엔터티로 확인되므로 이 구문을 사용하여 가져올 수 없습니다.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "모듈 '{0}'은(는) 'export ='을 사용하며 'export *'와 함께 사용할 수 없습니다.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "이 파일은 수정되지 않았으므로 '{0}' 모듈은 '{1}'에서 선언된 앰비언트 모듈로 확인되었습니다.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "'{0}' 모듈은 '{1}'에서 지역으로 선언된 앰비언트 모듈로 확인되었습니다.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "모듈 '{0}'이(가) '{1}'(으)로 확인되었지만 '--jsx'가 설정되지 않았습니다.", + "Module_Resolution_Options_6174": "모듈 확인 옵션", + "Module_name_0_matched_pattern_1_6092": "모듈 이름: '{0}', 일치하는 패턴: '{1}'", + "Module_name_0_was_not_resolved_6090": "======== 모듈 이름 '{0}'이(가) 확인되지 않았습니다. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.", + "Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.", + "NEWLINE_6061": "줄 바꿈", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "명명된 속성 '{0}'의 형식 '{1}' 및 '{2}'이(가) 동일하지 않습니다.", + "Namespace_0_has_no_exported_member_1_2694": "'{0}' 네임스페이스에 내보낸 멤버 '{1}'이(가) 없습니다.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "기본 생성자에 지정된 수의 형식 인수가 없습니다.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "'{0}' 구성 파일에서 입력을 찾을 수 없습니다. 지정된 '포함' 경로는 '{1}'이고 '제외' 경로는 '{2}'이었습니다.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "비추상 클래스 '{0}'은(는) '{2}' 클래스에서 상속된 추상 멤버 '{1}'을(를) 구현하지 않습니다.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "비추상 클래스 식은 '{1}' 클래스에서 상속된 추상 멤버 '{0}'을(를) 구현하지 않습니다.", + "Not_all_code_paths_return_a_value_7030": "일부 코드 경로가 값을 반환하지 않습니다.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "숫자 인덱스 형식 '{0}'을(를) 문자열 인덱스 형식 '{1}'에 할당할 수 없습니다.", + "Object_is_possibly_null_2531": "개체가 'null'인 것 같습니다.", + "Object_is_possibly_null_or_undefined_2533": "개체가 'null' 또는 'undefined'인 것 같습니다.", + "Object_is_possibly_undefined_2532": "개체가 'undefined'인 것 같습니다.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "개체 리터럴은 알려진 속성만 지정할 수 있으며 '{1}' 형식에 '{0}'이(가) 없습니다.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "개체 리터럴은 알려진 속성만 지정할 수 있지만 '{1}' 형식에 '{0}'이(가) 없습니다. '{2}'을(를) 쓰려고 했습니까?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "개체 리터럴의 '{0}' 속성에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Octal_digit_expected_1178": "8진수가 있어야 합니다.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "8진수 리터럴 형식은 ES2015 구문을 사용해야 합니다. '{0}' 구문을 사용하세요.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8진수 리터럴은 열거형 멤버 이니셜라이저에서 사용할 수 없습니다. '{0}' 구문을 사용하세요.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "strict 모드에서는 8진수 리터럴이 허용되지 않습니다.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 이상을 대상으로 하는 경우 8진수 리터럴을 사용할 수 없습니다. '{0}' 구문을 사용하세요.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 문에는 단일 변수 선언만 허용됩니다.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 문에는 단일 변수 선언만 허용됩니다.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "void 함수만 'new' 키워드로 호출할 수 있습니다.", + "Only_ambient_modules_can_use_quoted_names_1035": "앰비언트 모듈만 따옴표가 붙은 이름을 사용할 수 있습니다.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "'amd' 및 'system' 모듈만 --{0}과(와) 함께 사용할 수 있습니다.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "선택적 형식 인수가 포함된 식별자/정규화된 이름만 현재 클래스 'extends' 절에서 지원됩니다.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "기본 클래스의 공용 및 보호된 메서드만 'super' 키워드를 통해 액세스할 수 있습니다.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' 연산자를 '{1}' 및 '{2}' 형식에 적용할 수 없습니다.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "'{0}' 옵션은 'tsconfig.json' 파일에만 지정할 수 있습니다.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "'{0}' 옵션은 '--inlineSourceMap' 옵션 또는 '--sourceMap' 옵션이 제공되는 경우에만 사용할 수 있습니다.", + "Option_0_cannot_be_specified_with_option_1_5053": "'{0}' 옵션은 '{1}' 옵션과 함께 지정할 수 없습니다.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "'{1}' 옵션을 지정하지 않고 '{0}' 옵션을 지정할 수 없습니다.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "'{0}' 옵션은 문자열 배열 값을 사용해야 합니다.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' 옵션은 '--module' 옵션을 지정하거나 'target' 옵션이 'ES2015' 이상인 경우에만 사용할 수 있습니다.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'paths' 옵션은 '--baseUrl' 옵션을 지정하지 않고 사용할 수 없습니다.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "명령줄에서 'project' 옵션을 원본 파일과 혼합하여 사용할 수 없습니다.", + "Options_Colon_6027": "옵션:", + "Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "오버로드 시그니처가 함수 구현과 호환되지 않습니다.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "오버로드 시그니처는 모두 내보내거나 모두 내보내지 않아야 합니다.", + "Overload_signatures_must_all_be_optional_or_required_2386": "오버로드 시그니처는 모두 선택 사항이거나 필수 사항이어야 합니다.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "오버로드 시그니처는 모두 공용, 전용 또는 보호된 상태여야 합니다.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "매개 변수 '{0}'은(는) 해당 이니셜라이저에서 참조할 수 없습니다.", + "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' 매개 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' 매개 변수는 '{1}' 매개 변수와 같은 위치에 있지 않습니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "내보낸 함수의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "내보낸 함수의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "내보낸 함수의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "매개 변수에 물음표와 이니셜라이저를 사용할 수 없습니다.", + "Parameter_declaration_expected_1138": "매개 변수 선언이 필요합니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "strict 모드에서 구문 분석하고 각 소스 파일에 대해 \"use strict\"를 내보냅니다.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' 패턴에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", + "Prefix_0_with_an_underscore_90025": "'{0}' 앞에 밑줄을 붙이세요.", + "Print_names_of_files_part_of_the_compilation_6155": "컴파일의 일부인 파일의 이름을 인쇄합니다.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", + "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", + "Print_this_message_6017": "이 메시지를 출력합니다.", + "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.", + "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' 속성이 '{1}' 형식에 없습니다. '{2}'을(를) 사용하시겠습니까?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' 속성은 충돌하는 선언이 있고 '{1}' 형식에서 액세스할 수 없습니다.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' 속성에는 해당 set 접근자에 매개 변수 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' 형식의 '{0}' 속성을 '{2}' 형식에 할당할 수 없습니다.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "속성 '{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "Property_0_is_incompatible_with_index_signature_2530": "'{0}' 속성이 인덱스 시그니처와 호환되지 않습니다.", + "Property_0_is_missing_in_type_1_2324": "'{0}' 속성이 '{1}' 형식에 없습니다.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "'{0}' 속성은 '{1}' 형식에서 선택적이지만 '{2}' 형식에서는 필수입니다.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' 속성은 private이며 '{1}' 클래스 내에서만 액세스할 수 있습니다.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "'{0}' 속성은 '{1}' 형식에서 private이지만 '{2}' 형식에서는 그렇지 않습니다.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "'{0}' 속성은 보호된 속성이며 '{1}' 클래스의 인스턴스를 통해서만 액세스할 수 있습니다.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' 속성은 보호된 속성이며 '{1}' 클래스 및 해당 하위 클래스 내에서만 액세스할 수 있습니다.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' 속성은 보호된 속성이지만 '{1}' 형식은 '{2}'에서 파생된 클래스가 아닙니다.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "'{0}' 속성은 '{1}' 형식에서는 보호된 속성이지만 '{2}' 형식에서는 공용입니다.", + "Property_0_is_used_before_being_assigned_2565": "'{0}' 속성이 할당되기 전에 사용되었습니다.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 분배 특성의 '{0}' 속성을 대상 속성에 할당할 수 없습니다.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "내보낸 클래스 식의 속성 '{0}'이(가) 비공개가 아니거나 보호되지 않을 수 있습니다.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "내보낸 인터페이스의 '{0}' 속성이 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "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_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', 개체 리터럴 또는 배열 리터럴이어야 합니다.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'ES5' 또는 'ES3'을 대상으로 할 경우 'for-of', spread 및 소멸의 반복 가능한 개체를 완벽히 지원합니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "내보낸 클래스의 공용 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "내보낸 클래스의 공용 메서드 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "내보낸 클래스의 공용 메서드의 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "내보낸 클래스의 공용 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "내보낸 클래스의 공용 속성 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "내보낸 클래스의 공용 속성 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "내보낸 클래스에 있는 공용 정적 메서드 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "내보낸 클래스에 있는 공용 정적 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", + "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", + "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언을 제거합니다.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", + "Report_errors_in_js_files_8019": ".js 파일의 오류를 보고합니다.", + "Report_errors_on_unused_locals_6134": "사용되지 않은 로컬 항목에 대한 오류를 보고합니다.", + "Report_errors_on_unused_parameters_6135": "사용되지 않은 매개 변수에 대한 오류를 보고합니다.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.", + "Resolution_for_module_0_was_found_in_cache_6147": "'{0}' 모듈에 대한 해결을 캐시에서 찾았습니다.", + "Resolving_from_node_modules_folder_6118": "node_modules 폴더에서 확인하는 중...", + "Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.", + "Resolving_real_path_for_0_result_1_6130": "'{0}'의 실제 경로를 확인하는 중입니다. 결과: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: '{1}', 루트 디렉터리: '{2}' ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: '{1}', 루트 디렉터리: 설정되지 않음 ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: 설정되지 않음, 루트 디렉터리: '{1}' ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: 설정되지 않음, 루트 디렉터리: 설정되지 않음 ========", + "Resolving_using_primary_search_paths_6117": "기본 검색 경로를 사용하여 확인하는 중...", + "Resolving_with_primary_search_path_0_6121": "기본 검색 경로 '{0}'을(를) 사용하여 확인하는 중입니다.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest 매개 변수 '{0}'에는 암시적으로 'any[]' 형식이 포함됩니다.", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 유형은 개체 형식에서만 만들 수 있습니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "생성자 시그니처의 반환 형식을 클래스의 인스턴스 형식에 할당할 수 있어야 합니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "내보낸 함수의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "내보낸 함수의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "내보낸 함수의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "내보낸 인터페이스에 있는 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "내보낸 인터페이스에 있는 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "이전 프로그램에서 변경되지 않았으므로 '{0}'에서 발생하는 모듈 확인을 다시 사용합니다.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "'{0}' 모듈 확인을 이전 프로그램의 '{1}' 파일에 다시 사용합니다.", + "Rewrite_as_the_indexed_access_type_0_90026": "인덱싱된 액세스 형식 '{0}'(으)로 다시 작성하세요.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "루트 디렉터리를 확인할 수 없어 기본 검색 경로를 건너뜁니다.", + "STRATEGY_6039": "전략", + "Scoped_package_detected_looking_in_0_6182": "범위가 지정된 패키지가 검색되었습니다. '{0}'에서 찾습니다.", + "Setters_cannot_return_a_value_2408": "Setter가 값을 반환할 수 없습니다.", + "Show_all_compiler_options_6169": "모든 컴파일러 옵션을 표시합니다.", + "Show_diagnostic_information_6149": "진단 정보를 표시합니다.", + "Show_verbose_diagnostic_information_6150": "자세한 진단 정보를 표시합니다.", + "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", + "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", + "Source_Map_Options_6175": "소스 맵 옵션", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "동적 가져오기의 지정자는 스프레드 요소일 수 없습니다.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript 대상 버전을 'ES3'(기본값), 'ES5', 'ES2015', 'ES2016', 'ES2017' 또는 'ESNEXT'로 지정합니다.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX 코드 생성 'preserve', 'react-native' 또는 'react'를 지정합니다.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "컴파일에 포함할 라이브러리 파일 지정: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "모듈 코드 생성을 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' 또는 'ESNext'로 지정합니다.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "모듈 확인 전략 지정: 'node'(Node.js) 또는 'classic'(TypeScript 1.6 이전).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'react' JSX 내보내기를 대상으로 하는 경우 사용할 JSX 팩터리 함수를 지정합니다(예: 'React.createElement' 또는 'h').", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "파일을 내보낼 때 사용할 줄 시퀀스의 끝 지정: 'CRLF'(dos) 또는 'LF'(unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "소스 위치 대신 디버거가 TypeScript 파일을 찾아야 하는 위치를 지정하세요.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "생성된 위치 대신 디버거가 맵 파일을 찾아야 하는 위치를 지정하세요.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "입력 파일의 루트 디렉터리를 지정하세요. --outDir이 포함된 출력 디렉터리 구조를 제어하는 데 사용됩니다.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 식에서 Spread 연산자는 ECMAScript 5 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 유형은 개체 형식에서만 만들 수 있습니다.", + "Statement_expected_1129": "문이 필요합니다.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "앰비언트 컨텍스트에서는 문이 허용되지 않습니다.", + "Static_members_cannot_reference_class_type_parameters_2302": "정적 멤버는 클래스 형식 매개 변수를 참조할 수 없습니다.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "정적 속성 '{0}'이(가) 생성자 함수 '{1}'의 기본 제공 속성 'Function.{0}'과(와) 충돌합니다.", + "Strict_Type_Checking_Options_6173": "엄격한 형식 검사 옵션", + "String_literal_expected_1141": "문자열 리터럴이 필요합니다.", + "String_literal_with_double_quotes_expected_1327": "큰따옴표로 묶은 문자열 리터럴이 필요합니다.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "색과 컨텍스트를 사용하여 오류 및 메시지를 스타일화합니다(실험적).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "후속 변수 선언에 같은 형식이 있어야 합니다. '{0}' 변수가 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' 패턴에 대한 '{0}' 대체의 형식이 잘못되었습니다. 'string'이 필요한데 '{2}'을(를) 얻었습니다.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "'{1}' 패턴의 '{0}' 대체에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "'{0}' 패턴에 대한 대체는 배열이 되어야 합니다.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "패턴 '{0}'에 대한 대체에는 배열이 비어 있지 않아야 합니다.", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json 파일을 만들었습니다.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "생성자 밖이나 생성자 내부에 중첩된 함수에서는 Super 호출이 허용되지 않습니다.", + "Suppress_excess_property_checks_for_object_literals_6072": "개체 리터럴에 대한 초과 속성 검사를 생략합니다.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "인덱스 시그니처가 없는 개체 인덱싱에 대한 noImplicitAny 오류를 표시하지 않습니다.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'기호' 참조에서 전역 기호 생성자 개체를 참조하지 않습니다.", + "Syntax_Colon_0_6023": "구문: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 연산자는 'symbol' 유형에 적용될 수 없습니다.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' 연산자는 부울 형식에 사용할 수 없습니다. 대신 '{1}'을(를) 사용하세요.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 형식은 할당할 수 있는 다른 형식이 거의 없습니다. 대신 'any' 형식을 사용할까요?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "'arguments' 개체는 ES3 및 ES5의 화살표 함수에서 참조할 수 없습니다. 표준 함수 식을 사용해 보세요.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "'arguments' 개체는 ES3 및 ES5의 비동기 함수 또는 메서드에서 참조할 수 없습니다. 표준 함수 또는 메서드를 사용해 보세요.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' 문의 본문이 빈 문이면 안 됩니다.", + "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_files_list_in_config_file_0_is_empty_18002": "'{0}' 구성 파일의 '파일' 목록이 비어 있습니다.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "프라미스에서 'then' 메서드의 첫 번째 매개 변수는 콜백이어야 합니다.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "전역 형식 'JSX.{0}'에 속성이 둘 이상 있을 수 없습니다.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 문의 왼쪽에는 구조 파괴 패턴을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' 문의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' 문의 왼쪽은 'string' 또는 'any' 형식이어야 합니다.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' 문의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "산술 연산 왼쪽은 'any', 'number' 또는 열거형 형식이어야 합니다.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "할당 식의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' 식의 왼쪽은 'any', 'string', 'number' 또는 'symbol' 유형이어야 합니다.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 식 왼쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 합니다.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "사용자에게 메시지를 표시할 때 사용되는 로캘입니다(예: 'en-us').", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules에서 검색하고 JavaScript 파일을 로드할 최대 종속성 깊이입니다.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "delete 연산자의 피연산자는 읽기 전용 속성일 수 없습니다.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "delete 연산자의 피연산자는 속성 참조여야 합니다.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "증가 또는 감소 연산자의 피연산자는 변수 또는 속성 액세스여야 합니다.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 요소 생성자의 반환 형식은 개체 형식을 반환해야 합니다.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "매개 변수 데코레이터 함수의 반환 형식은 'void' 또는 'any'여야 합니다.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "속성 데코레이터 함수의 반환 형식은 'void' 또는 'any'여야 합니다.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "비동기 함수의 반환 형식은 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "비동기 함수 또는 메서드의 반환 형식은 전역 Promise 형식이어야 합니다.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "'for...in' 문 오른쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 합니다.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "산술 연산 오른쪽은 'any', 'number' 또는 열거형 형식이어야 합니다.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 식의 오른쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 합니다.", + "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": "개체 rest 할당의 대상은 변수 또는 속성 액세스여야 합니다.", + "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}'의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하세요.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "비동기 반복기의 'next()' 메서드에서 반환하는 형식은 'value' 속성이 있는 형식에 대한 프라미스여야 합니다.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "반복기의 'next()' 메서드에 의해 반환되는 형식에는 'value' 속성이 있어야 합니다.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' 문은 지원되지 않습니다. 'with' 블록의 모든 기호가 'any' 형식이 됩니다.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "이 구문에는 가져온 도우미가 필요하지만 '{0}' 모듈을 찾을 수 없습니다.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "이 구문에는 가져온 도우미 '{1}'이(가) 필요하지만 '{0}' 모듈에 내보낸 멤버 '{1}'이(가) 없습니다.", + "Trailing_comma_not_allowed_1009": "후행 쉼표는 허용되지 않습니다.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "각 파일을 별도 모듈로 변환 컴파일합니다('ts.transpileModule'과 유사).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "`npm install @types/{0}`이(가) 있으면 이를 사용하거나 `declare module '{0}';`이 포함된 선언(.d.ts) 파일을 추가하세요.", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs'의 다른 항목을 시도하는 중입니다.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "'{0}' 대체를 시도하는 중입니다. 후보 모듈 위치: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "길이가 '{1}'인 튜플 형식 '{0}'을(를) 길이가 '{2}'인 튜플에 할당할 수 없습니다.", + "Type_0_cannot_be_converted_to_type_1_2352": "'{0}' 형식을 '{1}' 형식으로 변환할 수 없습니다.", + "Type_0_cannot_be_used_as_an_index_type_2538": "'{0}' 형식을 인덱스 형식으로 사용할 수 없습니다.", + "Type_0_cannot_be_used_to_index_type_1_2536": "'{0}' 형식을 인덱스 형식 '{1}'에 사용할 수 없습니다.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "'{0}' 형식이 '{1}' 제약 조건을 만족하지 않습니다.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "'{0}' 형식에 '{1}' 형식에 대한 일치하는 인덱스 시그니처가 없습니다.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "'{0}' 유형에 '{1}' 유형과 공통적인 속성이 없습니다.", + "Type_0_has_no_property_1_2460": "'{0}' 형식에 '{1}' 속성이 없습니다.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "'{0}' 형식에 '{1}' 속성과 문자열 인덱스 시그니처가 없습니다.", + "Type_0_is_not_a_constructor_function_type_2507": "'{0}' 형식은 생성자 함수 형식이 아닙니다.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "'{0}' 형식은 Promise 호환 생성자 값을 참조하지 않으므로 ES5/ES3에서 유효한 비동기 함수 반환 형식이 아닙니다.", + "Type_0_is_not_an_array_type_2461": "'{0}' 형식은 배열 형식이 아닙니다.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아닙니다.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아니거나, 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' 형식은 배열 형식이 아니거나 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", + "Type_0_is_not_assignable_to_type_1_2322": "'{0}' 형식은 '{1}' 형식에 할당할 수 없습니다.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "'{0}' 형식을 '{1}' 형식에 할당할 수 없습니다. 이름이 같은 2개의 서로 다른 형식이 있지만 서로 관련은 없습니다.", + "Type_0_is_not_comparable_to_type_1_2678": "'{0}' 형식을 '{1}' 형식과 비교할 수 없습니다.", + "Type_0_is_not_generic_2315": "'{0}' 형식이 제네릭이 아닙니다.", + "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' 형식에서 '{1}' 시그니처에 대한 일치하는 항목을 제공하지 않습니다.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Type '{0}' 형식은 자기 자신을 기본 형식으로 재귀적으로 참조합니다.", + "Type_alias_0_circularly_references_itself_2456": "'{0}' 형식 별칭은 순환적으로 자신을 참조합니다.", + "Type_alias_name_cannot_be_0_2457": "형식 별칭 이름은 '{0}'일 수 없습니다.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "형식 주석은 생성자 선언에 표시될 수 없습니다.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "형식 인수 후보 '{1}'은(는) '{0}' 후보의 상위 형식이 아니므로 유효한 형식 인수가 아닙니다.", + "Type_argument_expected_1140": "형식 인수가 필요합니다.", + "Type_argument_list_cannot_be_empty_1099": "형식 인수 목록은 비워 둘 수 없습니다.", + "Type_declaration_files_to_be_included_in_compilation_6124": "컴파일에 포함할 선언 파일을 입력하세요.", + "Type_expected_1110": "형식이 필요합니다.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "형식은 자체 'then' 메서드의 처리 콜백에서 직간접적으로 참조됩니다.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "형식에는 비동기 반복기를 반환하는 '[Symbol.asyncIterator]()' 메서드가 있어야 합니다.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "형식에는 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 있어야 합니다.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", + "Type_parameter_0_has_a_circular_default_2716": "형식 매개 변수 '{0}'에 순환 기본값이 있습니다.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "내보낸 인터페이스에 있는 생성자 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "내보낸 클래스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "내보낸 함수의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "내보낸 인터페이스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "내보낸 형식 별칭의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "내보낸 인터페이스에 있는 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "내보낸 클래스에 있는 공용 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "내보낸 클래스에 있는 공용 정적 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_declaration_expected_1139": "형식 매개 변수 선언이 필요합니다.", + "Type_parameter_list_cannot_be_empty_1098": "형식 매개 변수 목록은 비워 둘 수 없습니다.", + "Type_parameter_name_cannot_be_0_2368": "형식 매개 변수 이름은 '{0}'일 수 없습니다.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "형식 매개 변수는 생성자 선언에 표시될 수 없습니다.", + "Type_predicate_0_is_not_assignable_to_1_1226": "형식 조건자 '{0}'을(를) '{1}'에 할당할 수 없습니다.", + "Type_reference_directive_0_was_not_resolved_6120": "======== 형식 참조 지시문 '{0}'이(가) 확인되지 않았습니다. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 형식 참조 지시문 '{0}'이(가) '{1}'(으)로 확인되었습니다. 주: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "형식에 별도의 전용 속성 '{0}' 선언이 있습니다.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' 및 '{1}' 매개 변수의 형식이 호환되지 않습니다.", + "Types_of_property_0_are_incompatible_2326": "'{0}' 속성의 형식이 호환되지 않습니다.", + "Unable_to_open_file_0_6050": "'{0}' 파일을 열 수 없습니다.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "식으로 호출된 경우 클래스 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "식으로 호출된 경우 메서드 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "식으로 호출된 경우 매개 변수 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "식으로 호출된 경우 속성 데코레이터의 서명을 확인할 수 없습니다.", + "Unexpected_end_of_text_1126": "예기치 않은 텍스트 끝입니다.", + "Unexpected_token_1012": "예기치 않은 토큰입니다.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "예기치 않은 토큰입니다. 생성자, 메서드, 접근자 또는 속성이 필요합니다.", + "Unexpected_token_expected_1179": "예기치 않은 토큰입니다. '{'가 있어야 합니다.", + "Unknown_compiler_option_0_5023": "알 수 없는 컴파일러 옵션 '{0}'입니다.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "알 수 없는 옵션 'excludes'입니다. 'exclude'를 사용하시겠습니까?", + "Unknown_type_acquisition_option_0_17010": "알 수 없는 형식 인식 옵션 '{0}'입니다.", + "Unreachable_code_detected_7027": "접근할 수 없는 코드가 있습니다.", + "Unsupported_locale_0_6049": "지원되지 않는 로캘 '{0}'입니다.", + "Unterminated_Unicode_escape_sequence_1199": "종결되지 않은 유니코드 이스케이프 시퀀스입니다.", + "Unterminated_quoted_string_in_response_file_0_6045": "응답 파일 '{0}'의 종결되지 않은 따옴표 붙은 문자열입니다.", + "Unterminated_regular_expression_literal_1161": "종결되지 않은 정규식 리터럴입니다.", + "Unterminated_string_literal_1002": "종결되지 않은 문자열 리터럴입니다.", + "Unterminated_template_literal_1160": "종결되지 않은 템플릿 리터럴입니다.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "형식화되지 않은 함수 호출에는 형식 인수를 사용할 수 없습니다.", + "Unused_label_7028": "사용되지 않는 레이블입니다.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", + "VERSION_6036": "버전", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' 형식의 값에 '{1}' 형식과 공통된 속성이 없습니다. 속성을 호출하려고 했습니까?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "'{0}' 형식의 값은 호출할 수 없습니다. 'new'를 포함하려고 했습니까?", + "Variable_0_implicitly_has_an_1_type_7005": "'{0}' 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "'{0}' 변수는 형식을 확인할 수 없는 경우 일부 위치에서 암시적으로 '{1}' 형식입니다.", + "Variable_0_is_used_before_being_assigned_2454": "'{0}' 변수가 할당되기 전에 사용되었습니다.", + "Variable_declaration_expected_1134": "변수 선언이 필요합니다.", + "Variable_declaration_list_cannot_be_empty_1123": "변수 선언 목록은 비워 둘 수 없습니다.", + "Version_0_6029": "버전 {0}", + "Watch_input_files_6005": "조사식 입력 파일입니다.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "표준 TypeScript 라이브러리에 정의된 요소의 이름을 바꿀 수 없습니다.", + "You_cannot_rename_this_element_8000": "이 요소의 이름을 바꿀 수 없습니다.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}'이(가) 여기에서 decorator로 사용할 인수를 너무 적게 허용합니다. 먼저 이를 호출하고 '@{0}()'을(를) 작성하시겠습니까?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}'이(가) 두 번 지정되었습니다. 이름이 '{0}'인 특성을 덮어씁니다.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}'은(는) .ts 파일에서만 사용할 수 있습니다.", + "_0_expected_1005": "'{0}'이(가) 필요합니다.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "반환 형식 주석이 없고 반환 식 중 하나에서 직간접적으로 참조되므로 '{0}'에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}'은(는) 형식 주석이 없고 자체 이니셜라이저에서 직간접적으로 참조되므로 암시적으로 'any' 형식입니다.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0}'은(는) 기본 개체이지만 '{1}'은(는) 래퍼 개체입니다. 가능한 경우 '{0}'을(를) 사용하세요.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}'은(는) '{1}' 키워드에 대한 올바른 메타 속성이 아닙니다. '{2}'을(를) 사용하시겠습니까?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}'은(는) 자체 기본 식에서 직간접적으로 참조됩니다.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}'은(는) 자체 형식 주석에서 직간접적으로 참조됩니다.", + "_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_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' 한정자는 클래스, 메서드 또는 속성 선언에만 나타날 수 있습니다.", + "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": "'='는 구조 파괴 할당 내의 개체 리터럴 속성에서만 사용할 수 있습니다.", + "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' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽에서만 사용할 수 있습니다.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "export_can_only_be_used_in_a_ts_file_8003": "'export='는 .ts 파일에서만 사용할 수 있습니다.", + "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}'을(를) 가지고 있거나 사용 중입니다.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "내보낸 인터페이스 '{0}'의 Extends 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "file_6025": "파일", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' 및 'set' 접근자는 동일한 'this' 형식이어야 합니다.", + "get_and_set_accessor_must_have_the_same_type_2380": "'get' 및 'set' 접근자의 형식이 같아야 합니다.", + "implements_clause_already_seen_1175": "'implements' 절이 이미 있습니다.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses'는 .ts 파일에서만 사용할 수 있습니다.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... ='는 .ts 파일에서만 사용할 수 있습니다.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "'let' 선언은 블록 내부에서만 선언될 수 있습니다.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let'은 'let' 또는 'const' 선언에서 이름으로 사용할 수 없습니다.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "배열을 만드는 데 'new T[]'를 사용할 수 없습니다. 대신 'new Array()'를 사용하세요.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "대상에 구문 시그니처가 없는 'new' 식에는 암시적으로 'any' 형식이 포함됩니다.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions'는 .ts 파일에서만 사용할 수 있습니다.", + "options_6024": "옵션", + "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 파일에서만 사용할 수 있습니다.", + "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' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 옵션이 설정되어 있습니다. 상대 모듈 이름 '{0}'을(를) 확인하려면 이 옵션을 사용합니다.", + "super_can_only_be_referenced_in_a_derived_class_2335": "파생 클래스에서만 'super'를 참조할 수 있습니다.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "파생 클래스 또는 개체 리터럴 식의 멤버에서만 'super'를 참조할 수 있습니다.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super'는 계산된 속성 이름에서 참조할 수 없습니다.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "super'는 생성자 인수에서 참조할 수 없습니다.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "옵션 'target'이 'ES2015' 이상인 경우 개체 리터럴 식의 멤버에서만 'super'를 사용할 수 있습니다.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "파생 클래스의 생성자에서 'super'의 속성에 액세스하기 전에 'super'를 호출해야 합니다.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "파생 클래스의 생성자에서 'this'에 액세스하기 전에 'super'를 호출해야 합니다.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' 다음에는 인수 목록 또는 멤버 액세스가 와야 합니다.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' 속성 액세스는 생성자, 멤버 함수 또는 파생 클래스의 멤버 접근자에서만 허용됩니다.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this'는 계산된 속성 이름에서 참조할 수 없습니다.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this'는 모듈 또는 네임스페이스 본문에서 참조될 수 없습니다.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "정적 속성 이니셜라이저에서 'this'를 참조할 수 없습니다.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "생성자 인수에서 'this'를 참조할 수 없습니다.", + "this_cannot_be_referenced_in_current_location_2332": "현재 위치에서 'this'를 참조할 수 없습니다.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this'에는 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases'는 .ts 파일에서만 사용할 수 있습니다.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments'는 .ts 파일에서만 사용할 수 있습니다.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions'는 .ts 파일에서만 사용할 수 있습니다.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations'는 .ts 파일에서만 사용할 수 있습니다.", + "types_can_only_be_used_in_a_ts_file_8010": "'types'는 .ts 파일에서만 사용할 수 있습니다.", + "unique_symbol_types_are_not_allowed_here_1335": "여기에서 '고유 기호' 형식은 허용되지 않습니다.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'고유 기호' 형식은 변수 문의 변수에만 허용됩니다.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'고유 기호' 형식은 바인딩 이름과 함께 변수 선언에 사용할 수 없습니다.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 문은 비동기 함수 블록에서 사용할 수 없습니다.", + "with_statements_are_not_allowed_in_strict_mode_1101": "'with' 문은 strict 모드에서 사용할 수 없습니다.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 식은 매개 변수 이니셜라이저에서 사용할 수 없습니다." +} \ No newline at end of file diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 7074d06c1a9b2..6d3d437bf6dec 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -82,6 +82,18 @@ declare function encodeURI(uri: string): string; */ declare function encodeURIComponent(uriComponent: string): string; +/** + * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. + * @param string A string value + */ +declare function escape(string: string): string; + +/** + * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. + * @param string A string value + */ +declare function unescape(string: string): string; + interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; @@ -1070,7 +1082,8 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1082,7 +1095,8 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1220,7 +1234,8 @@ interface Array { * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1232,7 +1247,8 @@ interface Array { * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1667,7 +1683,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1691,7 +1708,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -1934,7 +1952,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1958,7 +1977,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2201,7 +2221,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2225,7 +2246,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2466,7 +2488,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2490,7 +2513,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2734,7 +2758,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2758,7 +2783,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3001,7 +3027,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3025,7 +3052,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3267,7 +3295,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3291,7 +3320,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3534,7 +3564,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3558,7 +3589,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3802,7 +3834,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3826,7 +3859,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4166,8 +4200,8 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } -interface CustomEventInit extends EventInit { - detail?: any; +interface CustomEventInit extends EventInit { + detail?: T; } interface DeviceAccelerationDict { @@ -4287,7 +4321,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface IntersectionObserverEntryInit { @@ -4780,7 +4814,7 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; total?: PaymentItem; } @@ -4792,7 +4826,7 @@ interface PaymentItem { interface PaymentMethodData { data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; } interface PaymentOptions { @@ -4857,7 +4891,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -4869,7 +4903,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -5339,8 +5373,10 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ApplicationCache: { @@ -5396,8 +5432,10 @@ interface AudioBufferSourceNode extends AudioNode { readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AudioBufferSourceNode: { @@ -5438,8 +5476,10 @@ interface AudioContextBase extends EventTarget { createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; resume(): Promise; - addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface AudioContext extends AudioContextBase { @@ -5546,8 +5586,10 @@ interface AudioTrackList extends EventTarget { onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: AudioTrack; } @@ -5673,6 +5715,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { beginPath(): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; @@ -5682,11 +5725,13 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; restore(): void; @@ -6450,20 +6495,22 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } declare var CustomEvent: { prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; interface DataCue extends TextTrackCue { data: ArrayBuffer; - addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DataCue: { @@ -7314,7 +7361,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -7385,8 +7433,10 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Document: { @@ -7669,7 +7719,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -7698,6 +7749,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scroll(options?: ScrollToOptions): void; @@ -7710,8 +7763,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; - addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Element: { @@ -7847,8 +7902,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -7969,7 +8026,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface History { @@ -8080,8 +8137,10 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAnchorElement: { @@ -8154,8 +8213,10 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; - addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAppletElement: { @@ -8222,8 +8283,10 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAreaElement: { @@ -8240,8 +8303,10 @@ declare var HTMLAreasCollection: { }; interface HTMLAudioElement extends HTMLMediaElement { - addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAudioElement: { @@ -8258,8 +8323,10 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseElement: { @@ -8276,8 +8343,10 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseFontElement: { @@ -8317,11 +8386,7 @@ interface HTMLBodyElement extends HTMLElement { onafterprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; - onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; - onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; - onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; - onload: (this: HTMLBodyElement, ev: Event) => any; onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; onoffline: (this: HTMLBodyElement, ev: Event) => any; ononline: (this: HTMLBodyElement, ev: Event) => any; @@ -8330,13 +8395,14 @@ interface HTMLBodyElement extends HTMLElement { onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; onresize: (this: HTMLBodyElement, ev: UIEvent) => any; - onscroll: (this: HTMLBodyElement, ev: UIEvent) => any; onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBodyElement: { @@ -8349,8 +8415,10 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBRElement: { @@ -8422,8 +8490,10 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLButtonElement: { @@ -8457,8 +8527,10 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; - addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLCanvasElement: { @@ -8492,8 +8564,10 @@ declare var HTMLCollection: { interface HTMLDataElement extends HTMLElement { value: string; - addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataElement: { @@ -8503,8 +8577,10 @@ declare var HTMLDataElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; - addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataListElement: { @@ -8514,8 +8590,10 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDirectoryElement: { @@ -8532,8 +8610,10 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; - addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDivElement: { @@ -8543,8 +8623,10 @@ declare var HTMLDivElement: { interface HTMLDListElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDListElement: { @@ -8553,8 +8635,10 @@ declare var HTMLDListElement: { }; interface HTMLDocument extends Document { - addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDocument: { @@ -8726,8 +8810,10 @@ interface HTMLElement extends Element { dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLElement: { @@ -8782,8 +8868,10 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLEmbedElement: { @@ -8823,8 +8911,10 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFieldSetElement: { @@ -8837,8 +8927,10 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; - addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFontElement: { @@ -8922,8 +9014,11 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; - addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -8985,10 +9080,6 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -9001,8 +9092,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameElement: { @@ -9054,17 +9147,7 @@ interface HTMLFrameSetElement extends HTMLElement { onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; - onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; - onload: (this: HTMLFrameSetElement, ev: Event) => any; onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; onoffline: (this: HTMLFrameSetElement, ev: Event) => any; ononline: (this: HTMLFrameSetElement, ev: Event) => any; @@ -9073,15 +9156,16 @@ interface HTMLFrameSetElement extends HTMLElement { onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; - onscroll: (this: HTMLFrameSetElement, ev: UIEvent) => any; onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameSetElement: { @@ -9091,8 +9175,10 @@ declare var HTMLFrameSetElement: { interface HTMLHeadElement extends HTMLElement { profile: string; - addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadElement: { @@ -9105,8 +9191,10 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; - addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadingElement: { @@ -9127,8 +9215,10 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHRElement: { @@ -9141,8 +9231,10 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; - addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHtmlElement: { @@ -9209,10 +9301,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -9230,8 +9318,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLIFrameElement: { @@ -9321,8 +9411,10 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; - addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLImageElement: { @@ -9533,8 +9625,10 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; - addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLInputElement: { @@ -9551,8 +9645,11 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; - addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLabelElement: { @@ -9569,8 +9666,10 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement | null; - addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLegendElement: { @@ -9584,8 +9683,10 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLIElement: { @@ -9629,8 +9730,10 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; - addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLinkElement: { @@ -9647,8 +9750,10 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMapElement: { @@ -9679,8 +9784,10 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMarqueeElement: { @@ -9861,8 +9968,10 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMediaElement: { @@ -9882,8 +9991,10 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMenuElement: { @@ -9916,8 +10027,10 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; - addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMetaElement: { @@ -9932,8 +10045,10 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; - addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMeterElement: { @@ -9950,8 +10065,10 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; - addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLModElement: { @@ -10067,8 +10184,10 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLObjectElement: { @@ -10083,8 +10202,10 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; - addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOListElement: { @@ -10122,8 +10243,10 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptGroupElement: { @@ -10161,8 +10284,10 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptionElement: { @@ -10195,8 +10320,10 @@ interface HTMLOutputElement extends HTMLElement { checkValidity(): boolean; reportValidity(): boolean; setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOutputElement: { @@ -10210,8 +10337,10 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; - addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParagraphElement: { @@ -10236,8 +10365,10 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; - addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParamElement: { @@ -10246,8 +10377,10 @@ declare var HTMLParamElement: { }; interface HTMLPictureElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPictureElement: { @@ -10260,8 +10393,10 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPreElement: { @@ -10286,8 +10421,10 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; - addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLProgressElement: { @@ -10300,8 +10437,10 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; - addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLQuoteElement: { @@ -10341,8 +10480,10 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; - addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLScriptElement: { @@ -10437,8 +10578,10 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -10463,8 +10606,10 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; - addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSourceElement: { @@ -10473,8 +10618,10 @@ declare var HTMLSourceElement: { }; interface HTMLSpanElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSpanElement: { @@ -10492,8 +10639,10 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; - addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLStyleElement: { @@ -10510,8 +10659,10 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; - addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCaptionElement: { @@ -10565,8 +10716,10 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCellElement: { @@ -10587,8 +10740,10 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; - addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableColElement: { @@ -10597,8 +10752,10 @@ declare var HTMLTableColElement: { }; interface HTMLTableDataCellElement extends HTMLTableCellElement { - addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableDataCellElement: { @@ -10710,8 +10867,10 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableElement: { @@ -10724,8 +10883,10 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; - addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableHeaderCellElement: { @@ -10765,8 +10926,10 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableRowElement: { @@ -10793,8 +10956,10 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableSectionElement: { @@ -10804,8 +10969,10 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; - addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTemplateElement: { @@ -10911,8 +11078,10 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; - addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTextAreaElement: { @@ -10922,8 +11091,10 @@ declare var HTMLTextAreaElement: { interface HTMLTimeElement extends HTMLElement { dateTime: string; - addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTimeElement: { @@ -10936,8 +11107,10 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; - addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTitleElement: { @@ -10957,8 +11130,10 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; - addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTrackElement: { @@ -10973,8 +11148,10 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUListElement: { @@ -10983,8 +11160,10 @@ declare var HTMLUListElement: { }; interface HTMLUnknownElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUnknownElement: { @@ -11038,8 +11217,10 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullScreen(): void; webkitExitFullscreen(): void; webkitExitFullScreen(): void; - addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLVideoElement: { @@ -11096,9 +11277,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -11182,8 +11366,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -11204,8 +11390,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -11231,8 +11419,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -11401,8 +11591,10 @@ interface MediaDevices extends EventTarget { enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaDevices: { @@ -11573,8 +11765,10 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStream: { @@ -11645,8 +11839,10 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStreamTrack: { @@ -11695,8 +11891,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -11800,8 +11998,10 @@ interface MSAppAsyncOperation extends EventTarget { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSAppAsyncOperation: { @@ -11956,8 +12156,10 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; - addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSHTMLWebViewElement: { @@ -11982,8 +12184,10 @@ interface MSInputMethodContext extends EventTarget { getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSInputMethodContext: { @@ -12148,8 +12352,10 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSStreamReader: { @@ -12177,8 +12383,10 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSWebViewAsyncOperation: { @@ -12309,6 +12517,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly pointerEnabled: boolean; readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; + readonly doNotTrack: string | null; readonly hardwareConcurrency: number; readonly languages: string[]; getGamepads(): Gamepad[]; @@ -12467,8 +12676,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -12547,8 +12758,10 @@ interface OfflineAudioContext extends AudioContextBase { oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; startRendering(): Promise; suspend(suspendTime: number): Promise; - addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OfflineAudioContext: { @@ -12568,8 +12781,10 @@ interface OscillatorNode extends AudioNode { setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OscillatorNode: { @@ -12663,8 +12878,10 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; show(): Promise; - addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentRequest: { @@ -13170,8 +13387,10 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtlsTransport: { @@ -13200,8 +13419,10 @@ interface RTCDtmfSender extends EventTarget { readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtmfSender: { @@ -13251,8 +13472,10 @@ interface RTCIceGatherer extends RTCStatsProvider { createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidateDictionary[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceGatherer: { @@ -13289,8 +13512,10 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; stop(): void; - addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceTransport: { @@ -13344,8 +13569,10 @@ interface RTCPeerConnection extends EventTarget { removeStream(stream: MediaStream): void; setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCPeerConnection: { @@ -13376,8 +13603,10 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpReceiver: { @@ -13401,8 +13630,10 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpSender: { @@ -13429,8 +13660,10 @@ interface RTCSrtpSdesTransportEventMap { interface RTCSrtpSdesTransport extends EventTarget { onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCSrtpSdesTransport: { @@ -13501,8 +13734,10 @@ interface Screen extends EventTarget { readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -13527,8 +13762,10 @@ interface ScriptProcessorNodeEventMap { interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ScriptProcessorNode: { @@ -13579,8 +13816,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -13598,11 +13837,13 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(): Promise; + getRegistration(clientURL?: USVString): Promise; getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerContainer: { @@ -13639,8 +13880,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -13693,8 +13936,10 @@ interface SpeechSynthesis extends EventTarget { pause(): void; resume(): void; speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesis: { @@ -13738,8 +13983,10 @@ interface SpeechSynthesisUtterance extends EventTarget { text: string; voice: SpeechSynthesisVoice; volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesisUtterance: { @@ -13873,8 +14120,10 @@ declare var SubtleCrypto: { interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGAElement: { @@ -14030,8 +14279,10 @@ interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGCircleElement: { @@ -14041,8 +14292,10 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGClipPathElement: { @@ -14064,8 +14317,10 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGComponentTransferFunctionElement: { @@ -14080,8 +14335,10 @@ declare var SVGComponentTransferFunctionElement: { }; interface SVGDefsElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDefsElement: { @@ -14090,8 +14347,10 @@ declare var SVGDefsElement: { }; interface SVGDescElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDescElement: { @@ -14128,8 +14387,10 @@ interface SVGElement extends Element { readonly style: CSSStyleDeclaration; readonly viewportElement: SVGElement; xmlbase: string; - addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGElement: { @@ -14168,8 +14429,10 @@ interface SVGEllipseElement extends SVGGraphicsElement { readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGEllipseElement: { @@ -14198,8 +14461,10 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEBlendElement: { @@ -14233,8 +14498,10 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEColorMatrixElement: { @@ -14249,8 +14516,10 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEComponentTransferElement: { @@ -14273,8 +14542,10 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFECompositeElement: { @@ -14306,8 +14577,10 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEConvolveMatrixElement: { @@ -14325,8 +14598,10 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDiffuseLightingElement: { @@ -14345,8 +14620,10 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDisplacementMapElement: { @@ -14362,8 +14639,10 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDistantLightElement: { @@ -14372,8 +14651,10 @@ declare var SVGFEDistantLightElement: { }; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFloodElement: { @@ -14382,8 +14663,10 @@ declare var SVGFEFloodElement: { }; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncAElement: { @@ -14392,8 +14675,10 @@ declare var SVGFEFuncAElement: { }; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncBElement: { @@ -14402,8 +14687,10 @@ declare var SVGFEFuncBElement: { }; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncGElement: { @@ -14412,8 +14699,10 @@ declare var SVGFEFuncGElement: { }; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncRElement: { @@ -14426,8 +14715,10 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEGaussianBlurElement: { @@ -14437,8 +14728,10 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEImageElement: { @@ -14447,8 +14740,10 @@ declare var SVGFEImageElement: { }; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeElement: { @@ -14458,8 +14753,10 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeNodeElement: { @@ -14475,8 +14772,10 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMorphologyElement: { @@ -14491,8 +14790,10 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEOffsetElement: { @@ -14504,8 +14805,10 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEPointLightElement: { @@ -14520,8 +14823,10 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpecularLightingElement: { @@ -14538,8 +14843,10 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpotLightElement: { @@ -14549,8 +14856,10 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETileElement: { @@ -14571,8 +14880,10 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETurbulenceElement: { @@ -14596,8 +14907,10 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFilterElement: { @@ -14610,8 +14923,10 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGForeignObjectElement: { @@ -14620,8 +14935,10 @@ declare var SVGForeignObjectElement: { }; interface SVGGElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGElement: { @@ -14637,8 +14954,10 @@ interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGradientElement: { @@ -14658,8 +14977,10 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; - addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGraphicsElement: { @@ -14673,8 +14994,10 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGImageElement: { @@ -14739,8 +15062,10 @@ interface SVGLinearGradientElement extends SVGGradientElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLinearGradientElement: { @@ -14753,8 +15078,10 @@ interface SVGLineElement extends SVGGraphicsElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLineElement: { @@ -14778,8 +15105,10 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly SVG_MARKERUNITS_STROKEWIDTH: number; readonly SVG_MARKERUNITS_UNKNOWN: number; readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMarkerElement: { @@ -14800,8 +15129,10 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMaskElement: { @@ -14835,8 +15166,10 @@ declare var SVGMatrix: { }; interface SVGMetadataElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMetadataElement: { @@ -14893,8 +15226,10 @@ interface SVGPathElement extends SVGGraphicsElement { getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; - addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPathElement: { @@ -15186,8 +15521,10 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPatternElement: { @@ -15223,8 +15560,10 @@ declare var SVGPointList: { }; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolygonElement: { @@ -15233,8 +15572,10 @@ declare var SVGPolygonElement: { }; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolylineElement: { @@ -15286,8 +15627,10 @@ interface SVGRadialGradientElement extends SVGGradientElement { readonly fx: SVGAnimatedLength; readonly fy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRadialGradientElement: { @@ -15314,8 +15657,10 @@ interface SVGRectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRectElement: { @@ -15325,8 +15670,10 @@ declare var SVGRectElement: { interface SVGScriptElement extends SVGElement, SVGURIReference { type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGScriptElement: { @@ -15336,8 +15683,10 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement { readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStopElement: { @@ -15366,8 +15715,10 @@ interface SVGStyleElement extends SVGElement { media: string; title: string; type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStyleElement: { @@ -15427,8 +15778,10 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSVGElement: { @@ -15437,8 +15790,10 @@ declare var SVGSVGElement: { }; interface SVGSwitchElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSwitchElement: { @@ -15447,8 +15802,10 @@ declare var SVGSwitchElement: { }; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { - addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSymbolElement: { @@ -15471,8 +15828,10 @@ interface SVGTextContentElement extends SVGGraphicsElement { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextContentElement: { @@ -15484,8 +15843,10 @@ declare var SVGTextContentElement: { }; interface SVGTextElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextElement: { @@ -15503,8 +15864,10 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPathElement: { @@ -15524,8 +15887,10 @@ interface SVGTextPositioningElement extends SVGTextContentElement { readonly rotate: SVGAnimatedNumberList; readonly x: SVGAnimatedLengthList; readonly y: SVGAnimatedLengthList; - addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPositioningElement: { @@ -15534,8 +15899,10 @@ declare var SVGTextPositioningElement: { }; interface SVGTitleElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTitleElement: { @@ -15593,8 +15960,10 @@ declare var SVGTransformList: { }; interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTSpanElement: { @@ -15616,8 +15985,10 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGUseElement: { @@ -15627,8 +15998,10 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; - addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGViewElement: { @@ -15748,8 +16121,10 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrack: { @@ -15779,8 +16154,10 @@ interface TextTrackCue extends EventTarget { text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrackCue: { @@ -15808,8 +16185,10 @@ interface TextTrackList extends EventTarget { readonly length: number; onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: TextTrack; } @@ -16017,8 +16396,10 @@ interface VideoTrackList extends EventTarget { readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: VideoTrack; } @@ -16222,7 +16603,29 @@ interface WebGLRenderingContext { getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; - getExtension(name: string): any; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram | null): string | null; @@ -17036,8 +17439,10 @@ declare var WebKitPoint: { }; interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var webkitRTCPeerConnection: { @@ -17069,8 +17474,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -17361,7 +17768,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; postMessage(message: any, targetOrigin: string, transfer?: any[]): void; print(): void; prompt(message?: string, _default?: string): string | null; @@ -17382,8 +17789,10 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Window: { @@ -17399,8 +17808,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -17409,8 +17820,10 @@ declare var Worker: { }; interface XMLDocument extends Document { - addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLDocument: { @@ -17451,8 +17864,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -17466,8 +17881,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -17572,8 +17989,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -17718,8 +18137,10 @@ interface GlobalEventHandlers { onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; - addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface GlobalFetch { @@ -17771,8 +18192,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface MSFileSaver { @@ -17829,9 +18252,11 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; - querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -17918,8 +18343,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface BroadcastChannel extends EventTarget { @@ -17928,8 +18355,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -18110,7 +18539,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -18346,6 +18775,128 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -18413,28 +18964,46 @@ interface VoidFunction { } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; "audio": HTMLAudioElement; + "b": HTMLElement; "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; "col": HTMLTableColElement; "colgroup": HTMLTableColElement; "data": HTMLDataElement; "datalist": HTMLDataListElement; + "dd": HTMLElement; "del": HTMLModElement; + "dfn": HTMLElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; "embed": HTMLEmbedElement; "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; "font": HTMLFontElement; + "footer": HTMLElement; "form": HTMLFormElement; "frame": HTMLFrameElement; "frameset": HTMLFrameSetElement; @@ -18445,24 +19014,34 @@ interface HTMLElementTagNameMap { "h5": HTMLHeadingElement; "h6": HTMLHeadingElement; "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; "hr": HTMLHRElement; "html": HTMLHtmlElement; + "i": HTMLElement; "iframe": HTMLIFrameElement; "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; "listing": HTMLPreElement; "map": HTMLMapElement; + "mark": HTMLElement; "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; + "nav": HTMLElement; "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; "optgroup": HTMLOptGroupElement; @@ -18471,14 +19050,25 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; + "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; "script": HTMLScriptElement; + "section": HTMLElement; "select": HTMLSelectElement; + "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; "table": HTMLTableElement; "tbody": HTMLTableSectionElement; "td": HTMLTableDataCellElement; @@ -18491,33 +19081,22 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; "ul": HTMLUListElement; + "var": HTMLElement; "video": HTMLVideoElement; + "wbr": HTMLElement; "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } -interface ElementTagNameMap extends HTMLElementTagNameMap { - "abbr": HTMLElement; - "acronym": HTMLElement; - "address": HTMLElement; - "article": HTMLElement; - "aside": HTMLElement; - "b": HTMLElement; - "bdo": HTMLElement; - "big": HTMLElement; - "center": HTMLElement; +interface SVGElementTagNameMap { "circle": SVGCircleElement; - "cite": HTMLElement; "clippath": SVGClipPathElement; - "code": HTMLElement; - "dd": HTMLElement; "defs": SVGDefsElement; "desc": SVGDescElement; - "dfn": HTMLElement; - "dt": HTMLElement; "ellipse": SVGEllipseElement; - "em": HTMLElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -18542,63 +19121,33 @@ interface ElementTagNameMap extends HTMLElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "figcaption": HTMLElement; - "figure": HTMLElement; "filter": SVGFilterElement; - "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; "g": SVGGElement; - "header": HTMLElement; - "hgroup": HTMLElement; - "i": HTMLElement; "image": SVGImageElement; - "kbd": HTMLElement; - "keygen": HTMLElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "mark": HTMLElement; "marker": SVGMarkerElement; "mask": SVGMaskElement; "metadata": SVGMetadataElement; - "nav": HTMLElement; - "nobr": HTMLElement; - "noframes": HTMLElement; - "noscript": HTMLElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; - "rt": HTMLElement; - "ruby": HTMLElement; - "s": HTMLElement; - "samp": HTMLElement; - "section": HTMLElement; - "small": HTMLElement; "stop": SVGStopElement; - "strike": HTMLElement; - "strong": HTMLElement; - "sub": HTMLElement; - "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; "text": SVGTextElement; "textpath": SVGTextPathElement; "tspan": SVGTSpanElement; - "tt": HTMLElement; - "u": HTMLElement; "use": SVGUseElement; - "var": HTMLElement; "view": SVGViewElement; - "wbr": HTMLElement; } -type ElementListTagNameMap = { - [key in keyof ElementTagNameMap]: NodeListOf -}; +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; @@ -18761,7 +19310,7 @@ declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; @@ -18784,7 +19333,6 @@ declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; @@ -18810,8 +19358,10 @@ declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; -declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; @@ -18835,7 +19385,6 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -18856,6 +19405,7 @@ type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 948510a2bc386..0c3292a3bbc09 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -102,8 +102,8 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } -interface CustomEventInit extends EventInit { - detail?: any; +interface CustomEventInit extends EventInit { + detail?: T; } interface DeviceAccelerationDict { @@ -223,7 +223,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface IntersectionObserverEntryInit { @@ -716,7 +716,7 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; total?: PaymentItem; } @@ -728,7 +728,7 @@ interface PaymentItem { interface PaymentMethodData { data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; } interface PaymentOptions { @@ -793,7 +793,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -805,7 +805,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -1275,8 +1275,10 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ApplicationCache: { @@ -1332,8 +1334,10 @@ interface AudioBufferSourceNode extends AudioNode { readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AudioBufferSourceNode: { @@ -1374,8 +1378,10 @@ interface AudioContextBase extends EventTarget { createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; resume(): Promise; - addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface AudioContext extends AudioContextBase { @@ -1482,8 +1488,10 @@ interface AudioTrackList extends EventTarget { onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: AudioTrack; } @@ -1609,6 +1617,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { beginPath(): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; @@ -1618,11 +1627,13 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; restore(): void; @@ -2386,20 +2397,22 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } declare var CustomEvent: { prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; interface DataCue extends TextTrackCue { data: ArrayBuffer; - addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DataCue: { @@ -3250,7 +3263,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -3321,8 +3335,10 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Document: { @@ -3605,7 +3621,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -3634,6 +3651,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scroll(options?: ScrollToOptions): void; @@ -3646,8 +3665,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; - addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Element: { @@ -3783,8 +3804,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -3905,7 +3928,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface History { @@ -4016,8 +4039,10 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAnchorElement: { @@ -4090,8 +4115,10 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; - addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAppletElement: { @@ -4158,8 +4185,10 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAreaElement: { @@ -4176,8 +4205,10 @@ declare var HTMLAreasCollection: { }; interface HTMLAudioElement extends HTMLMediaElement { - addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAudioElement: { @@ -4194,8 +4225,10 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseElement: { @@ -4212,8 +4245,10 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseFontElement: { @@ -4253,11 +4288,7 @@ interface HTMLBodyElement extends HTMLElement { onafterprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; - onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; - onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; - onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; - onload: (this: HTMLBodyElement, ev: Event) => any; onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; onoffline: (this: HTMLBodyElement, ev: Event) => any; ononline: (this: HTMLBodyElement, ev: Event) => any; @@ -4266,13 +4297,14 @@ interface HTMLBodyElement extends HTMLElement { onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; onresize: (this: HTMLBodyElement, ev: UIEvent) => any; - onscroll: (this: HTMLBodyElement, ev: UIEvent) => any; onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBodyElement: { @@ -4285,8 +4317,10 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBRElement: { @@ -4358,8 +4392,10 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLButtonElement: { @@ -4393,8 +4429,10 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; - addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLCanvasElement: { @@ -4428,8 +4466,10 @@ declare var HTMLCollection: { interface HTMLDataElement extends HTMLElement { value: string; - addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataElement: { @@ -4439,8 +4479,10 @@ declare var HTMLDataElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; - addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataListElement: { @@ -4450,8 +4492,10 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDirectoryElement: { @@ -4468,8 +4512,10 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; - addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDivElement: { @@ -4479,8 +4525,10 @@ declare var HTMLDivElement: { interface HTMLDListElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDListElement: { @@ -4489,8 +4537,10 @@ declare var HTMLDListElement: { }; interface HTMLDocument extends Document { - addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDocument: { @@ -4662,8 +4712,10 @@ interface HTMLElement extends Element { dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLElement: { @@ -4718,8 +4770,10 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLEmbedElement: { @@ -4759,8 +4813,10 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFieldSetElement: { @@ -4773,8 +4829,10 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; - addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFontElement: { @@ -4858,8 +4916,11 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; - addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -4921,10 +4982,6 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -4937,8 +4994,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameElement: { @@ -4990,17 +5049,7 @@ interface HTMLFrameSetElement extends HTMLElement { onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; - onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; - onload: (this: HTMLFrameSetElement, ev: Event) => any; onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; onoffline: (this: HTMLFrameSetElement, ev: Event) => any; ononline: (this: HTMLFrameSetElement, ev: Event) => any; @@ -5009,15 +5058,16 @@ interface HTMLFrameSetElement extends HTMLElement { onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; - onscroll: (this: HTMLFrameSetElement, ev: UIEvent) => any; onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameSetElement: { @@ -5027,8 +5077,10 @@ declare var HTMLFrameSetElement: { interface HTMLHeadElement extends HTMLElement { profile: string; - addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadElement: { @@ -5041,8 +5093,10 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; - addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadingElement: { @@ -5063,8 +5117,10 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHRElement: { @@ -5077,8 +5133,10 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; - addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHtmlElement: { @@ -5145,10 +5203,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -5166,8 +5220,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLIFrameElement: { @@ -5257,8 +5313,10 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; - addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLImageElement: { @@ -5469,8 +5527,10 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; - addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLInputElement: { @@ -5487,8 +5547,11 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; - addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLabelElement: { @@ -5505,8 +5568,10 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement | null; - addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLegendElement: { @@ -5520,8 +5585,10 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLIElement: { @@ -5565,8 +5632,10 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; - addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLinkElement: { @@ -5583,8 +5652,10 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMapElement: { @@ -5615,8 +5686,10 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMarqueeElement: { @@ -5797,8 +5870,10 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMediaElement: { @@ -5818,8 +5893,10 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMenuElement: { @@ -5852,8 +5929,10 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; - addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMetaElement: { @@ -5868,8 +5947,10 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; - addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMeterElement: { @@ -5886,8 +5967,10 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; - addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLModElement: { @@ -6003,8 +6086,10 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLObjectElement: { @@ -6019,8 +6104,10 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; - addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOListElement: { @@ -6058,8 +6145,10 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptGroupElement: { @@ -6097,8 +6186,10 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptionElement: { @@ -6131,8 +6222,10 @@ interface HTMLOutputElement extends HTMLElement { checkValidity(): boolean; reportValidity(): boolean; setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOutputElement: { @@ -6146,8 +6239,10 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; - addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParagraphElement: { @@ -6172,8 +6267,10 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; - addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParamElement: { @@ -6182,8 +6279,10 @@ declare var HTMLParamElement: { }; interface HTMLPictureElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPictureElement: { @@ -6196,8 +6295,10 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPreElement: { @@ -6222,8 +6323,10 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; - addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLProgressElement: { @@ -6236,8 +6339,10 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; - addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLQuoteElement: { @@ -6277,8 +6382,10 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; - addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLScriptElement: { @@ -6373,8 +6480,10 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -6399,8 +6508,10 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; - addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSourceElement: { @@ -6409,8 +6520,10 @@ declare var HTMLSourceElement: { }; interface HTMLSpanElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSpanElement: { @@ -6428,8 +6541,10 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; - addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLStyleElement: { @@ -6446,8 +6561,10 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; - addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCaptionElement: { @@ -6501,8 +6618,10 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCellElement: { @@ -6523,8 +6642,10 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; - addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableColElement: { @@ -6533,8 +6654,10 @@ declare var HTMLTableColElement: { }; interface HTMLTableDataCellElement extends HTMLTableCellElement { - addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableDataCellElement: { @@ -6646,8 +6769,10 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableElement: { @@ -6660,8 +6785,10 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; - addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableHeaderCellElement: { @@ -6701,8 +6828,10 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableRowElement: { @@ -6729,8 +6858,10 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableSectionElement: { @@ -6740,8 +6871,10 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; - addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTemplateElement: { @@ -6847,8 +6980,10 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; - addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTextAreaElement: { @@ -6858,8 +6993,10 @@ declare var HTMLTextAreaElement: { interface HTMLTimeElement extends HTMLElement { dateTime: string; - addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTimeElement: { @@ -6872,8 +7009,10 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; - addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTitleElement: { @@ -6893,8 +7032,10 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; - addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTrackElement: { @@ -6909,8 +7050,10 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUListElement: { @@ -6919,8 +7062,10 @@ declare var HTMLUListElement: { }; interface HTMLUnknownElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUnknownElement: { @@ -6974,8 +7119,10 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullScreen(): void; webkitExitFullscreen(): void; webkitExitFullScreen(): void; - addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLVideoElement: { @@ -7032,9 +7179,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -7118,8 +7268,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -7140,8 +7292,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -7167,8 +7321,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -7337,8 +7493,10 @@ interface MediaDevices extends EventTarget { enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaDevices: { @@ -7509,8 +7667,10 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStream: { @@ -7581,8 +7741,10 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStreamTrack: { @@ -7631,8 +7793,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -7736,8 +7900,10 @@ interface MSAppAsyncOperation extends EventTarget { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSAppAsyncOperation: { @@ -7892,8 +8058,10 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; - addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSHTMLWebViewElement: { @@ -7918,8 +8086,10 @@ interface MSInputMethodContext extends EventTarget { getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSInputMethodContext: { @@ -8084,8 +8254,10 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSStreamReader: { @@ -8113,8 +8285,10 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSWebViewAsyncOperation: { @@ -8245,6 +8419,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly pointerEnabled: boolean; readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; + readonly doNotTrack: string | null; readonly hardwareConcurrency: number; readonly languages: string[]; getGamepads(): Gamepad[]; @@ -8403,8 +8578,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -8483,8 +8660,10 @@ interface OfflineAudioContext extends AudioContextBase { oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; startRendering(): Promise; suspend(suspendTime: number): Promise; - addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OfflineAudioContext: { @@ -8504,8 +8683,10 @@ interface OscillatorNode extends AudioNode { setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OscillatorNode: { @@ -8599,8 +8780,10 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; show(): Promise; - addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentRequest: { @@ -9106,8 +9289,10 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtlsTransport: { @@ -9136,8 +9321,10 @@ interface RTCDtmfSender extends EventTarget { readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtmfSender: { @@ -9187,8 +9374,10 @@ interface RTCIceGatherer extends RTCStatsProvider { createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidateDictionary[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceGatherer: { @@ -9225,8 +9414,10 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; stop(): void; - addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceTransport: { @@ -9280,8 +9471,10 @@ interface RTCPeerConnection extends EventTarget { removeStream(stream: MediaStream): void; setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCPeerConnection: { @@ -9312,8 +9505,10 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpReceiver: { @@ -9337,8 +9532,10 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpSender: { @@ -9365,8 +9562,10 @@ interface RTCSrtpSdesTransportEventMap { interface RTCSrtpSdesTransport extends EventTarget { onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCSrtpSdesTransport: { @@ -9437,8 +9636,10 @@ interface Screen extends EventTarget { readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -9463,8 +9664,10 @@ interface ScriptProcessorNodeEventMap { interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ScriptProcessorNode: { @@ -9515,8 +9718,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -9534,11 +9739,13 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(): Promise; + getRegistration(clientURL?: USVString): Promise; getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerContainer: { @@ -9575,8 +9782,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -9629,8 +9838,10 @@ interface SpeechSynthesis extends EventTarget { pause(): void; resume(): void; speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesis: { @@ -9674,8 +9885,10 @@ interface SpeechSynthesisUtterance extends EventTarget { text: string; voice: SpeechSynthesisVoice; volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesisUtterance: { @@ -9809,8 +10022,10 @@ declare var SubtleCrypto: { interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGAElement: { @@ -9966,8 +10181,10 @@ interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGCircleElement: { @@ -9977,8 +10194,10 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGClipPathElement: { @@ -10000,8 +10219,10 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGComponentTransferFunctionElement: { @@ -10016,8 +10237,10 @@ declare var SVGComponentTransferFunctionElement: { }; interface SVGDefsElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDefsElement: { @@ -10026,8 +10249,10 @@ declare var SVGDefsElement: { }; interface SVGDescElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDescElement: { @@ -10064,8 +10289,10 @@ interface SVGElement extends Element { readonly style: CSSStyleDeclaration; readonly viewportElement: SVGElement; xmlbase: string; - addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGElement: { @@ -10104,8 +10331,10 @@ interface SVGEllipseElement extends SVGGraphicsElement { readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGEllipseElement: { @@ -10134,8 +10363,10 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEBlendElement: { @@ -10169,8 +10400,10 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEColorMatrixElement: { @@ -10185,8 +10418,10 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEComponentTransferElement: { @@ -10209,8 +10444,10 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFECompositeElement: { @@ -10242,8 +10479,10 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEConvolveMatrixElement: { @@ -10261,8 +10500,10 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDiffuseLightingElement: { @@ -10281,8 +10522,10 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDisplacementMapElement: { @@ -10298,8 +10541,10 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDistantLightElement: { @@ -10308,8 +10553,10 @@ declare var SVGFEDistantLightElement: { }; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFloodElement: { @@ -10318,8 +10565,10 @@ declare var SVGFEFloodElement: { }; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncAElement: { @@ -10328,8 +10577,10 @@ declare var SVGFEFuncAElement: { }; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncBElement: { @@ -10338,8 +10589,10 @@ declare var SVGFEFuncBElement: { }; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncGElement: { @@ -10348,8 +10601,10 @@ declare var SVGFEFuncGElement: { }; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncRElement: { @@ -10362,8 +10617,10 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEGaussianBlurElement: { @@ -10373,8 +10630,10 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEImageElement: { @@ -10383,8 +10642,10 @@ declare var SVGFEImageElement: { }; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeElement: { @@ -10394,8 +10655,10 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeNodeElement: { @@ -10411,8 +10674,10 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMorphologyElement: { @@ -10427,8 +10692,10 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEOffsetElement: { @@ -10440,8 +10707,10 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEPointLightElement: { @@ -10456,8 +10725,10 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpecularLightingElement: { @@ -10474,8 +10745,10 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpotLightElement: { @@ -10485,8 +10758,10 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETileElement: { @@ -10507,8 +10782,10 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETurbulenceElement: { @@ -10532,8 +10809,10 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFilterElement: { @@ -10546,8 +10825,10 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGForeignObjectElement: { @@ -10556,8 +10837,10 @@ declare var SVGForeignObjectElement: { }; interface SVGGElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGElement: { @@ -10573,8 +10856,10 @@ interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGradientElement: { @@ -10594,8 +10879,10 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; - addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGraphicsElement: { @@ -10609,8 +10896,10 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGImageElement: { @@ -10675,8 +10964,10 @@ interface SVGLinearGradientElement extends SVGGradientElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLinearGradientElement: { @@ -10689,8 +10980,10 @@ interface SVGLineElement extends SVGGraphicsElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLineElement: { @@ -10714,8 +11007,10 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly SVG_MARKERUNITS_STROKEWIDTH: number; readonly SVG_MARKERUNITS_UNKNOWN: number; readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMarkerElement: { @@ -10736,8 +11031,10 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMaskElement: { @@ -10771,8 +11068,10 @@ declare var SVGMatrix: { }; interface SVGMetadataElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMetadataElement: { @@ -10829,8 +11128,10 @@ interface SVGPathElement extends SVGGraphicsElement { getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; - addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPathElement: { @@ -11122,8 +11423,10 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPatternElement: { @@ -11159,8 +11462,10 @@ declare var SVGPointList: { }; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolygonElement: { @@ -11169,8 +11474,10 @@ declare var SVGPolygonElement: { }; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolylineElement: { @@ -11222,8 +11529,10 @@ interface SVGRadialGradientElement extends SVGGradientElement { readonly fx: SVGAnimatedLength; readonly fy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRadialGradientElement: { @@ -11250,8 +11559,10 @@ interface SVGRectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRectElement: { @@ -11261,8 +11572,10 @@ declare var SVGRectElement: { interface SVGScriptElement extends SVGElement, SVGURIReference { type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGScriptElement: { @@ -11272,8 +11585,10 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement { readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStopElement: { @@ -11302,8 +11617,10 @@ interface SVGStyleElement extends SVGElement { media: string; title: string; type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStyleElement: { @@ -11363,8 +11680,10 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSVGElement: { @@ -11373,8 +11692,10 @@ declare var SVGSVGElement: { }; interface SVGSwitchElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSwitchElement: { @@ -11383,8 +11704,10 @@ declare var SVGSwitchElement: { }; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { - addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSymbolElement: { @@ -11407,8 +11730,10 @@ interface SVGTextContentElement extends SVGGraphicsElement { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextContentElement: { @@ -11420,8 +11745,10 @@ declare var SVGTextContentElement: { }; interface SVGTextElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextElement: { @@ -11439,8 +11766,10 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPathElement: { @@ -11460,8 +11789,10 @@ interface SVGTextPositioningElement extends SVGTextContentElement { readonly rotate: SVGAnimatedNumberList; readonly x: SVGAnimatedLengthList; readonly y: SVGAnimatedLengthList; - addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPositioningElement: { @@ -11470,8 +11801,10 @@ declare var SVGTextPositioningElement: { }; interface SVGTitleElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTitleElement: { @@ -11529,8 +11862,10 @@ declare var SVGTransformList: { }; interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTSpanElement: { @@ -11552,8 +11887,10 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGUseElement: { @@ -11563,8 +11900,10 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; - addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGViewElement: { @@ -11684,8 +12023,10 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrack: { @@ -11715,8 +12056,10 @@ interface TextTrackCue extends EventTarget { text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrackCue: { @@ -11744,8 +12087,10 @@ interface TextTrackList extends EventTarget { readonly length: number; onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: TextTrack; } @@ -11953,8 +12298,10 @@ interface VideoTrackList extends EventTarget { readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: VideoTrack; } @@ -12158,7 +12505,29 @@ interface WebGLRenderingContext { getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; - getExtension(name: string): any; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram | null): string | null; @@ -12972,8 +13341,10 @@ declare var WebKitPoint: { }; interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var webkitRTCPeerConnection: { @@ -13005,8 +13376,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -13297,7 +13670,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; postMessage(message: any, targetOrigin: string, transfer?: any[]): void; print(): void; prompt(message?: string, _default?: string): string | null; @@ -13318,8 +13691,10 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Window: { @@ -13335,8 +13710,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -13345,8 +13722,10 @@ declare var Worker: { }; interface XMLDocument extends Document { - addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLDocument: { @@ -13387,8 +13766,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -13402,8 +13783,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -13508,8 +13891,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -13654,8 +14039,10 @@ interface GlobalEventHandlers { onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; - addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface GlobalFetch { @@ -13707,8 +14094,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface MSFileSaver { @@ -13765,9 +14154,11 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; - querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -13854,8 +14245,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface BroadcastChannel extends EventTarget { @@ -13864,8 +14257,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -14046,7 +14441,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -14282,6 +14677,128 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14349,28 +14866,46 @@ interface VoidFunction { } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; "audio": HTMLAudioElement; + "b": HTMLElement; "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; "col": HTMLTableColElement; "colgroup": HTMLTableColElement; "data": HTMLDataElement; "datalist": HTMLDataListElement; + "dd": HTMLElement; "del": HTMLModElement; + "dfn": HTMLElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; "embed": HTMLEmbedElement; "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; "font": HTMLFontElement; + "footer": HTMLElement; "form": HTMLFormElement; "frame": HTMLFrameElement; "frameset": HTMLFrameSetElement; @@ -14381,24 +14916,34 @@ interface HTMLElementTagNameMap { "h5": HTMLHeadingElement; "h6": HTMLHeadingElement; "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; "hr": HTMLHRElement; "html": HTMLHtmlElement; + "i": HTMLElement; "iframe": HTMLIFrameElement; "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; "listing": HTMLPreElement; "map": HTMLMapElement; + "mark": HTMLElement; "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; + "nav": HTMLElement; "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; "optgroup": HTMLOptGroupElement; @@ -14407,14 +14952,25 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; + "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; "script": HTMLScriptElement; + "section": HTMLElement; "select": HTMLSelectElement; + "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; "table": HTMLTableElement; "tbody": HTMLTableSectionElement; "td": HTMLTableDataCellElement; @@ -14427,33 +14983,22 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; "ul": HTMLUListElement; + "var": HTMLElement; "video": HTMLVideoElement; + "wbr": HTMLElement; "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } -interface ElementTagNameMap extends HTMLElementTagNameMap { - "abbr": HTMLElement; - "acronym": HTMLElement; - "address": HTMLElement; - "article": HTMLElement; - "aside": HTMLElement; - "b": HTMLElement; - "bdo": HTMLElement; - "big": HTMLElement; - "center": HTMLElement; +interface SVGElementTagNameMap { "circle": SVGCircleElement; - "cite": HTMLElement; "clippath": SVGClipPathElement; - "code": HTMLElement; - "dd": HTMLElement; "defs": SVGDefsElement; "desc": SVGDescElement; - "dfn": HTMLElement; - "dt": HTMLElement; "ellipse": SVGEllipseElement; - "em": HTMLElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -14478,63 +15023,33 @@ interface ElementTagNameMap extends HTMLElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "figcaption": HTMLElement; - "figure": HTMLElement; "filter": SVGFilterElement; - "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; "g": SVGGElement; - "header": HTMLElement; - "hgroup": HTMLElement; - "i": HTMLElement; "image": SVGImageElement; - "kbd": HTMLElement; - "keygen": HTMLElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "mark": HTMLElement; "marker": SVGMarkerElement; "mask": SVGMaskElement; "metadata": SVGMetadataElement; - "nav": HTMLElement; - "nobr": HTMLElement; - "noframes": HTMLElement; - "noscript": HTMLElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; - "rt": HTMLElement; - "ruby": HTMLElement; - "s": HTMLElement; - "samp": HTMLElement; - "section": HTMLElement; - "small": HTMLElement; "stop": SVGStopElement; - "strike": HTMLElement; - "strong": HTMLElement; - "sub": HTMLElement; - "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; "text": SVGTextElement; "textpath": SVGTextPathElement; "tspan": SVGTSpanElement; - "tt": HTMLElement; - "u": HTMLElement; "use": SVGUseElement; - "var": HTMLElement; "view": SVGViewElement; - "wbr": HTMLElement; } -type ElementListTagNameMap = { - [key in keyof ElementTagNameMap]: NodeListOf -}; +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; @@ -14697,7 +15212,7 @@ declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; @@ -14720,7 +15235,6 @@ declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; @@ -14746,8 +15260,10 @@ declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; -declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; @@ -14771,7 +15287,6 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -14792,6 +15307,7 @@ type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index 382099148f66c..4914c210227f0 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -24,23 +24,6 @@ interface DOMTokenList { [Symbol.iterator](): IterableIterator; } -interface FormData { - /** - * Returns an array of key, value pairs for every entry in the list - */ - entries(): IterableIterator<[string, string | File]>; - /** - * Returns a list of keys in the list - */ - keys(): IterableIterator; - /** - * Returns a list of values in the list - */ - values(): IterableIterator; - - [Symbol.iterator](): IterableIterator; -} - interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** @@ -107,6 +90,31 @@ interface NodeListOf { [Symbol.iterator](): IterableIterator; } +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[string, string | File]>; + /** + * Returns a list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + interface URLSearchParams { /** * Returns an array of key, value pairs for every entry in the search params diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 610c46abc6010..f1734cedd8bc0 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -30,6 +30,7 @@ interface Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ + find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** @@ -69,10 +70,16 @@ interface ArrayConstructor { /** * Creates an array from an array-like object. * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): T[]; + + /** + * Creates an array from an iterable object. + * @param arrayLike An array-like object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. @@ -182,7 +189,7 @@ interface Math { * If any argument is NaN, the result is NaN. * If all arguments are either +0 or −0, the result is +0. */ - hypot(...values: number[] ): number; + hypot(...values: number[]): number; /** * Returns the integral part of the a numeric expression, x, removing any fractional digits. @@ -370,6 +377,7 @@ interface ReadonlyArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** @@ -461,7 +469,7 @@ interface String { /** * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. + * the empty string is returned. * @param count number of copies to append */ repeat(count: number): string; diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index edf2dbc77600c..16db98d991939 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -68,13 +68,19 @@ interface Array { } interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): T[]; + /** * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index 5017ec92da5a0..0b97de7157dc4 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -170,7 +170,7 @@ interface Promise { } interface PromiseConstructor { - readonly [Symbol.species]: Function; + readonly [Symbol.species]: PromiseConstructor; } interface RegExp { @@ -222,7 +222,7 @@ interface RegExp { } interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; + readonly [Symbol.species]: RegExpConstructor; } interface String { @@ -303,3 +303,16 @@ interface Float32Array { interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } + +interface ArrayConstructor { + readonly [Symbol.species]: ArrayConstructor; +} +interface MapConstructor { + readonly [Symbol.species]: MapConstructor; +} +interface SetConstructor { + readonly [Symbol.species]: SetConstructor; +} +interface ArrayBufferConstructor { + readonly [Symbol.species]: ArrayBufferConstructor; +} \ No newline at end of file diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 522e29a1034bf..b8a7dae039d4f 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -21,1691 +21,6 @@ and limitations under the License. /// /// -declare type PropertyKey = string | number | symbol; - -interface Array { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): this; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): T[]; -} - -interface DateConstructor { - new (value: Date): Date; -} - -interface Function { - /** - * Returns the name of the function. Function names are read-only and can not be changed. - */ - readonly name: string; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[] ): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - readonly EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - readonly MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - readonly MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface Object { - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean; -} - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source The source object from which to copy properties. - */ - assign(target: T, source: U): T & U; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V): T & U & V; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - * @param source3 The third source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects from which to copy properties - */ - assign(target: object, ...sources: any[]): any; - - /** - * Returns an array of all symbol properties found directly on object o. - * @param o Object to retrieve the symbols from. - */ - getOwnPropertySymbols(o: any): symbol[]; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - */ - setPrototypeOf(o: any, proto: object | null): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not - * inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript - * object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor - * property. - */ - defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; -} - -interface ReadonlyArray { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - readonly flags: string; - - /** - * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular - * expression. Default is false. Read-only. - */ - readonly sticky: boolean; - - /** - * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular - * expression. Default is false. Read-only. - */ - readonly unicode: boolean; -} - -interface RegExpConstructor { - new (pattern: RegExp, flags?: string): RegExp; - (pattern: RegExp, flags?: string): RegExp; -} - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number | undefined; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form?: string): string; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; - - /** - * Returns an HTML anchor element and sets the name attribute to the text value - * @param name - */ - anchor(name: string): string; - - /** Returns a HTML element */ - big(): string; - - /** Returns a HTML element */ - blink(): string; - - /** Returns a HTML element */ - bold(): string; - - /** Returns a HTML element */ - fixed(): string; - - /** Returns a HTML element and sets the color attribute value */ - fontcolor(color: string): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: number): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: string): string; - - /** Returns an HTML element */ - italics(): string; - - /** Returns an HTML element and sets the href attribute value */ - link(url: string): string; - - /** Returns a HTML element */ - small(): string; - - /** Returns a HTML element */ - strike(): string; - - /** Returns a HTML element */ - sub(): string; - - /** Returns a HTML element */ - sup(): string; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} - - -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value: V): this; - readonly size: number; -} - -interface MapConstructor { - new (): Map; - new (entries?: [K, V][]): Map; - readonly prototype: Map; -} -declare var Map: MapConstructor; - -interface ReadonlyMap { - forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - readonly size: number; -} - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value: V): this; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (entries?: [K, V][]): WeakMap; - readonly prototype: WeakMap; -} -declare var WeakMap: WeakMapConstructor; - -interface Set { - add(value: T): this; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface SetConstructor { - new (): Set; - new (values?: T[]): Set; - readonly prototype: Set; -} -declare var Set: SetConstructor; - -interface ReadonlySet { - forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface WeakSet { - add(value: T): this; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (values?: T[]): WeakSet; - readonly prototype: WeakSet; -} -declare var WeakSet: WeakSetConstructor; - - -interface Generator extends Iterator { } - -interface GeneratorFunction { - /** - * Creates a new Generator object. - * @param args A list of arguments the function accepts. - */ - new (...args: any[]): Generator; - /** - * Creates a new Generator object. - * @param args A list of arguments the function accepts. - */ - (...args: any[]): Generator; - /** - * The length of the arguments. - */ - readonly length: number; - /** - * Returns the name of the function. - */ - readonly name: string; - /** - * A reference to the prototype. - */ - readonly prototype: Generator; -} - -interface GeneratorFunctionConstructor { - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): GeneratorFunction; - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - (...args: string[]): GeneratorFunction; - /** - * The length of the arguments. - */ - readonly length: number; - /** - * Returns the name of the function. - */ - readonly name: string; - /** - * A reference to the prototype. - */ - readonly prototype: GeneratorFunction; -} -declare var GeneratorFunction: GeneratorFunctionConstructor; - - -/// - -interface SymbolConstructor { - /** - * A method that returns the default iterator for an object. Called by the semantics of the - * for-of statement. - */ - readonly iterator: symbol; -} - -interface IteratorResult { - done: boolean; - value: T; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface Iterable { - [Symbol.iterator](): Iterator; -} - -interface IterableIterator extends Iterator { - [Symbol.iterator](): IterableIterator; -} - -interface Array { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an iterable of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the array - */ - values(): IterableIterator; -} - -interface ArrayConstructor { - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; -} - -interface ReadonlyArray { - /** Iterator of values in the array. */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an iterable of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the array - */ - values(): IterableIterator; -} - -interface IArguments { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Map { - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](): IterableIterator<[K, V]>; - - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - entries(): IterableIterator<[K, V]>; - - /** - * Returns an iterable of keys in the map - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the map - */ - values(): IterableIterator; -} - -interface ReadonlyMap { - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](): IterableIterator<[K, V]>; - - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - entries(): IterableIterator<[K, V]>; - - /** - * Returns an iterable of keys in the map - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the map - */ - values(): IterableIterator; -} - -interface MapConstructor { - new (iterable: Iterable<[K, V]>): Map; -} - -interface WeakMap { } - -interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; -} - -interface Set { - /** Iterates over values in the set. */ - [Symbol.iterator](): IterableIterator; - /** - * Returns an iterable of [v,v] pairs for every value `v` in the set. - */ - entries(): IterableIterator<[T, T]>; - /** - * Despite its name, returns an iterable of the values in the set, - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the set. - */ - values(): IterableIterator; -} - -interface ReadonlySet { - /** Iterates over values in the set. */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of [v,v] pairs for every value `v` in the set. - */ - entries(): IterableIterator<[T, T]>; - - /** - * Despite its name, returns an iterable of the values in the set, - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the set. - */ - values(): IterableIterator; -} - -interface SetConstructor { - new (iterable: Iterable): Set; -} - -interface WeakSet { } - -interface WeakSetConstructor { - new (iterable: Iterable): WeakSet; -} - -interface Promise { } - -interface PromiseConstructor { - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: Iterable>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: Iterable>): Promise; -} - -declare namespace Reflect { - function enumerate(target: object): IterableIterator; -} - -interface String { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Int8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int8ArrayConstructor { - new (elements: Iterable): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; -} - -interface Uint8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ArrayConstructor { - new (elements: Iterable): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; -} - -interface Uint8ClampedArray { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ClampedArrayConstructor { - new (elements: Iterable): Uint8ClampedArray; - - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} - -interface Int16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int16ArrayConstructor { - new (elements: Iterable): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; -} - -interface Uint16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint16ArrayConstructor { - new (elements: Iterable): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; -} - -interface Int32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int32ArrayConstructor { - new (elements: Iterable): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} - -interface Uint32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint32ArrayConstructor { - new (elements: Iterable): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} - -interface Float32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float32ArrayConstructor { - new (elements: Iterable): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; -} - -interface Float64Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float64ArrayConstructor { - new (elements: Iterable): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -} - - -interface PromiseConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Promise; - - /** - * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, - * and a reject callback used to reject the promise with a provided reason or error. - */ - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: (T | PromiseLike)[]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: (T | PromiseLike)[]): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor; - -interface ProxyHandler { - getPrototypeOf? (target: T): object | null; - setPrototypeOf? (target: T, v: any): boolean; - isExtensible? (target: T): boolean; - preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; - has? (target: T, p: PropertyKey): boolean; - get? (target: T, p: PropertyKey, receiver: any): any; - set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; - deleteProperty? (target: T, p: PropertyKey): boolean; - defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; - enumerate? (target: T): PropertyKey[]; - ownKeys? (target: T): PropertyKey[]; - apply? (target: T, thisArg: any, argArray?: any): any; - construct? (target: T, argArray: any, newTarget?: any): object; -} - -interface ProxyConstructor { - revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; - new (target: T, handler: ProxyHandler): T; -} -declare var Proxy: ProxyConstructor; - - -declare namespace Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; - function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: object, propertyKey: PropertyKey): boolean; - function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; - function getPrototypeOf(target: object): object; - function has(target: object, propertyKey: PropertyKey): boolean; - function isExtensible(target: object): boolean; - function ownKeys(target: object): PropertyKey[]; - function preventExtensions(target: object): boolean; - function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: object, proto: any): boolean; -} - - -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): symbol; -} - -interface SymbolConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Symbol; - - /** - * Returns a new unique Symbol value. - * @param description Description of the new Symbol object. - */ - (description?: string | number): symbol; - - /** - * Returns a Symbol object from the global symbol registry matching the given key if found. - * Otherwise, returns a new symbol with this key. - * @param key key to search for. - */ - for(key: string): symbol; - - /** - * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. - * @param sym Symbol to find the key for. - */ - keyFor(sym: symbol): string | undefined; -} - -declare var Symbol: SymbolConstructor; - -/// - -interface SymbolConstructor { - /** - * A method that determines if a constructor object recognizes an object as one of the - * constructor’s instances. Called by the semantics of the instanceof operator. - */ - readonly hasInstance: symbol; - - /** - * A Boolean value that if true indicates that an object should flatten to its array elements - * by Array.prototype.concat. - */ - readonly isConcatSpreadable: symbol; - - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.match method. - */ - readonly match: symbol; - - /** - * A regular expression method that replaces matched substrings of a string. Called by the - * String.prototype.replace method. - */ - readonly replace: symbol; - - /** - * A regular expression method that returns the index within a string that matches the - * regular expression. Called by the String.prototype.search method. - */ - readonly search: symbol; - - /** - * A function valued property that is the constructor function that is used to create - * derived objects. - */ - readonly species: symbol; - - /** - * A regular expression method that splits a string at the indices that match the regular - * expression. Called by the String.prototype.split method. - */ - readonly split: symbol; - - /** - * A method that converts an object to a corresponding primitive value. - * Called by the ToPrimitive abstract operation. - */ - readonly toPrimitive: symbol; - - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - readonly toStringTag: symbol; - - /** - * An Object whose own property names are property names that are excluded from the 'with' - * environment bindings of the associated objects. - */ - readonly unscopables: symbol; -} - -interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; -} - -interface Array { - /** - * Returns an object whose properties have the value 'true' - * when they will be absent when used in a 'with' statement. - */ - [Symbol.unscopables](): { - copyWithin: boolean; - entries: boolean; - fill: boolean; - find: boolean; - findIndex: boolean; - keys: boolean; - values: boolean; - }; -} - -interface Date { - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "default"): string; - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "string"): string; - /** - * Converts a Date object to a number. - */ - [Symbol.toPrimitive](hint: "number"): number; - /** - * Converts a Date object to a string or number. - * - * @param hint The strings "number", "string", or "default" to specify what primitive to return. - * - * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". - * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". - */ - [Symbol.toPrimitive](hint: string): string | number; -} - -interface Map { - readonly [Symbol.toStringTag]: "Map"; -} - -interface WeakMap { - readonly [Symbol.toStringTag]: "WeakMap"; -} - -interface Set { - readonly [Symbol.toStringTag]: "Set"; -} - -interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; -} - -interface JSON { - readonly [Symbol.toStringTag]: "JSON"; -} - -interface Function { - /** - * Determines whether the given value inherits from this function if this function was used - * as a constructor function. - * - * A constructor function can control which objects are recognized as its instances by - * 'instanceof' by overriding this method. - */ - [Symbol.hasInstance](value: any): boolean; -} - -interface GeneratorFunction { - readonly [Symbol.toStringTag]: "GeneratorFunction"; -} - -interface Math { - readonly [Symbol.toStringTag]: "Math"; -} - -interface Promise { - readonly [Symbol.toStringTag]: "Promise"; -} - -interface PromiseConstructor { - readonly [Symbol.species]: Function; -} - -interface RegExp { - /** - * Matches a string with this regular expression, and returns an array containing the results of - * that search. - * @param string A string to search within. - */ - [Symbol.match](string: string): RegExpMatchArray | null; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replaceValue A String object or string literal containing the text to replace for every - * successful match of this regular expression. - */ - [Symbol.replace](string: string, replaceValue: string): string; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replacer A function that returns the replacement text. - */ - [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the position beginning first substring match in a regular expression search - * using this regular expression. - * - * @param string The string to search within. - */ - [Symbol.search](string: string): number; - - /** - * Returns an array of substrings that were delimited by strings in the original input that - * match against this regular expression. - * - * If the regular expression contains capturing parentheses, then each time this - * regular expression matches, the results (including any undefined results) of the - * capturing parentheses are spliced. - * - * @param string string value to split - * @param limit if not undefined, the output array is truncated so that it contains no more - * than 'limit' elements. - */ - [Symbol.split](string: string, limit?: number): string[]; -} - -interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; -} - -interface String { - /** - * Matches a string an object that supports being matched against, and returns an array containing the results of that search. - * @param matcher An object that supports being matched against. - */ - match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param searcher An object which supports searching within a string. - */ - search(searcher: { [Symbol.search](string: string): number; }): number; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param splitter An object that can split a string. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; -} - -interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; -} - -interface DataView { - readonly [Symbol.toStringTag]: "DataView"; -} - -interface Int8Array { - readonly [Symbol.toStringTag]: "Int8Array"; -} - -interface Uint8Array { - readonly [Symbol.toStringTag]: "UInt8Array"; -} - -interface Uint8ClampedArray { - readonly [Symbol.toStringTag]: "Uint8ClampedArray"; -} - -interface Int16Array { - readonly [Symbol.toStringTag]: "Int16Array"; -} - -interface Uint16Array { - readonly [Symbol.toStringTag]: "Uint16Array"; -} - -interface Int32Array { - readonly [Symbol.toStringTag]: "Int32Array"; -} - -interface Uint32Array { - readonly [Symbol.toStringTag]: "Uint32Array"; -} - -interface Float32Array { - readonly [Symbol.toStringTag]: "Float32Array"; -} - -interface Float64Array { - readonly [Symbol.toStringTag]: "Float64Array"; -} - - ///////////////////////////// /// DOM APIs @@ -1790,8 +105,8 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } -interface CustomEventInit extends EventInit { - detail?: any; +interface CustomEventInit extends EventInit { + detail?: T; } interface DeviceAccelerationDict { @@ -1911,7 +226,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface IntersectionObserverEntryInit { @@ -2404,7 +719,7 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; total?: PaymentItem; } @@ -2416,7 +731,7 @@ interface PaymentItem { interface PaymentMethodData { data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; } interface PaymentOptions { @@ -2481,7 +796,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -2493,7 +808,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -2963,8 +1278,10 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ApplicationCache: { @@ -3020,8 +1337,10 @@ interface AudioBufferSourceNode extends AudioNode { readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AudioBufferSourceNode: { @@ -3062,8 +1381,10 @@ interface AudioContextBase extends EventTarget { createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; resume(): Promise; - addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface AudioContext extends AudioContextBase { @@ -3170,8 +1491,10 @@ interface AudioTrackList extends EventTarget { onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: AudioTrack; } @@ -3297,6 +1620,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { beginPath(): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; @@ -3306,11 +1630,13 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; restore(): void; @@ -4074,20 +2400,22 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } declare var CustomEvent: { prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; interface DataCue extends TextTrackCue { data: ArrayBuffer; - addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DataCue: { @@ -4938,7 +3266,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -5009,8 +3338,10 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Document: { @@ -5293,7 +3624,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -5322,6 +3654,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scroll(options?: ScrollToOptions): void; @@ -5334,8 +3668,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; - addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Element: { @@ -5471,8 +3807,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -5593,7 +3931,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface History { @@ -5704,8 +4042,10 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAnchorElement: { @@ -5778,8 +4118,10 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; - addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAppletElement: { @@ -5846,8 +4188,10 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAreaElement: { @@ -5864,8 +4208,10 @@ declare var HTMLAreasCollection: { }; interface HTMLAudioElement extends HTMLMediaElement { - addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAudioElement: { @@ -5882,8 +4228,10 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseElement: { @@ -5900,8 +4248,10 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseFontElement: { @@ -5941,11 +4291,7 @@ interface HTMLBodyElement extends HTMLElement { onafterprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; - onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; - onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; - onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; - onload: (this: HTMLBodyElement, ev: Event) => any; onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; onoffline: (this: HTMLBodyElement, ev: Event) => any; ononline: (this: HTMLBodyElement, ev: Event) => any; @@ -5954,13 +4300,14 @@ interface HTMLBodyElement extends HTMLElement { onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; onresize: (this: HTMLBodyElement, ev: UIEvent) => any; - onscroll: (this: HTMLBodyElement, ev: UIEvent) => any; onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBodyElement: { @@ -5973,8 +4320,10 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBRElement: { @@ -6046,8 +4395,10 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLButtonElement: { @@ -6081,8 +4432,10 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; - addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLCanvasElement: { @@ -6116,8 +4469,10 @@ declare var HTMLCollection: { interface HTMLDataElement extends HTMLElement { value: string; - addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataElement: { @@ -6127,8 +4482,10 @@ declare var HTMLDataElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; - addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataListElement: { @@ -6138,8 +4495,10 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDirectoryElement: { @@ -6156,8 +4515,10 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; - addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDivElement: { @@ -6167,8 +4528,10 @@ declare var HTMLDivElement: { interface HTMLDListElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDListElement: { @@ -6177,8 +4540,10 @@ declare var HTMLDListElement: { }; interface HTMLDocument extends Document { - addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDocument: { @@ -6350,8 +4715,10 @@ interface HTMLElement extends Element { dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLElement: { @@ -6406,8 +4773,10 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLEmbedElement: { @@ -6447,8 +4816,10 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFieldSetElement: { @@ -6461,8 +4832,10 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; - addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFontElement: { @@ -6546,8 +4919,11 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; - addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -6609,10 +4985,6 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -6625,8 +4997,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameElement: { @@ -6678,17 +5052,7 @@ interface HTMLFrameSetElement extends HTMLElement { onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; - onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; - onload: (this: HTMLFrameSetElement, ev: Event) => any; onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; onoffline: (this: HTMLFrameSetElement, ev: Event) => any; ononline: (this: HTMLFrameSetElement, ev: Event) => any; @@ -6697,15 +5061,16 @@ interface HTMLFrameSetElement extends HTMLElement { onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; - onscroll: (this: HTMLFrameSetElement, ev: UIEvent) => any; onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameSetElement: { @@ -6715,8 +5080,10 @@ declare var HTMLFrameSetElement: { interface HTMLHeadElement extends HTMLElement { profile: string; - addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadElement: { @@ -6729,8 +5096,10 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; - addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadingElement: { @@ -6751,8 +5120,10 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHRElement: { @@ -6765,8 +5136,10 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; - addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHtmlElement: { @@ -6833,10 +5206,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -6854,8 +5223,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLIFrameElement: { @@ -6945,8 +5316,10 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; - addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLImageElement: { @@ -7157,8 +5530,10 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; - addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLInputElement: { @@ -7175,8 +5550,11 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; - addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLabelElement: { @@ -7193,8 +5571,10 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement | null; - addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLegendElement: { @@ -7208,8 +5588,10 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLIElement: { @@ -7253,8 +5635,10 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; - addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLinkElement: { @@ -7271,8 +5655,10 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMapElement: { @@ -7303,8 +5689,10 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMarqueeElement: { @@ -7485,8 +5873,10 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMediaElement: { @@ -7506,8 +5896,10 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMenuElement: { @@ -7540,8 +5932,10 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; - addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMetaElement: { @@ -7556,8 +5950,10 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; - addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMeterElement: { @@ -7574,8 +5970,10 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; - addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLModElement: { @@ -7691,8 +6089,10 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLObjectElement: { @@ -7707,8 +6107,10 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; - addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOListElement: { @@ -7746,8 +6148,10 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptGroupElement: { @@ -7785,8 +6189,10 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptionElement: { @@ -7819,8 +6225,10 @@ interface HTMLOutputElement extends HTMLElement { checkValidity(): boolean; reportValidity(): boolean; setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOutputElement: { @@ -7834,8 +6242,10 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; - addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParagraphElement: { @@ -7860,8 +6270,10 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; - addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParamElement: { @@ -7870,8 +6282,10 @@ declare var HTMLParamElement: { }; interface HTMLPictureElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPictureElement: { @@ -7884,8 +6298,10 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPreElement: { @@ -7910,8 +6326,10 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; - addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLProgressElement: { @@ -7924,8 +6342,10 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; - addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLQuoteElement: { @@ -7965,8 +6385,10 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; - addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLScriptElement: { @@ -8061,8 +6483,10 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -8087,8 +6511,10 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; - addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSourceElement: { @@ -8097,8 +6523,10 @@ declare var HTMLSourceElement: { }; interface HTMLSpanElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSpanElement: { @@ -8116,8 +6544,10 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; - addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLStyleElement: { @@ -8134,8 +6564,10 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; - addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCaptionElement: { @@ -8189,8 +6621,10 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCellElement: { @@ -8211,8 +6645,10 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; - addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableColElement: { @@ -8221,8 +6657,10 @@ declare var HTMLTableColElement: { }; interface HTMLTableDataCellElement extends HTMLTableCellElement { - addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableDataCellElement: { @@ -8334,8 +6772,10 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableElement: { @@ -8348,8 +6788,10 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; - addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableHeaderCellElement: { @@ -8389,8 +6831,10 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableRowElement: { @@ -8417,8 +6861,10 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableSectionElement: { @@ -8428,8 +6874,10 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; - addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTemplateElement: { @@ -8535,8 +6983,10 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; - addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTextAreaElement: { @@ -8546,8 +6996,10 @@ declare var HTMLTextAreaElement: { interface HTMLTimeElement extends HTMLElement { dateTime: string; - addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTimeElement: { @@ -8560,8 +7012,10 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; - addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTitleElement: { @@ -8581,8 +7035,10 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; - addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTrackElement: { @@ -8597,8 +7053,10 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUListElement: { @@ -8607,8 +7065,10 @@ declare var HTMLUListElement: { }; interface HTMLUnknownElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUnknownElement: { @@ -8662,8 +7122,10 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullScreen(): void; webkitExitFullscreen(): void; webkitExitFullScreen(): void; - addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLVideoElement: { @@ -8720,9 +7182,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -8806,8 +7271,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -8828,8 +7295,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -8855,8 +7324,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -9025,8 +7496,10 @@ interface MediaDevices extends EventTarget { enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaDevices: { @@ -9197,8 +7670,10 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStream: { @@ -9269,8 +7744,10 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStreamTrack: { @@ -9319,8 +7796,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -9424,8 +7903,10 @@ interface MSAppAsyncOperation extends EventTarget { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSAppAsyncOperation: { @@ -9580,8 +8061,10 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; - addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSHTMLWebViewElement: { @@ -9606,8 +8089,10 @@ interface MSInputMethodContext extends EventTarget { getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSInputMethodContext: { @@ -9772,8 +8257,10 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSStreamReader: { @@ -9801,8 +8288,10 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSWebViewAsyncOperation: { @@ -9933,6 +8422,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly pointerEnabled: boolean; readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; + readonly doNotTrack: string | null; readonly hardwareConcurrency: number; readonly languages: string[]; getGamepads(): Gamepad[]; @@ -10091,8 +8581,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -10171,8 +8663,10 @@ interface OfflineAudioContext extends AudioContextBase { oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; startRendering(): Promise; suspend(suspendTime: number): Promise; - addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OfflineAudioContext: { @@ -10192,8 +8686,10 @@ interface OscillatorNode extends AudioNode { setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OscillatorNode: { @@ -10287,8 +8783,10 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; show(): Promise; - addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentRequest: { @@ -10794,8 +9292,10 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtlsTransport: { @@ -10824,8 +9324,10 @@ interface RTCDtmfSender extends EventTarget { readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtmfSender: { @@ -10875,8 +9377,10 @@ interface RTCIceGatherer extends RTCStatsProvider { createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidateDictionary[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceGatherer: { @@ -10913,8 +9417,10 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; stop(): void; - addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceTransport: { @@ -10968,8 +9474,10 @@ interface RTCPeerConnection extends EventTarget { removeStream(stream: MediaStream): void; setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCPeerConnection: { @@ -11000,8 +9508,10 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpReceiver: { @@ -11025,8 +9535,10 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpSender: { @@ -11053,8 +9565,10 @@ interface RTCSrtpSdesTransportEventMap { interface RTCSrtpSdesTransport extends EventTarget { onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCSrtpSdesTransport: { @@ -11125,8 +9639,10 @@ interface Screen extends EventTarget { readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -11151,8 +9667,10 @@ interface ScriptProcessorNodeEventMap { interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ScriptProcessorNode: { @@ -11203,8 +9721,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -11222,11 +9742,13 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(): Promise; + getRegistration(clientURL?: USVString): Promise; getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerContainer: { @@ -11263,8 +9785,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -11317,8 +9841,10 @@ interface SpeechSynthesis extends EventTarget { pause(): void; resume(): void; speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesis: { @@ -11362,8 +9888,10 @@ interface SpeechSynthesisUtterance extends EventTarget { text: string; voice: SpeechSynthesisVoice; volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesisUtterance: { @@ -11497,8 +10025,10 @@ declare var SubtleCrypto: { interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGAElement: { @@ -11654,8 +10184,10 @@ interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGCircleElement: { @@ -11665,8 +10197,10 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGClipPathElement: { @@ -11688,8 +10222,10 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGComponentTransferFunctionElement: { @@ -11704,8 +10240,10 @@ declare var SVGComponentTransferFunctionElement: { }; interface SVGDefsElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDefsElement: { @@ -11714,8 +10252,10 @@ declare var SVGDefsElement: { }; interface SVGDescElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDescElement: { @@ -11752,8 +10292,10 @@ interface SVGElement extends Element { readonly style: CSSStyleDeclaration; readonly viewportElement: SVGElement; xmlbase: string; - addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGElement: { @@ -11792,8 +10334,10 @@ interface SVGEllipseElement extends SVGGraphicsElement { readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGEllipseElement: { @@ -11822,8 +10366,10 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEBlendElement: { @@ -11857,8 +10403,10 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEColorMatrixElement: { @@ -11873,8 +10421,10 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEComponentTransferElement: { @@ -11897,8 +10447,10 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFECompositeElement: { @@ -11930,8 +10482,10 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEConvolveMatrixElement: { @@ -11949,8 +10503,10 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDiffuseLightingElement: { @@ -11969,8 +10525,10 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDisplacementMapElement: { @@ -11986,8 +10544,10 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDistantLightElement: { @@ -11996,8 +10556,10 @@ declare var SVGFEDistantLightElement: { }; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFloodElement: { @@ -12006,8 +10568,10 @@ declare var SVGFEFloodElement: { }; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncAElement: { @@ -12016,8 +10580,10 @@ declare var SVGFEFuncAElement: { }; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncBElement: { @@ -12026,8 +10592,10 @@ declare var SVGFEFuncBElement: { }; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncGElement: { @@ -12036,8 +10604,10 @@ declare var SVGFEFuncGElement: { }; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncRElement: { @@ -12050,8 +10620,10 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEGaussianBlurElement: { @@ -12061,8 +10633,10 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEImageElement: { @@ -12071,8 +10645,10 @@ declare var SVGFEImageElement: { }; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeElement: { @@ -12082,8 +10658,10 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeNodeElement: { @@ -12099,8 +10677,10 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMorphologyElement: { @@ -12115,8 +10695,10 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEOffsetElement: { @@ -12128,8 +10710,10 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEPointLightElement: { @@ -12144,8 +10728,10 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpecularLightingElement: { @@ -12162,8 +10748,10 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpotLightElement: { @@ -12173,8 +10761,10 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETileElement: { @@ -12195,8 +10785,10 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETurbulenceElement: { @@ -12220,8 +10812,10 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFilterElement: { @@ -12234,8 +10828,10 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGForeignObjectElement: { @@ -12244,8 +10840,10 @@ declare var SVGForeignObjectElement: { }; interface SVGGElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGElement: { @@ -12261,8 +10859,10 @@ interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGradientElement: { @@ -12282,8 +10882,10 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; - addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGraphicsElement: { @@ -12297,8 +10899,10 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGImageElement: { @@ -12363,8 +10967,10 @@ interface SVGLinearGradientElement extends SVGGradientElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLinearGradientElement: { @@ -12377,8 +10983,10 @@ interface SVGLineElement extends SVGGraphicsElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLineElement: { @@ -12402,8 +11010,10 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly SVG_MARKERUNITS_STROKEWIDTH: number; readonly SVG_MARKERUNITS_UNKNOWN: number; readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMarkerElement: { @@ -12424,8 +11034,10 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMaskElement: { @@ -12459,8 +11071,10 @@ declare var SVGMatrix: { }; interface SVGMetadataElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMetadataElement: { @@ -12517,8 +11131,10 @@ interface SVGPathElement extends SVGGraphicsElement { getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; - addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPathElement: { @@ -12810,8 +11426,10 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPatternElement: { @@ -12847,8 +11465,10 @@ declare var SVGPointList: { }; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolygonElement: { @@ -12857,8 +11477,10 @@ declare var SVGPolygonElement: { }; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolylineElement: { @@ -12910,8 +11532,10 @@ interface SVGRadialGradientElement extends SVGGradientElement { readonly fx: SVGAnimatedLength; readonly fy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRadialGradientElement: { @@ -12938,8 +11562,10 @@ interface SVGRectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRectElement: { @@ -12949,8 +11575,10 @@ declare var SVGRectElement: { interface SVGScriptElement extends SVGElement, SVGURIReference { type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGScriptElement: { @@ -12960,8 +11588,10 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement { readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStopElement: { @@ -12990,8 +11620,10 @@ interface SVGStyleElement extends SVGElement { media: string; title: string; type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStyleElement: { @@ -13051,8 +11683,10 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSVGElement: { @@ -13061,8 +11695,10 @@ declare var SVGSVGElement: { }; interface SVGSwitchElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSwitchElement: { @@ -13071,8 +11707,10 @@ declare var SVGSwitchElement: { }; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { - addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSymbolElement: { @@ -13095,8 +11733,10 @@ interface SVGTextContentElement extends SVGGraphicsElement { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextContentElement: { @@ -13108,8 +11748,10 @@ declare var SVGTextContentElement: { }; interface SVGTextElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextElement: { @@ -13127,8 +11769,10 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPathElement: { @@ -13148,8 +11792,10 @@ interface SVGTextPositioningElement extends SVGTextContentElement { readonly rotate: SVGAnimatedNumberList; readonly x: SVGAnimatedLengthList; readonly y: SVGAnimatedLengthList; - addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPositioningElement: { @@ -13158,8 +11804,10 @@ declare var SVGTextPositioningElement: { }; interface SVGTitleElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTitleElement: { @@ -13217,8 +11865,10 @@ declare var SVGTransformList: { }; interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTSpanElement: { @@ -13240,8 +11890,10 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGUseElement: { @@ -13251,8 +11903,10 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; - addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGViewElement: { @@ -13372,8 +12026,10 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrack: { @@ -13403,8 +12059,10 @@ interface TextTrackCue extends EventTarget { text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrackCue: { @@ -13432,8 +12090,10 @@ interface TextTrackList extends EventTarget { readonly length: number; onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: TextTrack; } @@ -13641,8 +12301,10 @@ interface VideoTrackList extends EventTarget { readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: VideoTrack; } @@ -13846,7 +12508,29 @@ interface WebGLRenderingContext { getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; - getExtension(name: string): any; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram | null): string | null; @@ -14660,8 +13344,10 @@ declare var WebKitPoint: { }; interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var webkitRTCPeerConnection: { @@ -14693,8 +13379,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -14985,7 +13673,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; postMessage(message: any, targetOrigin: string, transfer?: any[]): void; print(): void; prompt(message?: string, _default?: string): string | null; @@ -15006,8 +13694,10 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Window: { @@ -15023,8 +13713,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -15033,8 +13725,10 @@ declare var Worker: { }; interface XMLDocument extends Document { - addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLDocument: { @@ -15075,8 +13769,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -15090,8 +13786,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -15196,8 +13894,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -15342,8 +14042,10 @@ interface GlobalEventHandlers { onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; - addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface GlobalFetch { @@ -15395,8 +14097,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface MSFileSaver { @@ -15453,9 +14157,11 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; - querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -15542,8 +14248,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface BroadcastChannel extends EventTarget { @@ -15552,8 +14260,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -15734,7 +14444,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -15970,6 +14680,128 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -16037,28 +14869,46 @@ interface VoidFunction { } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; "audio": HTMLAudioElement; + "b": HTMLElement; "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; "col": HTMLTableColElement; "colgroup": HTMLTableColElement; "data": HTMLDataElement; "datalist": HTMLDataListElement; + "dd": HTMLElement; "del": HTMLModElement; + "dfn": HTMLElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; "embed": HTMLEmbedElement; "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; "font": HTMLFontElement; + "footer": HTMLElement; "form": HTMLFormElement; "frame": HTMLFrameElement; "frameset": HTMLFrameSetElement; @@ -16069,24 +14919,34 @@ interface HTMLElementTagNameMap { "h5": HTMLHeadingElement; "h6": HTMLHeadingElement; "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; "hr": HTMLHRElement; "html": HTMLHtmlElement; + "i": HTMLElement; "iframe": HTMLIFrameElement; "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; "listing": HTMLPreElement; "map": HTMLMapElement; + "mark": HTMLElement; "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; + "nav": HTMLElement; "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; "optgroup": HTMLOptGroupElement; @@ -16095,14 +14955,25 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; + "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; "script": HTMLScriptElement; + "section": HTMLElement; "select": HTMLSelectElement; + "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; "table": HTMLTableElement; "tbody": HTMLTableSectionElement; "td": HTMLTableDataCellElement; @@ -16115,33 +14986,22 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; "ul": HTMLUListElement; + "var": HTMLElement; "video": HTMLVideoElement; + "wbr": HTMLElement; "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } -interface ElementTagNameMap extends HTMLElementTagNameMap { - "abbr": HTMLElement; - "acronym": HTMLElement; - "address": HTMLElement; - "article": HTMLElement; - "aside": HTMLElement; - "b": HTMLElement; - "bdo": HTMLElement; - "big": HTMLElement; - "center": HTMLElement; +interface SVGElementTagNameMap { "circle": SVGCircleElement; - "cite": HTMLElement; "clippath": SVGClipPathElement; - "code": HTMLElement; - "dd": HTMLElement; "defs": SVGDefsElement; "desc": SVGDescElement; - "dfn": HTMLElement; - "dt": HTMLElement; "ellipse": SVGEllipseElement; - "em": HTMLElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -16166,63 +15026,33 @@ interface ElementTagNameMap extends HTMLElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "figcaption": HTMLElement; - "figure": HTMLElement; "filter": SVGFilterElement; - "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; "g": SVGGElement; - "header": HTMLElement; - "hgroup": HTMLElement; - "i": HTMLElement; "image": SVGImageElement; - "kbd": HTMLElement; - "keygen": HTMLElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "mark": HTMLElement; "marker": SVGMarkerElement; "mask": SVGMaskElement; "metadata": SVGMetadataElement; - "nav": HTMLElement; - "nobr": HTMLElement; - "noframes": HTMLElement; - "noscript": HTMLElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; - "rt": HTMLElement; - "ruby": HTMLElement; - "s": HTMLElement; - "samp": HTMLElement; - "section": HTMLElement; - "small": HTMLElement; "stop": SVGStopElement; - "strike": HTMLElement; - "strong": HTMLElement; - "sub": HTMLElement; - "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; "text": SVGTextElement; "textpath": SVGTextPathElement; "tspan": SVGTSpanElement; - "tt": HTMLElement; - "u": HTMLElement; "use": SVGUseElement; - "var": HTMLElement; "view": SVGViewElement; - "wbr": HTMLElement; } -type ElementListTagNameMap = { - [key in keyof ElementTagNameMap]: NodeListOf -}; +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; @@ -16385,7 +15215,7 @@ declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; @@ -16408,7 +15238,6 @@ declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; @@ -16434,8 +15263,10 @@ declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; -declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; @@ -16459,7 +15290,6 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -16480,6 +15310,7 @@ type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -16870,23 +15701,6 @@ interface DOMTokenList { [Symbol.iterator](): IterableIterator; } -interface FormData { - /** - * Returns an array of key, value pairs for every entry in the list - */ - entries(): IterableIterator<[string, string | File]>; - /** - * Returns a list of keys in the list - */ - keys(): IterableIterator; - /** - * Returns a list of values in the list - */ - values(): IterableIterator; - - [Symbol.iterator](): IterableIterator; -} - interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** @@ -16953,6 +15767,31 @@ interface NodeListOf { [Symbol.iterator](): IterableIterator; } +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[string, string | File]>; + /** + * Returns a list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + interface URLSearchParams { /** * Returns an array of key, value pairs for every entry in the search params diff --git a/lib/lib.es2017.d.ts b/lib/lib.es2017.d.ts index b887f51e8c6bc..0598171a09194 100644 --- a/lib/lib.es2017.d.ts +++ b/lib/lib.es2017.d.ts @@ -23,3 +23,4 @@ and limitations under the License. /// /// /// +/// diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 96b589afafab7..6e021331e37da 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -23,1691 +23,7 @@ and limitations under the License. /// /// /// - - -declare type PropertyKey = string | number | symbol; - -interface Array { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): this; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): T[]; -} - -interface DateConstructor { - new (value: Date): Date; -} - -interface Function { - /** - * Returns the name of the function. Function names are read-only and can not be changed. - */ - readonly name: string; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[] ): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - readonly EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - readonly MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - readonly MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface Object { - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean; -} - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source The source object from which to copy properties. - */ - assign(target: T, source: U): T & U; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V): T & U & V; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - * @param source3 The third source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects from which to copy properties - */ - assign(target: object, ...sources: any[]): any; - - /** - * Returns an array of all symbol properties found directly on object o. - * @param o Object to retrieve the symbols from. - */ - getOwnPropertySymbols(o: any): symbol[]; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - */ - setPrototypeOf(o: any, proto: object | null): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not - * inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript - * object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor - * property. - */ - defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; -} - -interface ReadonlyArray { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - readonly flags: string; - - /** - * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular - * expression. Default is false. Read-only. - */ - readonly sticky: boolean; - - /** - * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular - * expression. Default is false. Read-only. - */ - readonly unicode: boolean; -} - -interface RegExpConstructor { - new (pattern: RegExp, flags?: string): RegExp; - (pattern: RegExp, flags?: string): RegExp; -} - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number | undefined; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form?: string): string; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; - - /** - * Returns an HTML anchor element and sets the name attribute to the text value - * @param name - */ - anchor(name: string): string; - - /** Returns a HTML element */ - big(): string; - - /** Returns a HTML element */ - blink(): string; - - /** Returns a HTML element */ - bold(): string; - - /** Returns a HTML element */ - fixed(): string; - - /** Returns a HTML element and sets the color attribute value */ - fontcolor(color: string): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: number): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: string): string; - - /** Returns an HTML element */ - italics(): string; - - /** Returns an HTML element and sets the href attribute value */ - link(url: string): string; - - /** Returns a HTML element */ - small(): string; - - /** Returns a HTML element */ - strike(): string; - - /** Returns a HTML element */ - sub(): string; - - /** Returns a HTML element */ - sup(): string; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} - - -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value: V): this; - readonly size: number; -} - -interface MapConstructor { - new (): Map; - new (entries?: [K, V][]): Map; - readonly prototype: Map; -} -declare var Map: MapConstructor; - -interface ReadonlyMap { - forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - readonly size: number; -} - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value: V): this; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (entries?: [K, V][]): WeakMap; - readonly prototype: WeakMap; -} -declare var WeakMap: WeakMapConstructor; - -interface Set { - add(value: T): this; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface SetConstructor { - new (): Set; - new (values?: T[]): Set; - readonly prototype: Set; -} -declare var Set: SetConstructor; - -interface ReadonlySet { - forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface WeakSet { - add(value: T): this; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (values?: T[]): WeakSet; - readonly prototype: WeakSet; -} -declare var WeakSet: WeakSetConstructor; - - -interface Generator extends Iterator { } - -interface GeneratorFunction { - /** - * Creates a new Generator object. - * @param args A list of arguments the function accepts. - */ - new (...args: any[]): Generator; - /** - * Creates a new Generator object. - * @param args A list of arguments the function accepts. - */ - (...args: any[]): Generator; - /** - * The length of the arguments. - */ - readonly length: number; - /** - * Returns the name of the function. - */ - readonly name: string; - /** - * A reference to the prototype. - */ - readonly prototype: Generator; -} - -interface GeneratorFunctionConstructor { - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): GeneratorFunction; - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - (...args: string[]): GeneratorFunction; - /** - * The length of the arguments. - */ - readonly length: number; - /** - * Returns the name of the function. - */ - readonly name: string; - /** - * A reference to the prototype. - */ - readonly prototype: GeneratorFunction; -} -declare var GeneratorFunction: GeneratorFunctionConstructor; - - -/// - -interface SymbolConstructor { - /** - * A method that returns the default iterator for an object. Called by the semantics of the - * for-of statement. - */ - readonly iterator: symbol; -} - -interface IteratorResult { - done: boolean; - value: T; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface Iterable { - [Symbol.iterator](): Iterator; -} - -interface IterableIterator extends Iterator { - [Symbol.iterator](): IterableIterator; -} - -interface Array { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an iterable of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the array - */ - values(): IterableIterator; -} - -interface ArrayConstructor { - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; -} - -interface ReadonlyArray { - /** Iterator of values in the array. */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an iterable of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the array - */ - values(): IterableIterator; -} - -interface IArguments { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Map { - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](): IterableIterator<[K, V]>; - - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - entries(): IterableIterator<[K, V]>; - - /** - * Returns an iterable of keys in the map - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the map - */ - values(): IterableIterator; -} - -interface ReadonlyMap { - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](): IterableIterator<[K, V]>; - - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - entries(): IterableIterator<[K, V]>; - - /** - * Returns an iterable of keys in the map - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the map - */ - values(): IterableIterator; -} - -interface MapConstructor { - new (iterable: Iterable<[K, V]>): Map; -} - -interface WeakMap { } - -interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; -} - -interface Set { - /** Iterates over values in the set. */ - [Symbol.iterator](): IterableIterator; - /** - * Returns an iterable of [v,v] pairs for every value `v` in the set. - */ - entries(): IterableIterator<[T, T]>; - /** - * Despite its name, returns an iterable of the values in the set, - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the set. - */ - values(): IterableIterator; -} - -interface ReadonlySet { - /** Iterates over values in the set. */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of [v,v] pairs for every value `v` in the set. - */ - entries(): IterableIterator<[T, T]>; - - /** - * Despite its name, returns an iterable of the values in the set, - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the set. - */ - values(): IterableIterator; -} - -interface SetConstructor { - new (iterable: Iterable): Set; -} - -interface WeakSet { } - -interface WeakSetConstructor { - new (iterable: Iterable): WeakSet; -} - -interface Promise { } - -interface PromiseConstructor { - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: Iterable>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: Iterable>): Promise; -} - -declare namespace Reflect { - function enumerate(target: object): IterableIterator; -} - -interface String { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Int8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int8ArrayConstructor { - new (elements: Iterable): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; -} - -interface Uint8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ArrayConstructor { - new (elements: Iterable): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; -} - -interface Uint8ClampedArray { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ClampedArrayConstructor { - new (elements: Iterable): Uint8ClampedArray; - - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} - -interface Int16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int16ArrayConstructor { - new (elements: Iterable): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; -} - -interface Uint16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint16ArrayConstructor { - new (elements: Iterable): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; -} - -interface Int32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int32ArrayConstructor { - new (elements: Iterable): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} - -interface Uint32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint32ArrayConstructor { - new (elements: Iterable): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} - -interface Float32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float32ArrayConstructor { - new (elements: Iterable): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; -} - -interface Float64Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float64ArrayConstructor { - new (elements: Iterable): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -} - - -interface PromiseConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Promise; - - /** - * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, - * and a reject callback used to reject the promise with a provided reason or error. - */ - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: (T | PromiseLike)[]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: (T | PromiseLike)[]): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor; - -interface ProxyHandler { - getPrototypeOf? (target: T): object | null; - setPrototypeOf? (target: T, v: any): boolean; - isExtensible? (target: T): boolean; - preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; - has? (target: T, p: PropertyKey): boolean; - get? (target: T, p: PropertyKey, receiver: any): any; - set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; - deleteProperty? (target: T, p: PropertyKey): boolean; - defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; - enumerate? (target: T): PropertyKey[]; - ownKeys? (target: T): PropertyKey[]; - apply? (target: T, thisArg: any, argArray?: any): any; - construct? (target: T, argArray: any, newTarget?: any): object; -} - -interface ProxyConstructor { - revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; - new (target: T, handler: ProxyHandler): T; -} -declare var Proxy: ProxyConstructor; - - -declare namespace Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; - function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: object, propertyKey: PropertyKey): boolean; - function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; - function getPrototypeOf(target: object): object; - function has(target: object, propertyKey: PropertyKey): boolean; - function isExtensible(target: object): boolean; - function ownKeys(target: object): PropertyKey[]; - function preventExtensions(target: object): boolean; - function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: object, proto: any): boolean; -} - - -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): symbol; -} - -interface SymbolConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Symbol; - - /** - * Returns a new unique Symbol value. - * @param description Description of the new Symbol object. - */ - (description?: string | number): symbol; - - /** - * Returns a Symbol object from the global symbol registry matching the given key if found. - * Otherwise, returns a new symbol with this key. - * @param key key to search for. - */ - for(key: string): symbol; - - /** - * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. - * @param sym Symbol to find the key for. - */ - keyFor(sym: symbol): string | undefined; -} - -declare var Symbol: SymbolConstructor; - -/// - -interface SymbolConstructor { - /** - * A method that determines if a constructor object recognizes an object as one of the - * constructor’s instances. Called by the semantics of the instanceof operator. - */ - readonly hasInstance: symbol; - - /** - * A Boolean value that if true indicates that an object should flatten to its array elements - * by Array.prototype.concat. - */ - readonly isConcatSpreadable: symbol; - - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.match method. - */ - readonly match: symbol; - - /** - * A regular expression method that replaces matched substrings of a string. Called by the - * String.prototype.replace method. - */ - readonly replace: symbol; - - /** - * A regular expression method that returns the index within a string that matches the - * regular expression. Called by the String.prototype.search method. - */ - readonly search: symbol; - - /** - * A function valued property that is the constructor function that is used to create - * derived objects. - */ - readonly species: symbol; - - /** - * A regular expression method that splits a string at the indices that match the regular - * expression. Called by the String.prototype.split method. - */ - readonly split: symbol; - - /** - * A method that converts an object to a corresponding primitive value. - * Called by the ToPrimitive abstract operation. - */ - readonly toPrimitive: symbol; - - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - readonly toStringTag: symbol; - - /** - * An Object whose own property names are property names that are excluded from the 'with' - * environment bindings of the associated objects. - */ - readonly unscopables: symbol; -} - -interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; -} - -interface Array { - /** - * Returns an object whose properties have the value 'true' - * when they will be absent when used in a 'with' statement. - */ - [Symbol.unscopables](): { - copyWithin: boolean; - entries: boolean; - fill: boolean; - find: boolean; - findIndex: boolean; - keys: boolean; - values: boolean; - }; -} - -interface Date { - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "default"): string; - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "string"): string; - /** - * Converts a Date object to a number. - */ - [Symbol.toPrimitive](hint: "number"): number; - /** - * Converts a Date object to a string or number. - * - * @param hint The strings "number", "string", or "default" to specify what primitive to return. - * - * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". - * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". - */ - [Symbol.toPrimitive](hint: string): string | number; -} - -interface Map { - readonly [Symbol.toStringTag]: "Map"; -} - -interface WeakMap { - readonly [Symbol.toStringTag]: "WeakMap"; -} - -interface Set { - readonly [Symbol.toStringTag]: "Set"; -} - -interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; -} - -interface JSON { - readonly [Symbol.toStringTag]: "JSON"; -} - -interface Function { - /** - * Determines whether the given value inherits from this function if this function was used - * as a constructor function. - * - * A constructor function can control which objects are recognized as its instances by - * 'instanceof' by overriding this method. - */ - [Symbol.hasInstance](value: any): boolean; -} - -interface GeneratorFunction { - readonly [Symbol.toStringTag]: "GeneratorFunction"; -} - -interface Math { - readonly [Symbol.toStringTag]: "Math"; -} - -interface Promise { - readonly [Symbol.toStringTag]: "Promise"; -} - -interface PromiseConstructor { - readonly [Symbol.species]: Function; -} - -interface RegExp { - /** - * Matches a string with this regular expression, and returns an array containing the results of - * that search. - * @param string A string to search within. - */ - [Symbol.match](string: string): RegExpMatchArray | null; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replaceValue A String object or string literal containing the text to replace for every - * successful match of this regular expression. - */ - [Symbol.replace](string: string, replaceValue: string): string; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replacer A function that returns the replacement text. - */ - [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the position beginning first substring match in a regular expression search - * using this regular expression. - * - * @param string The string to search within. - */ - [Symbol.search](string: string): number; - - /** - * Returns an array of substrings that were delimited by strings in the original input that - * match against this regular expression. - * - * If the regular expression contains capturing parentheses, then each time this - * regular expression matches, the results (including any undefined results) of the - * capturing parentheses are spliced. - * - * @param string string value to split - * @param limit if not undefined, the output array is truncated so that it contains no more - * than 'limit' elements. - */ - [Symbol.split](string: string, limit?: number): string[]; -} - -interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; -} - -interface String { - /** - * Matches a string an object that supports being matched against, and returns an array containing the results of that search. - * @param matcher An object that supports being matched against. - */ - match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param searcher An object which supports searching within a string. - */ - search(searcher: { [Symbol.search](string: string): number; }): number; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param splitter An object that can split a string. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; -} - -interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; -} - -interface DataView { - readonly [Symbol.toStringTag]: "DataView"; -} - -interface Int8Array { - readonly [Symbol.toStringTag]: "Int8Array"; -} - -interface Uint8Array { - readonly [Symbol.toStringTag]: "UInt8Array"; -} - -interface Uint8ClampedArray { - readonly [Symbol.toStringTag]: "Uint8ClampedArray"; -} - -interface Int16Array { - readonly [Symbol.toStringTag]: "Int16Array"; -} - -interface Uint16Array { - readonly [Symbol.toStringTag]: "Uint16Array"; -} - -interface Int32Array { - readonly [Symbol.toStringTag]: "Int32Array"; -} - -interface Uint32Array { - readonly [Symbol.toStringTag]: "Uint32Array"; -} - -interface Float32Array { - readonly [Symbol.toStringTag]: "Float32Array"; -} - -interface Float64Array { - readonly [Symbol.toStringTag]: "Float64Array"; -} +/// @@ -1794,8 +110,8 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } -interface CustomEventInit extends EventInit { - detail?: any; +interface CustomEventInit extends EventInit { + detail?: T; } interface DeviceAccelerationDict { @@ -1915,7 +231,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface IntersectionObserverEntryInit { @@ -2408,7 +724,7 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; total?: PaymentItem; } @@ -2420,7 +736,7 @@ interface PaymentItem { interface PaymentMethodData { data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; } interface PaymentOptions { @@ -2485,7 +801,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -2497,7 +813,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -2967,8 +1283,10 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ApplicationCache: { @@ -3024,8 +1342,10 @@ interface AudioBufferSourceNode extends AudioNode { readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AudioBufferSourceNode: { @@ -3066,8 +1386,10 @@ interface AudioContextBase extends EventTarget { createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; resume(): Promise; - addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface AudioContext extends AudioContextBase { @@ -3174,8 +1496,10 @@ interface AudioTrackList extends EventTarget { onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: AudioTrack; } @@ -3301,6 +1625,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { beginPath(): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; @@ -3310,11 +1635,13 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; restore(): void; @@ -4078,20 +2405,22 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } declare var CustomEvent: { prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; interface DataCue extends TextTrackCue { data: ArrayBuffer; - addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DataCue: { @@ -4942,7 +3271,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -5013,8 +3343,10 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Document: { @@ -5297,7 +3629,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -5326,6 +3659,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scroll(options?: ScrollToOptions): void; @@ -5338,8 +3673,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; - addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Element: { @@ -5475,8 +3812,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -5597,7 +3936,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface History { @@ -5708,8 +4047,10 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAnchorElement: { @@ -5782,8 +4123,10 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; - addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAppletElement: { @@ -5850,8 +4193,10 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAreaElement: { @@ -5868,8 +4213,10 @@ declare var HTMLAreasCollection: { }; interface HTMLAudioElement extends HTMLMediaElement { - addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAudioElement: { @@ -5886,8 +4233,10 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseElement: { @@ -5904,8 +4253,10 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseFontElement: { @@ -5945,11 +4296,7 @@ interface HTMLBodyElement extends HTMLElement { onafterprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; - onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; - onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; - onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; - onload: (this: HTMLBodyElement, ev: Event) => any; onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; onoffline: (this: HTMLBodyElement, ev: Event) => any; ononline: (this: HTMLBodyElement, ev: Event) => any; @@ -5958,13 +4305,14 @@ interface HTMLBodyElement extends HTMLElement { onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; onresize: (this: HTMLBodyElement, ev: UIEvent) => any; - onscroll: (this: HTMLBodyElement, ev: UIEvent) => any; onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBodyElement: { @@ -5977,8 +4325,10 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBRElement: { @@ -6050,8 +4400,10 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLButtonElement: { @@ -6085,8 +4437,10 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; - addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLCanvasElement: { @@ -6120,8 +4474,10 @@ declare var HTMLCollection: { interface HTMLDataElement extends HTMLElement { value: string; - addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataElement: { @@ -6131,8 +4487,10 @@ declare var HTMLDataElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; - addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataListElement: { @@ -6142,8 +4500,10 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDirectoryElement: { @@ -6160,8 +4520,10 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; - addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDivElement: { @@ -6171,8 +4533,10 @@ declare var HTMLDivElement: { interface HTMLDListElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDListElement: { @@ -6181,8 +4545,10 @@ declare var HTMLDListElement: { }; interface HTMLDocument extends Document { - addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDocument: { @@ -6354,8 +4720,10 @@ interface HTMLElement extends Element { dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLElement: { @@ -6410,8 +4778,10 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLEmbedElement: { @@ -6451,8 +4821,10 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFieldSetElement: { @@ -6465,8 +4837,10 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; - addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFontElement: { @@ -6550,8 +4924,11 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; - addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -6613,10 +4990,6 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -6629,8 +5002,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameElement: { @@ -6682,17 +5057,7 @@ interface HTMLFrameSetElement extends HTMLElement { onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; - onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; - onload: (this: HTMLFrameSetElement, ev: Event) => any; onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; onoffline: (this: HTMLFrameSetElement, ev: Event) => any; ononline: (this: HTMLFrameSetElement, ev: Event) => any; @@ -6701,15 +5066,16 @@ interface HTMLFrameSetElement extends HTMLElement { onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; - onscroll: (this: HTMLFrameSetElement, ev: UIEvent) => any; onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameSetElement: { @@ -6719,8 +5085,10 @@ declare var HTMLFrameSetElement: { interface HTMLHeadElement extends HTMLElement { profile: string; - addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadElement: { @@ -6733,8 +5101,10 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; - addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadingElement: { @@ -6755,8 +5125,10 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHRElement: { @@ -6769,8 +5141,10 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; - addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHtmlElement: { @@ -6837,10 +5211,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -6858,8 +5228,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLIFrameElement: { @@ -6949,8 +5321,10 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; - addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLImageElement: { @@ -7161,8 +5535,10 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; - addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLInputElement: { @@ -7179,8 +5555,11 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; - addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLabelElement: { @@ -7197,8 +5576,10 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement | null; - addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLegendElement: { @@ -7212,8 +5593,10 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLIElement: { @@ -7257,8 +5640,10 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; - addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLinkElement: { @@ -7275,8 +5660,10 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMapElement: { @@ -7307,8 +5694,10 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMarqueeElement: { @@ -7489,8 +5878,10 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMediaElement: { @@ -7510,8 +5901,10 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMenuElement: { @@ -7544,8 +5937,10 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; - addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMetaElement: { @@ -7560,8 +5955,10 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; - addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMeterElement: { @@ -7578,8 +5975,10 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; - addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLModElement: { @@ -7695,8 +6094,10 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLObjectElement: { @@ -7711,8 +6112,10 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; - addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOListElement: { @@ -7750,8 +6153,10 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptGroupElement: { @@ -7789,8 +6194,10 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptionElement: { @@ -7823,8 +6230,10 @@ interface HTMLOutputElement extends HTMLElement { checkValidity(): boolean; reportValidity(): boolean; setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOutputElement: { @@ -7838,8 +6247,10 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; - addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParagraphElement: { @@ -7864,8 +6275,10 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; - addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParamElement: { @@ -7874,8 +6287,10 @@ declare var HTMLParamElement: { }; interface HTMLPictureElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPictureElement: { @@ -7888,8 +6303,10 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPreElement: { @@ -7914,8 +6331,10 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; - addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLProgressElement: { @@ -7928,8 +6347,10 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; - addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLQuoteElement: { @@ -7969,8 +6390,10 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; - addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLScriptElement: { @@ -8065,8 +6488,10 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -8091,8 +6516,10 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; - addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSourceElement: { @@ -8101,8 +6528,10 @@ declare var HTMLSourceElement: { }; interface HTMLSpanElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSpanElement: { @@ -8120,8 +6549,10 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; - addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLStyleElement: { @@ -8138,8 +6569,10 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; - addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCaptionElement: { @@ -8193,8 +6626,10 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCellElement: { @@ -8215,8 +6650,10 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; - addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableColElement: { @@ -8225,8 +6662,10 @@ declare var HTMLTableColElement: { }; interface HTMLTableDataCellElement extends HTMLTableCellElement { - addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableDataCellElement: { @@ -8338,8 +6777,10 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableElement: { @@ -8352,8 +6793,10 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; - addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableHeaderCellElement: { @@ -8393,8 +6836,10 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableRowElement: { @@ -8421,8 +6866,10 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableSectionElement: { @@ -8432,8 +6879,10 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; - addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTemplateElement: { @@ -8539,8 +6988,10 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; - addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTextAreaElement: { @@ -8550,8 +7001,10 @@ declare var HTMLTextAreaElement: { interface HTMLTimeElement extends HTMLElement { dateTime: string; - addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTimeElement: { @@ -8564,8 +7017,10 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; - addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTitleElement: { @@ -8585,8 +7040,10 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; - addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTrackElement: { @@ -8601,8 +7058,10 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUListElement: { @@ -8611,8 +7070,10 @@ declare var HTMLUListElement: { }; interface HTMLUnknownElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUnknownElement: { @@ -8666,8 +7127,10 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullScreen(): void; webkitExitFullscreen(): void; webkitExitFullScreen(): void; - addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLVideoElement: { @@ -8724,9 +7187,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -8810,8 +7276,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -8832,8 +7300,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -8859,8 +7329,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -9029,8 +7501,10 @@ interface MediaDevices extends EventTarget { enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaDevices: { @@ -9201,8 +7675,10 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStream: { @@ -9273,8 +7749,10 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStreamTrack: { @@ -9323,8 +7801,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -9428,8 +7908,10 @@ interface MSAppAsyncOperation extends EventTarget { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSAppAsyncOperation: { @@ -9584,8 +8066,10 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; - addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSHTMLWebViewElement: { @@ -9610,8 +8094,10 @@ interface MSInputMethodContext extends EventTarget { getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSInputMethodContext: { @@ -9776,8 +8262,10 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSStreamReader: { @@ -9805,8 +8293,10 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSWebViewAsyncOperation: { @@ -9937,6 +8427,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly pointerEnabled: boolean; readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; + readonly doNotTrack: string | null; readonly hardwareConcurrency: number; readonly languages: string[]; getGamepads(): Gamepad[]; @@ -10095,8 +8586,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -10175,8 +8668,10 @@ interface OfflineAudioContext extends AudioContextBase { oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; startRendering(): Promise; suspend(suspendTime: number): Promise; - addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OfflineAudioContext: { @@ -10196,8 +8691,10 @@ interface OscillatorNode extends AudioNode { setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OscillatorNode: { @@ -10291,8 +8788,10 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; show(): Promise; - addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentRequest: { @@ -10798,8 +9297,10 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtlsTransport: { @@ -10828,8 +9329,10 @@ interface RTCDtmfSender extends EventTarget { readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtmfSender: { @@ -10879,8 +9382,10 @@ interface RTCIceGatherer extends RTCStatsProvider { createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidateDictionary[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceGatherer: { @@ -10917,8 +9422,10 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; stop(): void; - addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceTransport: { @@ -10972,8 +9479,10 @@ interface RTCPeerConnection extends EventTarget { removeStream(stream: MediaStream): void; setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCPeerConnection: { @@ -11004,8 +9513,10 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpReceiver: { @@ -11029,8 +9540,10 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpSender: { @@ -11057,8 +9570,10 @@ interface RTCSrtpSdesTransportEventMap { interface RTCSrtpSdesTransport extends EventTarget { onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCSrtpSdesTransport: { @@ -11129,8 +9644,10 @@ interface Screen extends EventTarget { readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -11155,8 +9672,10 @@ interface ScriptProcessorNodeEventMap { interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ScriptProcessorNode: { @@ -11207,8 +9726,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -11226,11 +9747,13 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(): Promise; + getRegistration(clientURL?: USVString): Promise; getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerContainer: { @@ -11267,8 +9790,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -11321,8 +9846,10 @@ interface SpeechSynthesis extends EventTarget { pause(): void; resume(): void; speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesis: { @@ -11366,8 +9893,10 @@ interface SpeechSynthesisUtterance extends EventTarget { text: string; voice: SpeechSynthesisVoice; volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesisUtterance: { @@ -11501,8 +10030,10 @@ declare var SubtleCrypto: { interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGAElement: { @@ -11658,8 +10189,10 @@ interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGCircleElement: { @@ -11669,8 +10202,10 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGClipPathElement: { @@ -11692,8 +10227,10 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGComponentTransferFunctionElement: { @@ -11708,8 +10245,10 @@ declare var SVGComponentTransferFunctionElement: { }; interface SVGDefsElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDefsElement: { @@ -11718,8 +10257,10 @@ declare var SVGDefsElement: { }; interface SVGDescElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDescElement: { @@ -11756,8 +10297,10 @@ interface SVGElement extends Element { readonly style: CSSStyleDeclaration; readonly viewportElement: SVGElement; xmlbase: string; - addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGElement: { @@ -11796,8 +10339,10 @@ interface SVGEllipseElement extends SVGGraphicsElement { readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGEllipseElement: { @@ -11826,8 +10371,10 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEBlendElement: { @@ -11861,8 +10408,10 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEColorMatrixElement: { @@ -11877,8 +10426,10 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEComponentTransferElement: { @@ -11901,8 +10452,10 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFECompositeElement: { @@ -11934,8 +10487,10 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEConvolveMatrixElement: { @@ -11953,8 +10508,10 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDiffuseLightingElement: { @@ -11973,8 +10530,10 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDisplacementMapElement: { @@ -11990,8 +10549,10 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDistantLightElement: { @@ -12000,8 +10561,10 @@ declare var SVGFEDistantLightElement: { }; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFloodElement: { @@ -12010,8 +10573,10 @@ declare var SVGFEFloodElement: { }; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncAElement: { @@ -12020,8 +10585,10 @@ declare var SVGFEFuncAElement: { }; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncBElement: { @@ -12030,8 +10597,10 @@ declare var SVGFEFuncBElement: { }; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncGElement: { @@ -12040,8 +10609,10 @@ declare var SVGFEFuncGElement: { }; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncRElement: { @@ -12054,8 +10625,10 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEGaussianBlurElement: { @@ -12065,8 +10638,10 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEImageElement: { @@ -12075,8 +10650,10 @@ declare var SVGFEImageElement: { }; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeElement: { @@ -12086,8 +10663,10 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeNodeElement: { @@ -12103,8 +10682,10 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMorphologyElement: { @@ -12119,8 +10700,10 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEOffsetElement: { @@ -12132,8 +10715,10 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEPointLightElement: { @@ -12148,8 +10733,10 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpecularLightingElement: { @@ -12166,8 +10753,10 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpotLightElement: { @@ -12177,8 +10766,10 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETileElement: { @@ -12199,8 +10790,10 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETurbulenceElement: { @@ -12224,8 +10817,10 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFilterElement: { @@ -12238,8 +10833,10 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGForeignObjectElement: { @@ -12248,8 +10845,10 @@ declare var SVGForeignObjectElement: { }; interface SVGGElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGElement: { @@ -12265,8 +10864,10 @@ interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGradientElement: { @@ -12286,8 +10887,10 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; - addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGraphicsElement: { @@ -12301,8 +10904,10 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGImageElement: { @@ -12367,8 +10972,10 @@ interface SVGLinearGradientElement extends SVGGradientElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLinearGradientElement: { @@ -12381,8 +10988,10 @@ interface SVGLineElement extends SVGGraphicsElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLineElement: { @@ -12406,8 +11015,10 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly SVG_MARKERUNITS_STROKEWIDTH: number; readonly SVG_MARKERUNITS_UNKNOWN: number; readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMarkerElement: { @@ -12428,8 +11039,10 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMaskElement: { @@ -12463,8 +11076,10 @@ declare var SVGMatrix: { }; interface SVGMetadataElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMetadataElement: { @@ -12521,8 +11136,10 @@ interface SVGPathElement extends SVGGraphicsElement { getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; - addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPathElement: { @@ -12814,8 +11431,10 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPatternElement: { @@ -12851,8 +11470,10 @@ declare var SVGPointList: { }; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolygonElement: { @@ -12861,8 +11482,10 @@ declare var SVGPolygonElement: { }; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolylineElement: { @@ -12914,8 +11537,10 @@ interface SVGRadialGradientElement extends SVGGradientElement { readonly fx: SVGAnimatedLength; readonly fy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRadialGradientElement: { @@ -12942,8 +11567,10 @@ interface SVGRectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRectElement: { @@ -12953,8 +11580,10 @@ declare var SVGRectElement: { interface SVGScriptElement extends SVGElement, SVGURIReference { type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGScriptElement: { @@ -12964,8 +11593,10 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement { readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStopElement: { @@ -12994,8 +11625,10 @@ interface SVGStyleElement extends SVGElement { media: string; title: string; type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStyleElement: { @@ -13055,8 +11688,10 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSVGElement: { @@ -13065,8 +11700,10 @@ declare var SVGSVGElement: { }; interface SVGSwitchElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSwitchElement: { @@ -13075,8 +11712,10 @@ declare var SVGSwitchElement: { }; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { - addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSymbolElement: { @@ -13099,8 +11738,10 @@ interface SVGTextContentElement extends SVGGraphicsElement { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextContentElement: { @@ -13112,8 +11753,10 @@ declare var SVGTextContentElement: { }; interface SVGTextElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextElement: { @@ -13131,8 +11774,10 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPathElement: { @@ -13152,8 +11797,10 @@ interface SVGTextPositioningElement extends SVGTextContentElement { readonly rotate: SVGAnimatedNumberList; readonly x: SVGAnimatedLengthList; readonly y: SVGAnimatedLengthList; - addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPositioningElement: { @@ -13162,8 +11809,10 @@ declare var SVGTextPositioningElement: { }; interface SVGTitleElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTitleElement: { @@ -13221,8 +11870,10 @@ declare var SVGTransformList: { }; interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTSpanElement: { @@ -13244,8 +11895,10 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGUseElement: { @@ -13255,8 +11908,10 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; - addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGViewElement: { @@ -13376,8 +12031,10 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrack: { @@ -13407,8 +12064,10 @@ interface TextTrackCue extends EventTarget { text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrackCue: { @@ -13436,8 +12095,10 @@ interface TextTrackList extends EventTarget { readonly length: number; onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: TextTrack; } @@ -13645,8 +12306,10 @@ interface VideoTrackList extends EventTarget { readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: VideoTrack; } @@ -13850,7 +12513,29 @@ interface WebGLRenderingContext { getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; - getExtension(name: string): any; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram | null): string | null; @@ -14664,8 +13349,10 @@ declare var WebKitPoint: { }; interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var webkitRTCPeerConnection: { @@ -14697,8 +13384,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -14989,7 +13678,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; postMessage(message: any, targetOrigin: string, transfer?: any[]): void; print(): void; prompt(message?: string, _default?: string): string | null; @@ -15010,8 +13699,10 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Window: { @@ -15027,8 +13718,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -15037,8 +13730,10 @@ declare var Worker: { }; interface XMLDocument extends Document { - addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLDocument: { @@ -15079,8 +13774,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -15094,8 +13791,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -15200,8 +13899,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -15346,8 +14047,10 @@ interface GlobalEventHandlers { onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; - addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface GlobalFetch { @@ -15399,8 +14102,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface MSFileSaver { @@ -15457,9 +14162,11 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; - querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -15546,8 +14253,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface BroadcastChannel extends EventTarget { @@ -15556,8 +14265,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -15738,7 +14449,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -15974,6 +14685,128 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -16041,28 +14874,46 @@ interface VoidFunction { } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; "audio": HTMLAudioElement; + "b": HTMLElement; "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; "col": HTMLTableColElement; "colgroup": HTMLTableColElement; "data": HTMLDataElement; "datalist": HTMLDataListElement; + "dd": HTMLElement; "del": HTMLModElement; + "dfn": HTMLElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; "embed": HTMLEmbedElement; "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; "font": HTMLFontElement; + "footer": HTMLElement; "form": HTMLFormElement; "frame": HTMLFrameElement; "frameset": HTMLFrameSetElement; @@ -16073,24 +14924,34 @@ interface HTMLElementTagNameMap { "h5": HTMLHeadingElement; "h6": HTMLHeadingElement; "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; "hr": HTMLHRElement; "html": HTMLHtmlElement; + "i": HTMLElement; "iframe": HTMLIFrameElement; "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; "listing": HTMLPreElement; "map": HTMLMapElement; + "mark": HTMLElement; "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; + "nav": HTMLElement; "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; "optgroup": HTMLOptGroupElement; @@ -16099,14 +14960,25 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; + "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; "script": HTMLScriptElement; + "section": HTMLElement; "select": HTMLSelectElement; + "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; "table": HTMLTableElement; "tbody": HTMLTableSectionElement; "td": HTMLTableDataCellElement; @@ -16119,33 +14991,22 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; "ul": HTMLUListElement; + "var": HTMLElement; "video": HTMLVideoElement; + "wbr": HTMLElement; "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } -interface ElementTagNameMap extends HTMLElementTagNameMap { - "abbr": HTMLElement; - "acronym": HTMLElement; - "address": HTMLElement; - "article": HTMLElement; - "aside": HTMLElement; - "b": HTMLElement; - "bdo": HTMLElement; - "big": HTMLElement; - "center": HTMLElement; +interface SVGElementTagNameMap { "circle": SVGCircleElement; - "cite": HTMLElement; "clippath": SVGClipPathElement; - "code": HTMLElement; - "dd": HTMLElement; "defs": SVGDefsElement; "desc": SVGDescElement; - "dfn": HTMLElement; - "dt": HTMLElement; "ellipse": SVGEllipseElement; - "em": HTMLElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -16170,63 +15031,33 @@ interface ElementTagNameMap extends HTMLElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "figcaption": HTMLElement; - "figure": HTMLElement; "filter": SVGFilterElement; - "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; "g": SVGGElement; - "header": HTMLElement; - "hgroup": HTMLElement; - "i": HTMLElement; "image": SVGImageElement; - "kbd": HTMLElement; - "keygen": HTMLElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "mark": HTMLElement; "marker": SVGMarkerElement; "mask": SVGMaskElement; "metadata": SVGMetadataElement; - "nav": HTMLElement; - "nobr": HTMLElement; - "noframes": HTMLElement; - "noscript": HTMLElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; - "rt": HTMLElement; - "ruby": HTMLElement; - "s": HTMLElement; - "samp": HTMLElement; - "section": HTMLElement; - "small": HTMLElement; "stop": SVGStopElement; - "strike": HTMLElement; - "strong": HTMLElement; - "sub": HTMLElement; - "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; "text": SVGTextElement; "textpath": SVGTextPathElement; "tspan": SVGTSpanElement; - "tt": HTMLElement; - "u": HTMLElement; "use": SVGUseElement; - "var": HTMLElement; "view": SVGViewElement; - "wbr": HTMLElement; } -type ElementListTagNameMap = { - [key in keyof ElementTagNameMap]: NodeListOf -}; +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; @@ -16389,7 +15220,7 @@ declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; @@ -16412,7 +15243,6 @@ declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; @@ -16438,8 +15268,10 @@ declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; -declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; @@ -16463,7 +15295,6 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -16484,6 +15315,7 @@ type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -16874,23 +15706,6 @@ interface DOMTokenList { [Symbol.iterator](): IterableIterator; } -interface FormData { - /** - * Returns an array of key, value pairs for every entry in the list - */ - entries(): IterableIterator<[string, string | File]>; - /** - * Returns a list of keys in the list - */ - keys(): IterableIterator; - /** - * Returns a list of values in the list - */ - values(): IterableIterator; - - [Symbol.iterator](): IterableIterator; -} - interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** @@ -16957,6 +15772,31 @@ interface NodeListOf { [Symbol.iterator](): IterableIterator; } +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[string, string | File]>; + /** + * Returns a list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + interface URLSearchParams { /** * Returns an array of key, value pairs for every entry in the search params diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index 7eecc25680df0..c0f782464fffb 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -23,7 +23,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: { [s: string]: T }): T[]; + values(o: { [s: string]: T } | { [n: number]: T }): T[]; /** * Returns an array of values of the enumerable properties of an object @@ -35,7 +35,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: { [s: string]: T }): [string, T][]; + entries(o: { [s: string]: T } | { [n: number]: T }): [string, T][]; /** * Returns an array of key/values of the enumerable properties of an object diff --git a/lib/lib.es2017.typedarrays.d.ts b/lib/lib.es2017.typedarrays.d.ts new file mode 100644 index 0000000000000..4f6f6e72d307e --- /dev/null +++ b/lib/lib.es2017.typedarrays.d.ts @@ -0,0 +1,55 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Int8ArrayConstructor { + new (): Int8Array; +} + +interface Uint8ArrayConstructor { + new (): Uint8Array; +} + +interface Uint8ClampedArrayConstructor { + new (): Uint8ClampedArray; +} + +interface Int16ArrayConstructor { + new (): Int16Array; +} + +interface Uint16ArrayConstructor { + new (): Uint16Array; +} + +interface Int32ArrayConstructor { + new (): Int32Array; +} + +interface Uint32ArrayConstructor { + new (): Uint32Array; +} + +interface Float32ArrayConstructor { + new (): Float32Array; +} + +interface Float64ArrayConstructor { + new (): Float64Array; +} diff --git a/lib/lib.es2018.d.ts b/lib/lib.es2018.d.ts new file mode 100644 index 0000000000000..c7ea194ecfde3 --- /dev/null +++ b/lib/lib.es2018.d.ts @@ -0,0 +1,21 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// \ No newline at end of file diff --git a/lib/lib.es2018.full.d.ts b/lib/lib.es2018.full.d.ts new file mode 100644 index 0000000000000..5333251034adc --- /dev/null +++ b/lib/lib.es2018.full.d.ts @@ -0,0 +1,15811 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// + + +///////////////////////////// +/// DOM APIs +///////////////////////////// + +interface Account { + displayName: string; + id: string; + imageURL?: string; + name?: string; + rpDisplayName: string; +} + +interface Algorithm { + name: string; +} + +interface AnimationEventInit extends EventInit { + animationName?: string; + elapsedTime?: number; +} + +interface AssertionOptions { + allowList?: ScopedCredentialDescriptor[]; + extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; +} + +interface CacheQueryOptions { + cacheName?: string; + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; +} + +interface ClientData { + challenge: string; + extensions?: WebAuthnExtensions; + hashAlg: string | Algorithm; + origin: string; + rpId: string; + tokenBinding?: string; +} + +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: string[]; +} + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface ConstrainDOMStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface ConstrainDoubleRange extends DoubleRange { + exact?: number; + ideal?: number; +} + +interface ConstrainLongRange extends LongRange { + exact?: number; + ideal?: number; +} + +interface ConstrainVideoFacingModeParameters { + exact?: VideoFacingModeEnum | VideoFacingModeEnum[]; + ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; +} + +interface CustomEventInit extends EventInit { + detail?: T; +} + +interface DeviceAccelerationDict { + x?: number | null; + y?: number | null; + z?: number | null; +} + +interface DeviceLightEventInit extends EventInit { + value?: number; +} + +interface DeviceMotionEventInit extends EventInit { + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; +} + +interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; +} + +interface DeviceRotationRateDict { + alpha?: number | null; + beta?: number | null; + gamma?: number | null; +} + +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DoubleRange { + max?: number; + min?: number; +} + +interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; +} + +interface EventInit { + scoped?: boolean; + bubbles?: boolean; + cancelable?: boolean; +} + +interface EventModifierInit extends UIEventInit { + altKey?: boolean; + ctrlKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierOS?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; + shiftKey?: boolean; +} + +interface ExceptionInformation { + domain?: string | null; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget | null; +} + +interface FocusNavigationEventInit extends EventInit { + navigationReason?: string | null; + originHeight?: number; + originLeft?: number; + originTop?: number; + originWidth?: number; +} + +interface FocusNavigationOrigin { + originHeight?: number; + originLeft?: number; + originTop?: number; + originWidth?: number; +} + +interface GamepadEventInit extends EventInit { + gamepad?: Gamepad | null; +} + +interface GetNotificationOptions { + tag?: string; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string | null; + oldURL?: string | null; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: string | string[]; +} + +interface IntersectionObserverEntryInit { + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; +} + +interface IntersectionObserverInit { + root?: Element | null; + rootMargin?: string; + threshold?: number | number[]; +} + +interface KeyAlgorithm { + name?: string; +} + +interface KeyboardEventInit extends EventModifierInit { + code?: string; + key?: string; + location?: number; + repeat?: boolean; +} + +interface LongRange { + max?: number; + min?: number; +} + +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer | null; + initDataType?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message?: ArrayBuffer | null; + messageType?: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + persistentState?: MediaKeysRequirement; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + robustness?: string; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamErrorEventInit extends EventInit { + error?: MediaStreamError | null; +} + +interface MediaStreamEventInit extends EventInit { + stream?: MediaStream; +} + +interface MediaStreamTrackEventInit extends EventInit { + track?: MediaStreamTrack | null; +} + +interface MediaTrackCapabilities { + aspectRatio?: number | DoubleRange; + deviceId?: string; + echoCancellation?: boolean[]; + facingMode?: string; + frameRate?: number | DoubleRange; + groupId?: string; + height?: number | LongRange; + sampleRate?: number | LongRange; + sampleSize?: number | LongRange; + volume?: number | DoubleRange; + width?: number | LongRange; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + aspectRatio?: number | ConstrainDoubleRange; + deviceId?: string | string[] | ConstrainDOMStringParameters; + echoCancelation?: boolean | ConstrainBooleanParameters; + facingMode?: string | string[] | ConstrainDOMStringParameters; + frameRate?: number | ConstrainDoubleRange; + groupId?: string | string[] | ConstrainDOMStringParameters; + height?: number | ConstrainLongRange; + sampleRate?: number | ConstrainLongRange; + sampleSize?: number | ConstrainLongRange; + volume?: number | ConstrainDoubleRange; + width?: number | ConstrainLongRange; +} + +interface MediaTrackSettings { + aspectRatio?: number; + deviceId?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + sampleRate?: number; + sampleSize?: number; + volume?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + deviceId?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + volume?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + lastEventId?: string; + channel?: string; + data?: any; + origin?: string; + ports?: MessagePort[]; + source?: Window; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + +interface MSAccountInfo { + accountImageUri?: string; + accountName?: string; + rpDisplayName: string; + userDisplayName: string; + userId?: string; +} + +interface MSAudioLocalClientEvent extends MSLocalClientEventBase { + cpuInsufficientEventRatio?: number; + deviceCaptureNotFunctioningEventRatio?: number; + deviceClippingEventRatio?: number; + deviceEchoEventRatio?: number; + deviceGlitchesEventRatio?: number; + deviceHalfDuplexAECEventRatio?: number; + deviceHowlingEventCount?: number; + deviceLowSNREventRatio?: number; + deviceLowSpeechLevelEventRatio?: number; + deviceMultipleEndpointsEventCount?: number; + deviceNearEndToEchoRatioEventRatio?: number; + deviceRenderMuteEventRatio?: number; + deviceRenderNotFunctioningEventRatio?: number; + deviceRenderZeroVolumeEventRatio?: number; + networkDelayEventRatio?: number; + networkSendQualityEventRatio?: number; +} + +interface MSAudioRecvPayload extends MSPayloadBase { + burstLossLength1?: number; + burstLossLength2?: number; + burstLossLength3?: number; + burstLossLength4?: number; + burstLossLength5?: number; + burstLossLength6?: number; + burstLossLength7?: number; + burstLossLength8OrHigher?: number; + fecRecvDistance1?: number; + fecRecvDistance2?: number; + fecRecvDistance3?: number; + packetReorderDepthAvg?: number; + packetReorderDepthMax?: number; + packetReorderRatio?: number; + ratioCompressedSamplesAvg?: number; + ratioConcealedSamplesAvg?: number; + ratioStretchedSamplesAvg?: number; + samplingRate?: number; + signal?: MSAudioRecvSignal; +} + +interface MSAudioRecvSignal { + initialSignalLevelRMS?: number; + recvNoiseLevelCh1?: number; + recvSignalLevelCh1?: number; + renderLoopbackSignalLevel?: number; + renderNoiseLevel?: number; + renderSignalLevel?: number; +} + +interface MSAudioSendPayload extends MSPayloadBase { + audioFECUsed?: boolean; + samplingRate?: number; + sendMutePercent?: number; + signal?: MSAudioSendSignal; +} + +interface MSAudioSendSignal { + noiseLevel?: number; + sendNoiseLevelCh1?: number; + sendSignalLevelCh1?: number; +} + +interface MSConnectivity { + iceType?: MSIceType; + iceWarningFlags?: MSIceWarningFlags; + relayAddress?: MSRelayAddress; +} + +interface MSCredentialFilter { + accept?: MSCredentialSpec[]; +} + +interface MSCredentialParameters { + type?: MSCredentialType; +} + +interface MSCredentialSpec { + id?: string; + type: MSCredentialType; +} + +interface MSDelay { + roundTrip?: number; + roundTripMax?: number; +} + +interface MSDescription extends RTCStats { + connectivity?: MSConnectivity; + deviceDevName?: string; + localAddr?: MSIPAddressInfo; + networkconnectivity?: MSNetworkConnectivityInfo; + reflexiveLocalIPAddr?: MSIPAddressInfo; + remoteAddr?: MSIPAddressInfo; + transport?: RTCIceProtocol; +} + +interface MSFIDOCredentialParameters extends MSCredentialParameters { + algorithm?: string | Algorithm; + authenticators?: AAGUID[]; +} + +interface MSIceWarningFlags { + allocationMessageIntegrityFailed?: boolean; + alternateServerReceived?: boolean; + connCheckMessageIntegrityFailed?: boolean; + connCheckOtherError?: boolean; + fipsAllocationFailure?: boolean; + multipleRelayServersAttempted?: boolean; + noRelayServersConfigured?: boolean; + portRangeExhausted?: boolean; + pseudoTLSFailure?: boolean; + tcpNatConnectivityFailed?: boolean; + tcpRelayConnectivityFailed?: boolean; + turnAuthUnknownUsernameError?: boolean; + turnTcpAllocateFailed?: boolean; + turnTcpSendFailed?: boolean; + turnTcpTimedOut?: boolean; + turnTurnTcpConnectivityFailed?: boolean; + turnUdpAllocateFailed?: boolean; + turnUdpSendFailed?: boolean; + udpLocalConnectivityFailed?: boolean; + udpNatConnectivityFailed?: boolean; + udpRelayConnectivityFailed?: boolean; + useCandidateChecksFailed?: boolean; +} + +interface MSIPAddressInfo { + ipAddr?: string; + manufacturerMacAddrMask?: string; + port?: number; +} + +interface MSJitter { + interArrival?: number; + interArrivalMax?: number; + interArrivalSD?: number; +} + +interface MSLocalClientEventBase extends RTCStats { + networkBandwidthLowEventRatio?: number; + networkReceiveQualityEventRatio?: number; +} + +interface MSNetwork extends RTCStats { + delay?: MSDelay; + jitter?: MSJitter; + packetLoss?: MSPacketLoss; + utilization?: MSUtilization; +} + +interface MSNetworkConnectivityInfo { + linkspeed?: number; + networkConnectionDetails?: string; + vpn?: boolean; +} + +interface MSNetworkInterfaceType { + interfaceTypeEthernet?: boolean; + interfaceTypePPP?: boolean; + interfaceTypeTunnel?: boolean; + interfaceTypeWireless?: boolean; + interfaceTypeWWAN?: boolean; +} + +interface MSOutboundNetwork extends MSNetwork { + appliedBandwidthLimit?: number; +} + +interface MSPacketLoss { + lossRate?: number; + lossRateMax?: number; +} + +interface MSPayloadBase extends RTCStats { + payloadDescription?: string; +} + +interface MSPortRange { + max?: number; + min?: number; +} + +interface MSRelayAddress { + port?: number; + relayAddress?: string; +} + +interface MSSignatureParameters { + userPrompt?: string; +} + +interface MSTransportDiagnosticsStats extends RTCStats { + allocationTimeInMs?: number; + baseAddress?: string; + baseInterface?: MSNetworkInterfaceType; + iceRole?: RTCIceRole; + iceWarningFlags?: MSIceWarningFlags; + interfaces?: MSNetworkInterfaceType; + localAddress?: string; + localAddrType?: MSIceAddrType; + localInterface?: MSNetworkInterfaceType; + localMR?: string; + localMRTCPPort?: number; + localSite?: string; + msRtcEngineVersion?: string; + networkName?: string; + numConsentReqReceived?: number; + numConsentReqSent?: number; + numConsentRespReceived?: number; + numConsentRespSent?: number; + portRangeMax?: number; + portRangeMin?: number; + protocol?: RTCIceProtocol; + remoteAddress?: string; + remoteAddrType?: MSIceAddrType; + remoteMR?: string; + remoteMRTCPPort?: number; + remoteSite?: string; + rtpRtcpMux?: boolean; + stunVer?: number; +} + +interface MSUtilization { + bandwidthEstimation?: number; + bandwidthEstimationAvg?: number; + bandwidthEstimationMax?: number; + bandwidthEstimationMin?: number; + bandwidthEstimationStdDev?: number; + packets?: number; +} + +interface MSVideoPayload extends MSPayloadBase { + durationSeconds?: number; + resolution?: string; + videoBitRateAvg?: number; + videoBitRateMax?: number; + videoFrameRateAvg?: number; + videoPacketLossRate?: number; +} + +interface MSVideoRecvPayload extends MSVideoPayload { + lowBitRateCallPercent?: number; + lowFrameRateCallPercent?: number; + recvBitRateAverage?: number; + recvBitRateMaximum?: number; + recvCodecType?: string; + recvFpsHarmonicAverage?: number; + recvFrameRateAverage?: number; + recvNumResSwitches?: number; + recvReorderBufferMaxSuccessfullyOrderedExtent?: number; + recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; + recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; + recvReorderBufferPacketsDroppedDueToTimeout?: number; + recvReorderBufferReorderedPackets?: number; + recvResolutionHeight?: number; + recvResolutionWidth?: number; + recvVideoStreamsMax?: number; + recvVideoStreamsMin?: number; + recvVideoStreamsMode?: number; + reorderBufferTotalPackets?: number; + videoFrameLossRate?: number; + videoPostFECPLR?: number; + videoResolutions?: MSVideoResolutionDistribution; +} + +interface MSVideoResolutionDistribution { + cifQuality?: number; + h1080Quality?: number; + h1440Quality?: number; + h2160Quality?: number; + h720Quality?: number; + vgaQuality?: number; +} + +interface MSVideoSendPayload extends MSVideoPayload { + sendBitRateAverage?: number; + sendBitRateMaximum?: number; + sendFrameRateAverage?: number; + sendResolutionHeight?: number; + sendResolutionWidth?: number; + sendVideoStreamsMax?: number; +} + +interface MsZoomToOptions { + animate?: string; + contentX?: number; + contentY?: number; + scaleFactor?: number; + viewportX?: string | null; + viewportY?: string | null; +} + +interface MutationObserverInit { + attributeFilter?: string[]; + attributeOldValue?: boolean; + attributes?: boolean; + characterData?: boolean; + characterDataOldValue?: boolean; + childList?: boolean; + subtree?: boolean; +} + +interface NotificationOptions { + body?: string; + dir?: NotificationDirection; + icon?: string; + lang?: string; + tag?: string; +} + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +interface PaymentCurrencyAmount { + currency: string; + currencySystem?: string; + value: string; +} + +interface PaymentDetails { + displayItems?: PaymentItem[]; + error?: string; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; + total?: PaymentItem; +} + +interface PaymentDetailsModifier { + additionalDisplayItems?: PaymentItem[]; + data?: any; + supportedMethods: string | string[]; + total?: PaymentItem; +} + +interface PaymentItem { + amount: PaymentCurrencyAmount; + label: string; + pending?: boolean; +} + +interface PaymentMethodData { + data?: any; + supportedMethods: string | string[]; +} + +interface PaymentOptions { + requestPayerEmail?: boolean; + requestPayerName?: boolean; + requestPayerPhone?: boolean; + requestShipping?: boolean; + shippingType?: string; +} + +interface PaymentRequestUpdateEventInit extends EventInit { +} + +interface PaymentShippingOption { + amount: PaymentCurrencyAmount; + id: string; + label: string; + selected?: boolean; +} + +interface PeriodicWaveConstraints { + disableNormalization?: boolean; +} + +interface PointerEventInit extends MouseEventInit { + height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; + pressure?: number; + tiltX?: number; + tiltY?: number; + width?: number; +} + +interface PopStateEventInit extends EventInit { + state?: any; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + maximumAge?: number; + timeout?: number; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface PushSubscriptionOptionsInit { + applicationServerKey?: any; + userVisibleOnly?: boolean; +} + +interface RegistrationOptions { + scope?: string; +} + +interface RequestInit { + body?: any; + cache?: RequestCache; + credentials?: RequestCredentials; + headers?: HeadersInit; + integrity?: string; + keepalive?: boolean; + method?: string; + mode?: RequestMode; + redirect?: RequestRedirect; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + window?: any; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; + iceServers?: RTCIceServer[]; + iceTransportPolicy?: RTCIceTransportPolicy; + peerIdentity?: string; +} + +interface RTCDtlsFingerprint { + algorithm?: string; + value?: string; +} + +interface RTCDtlsParameters { + fingerprints?: RTCDtlsFingerprint[]; + role?: RTCDtlsRole; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + +interface RTCIceCandidateAttributes extends RTCStats { + addressSourceUrl?: string; + candidateType?: RTCStatsIceCandidateType; + ipAddress?: string; + portNumber?: number; + priority?: number; + transport?: string; +} + +interface RTCIceCandidateComplete { +} + +interface RTCIceCandidateDictionary { + foundation?: string; + ip?: string; + msMTurnSessionId?: string; + port?: number; + priority?: number; + protocol?: RTCIceProtocol; + relatedAddress?: string; + relatedPort?: number; + tcpType?: RTCIceTcpCandidateType; + type?: RTCIceCandidateType; +} + +interface RTCIceCandidateInit { + candidate?: string; + sdpMid?: string; + sdpMLineIndex?: number; +} + +interface RTCIceCandidatePair { + local?: RTCIceCandidateDictionary; + remote?: RTCIceCandidateDictionary; +} + +interface RTCIceCandidatePairStats extends RTCStats { + availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesReceived?: number; + bytesSent?: number; + localCandidateId?: string; + nominated?: boolean; + priority?: number; + readable?: boolean; + remoteCandidateId?: string; + roundTripTime?: number; + state?: RTCStatsIceCandidatePairState; + transportId?: string; + writable?: boolean; +} + +interface RTCIceGatherOptions { + gatherPolicy?: RTCIceGatherPolicy; + iceservers?: RTCIceServer[]; + portRange?: MSPortRange; +} + +interface RTCIceParameters { + iceLite?: boolean | null; + password?: string; + usernameFragment?: string; +} + +interface RTCIceServer { + credential?: string | null; + urls?: any; + username?: string | null; +} + +interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { + bytesReceived?: number; + fractionLost?: number; + jitter?: number; + packetsLost?: number; + packetsReceived?: number; +} + +interface RTCMediaStreamTrackStats extends RTCStats { + audioLevel?: number; + echoReturnLoss?: number; + echoReturnLossEnhancement?: number; + frameHeight?: number; + framesCorrupted?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesSent?: number; + frameWidth?: number; + remoteSource?: boolean; + ssrcIds?: string[]; + trackIdentifier?: string; +} + +interface RTCOfferOptions { + iceRestart?: boolean; + offerToReceiveAudio?: number; + offerToReceiveVideo?: number; + voiceActivityDetection?: boolean; +} + +interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { + bytesSent?: number; + packetsSent?: number; + roundTripTime?: number; + targetBitrate?: number; +} + +interface RTCPeerConnectionIceEventInit extends EventInit { + candidate?: RTCIceCandidate; +} + +interface RTCRtcpFeedback { + parameter?: string; + type?: string; +} + +interface RTCRtcpParameters { + cname?: string; + mux?: boolean; + reducedSize?: boolean; + ssrc?: number; +} + +interface RTCRtpCapabilities { + codecs?: RTCRtpCodecCapability[]; + fecMechanisms?: string[]; + headerExtensions?: RTCRtpHeaderExtension[]; +} + +interface RTCRtpCodecCapability { + clockRate?: number; + kind?: string; + maxptime?: number; + maxSpatialLayers?: number; + maxTemporalLayers?: number; + name?: string; + numChannels?: number; + options?: any; + parameters?: any; + preferredPayloadType?: number; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; + svcMultiStreamSupport?: boolean; +} + +interface RTCRtpCodecParameters { + clockRate?: number; + maxptime?: number; + name?: string; + numChannels?: number; + parameters?: any; + payloadType?: any; + ptime?: number; + rtcpFeedback?: RTCRtcpFeedback[]; +} + +interface RTCRtpContributingSource { + audioLevel?: number; + csrc?: number; + timestamp?: number; +} + +interface RTCRtpEncodingParameters { + active?: boolean; + codecPayloadType?: number; + dependencyEncodingIds?: string[]; + encodingId?: string; + fec?: RTCRtpFecParameters; + framerateScale?: number; + maxBitrate?: number; + maxFramerate?: number; + minQuality?: number; + priority?: number; + resolutionScale?: number; + rtx?: RTCRtpRtxParameters; + ssrc?: number; + ssrcRange?: RTCSsrcRange; +} + +interface RTCRtpFecParameters { + mechanism?: string; + ssrc?: number; +} + +interface RTCRtpHeaderExtension { + kind?: string; + preferredEncrypt?: boolean; + preferredId?: number; + uri?: string; +} + +interface RTCRtpHeaderExtensionParameters { + encrypt?: boolean; + id?: number; + uri?: string; +} + +interface RTCRtpParameters { + codecs?: RTCRtpCodecParameters[]; + degradationPreference?: RTCDegradationPreference; + encodings?: RTCRtpEncodingParameters[]; + headerExtensions?: RTCRtpHeaderExtensionParameters[]; + muxId?: string; + rtcp?: RTCRtcpParameters; +} + +interface RTCRtpRtxParameters { + ssrc?: number; +} + +interface RTCRTPStreamStats extends RTCStats { + associateStatsId?: string; + codecId?: string; + firCount?: number; + isRemote?: boolean; + mediaTrackId?: string; + nackCount?: number; + pliCount?: number; + sliCount?: number; + ssrc?: string; + transportId?: string; +} + +interface RTCRtpUnhandled { + muxId?: string; + payloadType?: number; + ssrc?: number; +} + +interface RTCSessionDescriptionInit { + sdp?: string; + type?: RTCSdpType; +} + +interface RTCSrtpKeyParam { + keyMethod?: string; + keySalt?: string; + lifetime?: string; + mkiLength?: number; + mkiValue?: number; +} + +interface RTCSrtpSdesParameters { + cryptoSuite?: string; + keyParams?: RTCSrtpKeyParam[]; + sessionParams?: string[]; + tag?: number; +} + +interface RTCSsrcRange { + max?: number; + min?: number; +} + +interface RTCStats { + id?: string; + msType?: MSStatsType; + timestamp?: number; + type?: RTCStatsType; +} + +interface RTCStatsReport { +} + +interface RTCTransportStats extends RTCStats { + activeConnection?: boolean; + bytesReceived?: number; + bytesSent?: number; + localCertificateId?: string; + remoteCertificateId?: string; + rtcpTransportStatsId?: string; + selectedCandidatePairId?: string; +} + +interface ScopedCredentialDescriptor { + id: any; + transports?: Transport[]; + type: ScopedCredentialType; +} + +interface ScopedCredentialOptions { + excludeList?: ScopedCredentialDescriptor[]; + extensions?: WebAuthnExtensions; + rpId?: USVString; + timeoutSeconds?: number; +} + +interface ScopedCredentialParameters { + algorithm: string | Algorithm; + type: ScopedCredentialType; +} + +interface ServiceWorkerMessageEventInit extends EventInit { + data?: any; + lastEventId?: string; + origin?: string; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; +} + +interface SpeechSynthesisEventInit extends EventInit { + charIndex?: number; + elapsedTime?: number; + name?: string; + utterance?: SpeechSynthesisUtterance | null; +} + +interface StoreExceptionsInformation extends ExceptionInformation { + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: string[]; +} + +interface TrackEventInit extends EventInit { + track?: VideoTrack | AudioTrack | TextTrack | null; +} + +interface TransitionEventInit extends EventInit { + elapsedTime?: number; + propertyName?: string; +} + +interface UIEventInit extends EventInit { + detail?: number; + view?: Window | null; +} + +interface WebAuthnExtensions { +} + +interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; + alpha?: boolean; + antialias?: boolean; + depth?: boolean; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; + stencil?: boolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WheelEventInit extends MouseEventInit { + deltaMode?: number; + deltaX?: number; + deltaY?: number; + deltaZ?: number; +} + +interface EventListener { + (evt: Event): void; +} + +interface WebKitEntriesCallback { + (evt: Event): void; +} + +interface WebKitErrorCallback { + (evt: Event): void; +} + +interface WebKitFileCallback { + (evt: Event): void; +} + +interface AnalyserNode extends AudioNode { + fftSize: number; + readonly frequencyBinCount: number; + maxDecibels: number; + minDecibels: number; + smoothingTimeConstant: number; + getByteFrequencyData(array: Uint8Array): void; + getByteTimeDomainData(array: Uint8Array): void; + getFloatFrequencyData(array: Float32Array): void; + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(): AnalyserNode; +}; + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +}; + +interface AnimationEvent extends Event { + readonly animationName: string; + readonly elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; +}; + +interface ApplicationCacheEventMap { + "cached": Event; + "checking": Event; + "downloading": Event; + "error": Event; + "noupdate": Event; + "obsolete": Event; + "progress": ProgressEvent; + "updateready": Event; +} + +interface ApplicationCache extends EventTarget { + oncached: (this: ApplicationCache, ev: Event) => any; + onchecking: (this: ApplicationCache, ev: Event) => any; + ondownloading: (this: ApplicationCache, ev: Event) => any; + onerror: (this: ApplicationCache, ev: Event) => any; + onnoupdate: (this: ApplicationCache, ev: Event) => any; + onobsolete: (this: ApplicationCache, ev: Event) => any; + onprogress: (this: ApplicationCache, ev: ProgressEvent) => any; + onupdateready: (this: ApplicationCache, ev: Event) => any; + readonly status: number; + abort(): void; + swapCache(): void; + update(): void; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + readonly CHECKING: number; + readonly DOWNLOADING: number; + readonly IDLE: number; + readonly OBSOLETE: number; + readonly UNCACHED: number; + readonly UPDATEREADY: number; +}; + +interface Attr extends Node { + readonly name: string; + readonly ownerElement: Element; + readonly prefix: string | null; + readonly specified: boolean; + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +}; + +interface AudioBuffer { + readonly duration: number; + readonly length: number; + readonly numberOfChannels: number; + readonly sampleRate: number; + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(): AudioBuffer; +}; + +interface AudioBufferSourceNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface AudioBufferSourceNode extends AudioNode { + buffer: AudioBuffer | null; + readonly detune: AudioParam; + loop: boolean; + loopEnd: number; + loopStart: number; + onended: (this: AudioBufferSourceNode, ev: MediaStreamErrorEvent) => any; + readonly playbackRate: AudioParam; + start(when?: number, offset?: number, duration?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(): AudioBufferSourceNode; +}; + +interface AudioContextEventMap { + "statechange": Event; +} + +interface AudioContextBase extends EventTarget { + readonly currentTime: number; + readonly destination: AudioDestinationNode; + readonly listener: AudioListener; + onstatechange: (this: AudioContext, ev: Event) => any; + readonly sampleRate: number; + readonly state: AudioContextState; + close(): Promise; + createAnalyser(): AnalyserNode; + createBiquadFilter(): BiquadFilterNode; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + createBufferSource(): AudioBufferSourceNode; + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + createConvolver(): ConvolverNode; + createDelay(maxDelayTime?: number): DelayNode; + createDynamicsCompressor(): DynamicsCompressorNode; + createGain(): GainNode; + createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode; + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; + createOscillator(): OscillatorNode; + createPanner(): PannerNode; + createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + createStereoPanner(): StereoPannerNode; + createWaveShaper(): WaveShaperNode; + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; + resume(): Promise; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface AudioContext extends AudioContextBase { + suspend(): Promise; +} + +declare var AudioContext: { + prototype: AudioContext; + new(): AudioContext; +}; + +interface AudioDestinationNode extends AudioNode { + readonly maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +}; + +interface AudioListener { + dopplerFactor: number; + speedOfSound: number; + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +}; + +interface AudioNode extends EventTarget { + channelCount: number; + channelCountMode: ChannelCountMode; + channelInterpretation: ChannelInterpretation; + readonly context: AudioContext; + readonly numberOfInputs: number; + readonly numberOfOutputs: number; + connect(destination: AudioNode, output?: number, input?: number): AudioNode; + connect(destination: AudioParam, output?: number): void; + disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +}; + +interface AudioParam { + readonly defaultValue: number; + value: number; + cancelScheduledValues(startTime: number): AudioParam; + exponentialRampToValueAtTime(value: number, endTime: number): AudioParam; + linearRampToValueAtTime(value: number, endTime: number): AudioParam; + setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam; + setValueAtTime(value: number, startTime: number): AudioParam; + setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): AudioParam; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +}; + +interface AudioProcessingEvent extends Event { + readonly inputBuffer: AudioBuffer; + readonly outputBuffer: AudioBuffer; + readonly playbackTime: number; +} + +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(): AudioProcessingEvent; +}; + +interface AudioTrack { + enabled: boolean; + readonly id: string; + kind: string; + readonly label: string; + language: string; + readonly sourceBuffer: SourceBuffer; +} + +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +}; + +interface AudioTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface AudioTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: AudioTrackList, ev: TrackEvent) => any; + onchange: (this: AudioTrackList, ev: Event) => any; + onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack | null; + item(index: number): AudioTrack; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: AudioTrack; +} + +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +}; + +interface BarProp { + readonly visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +}; + +interface BeforeUnloadEvent extends Event { + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +}; + +interface BiquadFilterNode extends AudioNode { + readonly detune: AudioParam; + readonly frequency: AudioParam; + readonly gain: AudioParam; + readonly Q: AudioParam; + type: BiquadFilterType; + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(): BiquadFilterNode; +}; + +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +}; + +interface Cache { + add(request: RequestInfo): Promise; + addAll(requests: RequestInfo[]): Promise; + delete(request: RequestInfo, options?: CacheQueryOptions): Promise; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; + put(request: RequestInfo, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +interface CacheStorage { + delete(cacheName: string): Promise; + has(cacheName: string): Promise; + keys(): Promise; + match(request: RequestInfo, options?: CacheQueryOptions): Promise; + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPattern { + setTransform(matrix: SVGMatrix): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRenderingContext2D extends Object, CanvasPathMethods { + readonly canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + imageSmoothingEnabled: boolean; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: CanvasFillRule; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + mozImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + beginPath(): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawFocusIfNeeded(element: Element): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; + fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; + measureText(text: string): TextMetrics; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(path?: Path2D): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +}; + +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +}; + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +}; + +interface CharacterData extends Node, ChildNode { + data: string; + readonly length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ClientRect { + bottom: number; + readonly height: number; + left: number; + right: number; + top: number; + readonly width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +}; + +interface ClientRectList { + readonly length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +}; + +interface ClipboardEvent extends Event { + readonly clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +interface CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +}; + +interface CompositionEvent extends UIEvent { + readonly data: string; + readonly locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: any, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + exception(message?: string, ...optionalParams: any[]): void; + group(groupTitle?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + table(...data: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +}; + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer | null; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +}; + +interface Coordinates { + readonly accuracy: number; + readonly altitude: number | null; + readonly altitudeAccuracy: number | null; + readonly heading: number | null; + readonly latitude: number; + readonly longitude: number; + readonly speed: number | null; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +}; + +interface Crypto extends Object, RandomSource { + readonly subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +}; + +interface CSS { + supports(property: string, value?: string): boolean; +} +declare var CSS: CSS; + +interface CSSConditionRule extends CSSGroupingRule { + conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +}; + +interface CSSFontFaceRule extends CSSRule { + readonly style: CSSStyleDeclaration; +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +}; + +interface CSSGroupingRule extends CSSRule { + readonly cssRules: CSSRuleList; + deleteRule(index: number): void; + insertRule(rule: string, index: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +}; + +interface CSSImportRule extends CSSRule { + readonly href: string; + readonly media: MediaList; + readonly styleSheet: CSSStyleSheet; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +}; + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +}; + +interface CSSKeyframesRule extends CSSRule { + readonly cssRules: CSSRuleList; + name: string; + appendRule(rule: string): void; + deleteRule(rule: string): void; + findRule(rule: string): CSSKeyframeRule; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +}; + +interface CSSMediaRule extends CSSConditionRule { + readonly media: MediaList; +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +}; + +interface CSSNamespaceRule extends CSSRule { + readonly namespaceURI: string; + readonly prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +}; + +interface CSSPageRule extends CSSRule { + readonly pseudoClass: string; + readonly selector: string; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +}; + +interface CSSRule { + cssText: string; + readonly parentRule: CSSRule; + readonly parentStyleSheet: CSSStyleSheet; + readonly type: number; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + readonly CHARSET_RULE: number; + readonly FONT_FACE_RULE: number; + readonly IMPORT_RULE: number; + readonly KEYFRAME_RULE: number; + readonly KEYFRAMES_RULE: number; + readonly MEDIA_RULE: number; + readonly NAMESPACE_RULE: number; + readonly PAGE_RULE: number; + readonly STYLE_RULE: number; + readonly SUPPORTS_RULE: number; + readonly UNKNOWN_RULE: number; + readonly VIEWPORT_RULE: number; +}; + +interface CSSRuleList { + readonly length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +}; + +interface CSSStyleDeclaration { + alignContent: string | null; + alignItems: string | null; + alignmentBaseline: string | null; + alignSelf: string | null; + animation: string | null; + animationDelay: string | null; + animationDirection: string | null; + animationDuration: string | null; + animationFillMode: string | null; + animationIterationCount: string | null; + animationName: string | null; + animationPlayState: string | null; + animationTimingFunction: string | null; + backfaceVisibility: string | null; + background: string | null; + backgroundAttachment: string | null; + backgroundClip: string | null; + backgroundColor: string | null; + backgroundImage: string | null; + backgroundOrigin: string | null; + backgroundPosition: string | null; + backgroundPositionX: string | null; + backgroundPositionY: string | null; + backgroundRepeat: string | null; + backgroundSize: string | null; + baselineShift: string | null; + border: string | null; + borderBottom: string | null; + borderBottomColor: string | null; + borderBottomLeftRadius: string | null; + borderBottomRightRadius: string | null; + borderBottomStyle: string | null; + borderBottomWidth: string | null; + borderCollapse: string | null; + borderColor: string | null; + borderImage: string | null; + borderImageOutset: string | null; + borderImageRepeat: string | null; + borderImageSlice: string | null; + borderImageSource: string | null; + borderImageWidth: string | null; + borderLeft: string | null; + borderLeftColor: string | null; + borderLeftStyle: string | null; + borderLeftWidth: string | null; + borderRadius: string | null; + borderRight: string | null; + borderRightColor: string | null; + borderRightStyle: string | null; + borderRightWidth: string | null; + borderSpacing: string | null; + borderStyle: string | null; + borderTop: string | null; + borderTopColor: string | null; + borderTopLeftRadius: string | null; + borderTopRightRadius: string | null; + borderTopStyle: string | null; + borderTopWidth: string | null; + borderWidth: string | null; + bottom: string | null; + boxShadow: string | null; + boxSizing: string | null; + breakAfter: string | null; + breakBefore: string | null; + breakInside: string | null; + captionSide: string | null; + clear: string | null; + clip: string | null; + clipPath: string | null; + clipRule: string | null; + color: string | null; + colorInterpolationFilters: string | null; + columnCount: any; + columnFill: string | null; + columnGap: any; + columnRule: string | null; + columnRuleColor: any; + columnRuleStyle: string | null; + columnRuleWidth: any; + columns: string | null; + columnSpan: string | null; + columnWidth: any; + content: string | null; + counterIncrement: string | null; + counterReset: string | null; + cssFloat: string | null; + cssText: string; + cursor: string | null; + direction: string | null; + display: string | null; + dominantBaseline: string | null; + emptyCells: string | null; + enableBackground: string | null; + fill: string | null; + fillOpacity: string | null; + fillRule: string | null; + filter: string | null; + flex: string | null; + flexBasis: string | null; + flexDirection: string | null; + flexFlow: string | null; + flexGrow: string | null; + flexShrink: string | null; + flexWrap: string | null; + floodColor: string | null; + floodOpacity: string | null; + font: string | null; + fontFamily: string | null; + fontFeatureSettings: string | null; + fontSize: string | null; + fontSizeAdjust: string | null; + fontStretch: string | null; + fontStyle: string | null; + fontVariant: string | null; + fontWeight: string | null; + glyphOrientationHorizontal: string | null; + glyphOrientationVertical: string | null; + height: string | null; + imeMode: string | null; + justifyContent: string | null; + kerning: string | null; + layoutGrid: string | null; + layoutGridChar: string | null; + layoutGridLine: string | null; + layoutGridMode: string | null; + layoutGridType: string | null; + left: string | null; + readonly length: number; + letterSpacing: string | null; + lightingColor: string | null; + lineBreak: string | null; + lineHeight: string | null; + listStyle: string | null; + listStyleImage: string | null; + listStylePosition: string | null; + listStyleType: string | null; + margin: string | null; + marginBottom: string | null; + marginLeft: string | null; + marginRight: string | null; + marginTop: string | null; + marker: string | null; + markerEnd: string | null; + markerMid: string | null; + markerStart: string | null; + mask: string | null; + maxHeight: string | null; + maxWidth: string | null; + minHeight: string | null; + minWidth: string | null; + msContentZoomChaining: string | null; + msContentZooming: string | null; + msContentZoomLimit: string | null; + msContentZoomLimitMax: any; + msContentZoomLimitMin: any; + msContentZoomSnap: string | null; + msContentZoomSnapPoints: string | null; + msContentZoomSnapType: string | null; + msFlowFrom: string | null; + msFlowInto: string | null; + msFontFeatureSettings: string | null; + msGridColumn: any; + msGridColumnAlign: string | null; + msGridColumns: string | null; + msGridColumnSpan: any; + msGridRow: any; + msGridRowAlign: string | null; + msGridRows: string | null; + msGridRowSpan: any; + msHighContrastAdjust: string | null; + msHyphenateLimitChars: string | null; + msHyphenateLimitLines: any; + msHyphenateLimitZone: any; + msHyphens: string | null; + msImeAlign: string | null; + msOverflowStyle: string | null; + msScrollChaining: string | null; + msScrollLimit: string | null; + msScrollLimitXMax: any; + msScrollLimitXMin: any; + msScrollLimitYMax: any; + msScrollLimitYMin: any; + msScrollRails: string | null; + msScrollSnapPointsX: string | null; + msScrollSnapPointsY: string | null; + msScrollSnapType: string | null; + msScrollSnapX: string | null; + msScrollSnapY: string | null; + msScrollTranslation: string | null; + msTextCombineHorizontal: string | null; + msTextSizeAdjust: any; + msTouchAction: string | null; + msTouchSelect: string | null; + msUserSelect: string | null; + msWrapFlow: string; + msWrapMargin: any; + msWrapThrough: string; + opacity: string | null; + order: string | null; + orphans: string | null; + outline: string | null; + outlineColor: string | null; + outlineOffset: string | null; + outlineStyle: string | null; + outlineWidth: string | null; + overflow: string | null; + overflowX: string | null; + overflowY: string | null; + padding: string | null; + paddingBottom: string | null; + paddingLeft: string | null; + paddingRight: string | null; + paddingTop: string | null; + pageBreakAfter: string | null; + pageBreakBefore: string | null; + pageBreakInside: string | null; + readonly parentRule: CSSRule; + perspective: string | null; + perspectiveOrigin: string | null; + pointerEvents: string | null; + position: string | null; + quotes: string | null; + right: string | null; + rotate: string | null; + rubyAlign: string | null; + rubyOverhang: string | null; + rubyPosition: string | null; + scale: string | null; + stopColor: string | null; + stopOpacity: string | null; + stroke: string | null; + strokeDasharray: string | null; + strokeDashoffset: string | null; + strokeLinecap: string | null; + strokeLinejoin: string | null; + strokeMiterlimit: string | null; + strokeOpacity: string | null; + strokeWidth: string | null; + tableLayout: string | null; + textAlign: string | null; + textAlignLast: string | null; + textAnchor: string | null; + textDecoration: string | null; + textIndent: string | null; + textJustify: string | null; + textKashida: string | null; + textKashidaSpace: string | null; + textOverflow: string | null; + textShadow: string | null; + textTransform: string | null; + textUnderlinePosition: string | null; + top: string | null; + touchAction: string | null; + transform: string | null; + transformOrigin: string | null; + transformStyle: string | null; + transition: string | null; + transitionDelay: string | null; + transitionDuration: string | null; + transitionProperty: string | null; + transitionTimingFunction: string | null; + translate: string | null; + unicodeBidi: string | null; + verticalAlign: string | null; + visibility: string | null; + webkitAlignContent: string | null; + webkitAlignItems: string | null; + webkitAlignSelf: string | null; + webkitAnimation: string | null; + webkitAnimationDelay: string | null; + webkitAnimationDirection: string | null; + webkitAnimationDuration: string | null; + webkitAnimationFillMode: string | null; + webkitAnimationIterationCount: string | null; + webkitAnimationName: string | null; + webkitAnimationPlayState: string | null; + webkitAnimationTimingFunction: string | null; + webkitAppearance: string | null; + webkitBackfaceVisibility: string | null; + webkitBackgroundClip: string | null; + webkitBackgroundOrigin: string | null; + webkitBackgroundSize: string | null; + webkitBorderBottomLeftRadius: string | null; + webkitBorderBottomRightRadius: string | null; + webkitBorderImage: string | null; + webkitBorderRadius: string | null; + webkitBorderTopLeftRadius: string | null; + webkitBorderTopRightRadius: string | null; + webkitBoxAlign: string | null; + webkitBoxDirection: string | null; + webkitBoxFlex: string | null; + webkitBoxOrdinalGroup: string | null; + webkitBoxOrient: string | null; + webkitBoxPack: string | null; + webkitBoxSizing: string | null; + webkitColumnBreakAfter: string | null; + webkitColumnBreakBefore: string | null; + webkitColumnBreakInside: string | null; + webkitColumnCount: any; + webkitColumnGap: any; + webkitColumnRule: string | null; + webkitColumnRuleColor: any; + webkitColumnRuleStyle: string | null; + webkitColumnRuleWidth: any; + webkitColumns: string | null; + webkitColumnSpan: string | null; + webkitColumnWidth: any; + webkitFilter: string | null; + webkitFlex: string | null; + webkitFlexBasis: string | null; + webkitFlexDirection: string | null; + webkitFlexFlow: string | null; + webkitFlexGrow: string | null; + webkitFlexShrink: string | null; + webkitFlexWrap: string | null; + webkitJustifyContent: string | null; + webkitOrder: string | null; + webkitPerspective: string | null; + webkitPerspectiveOrigin: string | null; + webkitTapHighlightColor: string | null; + webkitTextFillColor: string | null; + webkitTextSizeAdjust: any; + webkitTextStroke: string | null; + webkitTextStrokeColor: string | null; + webkitTextStrokeWidth: string | null; + webkitTransform: string | null; + webkitTransformOrigin: string | null; + webkitTransformStyle: string | null; + webkitTransition: string | null; + webkitTransitionDelay: string | null; + webkitTransitionDuration: string | null; + webkitTransitionProperty: string | null; + webkitTransitionTimingFunction: string | null; + webkitUserModify: string | null; + webkitUserSelect: string | null; + webkitWritingMode: string | null; + whiteSpace: string | null; + widows: string | null; + width: string | null; + wordBreak: string | null; + wordSpacing: string | null; + wordWrap: string | null; + writingMode: string | null; + zIndex: string | null; + zoom: string | null; + resize: string | null; + userSelect: string | null; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + item(index: number): string; + removeProperty(propertyName: string): string; + setProperty(propertyName: string, value: string | null, priority?: string): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +}; + +interface CSSStyleRule extends CSSRule { + readonly readOnly: boolean; + selectorText: string; + readonly style: CSSStyleDeclaration; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +}; + +interface CSSStyleSheet extends StyleSheet { + readonly cssRules: CSSRuleList; + cssText: string; + readonly id: string; + readonly imports: StyleSheetList; + readonly isAlternate: boolean; + readonly isPrefAlternate: boolean; + readonly ownerRule: CSSRule; + readonly owningElement: Element; + readonly pages: StyleSheetPageList; + readonly readOnly: boolean; + readonly rules: CSSRuleList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; + removeImport(lIndex: number): void; + removeRule(lIndex: number): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +}; + +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +}; + +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +}; + +interface DataCue extends TextTrackCue { + data: ArrayBuffer; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var DataCue: { + prototype: DataCue; + new(): DataCue; +}; + +interface DataTransfer { + dropEffect: string; + effectAllowed: string; + readonly files: FileList; + readonly items: DataTransferItemList; + readonly types: string[]; + clearData(format?: string): boolean; + getData(format: string): string; + setData(format: string, data: string): boolean; + setDragImage(image: Element, x: number, y: number): void; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +}; + +interface DataTransferItem { + readonly kind: string; + readonly type: string; + getAsFile(): File | null; + getAsString(_callback: FunctionStringCallback | null): void; + webkitGetAsEntry(): any; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +}; + +interface DataTransferItemList { + readonly length: number; + add(data: File): DataTransferItem | null; + clear(): void; + item(index: number): DataTransferItem; + remove(index: number): void; + [index: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +}; + +interface DeferredPermissionRequest { + readonly id: number; + readonly type: MSWebViewPermissionType; + readonly uri: string; + allow(): void; + deny(): void; +} + +declare var DeferredPermissionRequest: { + prototype: DeferredPermissionRequest; + new(): DeferredPermissionRequest; +}; + +interface DelayNode extends AudioNode { + readonly delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(): DelayNode; +}; + +interface DeviceAcceleration { + readonly x: number | null; + readonly y: number | null; + readonly z: number | null; +} + +declare var DeviceAcceleration: { + prototype: DeviceAcceleration; + new(): DeviceAcceleration; +}; + +interface DeviceLightEvent extends Event { + readonly value: number; +} + +declare var DeviceLightEvent: { + prototype: DeviceLightEvent; + new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; +}; + +interface DeviceMotionEvent extends Event { + readonly acceleration: DeviceAcceleration | null; + readonly accelerationIncludingGravity: DeviceAcceleration | null; + readonly interval: number | null; + readonly rotationRate: DeviceRotationRate | null; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; +}; + +interface DeviceOrientationEvent extends Event { + readonly absolute: boolean; + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; +}; + +interface DeviceRotationRate { + readonly alpha: number | null; + readonly beta: number | null; + readonly gamma: number | null; +} + +declare var DeviceRotationRate: { + prototype: DeviceRotationRate; + new(): DeviceRotationRate; +}; + +interface DocumentEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforedeactivate": UIEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "fullscreenchange": Event; + "fullscreenerror": Event; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "mssitemodejumplistitemremoved": MSSiteModeEvent; + "msthumbnailclick": MSSiteModeEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointerlockchange": Event; + "pointerlockerror": Event; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": Event; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectionchange": Event; + "selectstart": Event; + "stalled": Event; + "stop": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "volumechange": Event; + "waiting": Event; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { + /** + * Gets the object that has the focus when the parent document has focus. + */ + readonly activeElement: Element; + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + */ + readonly all: HTMLAllCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollectionOf; + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollectionOf; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + readonly characterSet: string; + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + readonly compatMode: string; + cookie: string; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; + readonly defaultView: Window; + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + /** + * Sets or retrieves a value that indicates the reading order of the object. + */ + dir: string; + /** + * Gets an object representing the document type declaration associated with the current document. + */ + readonly doctype: DocumentType; + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + /** + * Sets or gets the security domain of the document. + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollectionOf; + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollectionOf; + readonly fullscreenElement: Element | null; + readonly fullscreenEnabled: boolean; + readonly head: HTMLHeadElement; + readonly hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollectionOf; + /** + * Gets the implementation object of the current document. + */ + readonly implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + readonly inputEncoding: string | null; + /** + * Gets the date that the page was last modified, if the page supplies one. + */ + readonly lastModified: string; + /** + * Sets or gets the color of the document links. + */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollectionOf; + /** + * Contains information about the current URL. + */ + readonly location: Location; + msCapsLockWarningOff: boolean; + msCSSOMElementFloatMetrics: boolean; + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (this: Document, ev: FocusEvent) => any; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (this: Document, ev: Event) => any; + oncanplaythrough: (this: Document, ev: Event) => any; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (this: Document, ev: PointerEvent) => any; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (this: Document, ev: UIEvent) => any; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (this: Document, ev: DragEvent) => any; + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ + ondragenter: (this: Document, ev: DragEvent) => any; + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ + ondragleave: (this: Document, ev: DragEvent) => any; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (this: Document, ev: DragEvent) => any; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (this: Document, ev: DragEvent) => any; + ondrop: (this: Document, ev: DragEvent) => any; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (this: Document, ev: Event) => any; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (this: Document, ev: Event) => any; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (this: Document, ev: MediaStreamErrorEvent) => any; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (this: Document, ev: ErrorEvent) => any; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (this: Document, ev: FocusEvent) => any; + onfullscreenchange: (this: Document, ev: Event) => any; + onfullscreenerror: (this: Document, ev: Event) => any; + oninput: (this: Document, ev: Event) => any; + oninvalid: (this: Document, ev: Event) => any; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (this: Document, ev: KeyboardEvent) => any; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (this: Document, ev: Event) => any; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (this: Document, ev: Event) => any; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (this: Document, ev: Event) => any; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (this: Document, ev: MouseEvent) => any; + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (this: Document, ev: WheelEvent) => any; + onmscontentzoom: (this: Document, ev: UIEvent) => any; + onmsgesturechange: (this: Document, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Document, ev: MSGestureEvent) => any; + onmsgestureend: (this: Document, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Document, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Document, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Document, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Document, ev: MSGestureEvent) => any; + onmsmanipulationstatechanged: (this: Document, ev: MSManipulationEvent) => any; + onmspointercancel: (this: Document, ev: MSPointerEvent) => any; + onmspointerdown: (this: Document, ev: MSPointerEvent) => any; + onmspointerenter: (this: Document, ev: MSPointerEvent) => any; + onmspointerleave: (this: Document, ev: MSPointerEvent) => any; + onmspointermove: (this: Document, ev: MSPointerEvent) => any; + onmspointerout: (this: Document, ev: MSPointerEvent) => any; + onmspointerover: (this: Document, ev: MSPointerEvent) => any; + onmspointerup: (this: Document, ev: MSPointerEvent) => any; + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (this: Document, ev: MSSiteModeEvent) => any; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (this: Document, ev: Event) => any; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (this: Document, ev: Event) => any; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (this: Document, ev: Event) => any; + onpointerlockchange: (this: Document, ev: Event) => any; + onpointerlockerror: (this: Document, ev: Event) => any; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (this: Document, ev: ProgressEvent) => any; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (this: Document, ev: Event) => any; + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (this: Document, ev: Event) => any; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (this: Document, ev: Event) => any; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (this: Document, ev: UIEvent) => any; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (this: Document, ev: Event) => any; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (this: Document, ev: Event) => any; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (this: Document, ev: UIEvent) => any; + /** + * Fires when the selection state of a document changes. + * @param ev The event. + */ + onselectionchange: (this: Document, ev: Event) => any; + onselectstart: (this: Document, ev: Event) => any; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (this: Document, ev: Event) => any; + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (this: Document, ev: Event) => any; + onsubmit: (this: Document, ev: Event) => any; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (this: Document, ev: Event) => any; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (this: Document, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (this: Document, ev: Event) => any; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (this: Document, ev: Event) => any; + onwebkitfullscreenchange: (this: Document, ev: Event) => any; + onwebkitfullscreenerror: (this: Document, ev: Event) => any; + plugins: HTMLCollectionOf; + readonly pointerLockElement: Element; + /** + * Retrieves a value that indicates the current state of the object. + */ + readonly readyState: string; + /** + * Gets the URL of the location that referred the user to the current page. + */ + readonly referrer: string; + /** + * Gets the root svg element in the document hierarchy. + */ + readonly rootElement: SVGSVGElement; + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollectionOf; + readonly scrollingElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + readonly styleSheets: StyleSheetList; + /** + * Contains the title of the document. + */ + title: string; + /** + * Sets or gets the URL for the current document. + */ + readonly URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + readonly URLUnencoded: string; + readonly visibilityState: VisibilityState; + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + readonly webkitCurrentFullScreenElement: Element | null; + readonly webkitFullscreenElement: Element | null; + readonly webkitFullscreenEnabled: boolean; + readonly webkitIsFullScreen: boolean; + readonly xmlEncoding: string | null; + xmlStandalone: boolean; + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string | null; + adoptNode(source: T): T; + captureEvents(): void; + caretRangeFromPoint(x: number, y: number): Range; + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: K): HTMLElementTagNameMap[K]; + createElement(tagName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; + createElementNS(namespaceURI: string | null, qualifiedName: string): Element; + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + /** + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNSResolver(nodeResolver: Node): XPathNSResolver; + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + /** + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouchList(...touches: Touch[]): TouchList; + /** + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + exitFullscreen(): void; + exitPointerLock(): void; + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + /** + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ + getElementById(elementId: string): HTMLElement | null; + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + importNode(importedNode: T, deep: boolean): T; + msElementsFromPoint(x: number, y: number): NodeListOf; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ + open(url?: string, name?: string, features?: string, replace?: boolean): Document; + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + queryCommandSupported(commandId: string): boolean; + /** + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ + queryCommandText(commandId: string): string; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + releaseEvents(): void; + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + webkitCancelFullScreen(): void; + webkitExitFullscreen(): void; + /** + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ + write(...content: string[]): void; + /** + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Document: { + prototype: Document; + new(): Document; +}; + +interface DocumentFragment extends Node, NodeSelector, ParentNode { + getElementById(elementId: string): HTMLElement | null; +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +}; + +interface DocumentType extends Node, ChildNode { + readonly entities: NamedNodeMap; + readonly internalSubset: string | null; + readonly name: string; + readonly notations: NamedNodeMap; + readonly publicId: string; + readonly systemId: string; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +}; + +interface DOMError { + readonly name: string; + toString(): string; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +}; + +interface DOMException { + readonly code: number; + readonly message: string; + readonly name: string; + toString(): string; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(message?: string, name?: string): DOMException; + readonly ABORT_ERR: number; + readonly DATA_CLONE_ERR: number; + readonly DOMSTRING_SIZE_ERR: number; + readonly HIERARCHY_REQUEST_ERR: number; + readonly INDEX_SIZE_ERR: number; + readonly INUSE_ATTRIBUTE_ERR: number; + readonly INVALID_ACCESS_ERR: number; + readonly INVALID_CHARACTER_ERR: number; + readonly INVALID_MODIFICATION_ERR: number; + readonly INVALID_NODE_TYPE_ERR: number; + readonly INVALID_STATE_ERR: number; + readonly NAMESPACE_ERR: number; + readonly NETWORK_ERR: number; + readonly NO_DATA_ALLOWED_ERR: number; + readonly NO_MODIFICATION_ALLOWED_ERR: number; + readonly NOT_FOUND_ERR: number; + readonly NOT_SUPPORTED_ERR: number; + readonly PARSE_ERR: number; + readonly QUOTA_EXCEEDED_ERR: number; + readonly SECURITY_ERR: number; + readonly SERIALIZE_ERR: number; + readonly SYNTAX_ERR: number; + readonly TIMEOUT_ERR: number; + readonly TYPE_MISMATCH_ERR: number; + readonly URL_MISMATCH_ERR: number; + readonly VALIDATION_ERR: number; + readonly WRONG_DOCUMENT_ERR: number; +}; + +interface DOMImplementation { + createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string | null, version: string | null): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +}; + +interface DOMStringList { + readonly length: number; + contains(str: string): boolean; + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +interface DOMTokenList { + readonly length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toggle(token: string, force?: boolean): boolean; + toString(): string; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + +interface DragEvent extends MouseEvent { + readonly dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +declare var DragEvent: { + prototype: DragEvent; + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; + +interface DynamicsCompressorNode extends AudioNode { + readonly attack: AudioParam; + readonly knee: AudioParam; + readonly ratio: AudioParam; + readonly reduction: number; + readonly release: AudioParam; + readonly threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(): DynamicsCompressorNode; +}; + +interface ElementEventMap extends GlobalEventHandlersEventMap { + "ariarequest": Event; + "command": Event; + "gotpointercapture": PointerEvent; + "lostpointercapture": PointerEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSGotPointerCapture": MSPointerEvent; + "MSInertiaStart": MSGestureEvent; + "MSLostPointerCapture": MSPointerEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "webkitfullscreenchange": Event; + "webkitfullscreenerror": Event; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode, ParentNode { + readonly classList: DOMTokenList; + className: string; + readonly clientHeight: number; + readonly clientLeft: number; + readonly clientTop: number; + readonly clientWidth: number; + id: string; + innerHTML: string; + msContentZoomFactor: number; + readonly msRegionOverflow: string; + onariarequest: (this: Element, ev: Event) => any; + oncommand: (this: Element, ev: Event) => any; + ongotpointercapture: (this: Element, ev: PointerEvent) => any; + onlostpointercapture: (this: Element, ev: PointerEvent) => any; + onmsgesturechange: (this: Element, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Element, ev: MSGestureEvent) => any; + onmsgestureend: (this: Element, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Element, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Element, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Element, ev: MSGestureEvent) => any; + onmsgotpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmsinertiastart: (this: Element, ev: MSGestureEvent) => any; + onmslostpointercapture: (this: Element, ev: MSPointerEvent) => any; + onmspointercancel: (this: Element, ev: MSPointerEvent) => any; + onmspointerdown: (this: Element, ev: MSPointerEvent) => any; + onmspointerenter: (this: Element, ev: MSPointerEvent) => any; + onmspointerleave: (this: Element, ev: MSPointerEvent) => any; + onmspointermove: (this: Element, ev: MSPointerEvent) => any; + onmspointerout: (this: Element, ev: MSPointerEvent) => any; + onmspointerover: (this: Element, ev: MSPointerEvent) => any; + onmspointerup: (this: Element, ev: MSPointerEvent) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onwebkitfullscreenchange: (this: Element, ev: Event) => any; + onwebkitfullscreenerror: (this: Element, ev: Event) => any; + outerHTML: string; + readonly prefix: string | null; + readonly scrollHeight: number; + scrollLeft: number; + scrollTop: number; + readonly scrollWidth: number; + readonly tagName: string; + readonly assignedSlot: HTMLSlotElement | null; + slot: string; + readonly shadowRoot: ShadowRoot | null; + getAttribute(name: string): string | null; + getAttributeNode(name: string): Attr; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNS(namespaceURI: string, localName: string): string; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; + hasAttribute(name: string): boolean; + hasAttributeNS(namespaceURI: string, localName: string): boolean; + msGetRegionContent(): MSRangeCollection; + msGetUntransformedBounds(): ClientRect; + msMatchesSelector(selectors: string): boolean; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; + msZoomTo(args: MsZoomToOptions): void; + releasePointerCapture(pointerId: number): void; + removeAttribute(qualifiedName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + removeAttributeNS(namespaceURI: string, localName: string): void; + requestFullscreen(): void; + requestPointerLock(): void; + setAttribute(name: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullscreen(): void; + webkitRequestFullScreen(): void; + getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: string): Element | null; + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; + insertAdjacentHTML(where: InsertPosition, html: string): void; + insertAdjacentText(where: InsertPosition, text: string): void; + attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +}; + +interface ErrorEvent extends Event { + readonly colno: number; + readonly error: any; + readonly filename: string; + readonly lineno: number; + readonly message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent; +}; + +interface Event { + readonly bubbles: boolean; + readonly cancelable: boolean; + cancelBubble: boolean; + readonly currentTarget: EventTarget; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + readonly isTrusted: boolean; + returnValue: boolean; + readonly srcElement: Element | null; + readonly target: EventTarget; + readonly timeStamp: number; + readonly type: string; + readonly scoped: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + deepPath(): EventTarget[]; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +} + +declare var Event: { + prototype: Event; + new(typeArg: string, eventInitDict?: EventInit): Event; + readonly AT_TARGET: number; + readonly BUBBLING_PHASE: number; + readonly CAPTURING_PHASE: number; +}; + +interface EventTarget { + addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + +interface EXT_frag_depth { +} + +declare var EXT_frag_depth: { + prototype: EXT_frag_depth; + new(): EXT_frag_depth; +}; + +interface EXT_texture_filter_anisotropic { + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + +interface ExtensionScriptApis { + extensionIdToShortId(extensionId: string): number; + fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean): void; + genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void; + genericSynchronousFunction(functionId: number, parameters?: string): string; + getExtensionId(): string; + registerGenericFunctionCallbackHandler(callbackHandler: any): void; + registerGenericPersistentCallbackHandler(callbackHandler: any): void; +} + +declare var ExtensionScriptApis: { + prototype: ExtensionScriptApis; + new(): ExtensionScriptApis; +}; + +interface External { +} + +declare var External: { + prototype: External; + new(): External; +}; + +interface File extends Blob { + readonly lastModifiedDate: any; + readonly name: string; + readonly webkitRelativePath: string; +} + +declare var File: { + prototype: File; + new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; +}; + +interface FileList { + readonly length: number; + item(index: number): File; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +}; + +interface FileReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; +}; + +interface FocusEvent extends UIEvent { + readonly relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; +}; + +interface FocusNavigationEvent extends Event { + readonly navigationReason: NavigationReason; + readonly originHeight: number; + readonly originLeft: number; + readonly originTop: number; + readonly originWidth: number; + requestFocus(): void; +} + +declare var FocusNavigationEvent: { + prototype: FocusNavigationEvent; + new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent; +}; + +interface FormData { + append(name: string, value: string | Blob, fileName?: string): void; + delete(name: string): void; + get(name: string): FormDataEntryValue | null; + getAll(name: string): FormDataEntryValue[]; + has(name: string): boolean; + set(name: string, value: string | Blob, fileName?: string): void; +} + +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +}; + +interface GainNode extends AudioNode { + readonly gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(): GainNode; +}; + +interface Gamepad { + readonly axes: number[]; + readonly buttons: GamepadButton[]; + readonly connected: boolean; + readonly id: string; + readonly index: number; + readonly mapping: string; + readonly timestamp: number; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +}; + +interface GamepadButton { + readonly pressed: boolean; + readonly value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +}; + +interface GamepadEvent extends Event { + readonly gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; +}; + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} + +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +}; + +interface HashChangeEvent extends Event { + readonly newURL: string | null; + readonly oldURL: string | null; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(typeArg: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +}; + +interface Headers { + append(name: string, value: string): void; + delete(name: string): void; + forEach(callback: ForEachCallback): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; +} + +declare var Headers: { + prototype: Headers; + new(init?: HeadersInit): Headers; +}; + +interface History { + readonly length: number; + readonly state: any; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; +} + +declare var History: { + prototype: History; + new(): History; +}; + +interface HTMLAllCollection { + readonly length: number; + item(nameOrIndex?: string): HTMLCollection | Element | null; + namedItem(name: string): HTMLCollection | Element | null; + [index: number]: Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +}; + +interface HTMLAnchorElement extends HTMLElement { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + Methods: string; + readonly mimeType: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + readonly nameProp: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + readonly protocolLong: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + type: string; + urn: string; + /** + * Returns a string representation of an object. + */ + toString(): string; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +}; + +interface HTMLAppletElement extends HTMLElement { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + object: string | null; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + vspace: number; + width: number; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +}; + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + download: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + rel: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns a string representation of an object. + */ + toString(): string; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +}; + +interface HTMLAreasCollection extends HTMLCollectionBase { +} + +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +}; + +interface HTMLAudioElement extends HTMLMediaElement { + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +}; + +interface HTMLBaseElement extends HTMLElement { + /** + * Gets or sets the baseline URL on which relative links are based. + */ + href: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +}; + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +}; + +interface HTMLBodyElementEventMap extends HTMLElementEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "resize": UIEvent; + "scroll": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLBodyElement extends HTMLElement { + aLink: any; + background: string; + bgColor: any; + bgProperties: string; + link: any; + noWrap: boolean; + onafterprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; + onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; + onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; + onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; + onoffline: (this: HTMLBodyElement, ev: Event) => any; + ononline: (this: HTMLBodyElement, ev: Event) => any; + onorientationchange: (this: HTMLBodyElement, ev: Event) => any; + onpagehide: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; + onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; + onresize: (this: HTMLBodyElement, ev: UIEvent) => any; + onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; + onunload: (this: HTMLBodyElement, ev: Event) => any; + text: any; + vLink: any; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +}; + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +}; + +interface HTMLButtonElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + status: any; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the default or selected value of the control. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +}; + +interface HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; + /** + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ + msToBlob(): Blob; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ + toDataURL(type?: string, ...args: any[]): string; + toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +}; + +interface HTMLCollectionBase { + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Retrieves an object from various collections. + */ + item(index: number): Element; + [index: number]: Element; +} + +interface HTMLCollection extends HTMLCollectionBase { + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element | null; +} + +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +}; + +interface HTMLDataElement extends HTMLElement { + value: string; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDataElement: { + prototype: HTMLDataElement; + new(): HTMLDataElement; +}; + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollectionOf; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +}; + +interface HTMLDirectoryElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +}; + +interface HTMLDivElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +}; + +interface HTMLDListElement extends HTMLElement { + compact: boolean; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +}; + +interface HTMLDocument extends Document { + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLDocument: { + prototype: HTMLDocument; + new(): HTMLDocument; +}; + +interface HTMLElementEventMap extends ElementEventMap { + "abort": UIEvent; + "activate": UIEvent; + "beforeactivate": UIEvent; + "beforecopy": ClipboardEvent; + "beforecut": ClipboardEvent; + "beforedeactivate": UIEvent; + "beforepaste": ClipboardEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "contextmenu": PointerEvent; + "copy": ClipboardEvent; + "cuechange": Event; + "cut": ClipboardEvent; + "dblclick": MouseEvent; + "deactivate": UIEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSContentZoom": UIEvent; + "MSManipulationStateChanged": MSManipulationEvent; + "paste": ClipboardEvent; + "pause": Event; + "play": Event; + "playing": Event; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "selectstart": Event; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "volumechange": Event; + "waiting": Event; +} + +interface HTMLElement extends Element { + accessKey: string; + readonly children: HTMLCollection; + contentEditable: string; + readonly dataset: DOMStringMap; + dir: string; + draggable: boolean; + hidden: boolean; + hideFocus: boolean; + innerText: string; + readonly isContentEditable: boolean; + lang: string; + readonly offsetHeight: number; + readonly offsetLeft: number; + readonly offsetParent: Element; + readonly offsetTop: number; + readonly offsetWidth: number; + onabort: (this: HTMLElement, ev: UIEvent) => any; + onactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforecopy: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforecut: (this: HTMLElement, ev: ClipboardEvent) => any; + onbeforedeactivate: (this: HTMLElement, ev: UIEvent) => any; + onbeforepaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onblur: (this: HTMLElement, ev: FocusEvent) => any; + oncanplay: (this: HTMLElement, ev: Event) => any; + oncanplaythrough: (this: HTMLElement, ev: Event) => any; + onchange: (this: HTMLElement, ev: Event) => any; + onclick: (this: HTMLElement, ev: MouseEvent) => any; + oncontextmenu: (this: HTMLElement, ev: PointerEvent) => any; + oncopy: (this: HTMLElement, ev: ClipboardEvent) => any; + oncuechange: (this: HTMLElement, ev: Event) => any; + oncut: (this: HTMLElement, ev: ClipboardEvent) => any; + ondblclick: (this: HTMLElement, ev: MouseEvent) => any; + ondeactivate: (this: HTMLElement, ev: UIEvent) => any; + ondrag: (this: HTMLElement, ev: DragEvent) => any; + ondragend: (this: HTMLElement, ev: DragEvent) => any; + ondragenter: (this: HTMLElement, ev: DragEvent) => any; + ondragleave: (this: HTMLElement, ev: DragEvent) => any; + ondragover: (this: HTMLElement, ev: DragEvent) => any; + ondragstart: (this: HTMLElement, ev: DragEvent) => any; + ondrop: (this: HTMLElement, ev: DragEvent) => any; + ondurationchange: (this: HTMLElement, ev: Event) => any; + onemptied: (this: HTMLElement, ev: Event) => any; + onended: (this: HTMLElement, ev: MediaStreamErrorEvent) => any; + onerror: (this: HTMLElement, ev: ErrorEvent) => any; + onfocus: (this: HTMLElement, ev: FocusEvent) => any; + oninput: (this: HTMLElement, ev: Event) => any; + oninvalid: (this: HTMLElement, ev: Event) => any; + onkeydown: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeypress: (this: HTMLElement, ev: KeyboardEvent) => any; + onkeyup: (this: HTMLElement, ev: KeyboardEvent) => any; + onload: (this: HTMLElement, ev: Event) => any; + onloadeddata: (this: HTMLElement, ev: Event) => any; + onloadedmetadata: (this: HTMLElement, ev: Event) => any; + onloadstart: (this: HTMLElement, ev: Event) => any; + onmousedown: (this: HTMLElement, ev: MouseEvent) => any; + onmouseenter: (this: HTMLElement, ev: MouseEvent) => any; + onmouseleave: (this: HTMLElement, ev: MouseEvent) => any; + onmousemove: (this: HTMLElement, ev: MouseEvent) => any; + onmouseout: (this: HTMLElement, ev: MouseEvent) => any; + onmouseover: (this: HTMLElement, ev: MouseEvent) => any; + onmouseup: (this: HTMLElement, ev: MouseEvent) => any; + onmousewheel: (this: HTMLElement, ev: WheelEvent) => any; + onmscontentzoom: (this: HTMLElement, ev: UIEvent) => any; + onmsmanipulationstatechanged: (this: HTMLElement, ev: MSManipulationEvent) => any; + onpaste: (this: HTMLElement, ev: ClipboardEvent) => any; + onpause: (this: HTMLElement, ev: Event) => any; + onplay: (this: HTMLElement, ev: Event) => any; + onplaying: (this: HTMLElement, ev: Event) => any; + onprogress: (this: HTMLElement, ev: ProgressEvent) => any; + onratechange: (this: HTMLElement, ev: Event) => any; + onreset: (this: HTMLElement, ev: Event) => any; + onscroll: (this: HTMLElement, ev: UIEvent) => any; + onseeked: (this: HTMLElement, ev: Event) => any; + onseeking: (this: HTMLElement, ev: Event) => any; + onselect: (this: HTMLElement, ev: UIEvent) => any; + onselectstart: (this: HTMLElement, ev: Event) => any; + onstalled: (this: HTMLElement, ev: Event) => any; + onsubmit: (this: HTMLElement, ev: Event) => any; + onsuspend: (this: HTMLElement, ev: Event) => any; + ontimeupdate: (this: HTMLElement, ev: Event) => any; + onvolumechange: (this: HTMLElement, ev: Event) => any; + onwaiting: (this: HTMLElement, ev: Event) => any; + outerText: string; + spellcheck: boolean; + readonly style: CSSStyleDeclaration; + tabIndex: number; + title: string; + blur(): void; + click(): void; + dragDrop(): boolean; + focus(): void; + msGetInputContext(): MSInputMethodContext; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +}; + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the height of the object. + */ + height: string; + hidden: any; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the palette used for the embedded document. + */ + readonly palette: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + readonly pluginspage: string; + readonly readyState: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +}; + +interface HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + name: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +}; + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +}; + +interface HTMLFormControlsCollection extends HTMLCollectionBase { + namedItem(name: string): HTMLCollection | Element | null; +} + +declare var HTMLFormControlsCollection: { + prototype: HTMLFormControlsCollection; + new(): HTMLFormControlsCollection; +}; + +interface HTMLFormElement extends HTMLElement { + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + readonly elements: HTMLFormControlsCollection; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Sets or retrieves the number of objects in a collection. + */ + readonly length: number; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(name: string): any; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [name: string]: any; +} + +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +}; + +interface HTMLFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument { + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string | number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the width of the object. + */ + width: string | number; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +}; + +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "load": Event; + "message": MessageEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "popstate": PopStateEvent; + "resize": UIEvent; + "scroll": UIEvent; + "storage": StorageEvent; + "unload": Event; +} + +interface HTMLFrameSetElement extends HTMLElement { + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + name: string; + onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; + onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; + onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; + onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; + onoffline: (this: HTMLFrameSetElement, ev: Event) => any; + ononline: (this: HTMLFrameSetElement, ev: Event) => any; + onorientationchange: (this: HTMLFrameSetElement, ev: Event) => any; + onpagehide: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; + onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; + onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; + onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; + onunload: (this: HTMLFrameSetElement, ev: Event) => any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +}; + +interface HTMLHeadElement extends HTMLElement { + profile: string; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +}; + +interface HTMLHeadingElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +}; + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +}; + +interface HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +}; + +interface HTMLIFrameElementEventMap extends HTMLElementEventMap { + "load": Event; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + allowFullscreen: boolean; + allowPaymentRequest: boolean; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + readonly contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + readonly sandbox: DOMSettableTokenList; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +}; + +interface HTMLImageElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + crossOrigin: string | null; + readonly currentSrc: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + lowsrc: string; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * The original height of the image resource before sizing. + */ + readonly naturalHeight: number; + /** + * The original width of the image resource before sizing. + */ + readonly naturalWidth: number; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + readonly x: number; + readonly y: number; + msGetAsCastingSource(): any; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; +}; + +interface HTMLInputElement extends HTMLElement { + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + readonly complete: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Returns a FileList object on a file type input object. + */ + readonly files: FileList | null; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + indeterminate: boolean; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + readonly list: HTMLElement; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + selectionDirection: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + size: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + status: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + valueAsDate: Date; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + webkitdirectory: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Makes the selection equal to the current object. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start?: number, end?: number, direction?: string): void; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +}; + +interface HTMLLabelElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +}; + +interface HTMLLegendElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +}; + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +}; + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + disabled: boolean; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + import?: Document; + integrity: string; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +}; + +interface HTMLMapElement extends HTMLElement { + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + readonly areas: HTMLAreasCollection; + /** + * Sets or retrieves the name of the object. + */ + name: string; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +}; + +interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { + "bounce": Event; + "finish": Event; + "start": Event; +} + +interface HTMLMarqueeElement extends HTMLElement { + behavior: string; + bgColor: any; + direction: string; + height: string; + hspace: number; + loop: number; + onbounce: (this: HTMLMarqueeElement, ev: Event) => any; + onfinish: (this: HTMLMarqueeElement, ev: Event) => any; + onstart: (this: HTMLMarqueeElement, ev: Event) => any; + scrollAmount: number; + scrollDelay: number; + trueSpeed: boolean; + vspace: number; + width: string; + start(): void; + stop(): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +}; + +interface HTMLMediaElementEventMap extends HTMLElementEventMap { + "encrypted": MediaEncryptedEvent; + "msneedkey": MSMediaKeyNeededEvent; +} + +interface HTMLMediaElement extends HTMLElement { + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + readonly audioTracks: AudioTrackList; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets a collection of buffered time ranges. + */ + readonly buffered: TimeRanges; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + crossOrigin: string | null; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + readonly currentSrc: string; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + defaultMuted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + readonly duration: number; + /** + * Gets information about whether the playback has ended or not. + */ + readonly ended: boolean; + /** + * Returns an object representing the current error state of the audio or video element. + */ + readonly error: MediaError; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + readonly mediaKeys: MediaKeys | null; + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + readonly msGraphicsTrustStatus: MSGraphicsTrust; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + readonly msKeys: MSMediaKeys; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets the current network activity for the element. + */ + readonly networkState: number; + onencrypted: (this: HTMLMediaElement, ev: MediaEncryptedEvent) => any; + onmsneedkey: (this: HTMLMediaElement, ev: MSMediaKeyNeededEvent) => any; + /** + * Gets a flag that specifies whether playback is paused. + */ + readonly paused: boolean; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + readonly played: TimeRanges; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + readyState: number; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + readonly seekable: TimeRanges; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + readonly seeking: boolean; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcObject: MediaStream | null; + readonly textTracks: TextTrackList; + readonly videoTracks: VideoTrackList; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + canPlayType(type: string): string; + /** + * Resets the audio or video object and loads a new media resource. + */ + load(): void; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + msGetAsCastingSource(): any; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): Promise; + setMediaKeys(mediaKeys: MediaKeys | null): Promise; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + readonly HAVE_CURRENT_DATA: number; + readonly HAVE_ENOUGH_DATA: number; + readonly HAVE_FUTURE_DATA: number; + readonly HAVE_METADATA: number; + readonly HAVE_NOTHING: number; + readonly NETWORK_EMPTY: number; + readonly NETWORK_IDLE: number; + readonly NETWORK_LOADING: number; + readonly NETWORK_NO_SOURCE: number; +}; + +interface HTMLMenuElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +}; + +interface HTMLMetaElement extends HTMLElement { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +}; + +interface HTMLMeterElement extends HTMLElement { + high: number; + low: number; + max: number; + min: number; + optimum: number; + value: number; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLMeterElement: { + prototype: HTMLMeterElement; + new(): HTMLMeterElement; +}; + +interface HTMLModElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +}; + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + readonly BaseHref: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + readonly contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + readonly msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +}; + +interface HTMLOListElement extends HTMLElement { + compact: boolean; + /** + * The starting number. + */ + start: number; + type: string; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +}; + +interface HTMLOptGroupElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + readonly text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +}; + +interface HTMLOptionElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + readonly index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; +}; + +interface HTMLOptionsCollection extends HTMLCollectionOf { + length: number; + selectedIndex: number; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + remove(index: number): void; +} + +declare var HTMLOptionsCollection: { + prototype: HTMLOptionsCollection; + new(): HTMLOptionsCollection; +}; + +interface HTMLOutputElement extends HTMLElement { + defaultValue: string; + readonly form: HTMLFormElement | null; + readonly htmlFor: DOMSettableTokenList; + name: string; + readonly type: string; + readonly validationMessage: string; + readonly validity: ValidityState; + value: string; + readonly willValidate: boolean; + checkValidity(): boolean; + reportValidity(): boolean; + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLOutputElement: { + prototype: HTMLOutputElement; + new(): HTMLOutputElement; +}; + +interface HTMLParagraphElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + clear: string; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +}; + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +}; + +interface HTMLPictureElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +}; + +interface HTMLPreElement extends HTMLElement { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +}; + +interface HTMLProgressElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + readonly position: number; + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +}; + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +}; + +interface HTMLScriptElement extends HTMLElement { + async: boolean; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + crossOrigin: string | null; + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * Sets or retrieves the event for which the script is written. + */ + event: string; + /** + * Sets or retrieves the object that is bound to the event script. + */ + htmlFor: string; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + integrity: string; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +}; + +interface HTMLSelectElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + readonly options: HTMLOptionsCollection; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + selectedOptions: HTMLCollectionOf; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [name: string]: any; +} + +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +}; + +interface HTMLSourceElement extends HTMLElement { + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + msKeySystem: string; + sizes: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Gets or sets the MIME type of a media resource. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +}; + +interface HTMLSpanElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +}; + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + disabled: boolean; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +}; + +interface HTMLTableCaptionElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +}; + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + bgColor: any; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + readonly cellIndex: number; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +}; + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; + /** + * Sets or retrieves the width of the object. + */ + width: any; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +}; + +interface HTMLTableDataCellElement extends HTMLTableCellElement { + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +}; + +interface HTMLTableElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + bgColor: any; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollectionOf; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLTableCaptionElement; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLTableSectionElement; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLTableSectionElement; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLTableSectionElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +}; + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +}; + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + bgColor: any; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollectionOf; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the position of the object in the rows collection for the table. + */ + readonly rowIndex: number; + /** + * Retrieves the position of the object in the collection. + */ + readonly sectionRowIndex: number; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLTableDataCellElement; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +}; + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollectionOf; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +}; + +interface HTMLTemplateElement extends HTMLElement { + readonly content: DocumentFragment; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +}; + +interface HTMLTextAreaElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + readonly form: HTMLFormElement | null; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves the type of control. + */ + readonly type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + readonly validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + readonly validity: ValidityState; + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + readonly willValidate: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + minLength: number; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Highlights the input area of a form element. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +}; + +interface HTMLTimeElement extends HTMLElement { + dateTime: string; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTimeElement: { + prototype: HTMLTimeElement; + new(): HTMLTimeElement; +}; + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +}; + +interface HTMLTrackElement extends HTMLElement { + default: boolean; + kind: string; + label: string; + readonly readyState: number; + src: string; + srclang: string; + readonly track: TextTrack; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; + readonly ERROR: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; +}; + +interface HTMLUListElement extends HTMLElement { + compact: boolean; + type: string; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +}; + +interface HTMLUnknownElement extends HTMLElement { + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +}; + +interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { + "MSVideoFormatChanged": Event; + "MSVideoFrameStepCompleted": Event; + "MSVideoOptimalLayoutChanged": Event; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the height of the video element. + */ + height: number; + msHorizontalMirror: boolean; + readonly msIsLayoutOptimalForPlayback: boolean; + readonly msIsStereo3D: boolean; + msStereo3DPackingMode: string; + msStereo3DRenderMode: string; + msZoom: boolean; + onMSVideoFormatChanged: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoFrameStepCompleted: (this: HTMLVideoElement, ev: Event) => any; + onMSVideoOptimalLayoutChanged: (this: HTMLVideoElement, ev: Event) => any; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoHeight: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + readonly videoWidth: number; + readonly webkitDisplayingFullscreen: boolean; + readonly webkitSupportsFullscreen: boolean; + /** + * Gets or sets the width of the video element. + */ + width: number; + getVideoPlaybackQuality(): VideoPlaybackQuality; + msFrameStep(forward: boolean): void; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + webkitEnterFullscreen(): void; + webkitEnterFullScreen(): void; + webkitExitFullscreen(): void; + webkitExitFullScreen(): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +}; + +interface IDBCursor { + readonly direction: IDBCursorDirection; + key: IDBKeyRange | IDBValidKey; + readonly primaryKey: any; + source: IDBObjectStore | IDBIndex; + advance(count: number): void; + continue(key?: IDBKeyRange | IDBValidKey): void; + delete(): IDBRequest; + update(value: any): IDBRequest; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; + readonly NEXT: string; + readonly NEXT_NO_DUPLICATE: string; + readonly PREV: string; + readonly PREV_NO_DUPLICATE: string; +}; + +interface IDBCursorWithValue extends IDBCursor { + readonly value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +}; + +interface IDBDatabaseEventMap { + "abort": Event; + "error": Event; +} + +interface IDBDatabase extends EventTarget { + readonly name: string; + readonly objectStoreNames: DOMStringList; + onabort: (this: IDBDatabase, ev: Event) => any; + onerror: (this: IDBDatabase, ev: Event) => any; + version: number; + onversionchange: (ev: IDBVersionChangeEvent) => any; + close(): void; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + deleteObjectStore(name: string): void; + transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +}; + +interface IDBFactory { + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +}; + +interface IDBIndex { + keyPath: string | string[]; + readonly name: string; + readonly objectStore: IDBObjectStore; + readonly unique: boolean; + multiEntry: boolean; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + get(key: IDBKeyRange | IDBValidKey): IDBRequest; + getKey(key: IDBKeyRange | IDBValidKey): IDBRequest; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +}; + +interface IDBKeyRange { + readonly lower: any; + readonly lowerOpen: boolean; + readonly upper: any; + readonly upperOpen: boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + lowerBound(lower: any, open?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + upperBound(upper: any, open?: boolean): IDBKeyRange; +}; + +interface IDBObjectStore { + readonly indexNames: DOMStringList; + keyPath: string | string[]; + readonly name: string; + readonly transaction: IDBTransaction; + autoIncrement: boolean; + add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; + clear(): IDBRequest; + count(key?: IDBKeyRange | IDBValidKey): IDBRequest; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; + delete(key: IDBKeyRange | IDBValidKey): IDBRequest; + deleteIndex(indexName: string): void; + get(key: any): IDBRequest; + index(name: string): IDBIndex; + openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +}; + +interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { + "blocked": Event; + "upgradeneeded": IDBVersionChangeEvent; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: (this: IDBOpenDBRequest, ev: Event) => any; + onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +}; + +interface IDBRequestEventMap { + "error": Event; + "success": Event; +} + +interface IDBRequest extends EventTarget { + readonly error: DOMException; + onerror: (this: IDBRequest, ev: Event) => any; + onsuccess: (this: IDBRequest, ev: Event) => any; + readonly readyState: IDBRequestReadyState; + readonly result: any; + source: IDBObjectStore | IDBIndex | IDBCursor; + readonly transaction: IDBTransaction; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +}; + +interface IDBTransactionEventMap { + "abort": Event; + "complete": Event; + "error": Event; +} + +interface IDBTransaction extends EventTarget { + readonly db: IDBDatabase; + readonly error: DOMException; + readonly mode: IDBTransactionMode; + onabort: (this: IDBTransaction, ev: Event) => any; + oncomplete: (this: IDBTransaction, ev: Event) => any; + onerror: (this: IDBTransaction, ev: Event) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; + readonly READ_ONLY: string; + readonly READ_WRITE: string; + readonly VERSION_CHANGE: string; +}; + +interface IDBVersionChangeEvent extends Event { + readonly newVersion: number | null; + readonly oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +}; + +interface IIRFilterNode extends AudioNode { + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var IIRFilterNode: { + prototype: IIRFilterNode; + new(): IIRFilterNode; +}; + +interface ImageData { + data: Uint8ClampedArray; + readonly height: number; + readonly width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +}; + +interface IntersectionObserver { + readonly root: Element | null; + readonly rootMargin: string; + readonly thresholds: number[]; + disconnect(): void; + observe(target: Element): void; + takeRecords(): IntersectionObserverEntry[]; + unobserve(target: Element): void; +} + +declare var IntersectionObserver: { + prototype: IntersectionObserver; + new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; +}; + +interface IntersectionObserverEntry { + readonly boundingClientRect: ClientRect; + readonly intersectionRatio: number; + readonly intersectionRect: ClientRect; + readonly rootBounds: ClientRect; + readonly target: Element; + readonly time: number; + readonly isIntersecting: boolean; +} + +declare var IntersectionObserverEntry: { + prototype: IntersectionObserverEntry; + new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; +}; + +interface KeyboardEvent extends UIEvent { + readonly altKey: boolean; + readonly char: string | null; + readonly charCode: number; + readonly ctrlKey: boolean; + readonly key: string; + readonly keyCode: number; + readonly locale: string; + readonly location: number; + readonly metaKey: boolean; + readonly repeat: boolean; + readonly shiftKey: boolean; + readonly which: number; + readonly code: string; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +} + +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; + readonly DOM_KEY_LOCATION_JOYSTICK: number; + readonly DOM_KEY_LOCATION_LEFT: number; + readonly DOM_KEY_LOCATION_MOBILE: number; + readonly DOM_KEY_LOCATION_NUMPAD: number; + readonly DOM_KEY_LOCATION_RIGHT: number; + readonly DOM_KEY_LOCATION_STANDARD: number; +}; + +interface ListeningStateChangedEvent extends Event { + readonly label: string; + readonly state: ListeningState; +} + +declare var ListeningStateChangedEvent: { + prototype: ListeningStateChangedEvent; + new(): ListeningStateChangedEvent; +}; + +interface Location { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + assign(url: string): void; + reload(forcedReload?: boolean): void; + replace(url: string): void; + toString(): string; +} + +declare var Location: { + prototype: Location; + new(): Location; +}; + +interface LongRunningScriptDetectedEvent extends Event { + readonly executionTime: number; + stopPageScriptExecution: boolean; +} + +declare var LongRunningScriptDetectedEvent: { + prototype: LongRunningScriptDetectedEvent; + new(): LongRunningScriptDetectedEvent; +}; + +interface MediaDeviceInfo { + readonly deviceId: string; + readonly groupId: string; + readonly kind: MediaDeviceKind; + readonly label: string; +} + +declare var MediaDeviceInfo: { + prototype: MediaDeviceInfo; + new(): MediaDeviceInfo; +}; + +interface MediaDevicesEventMap { + "devicechange": Event; +} + +interface MediaDevices extends EventTarget { + ondevicechange: (this: MediaDevices, ev: Event) => any; + enumerateDevices(): Promise; + getSupportedConstraints(): MediaTrackSupportedConstraints; + getUserMedia(constraints: MediaStreamConstraints): Promise; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaDevices: { + prototype: MediaDevices; + new(): MediaDevices; +}; + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +}; + +interface MediaEncryptedEvent extends Event { + readonly initData: ArrayBuffer | null; + readonly initDataType: string; +} + +declare var MediaEncryptedEvent: { + prototype: MediaEncryptedEvent; + new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent; +}; + +interface MediaError { + readonly code: number; + readonly msExtendedCode: number; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + readonly MEDIA_ERR_ABORTED: number; + readonly MEDIA_ERR_DECODE: number; + readonly MEDIA_ERR_NETWORK: number; + readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; + readonly MS_MEDIA_ERR_ENCRYPTED: number; +}; + +interface MediaKeyMessageEvent extends Event { + readonly message: ArrayBuffer; + readonly messageType: MediaKeyMessageType; +} + +declare var MediaKeyMessageEvent: { + prototype: MediaKeyMessageEvent; + new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent; +}; + +interface MediaKeys { + createSession(sessionType?: MediaKeySessionType): MediaKeySession; + setServerCertificate(serverCertificate: any): Promise; +} + +declare var MediaKeys: { + prototype: MediaKeys; + new(): MediaKeys; +}; + +interface MediaKeySession extends EventTarget { + readonly closed: Promise; + readonly expiration: number; + readonly keyStatuses: MediaKeyStatusMap; + readonly sessionId: string; + close(): Promise; + generateRequest(initDataType: string, initData: any): Promise; + load(sessionId: string): Promise; + remove(): Promise; + update(response: any): Promise; +} + +declare var MediaKeySession: { + prototype: MediaKeySession; + new(): MediaKeySession; +}; + +interface MediaKeyStatusMap { + readonly size: number; + forEach(callback: ForEachCallback): void; + get(keyId: any): MediaKeyStatus; + has(keyId: any): boolean; +} + +declare var MediaKeyStatusMap: { + prototype: MediaKeyStatusMap; + new(): MediaKeyStatusMap; +}; + +interface MediaKeySystemAccess { + readonly keySystem: string; + createMediaKeys(): Promise; + getConfiguration(): MediaKeySystemConfiguration; +} + +declare var MediaKeySystemAccess: { + prototype: MediaKeySystemAccess; + new(): MediaKeySystemAccess; +}; + +interface MediaList { + readonly length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +}; + +interface MediaQueryList { + readonly matches: boolean; + readonly media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +}; + +interface MediaSource extends EventTarget { + readonly activeSourceBuffers: SourceBufferList; + duration: number; + readonly readyState: string; + readonly sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +}; + +interface MediaStreamEventMap { + "active": Event; + "addtrack": MediaStreamTrackEvent; + "inactive": Event; + "removetrack": MediaStreamTrackEvent; +} + +interface MediaStream extends EventTarget { + readonly active: boolean; + readonly id: string; + onactive: (this: MediaStream, ev: Event) => any; + onaddtrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + oninactive: (this: MediaStream, ev: Event) => any; + onremovetrack: (this: MediaStream, ev: MediaStreamTrackEvent) => any; + addTrack(track: MediaStreamTrack): void; + clone(): MediaStream; + getAudioTracks(): MediaStreamTrack[]; + getTrackById(trackId: string): MediaStreamTrack | null; + getTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + removeTrack(track: MediaStreamTrack): void; + stop(): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaStream: { + prototype: MediaStream; + new(streamOrTracks?: MediaStream | MediaStreamTrack[]): MediaStream; +}; + +interface MediaStreamAudioSourceNode extends AudioNode { +} + +declare var MediaStreamAudioSourceNode: { + prototype: MediaStreamAudioSourceNode; + new(): MediaStreamAudioSourceNode; +}; + +interface MediaStreamError { + readonly constraintName: string | null; + readonly message: string | null; + readonly name: string; +} + +declare var MediaStreamError: { + prototype: MediaStreamError; + new(): MediaStreamError; +}; + +interface MediaStreamErrorEvent extends Event { + readonly error: MediaStreamError | null; +} + +declare var MediaStreamErrorEvent: { + prototype: MediaStreamErrorEvent; + new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; +}; + +interface MediaStreamEvent extends Event { + readonly stream: MediaStream | null; +} + +declare var MediaStreamEvent: { + prototype: MediaStreamEvent; + new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent; +}; + +interface MediaStreamTrackEventMap { + "ended": MediaStreamErrorEvent; + "mute": Event; + "overconstrained": MediaStreamErrorEvent; + "unmute": Event; +} + +interface MediaStreamTrack extends EventTarget { + enabled: boolean; + readonly id: string; + readonly kind: string; + readonly label: string; + readonly muted: boolean; + onended: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onmute: (this: MediaStreamTrack, ev: Event) => any; + onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any; + onunmute: (this: MediaStreamTrack, ev: Event) => any; + readonly readonly: boolean; + readonly readyState: MediaStreamTrackState; + readonly remote: boolean; + applyConstraints(constraints: MediaTrackConstraints): Promise; + clone(): MediaStreamTrack; + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + stop(): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new(): MediaStreamTrack; +}; + +interface MediaStreamTrackEvent extends Event { + readonly track: MediaStreamTrack; +} + +declare var MediaStreamTrackEvent: { + prototype: MediaStreamTrackEvent; + new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent; +}; + +interface MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +}; + +interface MessageEvent extends Event { + readonly data: any; + readonly origin: string; + readonly ports: any; + readonly source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; + +interface MessagePortEventMap { + "message": MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (this: MessagePort, ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, transfer?: any[]): void; + start(): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +}; + +interface MimeType { + readonly description: string; + readonly enabledPlugin: Plugin; + readonly suffixes: string; + readonly type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +}; + +interface MimeTypeArray { + readonly length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +}; + +interface MouseEvent extends UIEvent { + readonly altKey: boolean; + readonly button: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; + readonly ctrlKey: boolean; + readonly fromElement: Element; + readonly layerX: number; + readonly layerY: number; + readonly metaKey: boolean; + readonly movementX: number; + readonly movementY: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pageX: number; + readonly pageY: number; + readonly relatedTarget: EventTarget; + readonly screenX: number; + readonly screenY: number; + readonly shiftKey: boolean; + readonly toElement: Element; + readonly which: number; + readonly x: number; + readonly y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +}; + +interface MSApp { + clearTemporaryWebDataAsync(): MSAppAsyncOperation; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createDataPackage(object: any): any; + createDataPackageFromSelection(): any; + createFileFromStorageFile(storageFile: any): File; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + getCurrentPriority(): string; + getHtmlPrintDocumentSourceAsync(htmlDoc: any): Promise; + getViewId(view: any): any; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + pageHandlesAllApplicationActivations(enabled: boolean): void; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + terminateApp(exceptionObject: any): void; + readonly CURRENT: string; + readonly HIGH: string; + readonly IDLE: string; + readonly NORMAL: string; +} +declare var MSApp: MSApp; + +interface MSAppAsyncOperationEventMap { + "complete": Event; + "error": Event; +} + +interface MSAppAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSAppAsyncOperation, ev: Event) => any; + onerror: (this: MSAppAsyncOperation, ev: Event) => any; + readonly readyState: number; + readonly result: any; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSAppAsyncOperation: { + prototype: MSAppAsyncOperation; + new(): MSAppAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; +}; + +interface MSAssertion { + readonly id: string; + readonly type: MSCredentialType; +} + +declare var MSAssertion: { + prototype: MSAssertion; + new(): MSAssertion; +}; + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +}; + +interface MSCredentials { + getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; + makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): Promise; +} + +declare var MSCredentials: { + prototype: MSCredentials; + new(): MSCredentials; +}; + +interface MSFIDOCredentialAssertion extends MSAssertion { + readonly algorithm: string | Algorithm; + readonly attestation: any; + readonly publicKey: string; + readonly transportHints: MSTransportType[]; +} + +declare var MSFIDOCredentialAssertion: { + prototype: MSFIDOCredentialAssertion; + new(): MSFIDOCredentialAssertion; +}; + +interface MSFIDOSignature { + readonly authnrData: string; + readonly clientData: string; + readonly signature: string; +} + +declare var MSFIDOSignature: { + prototype: MSFIDOSignature; + new(): MSFIDOSignature; +}; + +interface MSFIDOSignatureAssertion extends MSAssertion { + readonly signature: MSFIDOSignature; +} + +declare var MSFIDOSignatureAssertion: { + prototype: MSFIDOSignatureAssertion; + new(): MSFIDOSignatureAssertion; +}; + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} + +declare var MSGesture: { + prototype: MSGesture; + new(): MSGesture; +}; + +interface MSGestureEvent extends UIEvent { + readonly clientX: number; + readonly clientY: number; + readonly expansion: number; + readonly gestureObject: any; + readonly hwTimestamp: number; + readonly offsetX: number; + readonly offsetY: number; + readonly rotation: number; + readonly scale: number; + readonly screenX: number; + readonly screenY: number; + readonly translationX: number; + readonly translationY: number; + readonly velocityAngular: number; + readonly velocityExpansion: number; + readonly velocityX: number; + readonly velocityY: number; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +} + +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + readonly MSGESTURE_FLAG_BEGIN: number; + readonly MSGESTURE_FLAG_CANCEL: number; + readonly MSGESTURE_FLAG_END: number; + readonly MSGESTURE_FLAG_INERTIA: number; + readonly MSGESTURE_FLAG_NONE: number; +}; + +interface MSGraphicsTrust { + readonly constrictionActive: boolean; + readonly status: string; +} + +declare var MSGraphicsTrust: { + prototype: MSGraphicsTrust; + new(): MSGraphicsTrust; +}; + +interface MSHTMLWebViewElement extends HTMLElement { + readonly canGoBack: boolean; + readonly canGoForward: boolean; + readonly containsFullScreenElement: boolean; + readonly documentTitle: string; + height: number; + readonly settings: MSWebViewSettings; + src: string; + width: number; + addWebAllowedObject(name: string, applicationObject: any): void; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; + getDeferredPermissionRequests(): DeferredPermissionRequest[]; + goBack(): void; + goForward(): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + navigate(uri: string): void; + navigateFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + navigateToString(contents: string): void; + navigateWithHttpRequestMessage(requestMessage: any): void; + refresh(): void; + stop(): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSHTMLWebViewElement: { + prototype: MSHTMLWebViewElement; + new(): MSHTMLWebViewElement; +}; + +interface MSInputMethodContextEventMap { + "MSCandidateWindowHide": Event; + "MSCandidateWindowShow": Event; + "MSCandidateWindowUpdate": Event; +} + +interface MSInputMethodContext extends EventTarget { + readonly compositionEndOffset: number; + readonly compositionStartOffset: number; + oncandidatewindowhide: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowshow: (this: MSInputMethodContext, ev: Event) => any; + oncandidatewindowupdate: (this: MSInputMethodContext, ev: Event) => any; + readonly target: HTMLElement; + getCandidateWindowClientRect(): ClientRect; + getCompositionAlternatives(): string[]; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSInputMethodContext: { + prototype: MSInputMethodContext; + new(): MSInputMethodContext; +}; + +interface MSManipulationEvent extends UIEvent { + readonly currentState: number; + readonly inertiaDestinationX: number; + readonly inertiaDestinationY: number; + readonly lastState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +} + +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + readonly MS_MANIPULATION_STATE_ACTIVE: number; + readonly MS_MANIPULATION_STATE_CANCELLED: number; + readonly MS_MANIPULATION_STATE_COMMITTED: number; + readonly MS_MANIPULATION_STATE_DRAGGING: number; + readonly MS_MANIPULATION_STATE_INERTIA: number; + readonly MS_MANIPULATION_STATE_PRESELECT: number; + readonly MS_MANIPULATION_STATE_SELECTING: number; + readonly MS_MANIPULATION_STATE_STOPPED: number; +}; + +interface MSMediaKeyError { + readonly code: number; + readonly systemCode: number; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +} + +declare var MSMediaKeyError: { + prototype: MSMediaKeyError; + new(): MSMediaKeyError; + readonly MS_MEDIA_KEYERR_CLIENT: number; + readonly MS_MEDIA_KEYERR_DOMAIN: number; + readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number; + readonly MS_MEDIA_KEYERR_OUTPUT: number; + readonly MS_MEDIA_KEYERR_SERVICE: number; + readonly MS_MEDIA_KEYERR_UNKNOWN: number; +}; + +interface MSMediaKeyMessageEvent extends Event { + readonly destinationURL: string | null; + readonly message: Uint8Array; +} + +declare var MSMediaKeyMessageEvent: { + prototype: MSMediaKeyMessageEvent; + new(): MSMediaKeyMessageEvent; +}; + +interface MSMediaKeyNeededEvent extends Event { + readonly initData: Uint8Array | null; +} + +declare var MSMediaKeyNeededEvent: { + prototype: MSMediaKeyNeededEvent; + new(): MSMediaKeyNeededEvent; +}; + +interface MSMediaKeys { + readonly keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; + isTypeSupportedWithFeatures(keySystem: string, type?: string): string; +}; + +interface MSMediaKeySession extends EventTarget { + readonly error: MSMediaKeyError | null; + readonly keySystem: string; + readonly sessionId: string; + close(): void; + update(key: Uint8Array): void; +} + +declare var MSMediaKeySession: { + prototype: MSMediaKeySession; + new(): MSMediaKeySession; +}; + +interface MSPointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; +}; + +interface MSRangeCollection { + readonly length: number; + item(index: number): Range; + [index: number]: Range; +} + +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +}; + +interface MSSiteModeEvent extends Event { + readonly actionURL: string; + readonly buttonID: number; +} + +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +}; + +interface MSStream { + readonly type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +}; + +interface MSStreamReader extends EventTarget, MSBaseReader { + readonly error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBinaryString(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; +}; + +interface MSWebViewAsyncOperationEventMap { + "complete": Event; + "error": Event; +} + +interface MSWebViewAsyncOperation extends EventTarget { + readonly error: DOMError; + oncomplete: (this: MSWebViewAsyncOperation, ev: Event) => any; + onerror: (this: MSWebViewAsyncOperation, ev: Event) => any; + readonly readyState: number; + readonly result: any; + readonly target: MSHTMLWebViewElement; + readonly type: number; + start(): void; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var MSWebViewAsyncOperation: { + prototype: MSWebViewAsyncOperation; + new(): MSWebViewAsyncOperation; + readonly COMPLETED: number; + readonly ERROR: number; + readonly STARTED: number; + readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + readonly TYPE_INVOKE_SCRIPT: number; +}; + +interface MSWebViewSettings { + isIndexedDBEnabled: boolean; + isJavaScriptEnabled: boolean; +} + +declare var MSWebViewSettings: { + prototype: MSWebViewSettings; + new(): MSWebViewSettings; +}; + +interface MutationEvent extends Event { + readonly attrChange: number; + readonly attrName: string; + readonly newValue: string; + readonly prevValue: string; + readonly relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +} + +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + readonly ADDITION: number; + readonly MODIFICATION: number; + readonly REMOVAL: number; +}; + +interface MutationObserver { + disconnect(): void; + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; +} + +declare var MutationObserver: { + prototype: MutationObserver; + new(callback: MutationCallback): MutationObserver; +}; + +interface MutationRecord { + readonly addedNodes: NodeList; + readonly attributeName: string | null; + readonly attributeNamespace: string | null; + readonly nextSibling: Node | null; + readonly oldValue: string | null; + readonly previousSibling: Node | null; + readonly removedNodes: NodeList; + readonly target: Node; + readonly type: string; +} + +declare var MutationRecord: { + prototype: MutationRecord; + new(): MutationRecord; +}; + +interface NamedNodeMap { + readonly length: number; + getNamedItem(name: string): Attr; + getNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + item(index: number): Attr; + removeNamedItem(name: string): Attr; + removeNamedItemNS(namespaceURI: string | null, localName: string | null): Attr; + setNamedItem(arg: Attr): Attr; + setNamedItemNS(arg: Attr): Attr; + [index: number]: Attr; +} + +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +}; + +interface NavigationCompletedEvent extends NavigationEvent { + readonly isSuccess: boolean; + readonly webErrorStatus: number; +} + +declare var NavigationCompletedEvent: { + prototype: NavigationCompletedEvent; + new(): NavigationCompletedEvent; +}; + +interface NavigationEvent extends Event { + readonly uri: string; +} + +declare var NavigationEvent: { + prototype: NavigationEvent; + new(): NavigationEvent; +}; + +interface NavigationEventWithReferrer extends NavigationEvent { + readonly referer: string; +} + +declare var NavigationEventWithReferrer: { + prototype: NavigationEventWithReferrer; + new(): NavigationEventWithReferrer; +}; + +interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia { + readonly authentication: WebAuthentication; + readonly cookieEnabled: boolean; + gamepadInputEmulation: GamepadInputEmulationType; + readonly language: string; + readonly maxTouchPoints: number; + readonly mimeTypes: MimeTypeArray; + readonly msManipulationViewsEnabled: boolean; + readonly msMaxTouchPoints: number; + readonly msPointerEnabled: boolean; + readonly plugins: PluginArray; + readonly pointerEnabled: boolean; + readonly serviceWorker: ServiceWorkerContainer; + readonly webdriver: boolean; + readonly doNotTrack: string | null; + readonly hardwareConcurrency: number; + readonly languages: string[]; + getGamepads(): Gamepad[]; + javaEnabled(): boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; + vibrate(pattern: number | number[]): boolean; +} + +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +}; + +interface Node extends EventTarget { + readonly attributes: NamedNodeMap; + readonly baseURI: string | null; + readonly childNodes: NodeList; + readonly firstChild: Node | null; + readonly lastChild: Node | null; + readonly localName: string | null; + readonly namespaceURI: string | null; + readonly nextSibling: Node | null; + readonly nodeName: string; + readonly nodeType: number; + nodeValue: string | null; + readonly ownerDocument: Document; + readonly parentElement: HTMLElement | null; + readonly parentNode: Node | null; + readonly previousSibling: Node | null; + textContent: string | null; + appendChild(newChild: T): T; + cloneNode(deep?: boolean): Node; + compareDocumentPosition(other: Node): number; + contains(child: Node): boolean; + hasAttributes(): boolean; + hasChildNodes(): boolean; + insertBefore(newChild: T, refChild: Node | null): T; + isDefaultNamespace(namespaceURI: string | null): boolean; + isEqualNode(arg: Node): boolean; + isSameNode(other: Node): boolean; + lookupNamespaceURI(prefix: string | null): string | null; + lookupPrefix(namespaceURI: string | null): string | null; + normalize(): void; + removeChild(oldChild: T): T; + replaceChild(newChild: Node, oldChild: T): T; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +} + +declare var Node: { + prototype: Node; + new(): Node; + readonly ATTRIBUTE_NODE: number; + readonly CDATA_SECTION_NODE: number; + readonly COMMENT_NODE: number; + readonly DOCUMENT_FRAGMENT_NODE: number; + readonly DOCUMENT_NODE: number; + readonly DOCUMENT_POSITION_CONTAINED_BY: number; + readonly DOCUMENT_POSITION_CONTAINS: number; + readonly DOCUMENT_POSITION_DISCONNECTED: number; + readonly DOCUMENT_POSITION_FOLLOWING: number; + readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + readonly DOCUMENT_POSITION_PRECEDING: number; + readonly DOCUMENT_TYPE_NODE: number; + readonly ELEMENT_NODE: number; + readonly ENTITY_NODE: number; + readonly ENTITY_REFERENCE_NODE: number; + readonly NOTATION_NODE: number; + readonly PROCESSING_INSTRUCTION_NODE: number; + readonly TEXT_NODE: number; +}; + +interface NodeFilter { + acceptNode(n: Node): number; +} + +declare var NodeFilter: { + readonly FILTER_ACCEPT: number; + readonly FILTER_REJECT: number; + readonly FILTER_SKIP: number; + readonly SHOW_ALL: number; + readonly SHOW_ATTRIBUTE: number; + readonly SHOW_CDATA_SECTION: number; + readonly SHOW_COMMENT: number; + readonly SHOW_DOCUMENT: number; + readonly SHOW_DOCUMENT_FRAGMENT: number; + readonly SHOW_DOCUMENT_TYPE: number; + readonly SHOW_ELEMENT: number; + readonly SHOW_ENTITY: number; + readonly SHOW_ENTITY_REFERENCE: number; + readonly SHOW_NOTATION: number; + readonly SHOW_PROCESSING_INSTRUCTION: number; + readonly SHOW_TEXT: number; +}; + +interface NodeIterator { + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + detach(): void; + nextNode(): Node; + previousNode(): Node; +} + +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +}; + +interface NodeList { + readonly length: number; + item(index: number): Node; + [index: number]: Node; +} + +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +}; + +interface NotificationEventMap { + "click": Event; + "close": Event; + "error": Event; + "show": Event; +} + +interface Notification extends EventTarget { + readonly body: string; + readonly dir: NotificationDirection; + readonly icon: string; + readonly lang: string; + onclick: (this: Notification, ev: Event) => any; + onclose: (this: Notification, ev: Event) => any; + onerror: (this: Notification, ev: Event) => any; + onshow: (this: Notification, ev: Event) => any; + readonly permission: NotificationPermission; + readonly tag: string; + readonly title: string; + close(): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Notification: { + prototype: Notification; + new(title: string, options?: NotificationOptions): Notification; + requestPermission(callback?: NotificationPermissionCallback): Promise; +}; + +interface OES_element_index_uint { +} + +declare var OES_element_index_uint: { + prototype: OES_element_index_uint; + new(): OES_element_index_uint; +}; + +interface OES_standard_derivatives { + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +declare var OES_standard_derivatives: { + prototype: OES_standard_derivatives; + new(): OES_standard_derivatives; + readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +}; + +interface OES_texture_float { +} + +declare var OES_texture_float: { + prototype: OES_texture_float; + new(): OES_texture_float; +}; + +interface OES_texture_float_linear { +} + +declare var OES_texture_float_linear: { + prototype: OES_texture_float_linear; + new(): OES_texture_float_linear; +}; + +interface OES_texture_half_float { + readonly HALF_FLOAT_OES: number; +} + +declare var OES_texture_half_float: { + prototype: OES_texture_half_float; + new(): OES_texture_half_float; + readonly HALF_FLOAT_OES: number; +}; + +interface OES_texture_half_float_linear { +} + +declare var OES_texture_half_float_linear: { + prototype: OES_texture_half_float_linear; + new(): OES_texture_half_float_linear; +}; + +interface OfflineAudioCompletionEvent extends Event { + readonly renderedBuffer: AudioBuffer; +} + +declare var OfflineAudioCompletionEvent: { + prototype: OfflineAudioCompletionEvent; + new(): OfflineAudioCompletionEvent; +}; + +interface OfflineAudioContextEventMap extends AudioContextEventMap { + "complete": OfflineAudioCompletionEvent; +} + +interface OfflineAudioContext extends AudioContextBase { + readonly length: number; + oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; + startRendering(): Promise; + suspend(suspendTime: number): Promise; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OfflineAudioContext: { + prototype: OfflineAudioContext; + new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +}; + +interface OscillatorNodeEventMap { + "ended": MediaStreamErrorEvent; +} + +interface OscillatorNode extends AudioNode { + readonly detune: AudioParam; + readonly frequency: AudioParam; + onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any; + type: OscillatorType; + setPeriodicWave(periodicWave: PeriodicWave): void; + start(when?: number): void; + stop(when?: number): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OscillatorNode: { + prototype: OscillatorNode; + new(): OscillatorNode; +}; + +interface OverflowEvent extends UIEvent { + readonly horizontalOverflow: boolean; + readonly orient: number; + readonly verticalOverflow: boolean; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +} + +declare var OverflowEvent: { + prototype: OverflowEvent; + new(): OverflowEvent; + readonly BOTH: number; + readonly HORIZONTAL: number; + readonly VERTICAL: number; +}; + +interface PageTransitionEvent extends Event { + readonly persisted: boolean; +} + +declare var PageTransitionEvent: { + prototype: PageTransitionEvent; + new(): PageTransitionEvent; +}; + +interface PannerNode extends AudioNode { + coneInnerAngle: number; + coneOuterAngle: number; + coneOuterGain: number; + distanceModel: DistanceModelType; + maxDistance: number; + panningModel: PanningModelType; + refDistance: number; + rolloffFactor: number; + setOrientation(x: number, y: number, z: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var PannerNode: { + prototype: PannerNode; + new(): PannerNode; +}; + +interface Path2D extends Object, CanvasPathMethods { +} + +declare var Path2D: { + prototype: Path2D; + new(path?: Path2D): Path2D; +}; + +interface PaymentAddress { + readonly addressLine: string[]; + readonly city: string; + readonly country: string; + readonly dependentLocality: string; + readonly languageCode: string; + readonly organization: string; + readonly phone: string; + readonly postalCode: string; + readonly recipient: string; + readonly region: string; + readonly sortingCode: string; + toJSON(): any; +} + +declare var PaymentAddress: { + prototype: PaymentAddress; + new(): PaymentAddress; +}; + +interface PaymentRequestEventMap { + "shippingaddresschange": Event; + "shippingoptionchange": Event; +} + +interface PaymentRequest extends EventTarget { + onshippingaddresschange: (this: PaymentRequest, ev: Event) => any; + onshippingoptionchange: (this: PaymentRequest, ev: Event) => any; + readonly shippingAddress: PaymentAddress | null; + readonly shippingOption: string | null; + readonly shippingType: PaymentShippingType | null; + abort(): Promise; + show(): Promise; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var PaymentRequest: { + prototype: PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; +}; + +interface PaymentRequestUpdateEvent extends Event { + updateWith(d: Promise): void; +} + +declare var PaymentRequestUpdateEvent: { + prototype: PaymentRequestUpdateEvent; + new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; +}; + +interface PaymentResponse { + readonly details: any; + readonly methodName: string; + readonly payerEmail: string | null; + readonly payerName: string | null; + readonly payerPhone: string | null; + readonly shippingAddress: PaymentAddress | null; + readonly shippingOption: string | null; + complete(result?: PaymentComplete): Promise; + toJSON(): any; +} + +declare var PaymentResponse: { + prototype: PaymentResponse; + new(): PaymentResponse; +}; + +interface Performance { + readonly navigation: PerformanceNavigation; + readonly timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +}; + +interface PerformanceEntry { + readonly duration: number; + readonly entryType: string; + readonly name: string; + readonly startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +}; + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +}; + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +}; + +interface PerformanceNavigation { + readonly redirectCount: number; + readonly type: number; + toJSON(): any; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + readonly TYPE_BACK_FORWARD: number; + readonly TYPE_NAVIGATE: number; + readonly TYPE_RELOAD: number; + readonly TYPE_RESERVED: number; +}; + +interface PerformanceNavigationTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly navigationStart: number; + readonly redirectCount: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly type: NavigationType; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +}; + +interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly fetchStart: number; + readonly initiatorType: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +}; + +interface PerformanceTiming { + readonly connectEnd: number; + readonly connectStart: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly domComplete: number; + readonly domContentLoadedEventEnd: number; + readonly domContentLoadedEventStart: number; + readonly domInteractive: number; + readonly domLoading: number; + readonly fetchStart: number; + readonly loadEventEnd: number; + readonly loadEventStart: number; + readonly msFirstPaint: number; + readonly navigationStart: number; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly unloadEventEnd: number; + readonly unloadEventStart: number; + readonly secureConnectionStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +}; + +interface PerfWidgetExternal { + readonly activeNetworkRequestCount: number; + readonly averageFrameTime: number; + readonly averagePaintTime: number; + readonly extraInformationEnabled: boolean; + readonly independentRenderingEnabled: boolean; + readonly irDisablingContentString: string; + readonly irStatusAvailable: boolean; + readonly maxCpuSpeed: number; + readonly paintRequestsPerSecond: number; + readonly performanceCounter: number; + readonly performanceCounterFrequency: number; + addEventListener(eventType: string, callback: Function): void; + getMemoryUsage(): number; + getProcessCpuUsage(): number; + getRecentCpuUsage(last: number | null): any; + getRecentFrames(last: number | null): any; + getRecentMemoryUsage(last: number | null): any; + getRecentPaintRequests(last: number | null): any; + removeEventListener(eventType: string, callback: Function): void; + repositionWindow(x: number, y: number): void; + resizeWindow(width: number, height: number): void; +} + +declare var PerfWidgetExternal: { + prototype: PerfWidgetExternal; + new(): PerfWidgetExternal; +}; + +interface PeriodicWave { +} + +declare var PeriodicWave: { + prototype: PeriodicWave; + new(): PeriodicWave; +}; + +interface PermissionRequest extends DeferredPermissionRequest { + readonly state: MSWebViewPermissionState; + defer(): void; +} + +declare var PermissionRequest: { + prototype: PermissionRequest; + new(): PermissionRequest; +}; + +interface PermissionRequestedEvent extends Event { + readonly permissionRequest: PermissionRequest; +} + +declare var PermissionRequestedEvent: { + prototype: PermissionRequestedEvent; + new(): PermissionRequestedEvent; +}; + +interface Plugin { + readonly description: string; + readonly filename: string; + readonly length: number; + readonly name: string; + readonly version: string; + item(index: number): MimeType; + namedItem(type: string): MimeType; + [index: number]: MimeType; +} + +declare var Plugin: { + prototype: Plugin; + new(): Plugin; +}; + +interface PluginArray { + readonly length: number; + item(index: number): Plugin; + namedItem(name: string): Plugin; + refresh(reload?: boolean): void; + [index: number]: Plugin; +} + +declare var PluginArray: { + prototype: PluginArray; + new(): PluginArray; +}; + +interface PointerEvent extends MouseEvent { + readonly currentPoint: any; + readonly height: number; + readonly hwTimestamp: number; + readonly intermediatePoints: any; + readonly isPrimary: boolean; + readonly pointerId: number; + readonly pointerType: any; + readonly pressure: number; + readonly rotation: number; + readonly tiltX: number; + readonly tiltY: number; + readonly width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var PointerEvent: { + prototype: PointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; +}; + +interface PopStateEvent extends Event { + readonly state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +declare var PopStateEvent: { + prototype: PopStateEvent; + new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; +}; + +interface Position { + readonly coords: Coordinates; + readonly timestamp: number; +} + +declare var Position: { + prototype: Position; + new(): Position; +}; + +interface PositionError { + readonly code: number; + readonly message: string; + toString(): string; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +} + +declare var PositionError: { + prototype: PositionError; + new(): PositionError; + readonly PERMISSION_DENIED: number; + readonly POSITION_UNAVAILABLE: number; + readonly TIMEOUT: number; +}; + +interface ProcessingInstruction extends CharacterData { + readonly target: string; +} + +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +}; + +interface ProgressEvent extends Event { + readonly lengthComputable: boolean; + readonly loaded: number; + readonly total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +}; + +interface PushManager { + getSubscription(): Promise; + permissionState(options?: PushSubscriptionOptionsInit): Promise; + subscribe(options?: PushSubscriptionOptionsInit): Promise; +} + +declare var PushManager: { + prototype: PushManager; + new(): PushManager; +}; + +interface PushSubscription { + readonly endpoint: USVString; + readonly options: PushSubscriptionOptions; + getKey(name: PushEncryptionKeyName): ArrayBuffer | null; + toJSON(): any; + unsubscribe(): Promise; +} + +declare var PushSubscription: { + prototype: PushSubscription; + new(): PushSubscription; +}; + +interface PushSubscriptionOptions { + readonly applicationServerKey: ArrayBuffer | null; + readonly userVisibleOnly: boolean; +} + +declare var PushSubscriptionOptions: { + prototype: PushSubscriptionOptions; + new(): PushSubscriptionOptions; +}; + +interface Range { + readonly collapsed: boolean; + readonly commonAncestorContainer: Node; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: ExpandGranularity): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +} + +declare var Range: { + prototype: Range; + new(): Range; + readonly END_TO_END: number; + readonly END_TO_START: number; + readonly START_TO_END: number; + readonly START_TO_START: number; +}; + +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; + getReader(): ReadableStreamReader; +} + +declare var ReadableStream: { + prototype: ReadableStream; + new(): ReadableStream; +}; + +interface ReadableStreamReader { + cancel(): Promise; + read(): Promise; + releaseLock(): void; +} + +declare var ReadableStreamReader: { + prototype: ReadableStreamReader; + new(): ReadableStreamReader; +}; + +interface Request extends Object, Body { + readonly cache: RequestCache; + readonly credentials: RequestCredentials; + readonly destination: RequestDestination; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: RequestMode; + readonly redirect: RequestRedirect; + readonly referrer: string; + readonly referrerPolicy: ReferrerPolicy; + readonly type: RequestType; + readonly url: string; + clone(): Request; +} + +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; +}; + +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: ResponseType; + readonly url: string; + readonly redirected: boolean; + clone(): Response; +} + +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; + error: () => Response; + redirect: (url: string, status?: number) => Response; +}; + +interface RTCDtlsTransportEventMap { + "dtlsstatechange": RTCDtlsTransportStateChangedEvent; + "error": Event; +} + +interface RTCDtlsTransport extends RTCStatsProvider { + ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null; + onerror: ((this: RTCDtlsTransport, ev: Event) => any) | null; + readonly state: RTCDtlsTransportState; + readonly transport: RTCIceTransport; + getLocalParameters(): RTCDtlsParameters; + getRemoteCertificates(): ArrayBuffer[]; + getRemoteParameters(): RTCDtlsParameters | null; + start(remoteParameters: RTCDtlsParameters): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCDtlsTransport: { + prototype: RTCDtlsTransport; + new(transport: RTCIceTransport): RTCDtlsTransport; +}; + +interface RTCDtlsTransportStateChangedEvent extends Event { + readonly state: RTCDtlsTransportState; +} + +declare var RTCDtlsTransportStateChangedEvent: { + prototype: RTCDtlsTransportStateChangedEvent; + new(): RTCDtlsTransportStateChangedEvent; +}; + +interface RTCDtmfSenderEventMap { + "tonechange": RTCDTMFToneChangeEvent; +} + +interface RTCDtmfSender extends EventTarget { + readonly canInsertDTMF: boolean; + readonly duration: number; + readonly interToneGap: number; + ontonechange: (this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any; + readonly sender: RTCRtpSender; + readonly toneBuffer: string; + insertDTMF(tones: string, duration?: number, interToneGap?: number): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCDtmfSender: { + prototype: RTCDtmfSender; + new(sender: RTCRtpSender): RTCDtmfSender; +}; + +interface RTCDTMFToneChangeEvent extends Event { + readonly tone: string; +} + +declare var RTCDTMFToneChangeEvent: { + prototype: RTCDTMFToneChangeEvent; + new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; +}; + +interface RTCIceCandidate { + candidate: string | null; + sdpMid: string | null; + sdpMLineIndex: number | null; + toJSON(): any; +} + +declare var RTCIceCandidate: { + prototype: RTCIceCandidate; + new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate; +}; + +interface RTCIceCandidatePairChangedEvent extends Event { + readonly pair: RTCIceCandidatePair; +} + +declare var RTCIceCandidatePairChangedEvent: { + prototype: RTCIceCandidatePairChangedEvent; + new(): RTCIceCandidatePairChangedEvent; +}; + +interface RTCIceGathererEventMap { + "error": Event; + "localcandidate": RTCIceGathererEvent; +} + +interface RTCIceGatherer extends RTCStatsProvider { + readonly component: RTCIceComponent; + onerror: ((this: RTCIceGatherer, ev: Event) => any) | null; + onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null; + createAssociatedGatherer(): RTCIceGatherer; + getLocalCandidates(): RTCIceCandidateDictionary[]; + getLocalParameters(): RTCIceParameters; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCIceGatherer: { + prototype: RTCIceGatherer; + new(options: RTCIceGatherOptions): RTCIceGatherer; +}; + +interface RTCIceGathererEvent extends Event { + readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; +} + +declare var RTCIceGathererEvent: { + prototype: RTCIceGathererEvent; + new(): RTCIceGathererEvent; +}; + +interface RTCIceTransportEventMap { + "candidatepairchange": RTCIceCandidatePairChangedEvent; + "icestatechange": RTCIceTransportStateChangedEvent; +} + +interface RTCIceTransport extends RTCStatsProvider { + readonly component: RTCIceComponent; + readonly iceGatherer: RTCIceGatherer | null; + oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null; + onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null; + readonly role: RTCIceRole; + readonly state: RTCIceTransportState; + addRemoteCandidate(remoteCandidate: RTCIceCandidateDictionary | RTCIceCandidateComplete): void; + createAssociatedTransport(): RTCIceTransport; + getNominatedCandidatePair(): RTCIceCandidatePair | null; + getRemoteCandidates(): RTCIceCandidateDictionary[]; + getRemoteParameters(): RTCIceParameters | null; + setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; + start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCIceTransport: { + prototype: RTCIceTransport; + new(): RTCIceTransport; +}; + +interface RTCIceTransportStateChangedEvent extends Event { + readonly state: RTCIceTransportState; +} + +declare var RTCIceTransportStateChangedEvent: { + prototype: RTCIceTransportStateChangedEvent; + new(): RTCIceTransportStateChangedEvent; +}; + +interface RTCPeerConnectionEventMap { + "addstream": MediaStreamEvent; + "icecandidate": RTCPeerConnectionIceEvent; + "iceconnectionstatechange": Event; + "icegatheringstatechange": Event; + "negotiationneeded": Event; + "removestream": MediaStreamEvent; + "signalingstatechange": Event; +} + +interface RTCPeerConnection extends EventTarget { + readonly canTrickleIceCandidates: boolean | null; + readonly iceConnectionState: RTCIceConnectionState; + readonly iceGatheringState: RTCIceGatheringState; + readonly localDescription: RTCSessionDescription | null; + onaddstream: (this: RTCPeerConnection, ev: MediaStreamEvent) => any; + onicecandidate: (this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any; + oniceconnectionstatechange: (this: RTCPeerConnection, ev: Event) => any; + onicegatheringstatechange: (this: RTCPeerConnection, ev: Event) => any; + onnegotiationneeded: (this: RTCPeerConnection, ev: Event) => any; + onremovestream: (this: RTCPeerConnection, ev: MediaStreamEvent) => any; + onsignalingstatechange: (this: RTCPeerConnection, ev: Event) => any; + readonly remoteDescription: RTCSessionDescription | null; + readonly signalingState: RTCSignalingState; + addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addStream(stream: MediaStream): void; + close(): void; + createAnswer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + createOffer(successCallback?: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, options?: RTCOfferOptions): Promise; + getConfiguration(): RTCConfiguration; + getLocalStreams(): MediaStream[]; + getRemoteStreams(): MediaStream[]; + getStats(selector: MediaStreamTrack | null, successCallback?: RTCStatsCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + getStreamById(streamId: string): MediaStream | null; + removeStream(stream: MediaStream): void; + setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCPeerConnection: { + prototype: RTCPeerConnection; + new(configuration: RTCConfiguration): RTCPeerConnection; +}; + +interface RTCPeerConnectionIceEvent extends Event { + readonly candidate: RTCIceCandidate; +} + +declare var RTCPeerConnectionIceEvent: { + prototype: RTCPeerConnectionIceEvent; + new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; +}; + +interface RTCRtpReceiverEventMap { + "error": Event; +} + +interface RTCRtpReceiver extends RTCStatsProvider { + onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack | null; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + getContributingSources(): RTCRtpContributingSource[]; + receive(parameters: RTCRtpParameters): void; + requestSendCSRC(csrc: number): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCRtpReceiver: { + prototype: RTCRtpReceiver; + new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; + getCapabilities(kind?: string): RTCRtpCapabilities; +}; + +interface RTCRtpSenderEventMap { + "error": Event; + "ssrcconflict": RTCSsrcConflictEvent; +} + +interface RTCRtpSender extends RTCStatsProvider { + onerror: ((this: RTCRtpSender, ev: Event) => any) | null; + onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null; + readonly rtcpTransport: RTCDtlsTransport; + readonly track: MediaStreamTrack; + readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; + send(parameters: RTCRtpParameters): void; + setTrack(track: MediaStreamTrack): void; + setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; + stop(): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCRtpSender: { + prototype: RTCRtpSender; + new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; + getCapabilities(kind?: string): RTCRtpCapabilities; +}; + +interface RTCSessionDescription { + sdp: string | null; + type: RTCSdpType | null; + toJSON(): any; +} + +declare var RTCSessionDescription: { + prototype: RTCSessionDescription; + new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; +}; + +interface RTCSrtpSdesTransportEventMap { + "error": Event; +} + +interface RTCSrtpSdesTransport extends EventTarget { + onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; + readonly transport: RTCIceTransport; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var RTCSrtpSdesTransport: { + prototype: RTCSrtpSdesTransport; + new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; + getLocalParameters(): RTCSrtpSdesParameters[]; +}; + +interface RTCSsrcConflictEvent extends Event { + readonly ssrc: number; +} + +declare var RTCSsrcConflictEvent: { + prototype: RTCSsrcConflictEvent; + new(): RTCSsrcConflictEvent; +}; + +interface RTCStatsProvider extends EventTarget { + getStats(): Promise; + msGetStats(): Promise; +} + +declare var RTCStatsProvider: { + prototype: RTCStatsProvider; + new(): RTCStatsProvider; +}; + +interface ScopedCredential { + readonly id: ArrayBuffer; + readonly type: ScopedCredentialType; +} + +declare var ScopedCredential: { + prototype: ScopedCredential; + new(): ScopedCredential; +}; + +interface ScopedCredentialInfo { + readonly credential: ScopedCredential; + readonly publicKey: CryptoKey; +} + +declare var ScopedCredentialInfo: { + prototype: ScopedCredentialInfo; + new(): ScopedCredentialInfo; +}; + +interface ScreenEventMap { + "MSOrientationChange": Event; +} + +interface Screen extends EventTarget { + readonly availHeight: number; + readonly availWidth: number; + bufferDepth: number; + readonly colorDepth: number; + readonly deviceXDPI: number; + readonly deviceYDPI: number; + readonly fontSmoothingEnabled: boolean; + readonly height: number; + readonly logicalXDPI: number; + readonly logicalYDPI: number; + readonly msOrientation: string; + onmsorientationchange: (this: Screen, ev: Event) => any; + readonly pixelDepth: number; + readonly systemXDPI: number; + readonly systemYDPI: number; + readonly width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +}; + +interface ScriptNotifyEvent extends Event { + readonly callingUri: string; + readonly value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +}; + +interface ScriptProcessorNodeEventMap { + "audioprocess": AudioProcessingEvent; +} + +interface ScriptProcessorNode extends AudioNode { + readonly bufferSize: number; + onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +}; + +interface Selection { + readonly anchorNode: Node; + readonly anchorOffset: number; + readonly baseNode: Node; + readonly baseOffset: number; + readonly extentNode: Node; + readonly extentOffset: number; + readonly focusNode: Node; + readonly focusOffset: number; + readonly isCollapsed: boolean; + readonly rangeCount: number; + readonly type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + setPosition(parentNode: Node, offset: number): void; + toString(): string; +} + +declare var Selection: { + prototype: Selection; + new(): Selection; +}; + +interface ServiceWorkerEventMap extends AbstractWorkerEventMap { + "statechange": Event; +} + +interface ServiceWorker extends EventTarget, AbstractWorker { + onstatechange: (this: ServiceWorker, ev: Event) => any; + readonly scriptURL: USVString; + readonly state: ServiceWorkerState; + postMessage(message: any, transfer?: any[]): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorker: { + prototype: ServiceWorker; + new(): ServiceWorker; +}; + +interface ServiceWorkerContainerEventMap { + "controllerchange": Event; + "message": ServiceWorkerMessageEvent; +} + +interface ServiceWorkerContainer extends EventTarget { + readonly controller: ServiceWorker | null; + oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; + onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; + readonly ready: Promise; + getRegistration(clientURL?: USVString): Promise; + getRegistrations(): Promise; + register(scriptURL: USVString, options?: RegistrationOptions): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerContainer: { + prototype: ServiceWorkerContainer; + new(): ServiceWorkerContainer; +}; + +interface ServiceWorkerMessageEvent extends Event { + readonly data: any; + readonly lastEventId: string; + readonly origin: string; + readonly ports: MessagePort[] | null; + readonly source: ServiceWorker | MessagePort | null; +} + +declare var ServiceWorkerMessageEvent: { + prototype: ServiceWorkerMessageEvent; + new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; +}; + +interface ServiceWorkerRegistrationEventMap { + "updatefound": Event; +} + +interface ServiceWorkerRegistration extends EventTarget { + readonly active: ServiceWorker | null; + readonly installing: ServiceWorker | null; + onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any; + readonly pushManager: PushManager; + readonly scope: USVString; + readonly sync: SyncManager; + readonly waiting: ServiceWorker | null; + getNotifications(filter?: GetNotificationOptions): Promise; + showNotification(title: string, options?: NotificationOptions): Promise; + unregister(): Promise; + update(): Promise; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ServiceWorkerRegistration: { + prototype: ServiceWorkerRegistration; + new(): ServiceWorkerRegistration; +}; + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + readonly audioTracks: AudioTrackList; + readonly buffered: TimeRanges; + mode: AppendMode; + timestampOffset: number; + readonly updating: boolean; + readonly videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechSynthesisEventMap { + "voiceschanged": Event; +} + +interface SpeechSynthesis extends EventTarget { + onvoiceschanged: (this: SpeechSynthesis, ev: Event) => any; + readonly paused: boolean; + readonly pending: boolean; + readonly speaking: boolean; + cancel(): void; + getVoices(): SpeechSynthesisVoice[]; + pause(): void; + resume(): void; + speak(utterance: SpeechSynthesisUtterance): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SpeechSynthesis: { + prototype: SpeechSynthesis; + new(): SpeechSynthesis; +}; + +interface SpeechSynthesisEvent extends Event { + readonly charIndex: number; + readonly elapsedTime: number; + readonly name: string; + readonly utterance: SpeechSynthesisUtterance | null; +} + +declare var SpeechSynthesisEvent: { + prototype: SpeechSynthesisEvent; + new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; +}; + +interface SpeechSynthesisUtteranceEventMap { + "boundary": Event; + "end": Event; + "error": Event; + "mark": Event; + "pause": Event; + "resume": Event; + "start": Event; +} + +interface SpeechSynthesisUtterance extends EventTarget { + lang: string; + onboundary: (this: SpeechSynthesisUtterance, ev: Event) => any; + onend: (this: SpeechSynthesisUtterance, ev: Event) => any; + onerror: (this: SpeechSynthesisUtterance, ev: Event) => any; + onmark: (this: SpeechSynthesisUtterance, ev: Event) => any; + onpause: (this: SpeechSynthesisUtterance, ev: Event) => any; + onresume: (this: SpeechSynthesisUtterance, ev: Event) => any; + onstart: (this: SpeechSynthesisUtterance, ev: Event) => any; + pitch: number; + rate: number; + text: string; + voice: SpeechSynthesisVoice; + volume: number; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SpeechSynthesisUtterance: { + prototype: SpeechSynthesisUtterance; + new(text?: string): SpeechSynthesisUtterance; +}; + +interface SpeechSynthesisVoice { + readonly default: boolean; + readonly lang: string; + readonly localService: boolean; + readonly name: string; + readonly voiceURI: string; +} + +declare var SpeechSynthesisVoice: { + prototype: SpeechSynthesisVoice; + new(): SpeechSynthesisVoice; +}; + +interface StereoPannerNode extends AudioNode { + readonly pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +}; + +interface Storage { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +}; + +interface StorageEvent extends Event { + readonly url: string; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +}; + +interface StyleMedia { + readonly type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +}; + +interface StyleSheet { + disabled: boolean; + readonly href: string; + readonly media: MediaList; + readonly ownerNode: Node; + readonly parentStyleSheet: StyleSheet; + readonly title: string; + readonly type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +}; + +interface StyleSheetList { + readonly length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +}; + +interface StyleSheetPageList { + readonly length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +}; + +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + +interface SVGAElement extends SVGGraphicsElement, SVGURIReference { + readonly target: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +}; + +interface SVGAngle { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +} + +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + readonly SVG_ANGLETYPE_DEG: number; + readonly SVG_ANGLETYPE_GRAD: number; + readonly SVG_ANGLETYPE_RAD: number; + readonly SVG_ANGLETYPE_UNKNOWN: number; + readonly SVG_ANGLETYPE_UNSPECIFIED: number; +}; + +interface SVGAnimatedAngle { + readonly animVal: SVGAngle; + readonly baseVal: SVGAngle; +} + +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +}; + +interface SVGAnimatedBoolean { + readonly animVal: boolean; + baseVal: boolean; +} + +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +}; + +interface SVGAnimatedEnumeration { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +}; + +interface SVGAnimatedInteger { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +}; + +interface SVGAnimatedLength { + readonly animVal: SVGLength; + readonly baseVal: SVGLength; +} + +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +}; + +interface SVGAnimatedLengthList { + readonly animVal: SVGLengthList; + readonly baseVal: SVGLengthList; +} + +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +}; + +interface SVGAnimatedNumber { + readonly animVal: number; + baseVal: number; +} + +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +}; + +interface SVGAnimatedNumberList { + readonly animVal: SVGNumberList; + readonly baseVal: SVGNumberList; +} + +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +}; + +interface SVGAnimatedPreserveAspectRatio { + readonly animVal: SVGPreserveAspectRatio; + readonly baseVal: SVGPreserveAspectRatio; +} + +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +}; + +interface SVGAnimatedRect { + readonly animVal: SVGRect; + readonly baseVal: SVGRect; +} + +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +}; + +interface SVGAnimatedString { + readonly animVal: string; + baseVal: string; +} + +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +}; + +interface SVGAnimatedTransformList { + readonly animVal: SVGTransformList; + readonly baseVal: SVGTransformList; +} + +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +}; + +interface SVGCircleElement extends SVGGraphicsElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +}; + +interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { + readonly clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +}; + +interface SVGComponentTransferFunctionElement extends SVGElement { + readonly amplitude: SVGAnimatedNumber; + readonly exponent: SVGAnimatedNumber; + readonly intercept: SVGAnimatedNumber; + readonly offset: SVGAnimatedNumber; + readonly slope: SVGAnimatedNumber; + readonly tableValues: SVGAnimatedNumberList; + readonly type: SVGAnimatedEnumeration; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +}; + +interface SVGDefsElement extends SVGGraphicsElement { + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +}; + +interface SVGDescElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +}; + +interface SVGElementEventMap extends ElementEventMap { + "click": MouseEvent; + "dblclick": MouseEvent; + "focusin": FocusEvent; + "focusout": FocusEvent; + "load": Event; + "mousedown": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; +} + +interface SVGElement extends Element { + className: any; + onclick: (this: SVGElement, ev: MouseEvent) => any; + ondblclick: (this: SVGElement, ev: MouseEvent) => any; + onfocusin: (this: SVGElement, ev: FocusEvent) => any; + onfocusout: (this: SVGElement, ev: FocusEvent) => any; + onload: (this: SVGElement, ev: Event) => any; + onmousedown: (this: SVGElement, ev: MouseEvent) => any; + onmousemove: (this: SVGElement, ev: MouseEvent) => any; + onmouseout: (this: SVGElement, ev: MouseEvent) => any; + onmouseover: (this: SVGElement, ev: MouseEvent) => any; + onmouseup: (this: SVGElement, ev: MouseEvent) => any; + readonly ownerSVGElement: SVGSVGElement; + readonly style: CSSStyleDeclaration; + readonly viewportElement: SVGElement; + xmlbase: string; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +}; + +interface SVGElementInstance extends EventTarget { + readonly childNodes: SVGElementInstanceList; + readonly correspondingElement: SVGElement; + readonly correspondingUseElement: SVGUseElement; + readonly firstChild: SVGElementInstance; + readonly lastChild: SVGElementInstance; + readonly nextSibling: SVGElementInstance; + readonly parentNode: SVGElementInstance; + readonly previousSibling: SVGElementInstance; +} + +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +}; + +interface SVGElementInstanceList { + readonly length: number; + item(index: number): SVGElementInstance; +} + +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +}; + +interface SVGEllipseElement extends SVGGraphicsElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +}; + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly mode: SVGAnimatedEnumeration; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + readonly SVG_FEBLEND_MODE_COLOR: number; + readonly SVG_FEBLEND_MODE_COLOR_BURN: number; + readonly SVG_FEBLEND_MODE_COLOR_DODGE: number; + readonly SVG_FEBLEND_MODE_DARKEN: number; + readonly SVG_FEBLEND_MODE_DIFFERENCE: number; + readonly SVG_FEBLEND_MODE_EXCLUSION: number; + readonly SVG_FEBLEND_MODE_HARD_LIGHT: number; + readonly SVG_FEBLEND_MODE_HUE: number; + readonly SVG_FEBLEND_MODE_LIGHTEN: number; + readonly SVG_FEBLEND_MODE_LUMINOSITY: number; + readonly SVG_FEBLEND_MODE_MULTIPLY: number; + readonly SVG_FEBLEND_MODE_NORMAL: number; + readonly SVG_FEBLEND_MODE_OVERLAY: number; + readonly SVG_FEBLEND_MODE_SATURATION: number; + readonly SVG_FEBLEND_MODE_SCREEN: number; + readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; + readonly SVG_FEBLEND_MODE_UNKNOWN: number; +}; + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly type: SVGAnimatedEnumeration; + readonly values: SVGAnimatedNumberList; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; + readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; + readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; +}; + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +}; + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly k1: SVGAnimatedNumber; + readonly k2: SVGAnimatedNumber; + readonly k3: SVGAnimatedNumber; + readonly k4: SVGAnimatedNumber; + readonly operator: SVGAnimatedEnumeration; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number; + readonly SVG_FECOMPOSITE_OPERATOR_IN: number; + readonly SVG_FECOMPOSITE_OPERATOR_OUT: number; + readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; + readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; +}; + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly bias: SVGAnimatedNumber; + readonly divisor: SVGAnimatedNumber; + readonly edgeMode: SVGAnimatedEnumeration; + readonly in1: SVGAnimatedString; + readonly kernelMatrix: SVGAnimatedNumberList; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly orderX: SVGAnimatedInteger; + readonly orderY: SVGAnimatedInteger; + readonly preserveAlpha: SVGAnimatedBoolean; + readonly targetX: SVGAnimatedInteger; + readonly targetY: SVGAnimatedInteger; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + readonly SVG_EDGEMODE_DUPLICATE: number; + readonly SVG_EDGEMODE_NONE: number; + readonly SVG_EDGEMODE_UNKNOWN: number; + readonly SVG_EDGEMODE_WRAP: number; +}; + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly diffuseConstant: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +}; + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly in2: SVGAnimatedString; + readonly scale: SVGAnimatedNumber; + readonly xChannelSelector: SVGAnimatedEnumeration; + readonly yChannelSelector: SVGAnimatedEnumeration; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + readonly SVG_CHANNEL_A: number; + readonly SVG_CHANNEL_B: number; + readonly SVG_CHANNEL_G: number; + readonly SVG_CHANNEL_R: number; + readonly SVG_CHANNEL_UNKNOWN: number; +}; + +interface SVGFEDistantLightElement extends SVGElement { + readonly azimuth: SVGAnimatedNumber; + readonly elevation: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +}; + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +}; + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +}; + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +}; + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +}; + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +}; + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly stdDeviationX: SVGAnimatedNumber; + readonly stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +}; + +interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +}; + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +}; + +interface SVGFEMergeNodeElement extends SVGElement { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +}; + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly operator: SVGAnimatedEnumeration; + readonly radiusX: SVGAnimatedNumber; + readonly radiusY: SVGAnimatedNumber; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; + readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; + readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; +}; + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly dx: SVGAnimatedNumber; + readonly dy: SVGAnimatedNumber; + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +}; + +interface SVGFEPointLightElement extends SVGElement { + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +}; + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + readonly kernelUnitLengthX: SVGAnimatedNumber; + readonly kernelUnitLengthY: SVGAnimatedNumber; + readonly specularConstant: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly surfaceScale: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +}; + +interface SVGFESpotLightElement extends SVGElement { + readonly limitingConeAngle: SVGAnimatedNumber; + readonly pointsAtX: SVGAnimatedNumber; + readonly pointsAtY: SVGAnimatedNumber; + readonly pointsAtZ: SVGAnimatedNumber; + readonly specularExponent: SVGAnimatedNumber; + readonly x: SVGAnimatedNumber; + readonly y: SVGAnimatedNumber; + readonly z: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +}; + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly in1: SVGAnimatedString; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +}; + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + readonly baseFrequencyX: SVGAnimatedNumber; + readonly baseFrequencyY: SVGAnimatedNumber; + readonly numOctaves: SVGAnimatedInteger; + readonly seed: SVGAnimatedNumber; + readonly stitchTiles: SVGAnimatedEnumeration; + readonly type: SVGAnimatedEnumeration; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + readonly SVG_STITCHTYPE_NOSTITCH: number; + readonly SVG_STITCHTYPE_STITCH: number; + readonly SVG_STITCHTYPE_UNKNOWN: number; + readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; + readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; +}; + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { + readonly filterResX: SVGAnimatedInteger; + readonly filterResY: SVGAnimatedInteger; + readonly filterUnits: SVGAnimatedEnumeration; + readonly height: SVGAnimatedLength; + readonly primitiveUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +}; + +interface SVGForeignObjectElement extends SVGGraphicsElement { + readonly height: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGForeignObjectElement: { + prototype: SVGForeignObjectElement; + new(): SVGForeignObjectElement; +}; + +interface SVGGElement extends SVGGraphicsElement { + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +}; + +interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { + readonly gradientTransform: SVGAnimatedTransformList; + readonly gradientUnits: SVGAnimatedEnumeration; + readonly spreadMethod: SVGAnimatedEnumeration; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + readonly SVG_SPREADMETHOD_PAD: number; + readonly SVG_SPREADMETHOD_REFLECT: number; + readonly SVG_SPREADMETHOD_REPEAT: number; + readonly SVG_SPREADMETHOD_UNKNOWN: number; +}; + +interface SVGGraphicsElement extends SVGElement, SVGTests { + readonly farthestViewportElement: SVGElement; + readonly nearestViewportElement: SVGElement; + readonly transform: SVGAnimatedTransformList; + getBBox(): SVGRect; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; + getTransformToElement(element: SVGElement): SVGMatrix; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGraphicsElement: { + prototype: SVGGraphicsElement; + new(): SVGGraphicsElement; +}; + +interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +}; + +interface SVGLength { + readonly unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +} + +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + readonly SVG_LENGTHTYPE_CM: number; + readonly SVG_LENGTHTYPE_EMS: number; + readonly SVG_LENGTHTYPE_EXS: number; + readonly SVG_LENGTHTYPE_IN: number; + readonly SVG_LENGTHTYPE_MM: number; + readonly SVG_LENGTHTYPE_NUMBER: number; + readonly SVG_LENGTHTYPE_PC: number; + readonly SVG_LENGTHTYPE_PERCENTAGE: number; + readonly SVG_LENGTHTYPE_PT: number; + readonly SVG_LENGTHTYPE_PX: number; + readonly SVG_LENGTHTYPE_UNKNOWN: number; +}; + +interface SVGLengthList { + readonly numberOfItems: number; + appendItem(newItem: SVGLength): SVGLength; + clear(): void; + getItem(index: number): SVGLength; + initialize(newItem: SVGLength): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; + removeItem(index: number): SVGLength; + replaceItem(newItem: SVGLength, index: number): SVGLength; +} + +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +}; + +interface SVGLinearGradientElement extends SVGGradientElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +}; + +interface SVGLineElement extends SVGGraphicsElement { + readonly x1: SVGAnimatedLength; + readonly x2: SVGAnimatedLength; + readonly y1: SVGAnimatedLength; + readonly y2: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +}; + +interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { + readonly markerHeight: SVGAnimatedLength; + readonly markerUnits: SVGAnimatedEnumeration; + readonly markerWidth: SVGAnimatedLength; + readonly orientAngle: SVGAnimatedAngle; + readonly orientType: SVGAnimatedEnumeration; + readonly refX: SVGAnimatedLength; + readonly refY: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + readonly SVG_MARKER_ORIENT_ANGLE: number; + readonly SVG_MARKER_ORIENT_AUTO: number; + readonly SVG_MARKER_ORIENT_UNKNOWN: number; + readonly SVG_MARKERUNITS_STROKEWIDTH: number; + readonly SVG_MARKERUNITS_UNKNOWN: number; + readonly SVG_MARKERUNITS_USERSPACEONUSE: number; +}; + +interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { + readonly height: SVGAnimatedLength; + readonly maskContentUnits: SVGAnimatedEnumeration; + readonly maskUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +}; + +interface SVGMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + flipX(): SVGMatrix; + flipY(): SVGMatrix; + inverse(): SVGMatrix; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + rotate(angle: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + skewX(angle: number): SVGMatrix; + skewY(angle: number): SVGMatrix; + translate(x: number, y: number): SVGMatrix; +} + +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +}; + +interface SVGMetadataElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +}; + +interface SVGNumber { + value: number; +} + +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +}; + +interface SVGNumberList { + readonly numberOfItems: number; + appendItem(newItem: SVGNumber): SVGNumber; + clear(): void; + getItem(index: number): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; + removeItem(index: number): SVGNumber; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; +} + +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +}; + +interface SVGPathElement extends SVGGraphicsElement { + readonly pathSegList: SVGPathSegList; + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + getTotalLength(): number; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +}; + +interface SVGPathSeg { + readonly pathSegType: number; + readonly pathSegTypeAsLetter: string; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +} + +declare var SVGPathSeg: { + prototype: SVGPathSeg; + new(): SVGPathSeg; + readonly PATHSEG_ARC_ABS: number; + readonly PATHSEG_ARC_REL: number; + readonly PATHSEG_CLOSEPATH: number; + readonly PATHSEG_CURVETO_CUBIC_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_REL: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_REL: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + readonly PATHSEG_LINETO_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_ABS: number; + readonly PATHSEG_LINETO_HORIZONTAL_REL: number; + readonly PATHSEG_LINETO_REL: number; + readonly PATHSEG_LINETO_VERTICAL_ABS: number; + readonly PATHSEG_LINETO_VERTICAL_REL: number; + readonly PATHSEG_MOVETO_ABS: number; + readonly PATHSEG_MOVETO_REL: number; + readonly PATHSEG_UNKNOWN: number; +}; + +interface SVGPathSegArcAbs extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +}; + +interface SVGPathSegArcRel extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +}; + +interface SVGPathSegClosePath extends SVGPathSeg { +} + +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +}; + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +}; + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +}; + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +}; + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +}; + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +}; + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +}; + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +}; + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +}; + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +}; + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +}; + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +}; + +interface SVGPathSegLinetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +}; + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +}; + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +}; + +interface SVGPathSegList { + readonly numberOfItems: number; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + clear(): void; + getItem(index: number): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; +} + +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +}; + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +}; + +interface SVGPathSegMovetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +}; + +interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { + readonly height: SVGAnimatedLength; + readonly patternContentUnits: SVGAnimatedEnumeration; + readonly patternTransform: SVGAnimatedTransformList; + readonly patternUnits: SVGAnimatedEnumeration; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +}; + +interface SVGPoint { + x: number; + y: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} + +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +}; + +interface SVGPointList { + readonly numberOfItems: number; + appendItem(newItem: SVGPoint): SVGPoint; + clear(): void; + getItem(index: number): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; + removeItem(index: number): SVGPoint; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; +} + +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +}; + +interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +}; + +interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +}; + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + readonly SVG_MEETORSLICE_MEET: number; + readonly SVG_MEETORSLICE_SLICE: number; + readonly SVG_MEETORSLICE_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_NONE: number; + readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number; + readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +}; + +interface SVGRadialGradientElement extends SVGGradientElement { + readonly cx: SVGAnimatedLength; + readonly cy: SVGAnimatedLength; + readonly fx: SVGAnimatedLength; + readonly fy: SVGAnimatedLength; + readonly r: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +}; + +interface SVGRect { + height: number; + width: number; + x: number; + y: number; +} + +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +}; + +interface SVGRectElement extends SVGGraphicsElement { + readonly height: SVGAnimatedLength; + readonly rx: SVGAnimatedLength; + readonly ry: SVGAnimatedLength; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +}; + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +}; + +interface SVGStopElement extends SVGElement { + readonly offset: SVGAnimatedNumber; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +}; + +interface SVGStringList { + readonly numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +}; + +interface SVGStyleElement extends SVGElement { + disabled: boolean; + media: string; + title: string; + type: string; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +}; + +interface SVGSVGElementEventMap extends SVGElementEventMap { + "SVGAbort": Event; + "SVGError": Event; + "resize": UIEvent; + "scroll": UIEvent; + "SVGUnload": Event; + "SVGZoom": SVGZoomEvent; +} + +interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { + contentScriptType: string; + contentStyleType: string; + currentScale: number; + readonly currentTranslate: SVGPoint; + readonly height: SVGAnimatedLength; + onabort: (this: SVGSVGElement, ev: Event) => any; + onerror: (this: SVGSVGElement, ev: Event) => any; + onresize: (this: SVGSVGElement, ev: UIEvent) => any; + onscroll: (this: SVGSVGElement, ev: UIEvent) => any; + onunload: (this: SVGSVGElement, ev: Event) => any; + onzoom: (this: SVGSVGElement, ev: SVGZoomEvent) => any; + readonly pixelUnitToMillimeterX: number; + readonly pixelUnitToMillimeterY: number; + readonly screenPixelToMillimeterX: number; + readonly screenPixelToMillimeterY: number; + readonly viewport: SVGRect; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + createSVGAngle(): SVGAngle; + createSVGLength(): SVGLength; + createSVGMatrix(): SVGMatrix; + createSVGNumber(): SVGNumber; + createSVGPoint(): SVGPoint; + createSVGRect(): SVGRect; + createSVGTransform(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + deselectAll(): void; + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf; + pauseAnimations(): void; + setCurrentTime(seconds: number): void; + suspendRedraw(maxWaitMilliseconds: number): number; + unpauseAnimations(): void; + unsuspendRedraw(suspendHandleID: number): void; + unsuspendRedrawAll(): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +}; + +interface SVGSwitchElement extends SVGGraphicsElement { + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +}; + +interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +}; + +interface SVGTextContentElement extends SVGGraphicsElement { + readonly lengthAdjust: SVGAnimatedEnumeration; + readonly textLength: SVGAnimatedLength; + getCharNumAtPosition(point: SVGPoint): number; + getComputedTextLength(): number; + getEndPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + readonly LENGTHADJUST_SPACING: number; + readonly LENGTHADJUST_SPACINGANDGLYPHS: number; + readonly LENGTHADJUST_UNKNOWN: number; +}; + +interface SVGTextElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +}; + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + readonly method: SVGAnimatedEnumeration; + readonly spacing: SVGAnimatedEnumeration; + readonly startOffset: SVGAnimatedLength; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + readonly TEXTPATH_METHODTYPE_ALIGN: number; + readonly TEXTPATH_METHODTYPE_STRETCH: number; + readonly TEXTPATH_METHODTYPE_UNKNOWN: number; + readonly TEXTPATH_SPACINGTYPE_AUTO: number; + readonly TEXTPATH_SPACINGTYPE_EXACT: number; + readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; +}; + +interface SVGTextPositioningElement extends SVGTextContentElement { + readonly dx: SVGAnimatedLengthList; + readonly dy: SVGAnimatedLengthList; + readonly rotate: SVGAnimatedNumberList; + readonly x: SVGAnimatedLengthList; + readonly y: SVGAnimatedLengthList; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +}; + +interface SVGTitleElement extends SVGElement { + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +}; + +interface SVGTransform { + readonly angle: number; + readonly matrix: SVGMatrix; + readonly type: number; + setMatrix(matrix: SVGMatrix): void; + setRotate(angle: number, cx: number, cy: number): void; + setScale(sx: number, sy: number): void; + setSkewX(angle: number): void; + setSkewY(angle: number): void; + setTranslate(tx: number, ty: number): void; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +} + +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + readonly SVG_TRANSFORM_MATRIX: number; + readonly SVG_TRANSFORM_ROTATE: number; + readonly SVG_TRANSFORM_SCALE: number; + readonly SVG_TRANSFORM_SKEWX: number; + readonly SVG_TRANSFORM_SKEWY: number; + readonly SVG_TRANSFORM_TRANSLATE: number; + readonly SVG_TRANSFORM_UNKNOWN: number; +}; + +interface SVGTransformList { + readonly numberOfItems: number; + appendItem(newItem: SVGTransform): SVGTransform; + clear(): void; + consolidate(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getItem(index: number): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + removeItem(index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; +} + +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +}; + +interface SVGTSpanElement extends SVGTextPositioningElement { + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +}; + +interface SVGUnitTypes { + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: SVGUnitTypes; + +interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { + readonly animatedInstanceRoot: SVGElementInstance; + readonly height: SVGAnimatedLength; + readonly instanceRoot: SVGElementInstance; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +}; + +interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { + readonly viewTarget: SVGStringList; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +}; + +interface SVGZoomAndPan { + readonly zoomAndPan: number; +} + +declare var SVGZoomAndPan: { + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; +}; + +interface SVGZoomEvent extends UIEvent { + readonly newScale: number; + readonly newTranslate: SVGPoint; + readonly previousScale: number; + readonly previousTranslate: SVGPoint; + readonly zoomRectScreen: SVGRect; +} + +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +}; + +interface SyncManager { + getTags(): Promise; + register(tag: string): Promise; +} + +declare var SyncManager: { + prototype: SyncManager; + new(): SyncManager; +}; + +interface Text extends CharacterData { + readonly wholeText: string; + readonly assignedSlot: HTMLSlotElement | null; + splitText(offset: number): Text; +} + +declare var Text: { + prototype: Text; + new(data?: string): Text; +}; + +interface TextEvent extends UIEvent { + readonly data: string; + readonly inputMethod: number; + readonly locale: string; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +} + +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + readonly DOM_INPUT_METHOD_DROP: number; + readonly DOM_INPUT_METHOD_HANDWRITING: number; + readonly DOM_INPUT_METHOD_IME: number; + readonly DOM_INPUT_METHOD_KEYBOARD: number; + readonly DOM_INPUT_METHOD_MULTIMODAL: number; + readonly DOM_INPUT_METHOD_OPTION: number; + readonly DOM_INPUT_METHOD_PASTE: number; + readonly DOM_INPUT_METHOD_SCRIPT: number; + readonly DOM_INPUT_METHOD_UNKNOWN: number; + readonly DOM_INPUT_METHOD_VOICE: number; +}; + +interface TextMetrics { + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +}; + +interface TextTrackEventMap { + "cuechange": Event; + "error": Event; + "load": Event; +} + +interface TextTrack extends EventTarget { + readonly activeCues: TextTrackCueList; + readonly cues: TextTrackCueList; + readonly inBandMetadataTrackDispatchType: string; + readonly kind: string; + readonly label: string; + readonly language: string; + mode: any; + oncuechange: (this: TextTrack, ev: Event) => any; + onerror: (this: TextTrack, ev: Event) => any; + onload: (this: TextTrack, ev: Event) => any; + readonly readyState: number; + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + readonly DISABLED: number; + readonly ERROR: number; + readonly HIDDEN: number; + readonly LOADED: number; + readonly LOADING: number; + readonly NONE: number; + readonly SHOWING: number; +}; + +interface TextTrackCueEventMap { + "enter": Event; + "exit": Event; +} + +interface TextTrackCue extends EventTarget { + endTime: number; + id: string; + onenter: (this: TextTrackCue, ev: Event) => any; + onexit: (this: TextTrackCue, ev: Event) => any; + pauseOnExit: boolean; + startTime: number; + text: string; + readonly track: TextTrack; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var TextTrackCue: { + prototype: TextTrackCue; + new(startTime: number, endTime: number, text: string): TextTrackCue; +}; + +interface TextTrackCueList { + readonly length: number; + getCueById(id: string): TextTrackCue; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; +} + +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +}; + +interface TextTrackListEventMap { + "addtrack": TrackEvent; +} + +interface TextTrackList extends EventTarget { + readonly length: number; + onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; + item(index: number): TextTrack; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: TextTrack; +} + +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +}; + +interface TimeRanges { + readonly length: number; + end(index: number): number; + start(index: number): number; +} + +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +}; + +interface Touch { + readonly clientX: number; + readonly clientY: number; + readonly identifier: number; + readonly pageX: number; + readonly pageY: number; + readonly screenX: number; + readonly screenY: number; + readonly target: EventTarget; +} + +declare var Touch: { + prototype: Touch; + new(): Touch; +}; + +interface TouchEvent extends UIEvent { + readonly altKey: boolean; + readonly changedTouches: TouchList; + readonly charCode: number; + readonly ctrlKey: boolean; + readonly keyCode: number; + readonly metaKey: boolean; + readonly shiftKey: boolean; + readonly targetTouches: TouchList; + readonly touches: TouchList; + readonly which: number; +} + +declare var TouchEvent: { + prototype: TouchEvent; + new(type: string, touchEventInit?: TouchEventInit): TouchEvent; +}; + +interface TouchList { + readonly length: number; + item(index: number): Touch | null; + [index: number]: Touch; +} + +declare var TouchList: { + prototype: TouchList; + new(): TouchList; +}; + +interface TrackEvent extends Event { + readonly track: VideoTrack | AudioTrack | TextTrack | null; +} + +declare var TrackEvent: { + prototype: TrackEvent; + new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; +}; + +interface TransitionEvent extends Event { + readonly elapsedTime: number; + readonly propertyName: string; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +declare var TransitionEvent: { + prototype: TransitionEvent; + new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; +}; + +interface TreeWalker { + currentNode: Node; + readonly expandEntityReferences: boolean; + readonly filter: NodeFilter; + readonly root: Node; + readonly whatToShow: number; + firstChild(): Node; + lastChild(): Node; + nextNode(): Node; + nextSibling(): Node; + parentNode(): Node; + previousNode(): Node; + previousSibling(): Node; +} + +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +}; + +interface UIEvent extends Event { + readonly detail: number; + readonly view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} + +declare var UIEvent: { + prototype: UIEvent; + new(typeArg: string, eventInitDict?: UIEventInit): UIEvent; +}; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + readonly mediaType: string; +} + +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +}; + +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + username: string; + readonly searchParams: URLSearchParams; + toString(): string; +} + +declare var URL: { + prototype: URL; + new(url: string, base?: string): URL; + createObjectURL(object: any, options?: ObjectURLOptions): string; + revokeObjectURL(url: string): void; +}; + +interface ValidityState { + readonly badInput: boolean; + readonly customError: boolean; + readonly patternMismatch: boolean; + readonly rangeOverflow: boolean; + readonly rangeUnderflow: boolean; + readonly stepMismatch: boolean; + readonly tooLong: boolean; + readonly typeMismatch: boolean; + readonly valid: boolean; + readonly valueMissing: boolean; + readonly tooShort: boolean; +} + +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +}; + +interface VideoPlaybackQuality { + readonly corruptedVideoFrames: number; + readonly creationTime: number; + readonly droppedVideoFrames: number; + readonly totalFrameDelay: number; + readonly totalVideoFrames: number; +} + +declare var VideoPlaybackQuality: { + prototype: VideoPlaybackQuality; + new(): VideoPlaybackQuality; +}; + +interface VideoTrack { + readonly id: string; + kind: string; + readonly label: string; + language: string; + selected: boolean; + readonly sourceBuffer: SourceBuffer; +} + +declare var VideoTrack: { + prototype: VideoTrack; + new(): VideoTrack; +}; + +interface VideoTrackListEventMap { + "addtrack": TrackEvent; + "change": Event; + "removetrack": TrackEvent; +} + +interface VideoTrackList extends EventTarget { + readonly length: number; + onaddtrack: (this: VideoTrackList, ev: TrackEvent) => any; + onchange: (this: VideoTrackList, ev: Event) => any; + onremovetrack: (this: VideoTrackList, ev: TrackEvent) => any; + readonly selectedIndex: number; + getTrackById(id: string): VideoTrack | null; + item(index: number): VideoTrack; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: VideoTrack; +} + +declare var VideoTrackList: { + prototype: VideoTrackList; + new(): VideoTrackList; +}; + +interface WaveShaperNode extends AudioNode { + curve: Float32Array | null; + oversample: OverSampleType; +} + +declare var WaveShaperNode: { + prototype: WaveShaperNode; + new(): WaveShaperNode; +}; + +interface WebAuthentication { + getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; +} + +declare var WebAuthentication: { + prototype: WebAuthentication; + new(): WebAuthentication; +}; + +interface WebAuthnAssertion { + readonly authenticatorData: ArrayBuffer; + readonly clientData: ArrayBuffer; + readonly credential: ScopedCredential; + readonly signature: ArrayBuffer; +} + +declare var WebAuthnAssertion: { + prototype: WebAuthnAssertion; + new(): WebAuthnAssertion; +}; + +interface WEBGL_compressed_texture_s3tc { + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number; +}; + +interface WEBGL_debug_renderer_info { + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + readonly UNMASKED_RENDERER_WEBGL: number; + readonly UNMASKED_VENDOR_WEBGL: number; +}; + +interface WEBGL_depth_texture { + readonly UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + readonly UNSIGNED_INT_24_8_WEBGL: number; +}; + +interface WebGLActiveInfo { + readonly name: string; + readonly size: number; + readonly type: number; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +}; + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +}; + +interface WebGLContextEvent extends Event { + readonly statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; +}; + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +}; + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +}; + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +}; + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +}; + +interface WebGLRenderingContext { + readonly canvas: HTMLCanvasElement; + readonly drawingBufferHeight: number; + readonly drawingBufferWidth: number; + activeTexture(texture: number): void; + attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; + bindBuffer(target: number, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: number, texture: WebGLTexture | null): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + blendEquation(mode: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + blendFunc(sfactor: number, dfactor: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; + checkFramebufferStatus(target: number): number; + clear(mask: number): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + clearDepth(depth: number): void; + clearStencil(s: number): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compileShader(shader: WebGLShader | null): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + createBuffer(): WebGLBuffer | null; + createFramebuffer(): WebGLFramebuffer | null; + createProgram(): WebGLProgram | null; + createRenderbuffer(): WebGLRenderbuffer | null; + createShader(type: number): WebGLShader | null; + createTexture(): WebGLTexture | null; + cullFace(mode: number): void; + deleteBuffer(buffer: WebGLBuffer | null): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; + deleteProgram(program: WebGLProgram | null): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; + deleteShader(shader: WebGLShader | null): void; + deleteTexture(texture: WebGLTexture | null): void; + depthFunc(func: number): void; + depthMask(flag: boolean): void; + depthRange(zNear: number, zFar: number): void; + detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; + disable(cap: number): void; + disableVertexAttribArray(index: number): void; + drawArrays(mode: number, first: number, count: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + enable(cap: number): void; + enableVertexAttribArray(index: number): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; + frontFace(mode: number): void; + generateMipmap(target: number): void; + getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram | null, name: string): number; + getBufferParameter(target: number, pname: number): any; + getContextAttributes(): WebGLContextAttributes; + getError(): number; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + getParameter(pname: number): any; + getProgramInfoLog(program: WebGLProgram | null): string | null; + getProgramParameter(program: WebGLProgram | null, pname: number): any; + getRenderbufferParameter(target: number, pname: number): any; + getShaderInfoLog(shader: WebGLShader | null): string | null; + getShaderParameter(shader: WebGLShader | null, pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader | null): string | null; + getSupportedExtensions(): string[] | null; + getTexParameter(target: number, pname: number): any; + getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; + getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: number, pname: number): any; + getVertexAttribOffset(index: number, pname: number): number; + hint(target: number, mode: number): void; + isBuffer(buffer: WebGLBuffer | null): boolean; + isContextLost(): boolean; + isEnabled(cap: number): boolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; + isProgram(program: WebGLProgram | null): boolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; + isShader(shader: WebGLShader | null): boolean; + isTexture(texture: WebGLTexture | null): boolean; + lineWidth(width: number): void; + linkProgram(program: WebGLProgram | null): void; + pixelStorei(pname: number, param: number | boolean): void; + polygonOffset(factor: number, units: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + sampleCoverage(value: number, invert: boolean): void; + scissor(x: number, y: number, width: number, height: number): void; + shaderSource(shader: WebGLShader | null, source: string): void; + stencilFunc(func: number, ref: number, mask: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + stencilMask(mask: number): void; + stencilMaskSeparate(face: number, mask: number): void; + stencilOp(fail: number, zfail: number, zpass: number): void; + stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView | null): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; + texParameterf(target: number, pname: number, param: number): void; + texParameteri(target: number, pname: number, param: number): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; + uniform1f(location: WebGLUniformLocation | null, x: number): void; + uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform1i(location: WebGLUniformLocation | null, x: number): void; + uniform1iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; + uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array | number[]): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | number[]): void; + useProgram(program: WebGLProgram | null): void; + validateProgram(program: WebGLProgram | null): void; + vertexAttrib1f(indx: number, x: number): void; + vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib2f(indx: number, x: number, y: number): void; + vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + viewport(x: number, y: number, width: number, height: number): void; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NO_ERROR: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB5_A1: number; + readonly RGB565: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: number; + readonly ACTIVE_TEXTURE: number; + readonly ACTIVE_UNIFORMS: number; + readonly ALIASED_LINE_WIDTH_RANGE: number; + readonly ALIASED_POINT_SIZE_RANGE: number; + readonly ALPHA: number; + readonly ALPHA_BITS: number; + readonly ALWAYS: number; + readonly ARRAY_BUFFER: number; + readonly ARRAY_BUFFER_BINDING: number; + readonly ATTACHED_SHADERS: number; + readonly BACK: number; + readonly BLEND: number; + readonly BLEND_COLOR: number; + readonly BLEND_DST_ALPHA: number; + readonly BLEND_DST_RGB: number; + readonly BLEND_EQUATION: number; + readonly BLEND_EQUATION_ALPHA: number; + readonly BLEND_EQUATION_RGB: number; + readonly BLEND_SRC_ALPHA: number; + readonly BLEND_SRC_RGB: number; + readonly BLUE_BITS: number; + readonly BOOL: number; + readonly BOOL_VEC2: number; + readonly BOOL_VEC3: number; + readonly BOOL_VEC4: number; + readonly BROWSER_DEFAULT_WEBGL: number; + readonly BUFFER_SIZE: number; + readonly BUFFER_USAGE: number; + readonly BYTE: number; + readonly CCW: number; + readonly CLAMP_TO_EDGE: number; + readonly COLOR_ATTACHMENT0: number; + readonly COLOR_BUFFER_BIT: number; + readonly COLOR_CLEAR_VALUE: number; + readonly COLOR_WRITEMASK: number; + readonly COMPILE_STATUS: number; + readonly COMPRESSED_TEXTURE_FORMATS: number; + readonly CONSTANT_ALPHA: number; + readonly CONSTANT_COLOR: number; + readonly CONTEXT_LOST_WEBGL: number; + readonly CULL_FACE: number; + readonly CULL_FACE_MODE: number; + readonly CURRENT_PROGRAM: number; + readonly CURRENT_VERTEX_ATTRIB: number; + readonly CW: number; + readonly DECR: number; + readonly DECR_WRAP: number; + readonly DELETE_STATUS: number; + readonly DEPTH_ATTACHMENT: number; + readonly DEPTH_BITS: number; + readonly DEPTH_BUFFER_BIT: number; + readonly DEPTH_CLEAR_VALUE: number; + readonly DEPTH_COMPONENT: number; + readonly DEPTH_COMPONENT16: number; + readonly DEPTH_FUNC: number; + readonly DEPTH_RANGE: number; + readonly DEPTH_STENCIL: number; + readonly DEPTH_STENCIL_ATTACHMENT: number; + readonly DEPTH_TEST: number; + readonly DEPTH_WRITEMASK: number; + readonly DITHER: number; + readonly DONT_CARE: number; + readonly DST_ALPHA: number; + readonly DST_COLOR: number; + readonly DYNAMIC_DRAW: number; + readonly ELEMENT_ARRAY_BUFFER: number; + readonly ELEMENT_ARRAY_BUFFER_BINDING: number; + readonly EQUAL: number; + readonly FASTEST: number; + readonly FLOAT: number; + readonly FLOAT_MAT2: number; + readonly FLOAT_MAT3: number; + readonly FLOAT_MAT4: number; + readonly FLOAT_VEC2: number; + readonly FLOAT_VEC3: number; + readonly FLOAT_VEC4: number; + readonly FRAGMENT_SHADER: number; + readonly FRAMEBUFFER: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + readonly FRAMEBUFFER_BINDING: number; + readonly FRAMEBUFFER_COMPLETE: number; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + readonly FRAMEBUFFER_UNSUPPORTED: number; + readonly FRONT: number; + readonly FRONT_AND_BACK: number; + readonly FRONT_FACE: number; + readonly FUNC_ADD: number; + readonly FUNC_REVERSE_SUBTRACT: number; + readonly FUNC_SUBTRACT: number; + readonly GENERATE_MIPMAP_HINT: number; + readonly GEQUAL: number; + readonly GREATER: number; + readonly GREEN_BITS: number; + readonly HIGH_FLOAT: number; + readonly HIGH_INT: number; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; + readonly IMPLEMENTATION_COLOR_READ_TYPE: number; + readonly INCR: number; + readonly INCR_WRAP: number; + readonly INT: number; + readonly INT_VEC2: number; + readonly INT_VEC3: number; + readonly INT_VEC4: number; + readonly INVALID_ENUM: number; + readonly INVALID_FRAMEBUFFER_OPERATION: number; + readonly INVALID_OPERATION: number; + readonly INVALID_VALUE: number; + readonly INVERT: number; + readonly KEEP: number; + readonly LEQUAL: number; + readonly LESS: number; + readonly LINE_LOOP: number; + readonly LINE_STRIP: number; + readonly LINE_WIDTH: number; + readonly LINEAR: number; + readonly LINEAR_MIPMAP_LINEAR: number; + readonly LINEAR_MIPMAP_NEAREST: number; + readonly LINES: number; + readonly LINK_STATUS: number; + readonly LOW_FLOAT: number; + readonly LOW_INT: number; + readonly LUMINANCE: number; + readonly LUMINANCE_ALPHA: number; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; + readonly MAX_RENDERBUFFER_SIZE: number; + readonly MAX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_TEXTURE_SIZE: number; + readonly MAX_VARYING_VECTORS: number; + readonly MAX_VERTEX_ATTRIBS: number; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + readonly MAX_VERTEX_UNIFORM_VECTORS: number; + readonly MAX_VIEWPORT_DIMS: number; + readonly MEDIUM_FLOAT: number; + readonly MEDIUM_INT: number; + readonly MIRRORED_REPEAT: number; + readonly NEAREST: number; + readonly NEAREST_MIPMAP_LINEAR: number; + readonly NEAREST_MIPMAP_NEAREST: number; + readonly NEVER: number; + readonly NICEST: number; + readonly NO_ERROR: number; + readonly NONE: number; + readonly NOTEQUAL: number; + readonly ONE: number; + readonly ONE_MINUS_CONSTANT_ALPHA: number; + readonly ONE_MINUS_CONSTANT_COLOR: number; + readonly ONE_MINUS_DST_ALPHA: number; + readonly ONE_MINUS_DST_COLOR: number; + readonly ONE_MINUS_SRC_ALPHA: number; + readonly ONE_MINUS_SRC_COLOR: number; + readonly OUT_OF_MEMORY: number; + readonly PACK_ALIGNMENT: number; + readonly POINTS: number; + readonly POLYGON_OFFSET_FACTOR: number; + readonly POLYGON_OFFSET_FILL: number; + readonly POLYGON_OFFSET_UNITS: number; + readonly RED_BITS: number; + readonly RENDERBUFFER: number; + readonly RENDERBUFFER_ALPHA_SIZE: number; + readonly RENDERBUFFER_BINDING: number; + readonly RENDERBUFFER_BLUE_SIZE: number; + readonly RENDERBUFFER_DEPTH_SIZE: number; + readonly RENDERBUFFER_GREEN_SIZE: number; + readonly RENDERBUFFER_HEIGHT: number; + readonly RENDERBUFFER_INTERNAL_FORMAT: number; + readonly RENDERBUFFER_RED_SIZE: number; + readonly RENDERBUFFER_STENCIL_SIZE: number; + readonly RENDERBUFFER_WIDTH: number; + readonly RENDERER: number; + readonly REPEAT: number; + readonly REPLACE: number; + readonly RGB: number; + readonly RGB5_A1: number; + readonly RGB565: number; + readonly RGBA: number; + readonly RGBA4: number; + readonly SAMPLE_ALPHA_TO_COVERAGE: number; + readonly SAMPLE_BUFFERS: number; + readonly SAMPLE_COVERAGE: number; + readonly SAMPLE_COVERAGE_INVERT: number; + readonly SAMPLE_COVERAGE_VALUE: number; + readonly SAMPLER_2D: number; + readonly SAMPLER_CUBE: number; + readonly SAMPLES: number; + readonly SCISSOR_BOX: number; + readonly SCISSOR_TEST: number; + readonly SHADER_TYPE: number; + readonly SHADING_LANGUAGE_VERSION: number; + readonly SHORT: number; + readonly SRC_ALPHA: number; + readonly SRC_ALPHA_SATURATE: number; + readonly SRC_COLOR: number; + readonly STATIC_DRAW: number; + readonly STENCIL_ATTACHMENT: number; + readonly STENCIL_BACK_FAIL: number; + readonly STENCIL_BACK_FUNC: number; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; + readonly STENCIL_BACK_PASS_DEPTH_PASS: number; + readonly STENCIL_BACK_REF: number; + readonly STENCIL_BACK_VALUE_MASK: number; + readonly STENCIL_BACK_WRITEMASK: number; + readonly STENCIL_BITS: number; + readonly STENCIL_BUFFER_BIT: number; + readonly STENCIL_CLEAR_VALUE: number; + readonly STENCIL_FAIL: number; + readonly STENCIL_FUNC: number; + readonly STENCIL_INDEX: number; + readonly STENCIL_INDEX8: number; + readonly STENCIL_PASS_DEPTH_FAIL: number; + readonly STENCIL_PASS_DEPTH_PASS: number; + readonly STENCIL_REF: number; + readonly STENCIL_TEST: number; + readonly STENCIL_VALUE_MASK: number; + readonly STENCIL_WRITEMASK: number; + readonly STREAM_DRAW: number; + readonly SUBPIXEL_BITS: number; + readonly TEXTURE: number; + readonly TEXTURE_2D: number; + readonly TEXTURE_BINDING_2D: number; + readonly TEXTURE_BINDING_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; + readonly TEXTURE_MAG_FILTER: number; + readonly TEXTURE_MIN_FILTER: number; + readonly TEXTURE_WRAP_S: number; + readonly TEXTURE_WRAP_T: number; + readonly TEXTURE0: number; + readonly TEXTURE1: number; + readonly TEXTURE10: number; + readonly TEXTURE11: number; + readonly TEXTURE12: number; + readonly TEXTURE13: number; + readonly TEXTURE14: number; + readonly TEXTURE15: number; + readonly TEXTURE16: number; + readonly TEXTURE17: number; + readonly TEXTURE18: number; + readonly TEXTURE19: number; + readonly TEXTURE2: number; + readonly TEXTURE20: number; + readonly TEXTURE21: number; + readonly TEXTURE22: number; + readonly TEXTURE23: number; + readonly TEXTURE24: number; + readonly TEXTURE25: number; + readonly TEXTURE26: number; + readonly TEXTURE27: number; + readonly TEXTURE28: number; + readonly TEXTURE29: number; + readonly TEXTURE3: number; + readonly TEXTURE30: number; + readonly TEXTURE31: number; + readonly TEXTURE4: number; + readonly TEXTURE5: number; + readonly TEXTURE6: number; + readonly TEXTURE7: number; + readonly TEXTURE8: number; + readonly TEXTURE9: number; + readonly TRIANGLE_FAN: number; + readonly TRIANGLE_STRIP: number; + readonly TRIANGLES: number; + readonly UNPACK_ALIGNMENT: number; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + readonly UNPACK_FLIP_Y_WEBGL: number; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + readonly UNSIGNED_BYTE: number; + readonly UNSIGNED_INT: number; + readonly UNSIGNED_SHORT: number; + readonly UNSIGNED_SHORT_4_4_4_4: number; + readonly UNSIGNED_SHORT_5_5_5_1: number; + readonly UNSIGNED_SHORT_5_6_5: number; + readonly VALIDATE_STATUS: number; + readonly VENDOR: number; + readonly VERSION: number; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + readonly VERTEX_ATTRIB_ARRAY_POINTER: number; + readonly VERTEX_ATTRIB_ARRAY_SIZE: number; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; + readonly VERTEX_ATTRIB_ARRAY_TYPE: number; + readonly VERTEX_SHADER: number; + readonly VIEWPORT: number; + readonly ZERO: number; +}; + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +}; + +interface WebGLShaderPrecisionFormat { + readonly precision: number; + readonly rangeMax: number; + readonly rangeMin: number; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +}; + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +}; + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +}; + +interface WebKitCSSMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + inverse(): WebKitCSSMatrix; + multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; + rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; + setMatrixValue(value: string): void; + skewX(angle: number): WebKitCSSMatrix; + skewY(angle: number): WebKitCSSMatrix; + toString(): string; + translate(x: number, y: number, z?: number): WebKitCSSMatrix; +} + +declare var WebKitCSSMatrix: { + prototype: WebKitCSSMatrix; + new(text?: string): WebKitCSSMatrix; +}; + +interface WebKitDirectoryEntry extends WebKitEntry { + createReader(): WebKitDirectoryReader; +} + +declare var WebKitDirectoryEntry: { + prototype: WebKitDirectoryEntry; + new(): WebKitDirectoryEntry; +}; + +interface WebKitDirectoryReader { + readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; +} + +declare var WebKitDirectoryReader: { + prototype: WebKitDirectoryReader; + new(): WebKitDirectoryReader; +}; + +interface WebKitEntry { + readonly filesystem: WebKitFileSystem; + readonly fullPath: string; + readonly isDirectory: boolean; + readonly isFile: boolean; + readonly name: string; +} + +declare var WebKitEntry: { + prototype: WebKitEntry; + new(): WebKitEntry; +}; + +interface WebKitFileEntry extends WebKitEntry { + file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; +} + +declare var WebKitFileEntry: { + prototype: WebKitFileEntry; + new(): WebKitFileEntry; +}; + +interface WebKitFileSystem { + readonly name: string; + readonly root: WebKitDirectoryEntry; +} + +declare var WebKitFileSystem: { + prototype: WebKitFileSystem; + new(): WebKitFileSystem; +}; + +interface WebKitPoint { + x: number; + y: number; +} + +declare var WebKitPoint: { + prototype: WebKitPoint; + new(x?: number, y?: number): WebKitPoint; +}; + +interface webkitRTCPeerConnection extends RTCPeerConnection { + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new(configuration: RTCConfiguration): webkitRTCPeerConnection; +}; + +interface WebSocketEventMap { + "close": CloseEvent; + "error": Event; + "message": MessageEvent; + "open": Event; +} + +interface WebSocket extends EventTarget { + binaryType: string; + readonly bufferedAmount: number; + readonly extensions: string; + onclose: (this: WebSocket, ev: CloseEvent) => any; + onerror: (this: WebSocket, ev: Event) => any; + onmessage: (this: WebSocket, ev: MessageEvent) => any; + onopen: (this: WebSocket, ev: Event) => any; + readonly protocol: string; + readonly readyState: number; + readonly url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + readonly CLOSED: number; + readonly CLOSING: number; + readonly CONNECTING: number; + readonly OPEN: number; +}; + +interface WheelEvent extends MouseEvent { + readonly deltaMode: number; + readonly deltaX: number; + readonly deltaY: number; + readonly deltaZ: number; + readonly wheelDelta: number; + readonly wheelDeltaX: number; + readonly wheelDeltaY: number; + getCurrentPoint(element: Element): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +} + +declare var WheelEvent: { + prototype: WheelEvent; + new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; + readonly DOM_DELTA_LINE: number; + readonly DOM_DELTA_PAGE: number; + readonly DOM_DELTA_PIXEL: number; +}; + +interface WindowEventMap extends GlobalEventHandlersEventMap { + "abort": UIEvent; + "afterprint": Event; + "beforeprint": Event; + "beforeunload": BeforeUnloadEvent; + "blur": FocusEvent; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "compassneedscalibration": Event; + "contextmenu": PointerEvent; + "dblclick": MouseEvent; + "devicelight": DeviceLightEvent; + "devicemotion": DeviceMotionEvent; + "deviceorientation": DeviceOrientationEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": MediaStreamErrorEvent; + "error": ErrorEvent; + "focus": FocusEvent; + "hashchange": HashChangeEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "message": MessageEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "mousewheel": WheelEvent; + "MSGestureChange": MSGestureEvent; + "MSGestureDoubleTap": MSGestureEvent; + "MSGestureEnd": MSGestureEvent; + "MSGestureHold": MSGestureEvent; + "MSGestureStart": MSGestureEvent; + "MSGestureTap": MSGestureEvent; + "MSInertiaStart": MSGestureEvent; + "MSPointerCancel": MSPointerEvent; + "MSPointerDown": MSPointerEvent; + "MSPointerEnter": MSPointerEvent; + "MSPointerLeave": MSPointerEvent; + "MSPointerMove": MSPointerEvent; + "MSPointerOut": MSPointerEvent; + "MSPointerOver": MSPointerEvent; + "MSPointerUp": MSPointerEvent; + "offline": Event; + "online": Event; + "orientationchange": Event; + "pagehide": PageTransitionEvent; + "pageshow": PageTransitionEvent; + "pause": Event; + "play": Event; + "playing": Event; + "popstate": PopStateEvent; + "progress": ProgressEvent; + "ratechange": Event; + "readystatechange": ProgressEvent; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "storage": StorageEvent; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "unload": Event; + "volumechange": Event; + "waiting": Event; +} + +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { + readonly applicationCache: ApplicationCache; + readonly caches: CacheStorage; + readonly clientInformation: Navigator; + readonly closed: boolean; + readonly crypto: Crypto; + defaultStatus: string; + readonly devicePixelRatio: number; + readonly document: Document; + readonly doNotTrack: string; + event: Event | undefined; + readonly external: External; + readonly frameElement: Element; + readonly frames: Window; + readonly history: History; + readonly innerHeight: number; + readonly innerWidth: number; + readonly isSecureContext: boolean; + readonly length: number; + readonly location: Location; + readonly locationbar: BarProp; + readonly menubar: BarProp; + readonly msContentScript: ExtensionScriptApis; + readonly msCredentials: MSCredentials; + name: string; + readonly navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (this: Window, ev: UIEvent) => any; + onafterprint: (this: Window, ev: Event) => any; + onbeforeprint: (this: Window, ev: Event) => any; + onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; + onblur: (this: Window, ev: FocusEvent) => any; + oncanplay: (this: Window, ev: Event) => any; + oncanplaythrough: (this: Window, ev: Event) => any; + onchange: (this: Window, ev: Event) => any; + onclick: (this: Window, ev: MouseEvent) => any; + oncompassneedscalibration: (this: Window, ev: Event) => any; + oncontextmenu: (this: Window, ev: PointerEvent) => any; + ondblclick: (this: Window, ev: MouseEvent) => any; + ondevicelight: (this: Window, ev: DeviceLightEvent) => any; + ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; + ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; + ondrag: (this: Window, ev: DragEvent) => any; + ondragend: (this: Window, ev: DragEvent) => any; + ondragenter: (this: Window, ev: DragEvent) => any; + ondragleave: (this: Window, ev: DragEvent) => any; + ondragover: (this: Window, ev: DragEvent) => any; + ondragstart: (this: Window, ev: DragEvent) => any; + ondrop: (this: Window, ev: DragEvent) => any; + ondurationchange: (this: Window, ev: Event) => any; + onemptied: (this: Window, ev: Event) => any; + onended: (this: Window, ev: MediaStreamErrorEvent) => any; + onerror: ErrorEventHandler; + onfocus: (this: Window, ev: FocusEvent) => any; + onhashchange: (this: Window, ev: HashChangeEvent) => any; + oninput: (this: Window, ev: Event) => any; + oninvalid: (this: Window, ev: Event) => any; + onkeydown: (this: Window, ev: KeyboardEvent) => any; + onkeypress: (this: Window, ev: KeyboardEvent) => any; + onkeyup: (this: Window, ev: KeyboardEvent) => any; + onload: (this: Window, ev: Event) => any; + onloadeddata: (this: Window, ev: Event) => any; + onloadedmetadata: (this: Window, ev: Event) => any; + onloadstart: (this: Window, ev: Event) => any; + onmessage: (this: Window, ev: MessageEvent) => any; + onmousedown: (this: Window, ev: MouseEvent) => any; + onmouseenter: (this: Window, ev: MouseEvent) => any; + onmouseleave: (this: Window, ev: MouseEvent) => any; + onmousemove: (this: Window, ev: MouseEvent) => any; + onmouseout: (this: Window, ev: MouseEvent) => any; + onmouseover: (this: Window, ev: MouseEvent) => any; + onmouseup: (this: Window, ev: MouseEvent) => any; + onmousewheel: (this: Window, ev: WheelEvent) => any; + onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; + onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; + onmsgestureend: (this: Window, ev: MSGestureEvent) => any; + onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; + onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; + onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; + onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; + onmspointercancel: (this: Window, ev: MSPointerEvent) => any; + onmspointerdown: (this: Window, ev: MSPointerEvent) => any; + onmspointerenter: (this: Window, ev: MSPointerEvent) => any; + onmspointerleave: (this: Window, ev: MSPointerEvent) => any; + onmspointermove: (this: Window, ev: MSPointerEvent) => any; + onmspointerout: (this: Window, ev: MSPointerEvent) => any; + onmspointerover: (this: Window, ev: MSPointerEvent) => any; + onmspointerup: (this: Window, ev: MSPointerEvent) => any; + onoffline: (this: Window, ev: Event) => any; + ononline: (this: Window, ev: Event) => any; + onorientationchange: (this: Window, ev: Event) => any; + onpagehide: (this: Window, ev: PageTransitionEvent) => any; + onpageshow: (this: Window, ev: PageTransitionEvent) => any; + onpause: (this: Window, ev: Event) => any; + onplay: (this: Window, ev: Event) => any; + onplaying: (this: Window, ev: Event) => any; + onpopstate: (this: Window, ev: PopStateEvent) => any; + onprogress: (this: Window, ev: ProgressEvent) => any; + onratechange: (this: Window, ev: Event) => any; + onreadystatechange: (this: Window, ev: ProgressEvent) => any; + onreset: (this: Window, ev: Event) => any; + onresize: (this: Window, ev: UIEvent) => any; + onscroll: (this: Window, ev: UIEvent) => any; + onseeked: (this: Window, ev: Event) => any; + onseeking: (this: Window, ev: Event) => any; + onselect: (this: Window, ev: UIEvent) => any; + onstalled: (this: Window, ev: Event) => any; + onstorage: (this: Window, ev: StorageEvent) => any; + onsubmit: (this: Window, ev: Event) => any; + onsuspend: (this: Window, ev: Event) => any; + ontimeupdate: (this: Window, ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onunload: (this: Window, ev: Event) => any; + onvolumechange: (this: Window, ev: Event) => any; + onwaiting: (this: Window, ev: Event) => any; + opener: any; + orientation: string | number; + readonly outerHeight: number; + readonly outerWidth: number; + readonly pageXOffset: number; + readonly pageYOffset: number; + readonly parent: Window; + readonly performance: Performance; + readonly personalbar: BarProp; + readonly screen: Screen; + readonly screenLeft: number; + readonly screenTop: number; + readonly screenX: number; + readonly screenY: number; + readonly scrollbars: BarProp; + readonly scrollX: number; + readonly scrollY: number; + readonly self: Window; + readonly speechSynthesis: SpeechSynthesis; + status: string; + readonly statusbar: BarProp; + readonly styleMedia: StyleMedia; + readonly toolbar: BarProp; + readonly top: Window; + readonly window: Window; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + Blob: typeof Blob; + customElements: CustomElementRegistry; + alert(message?: any): void; + blur(): void; + cancelAnimationFrame(handle: number): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + matchMedia(mediaQuery: string): MediaQueryList; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; + postMessage(message: any, targetOrigin: string, transfer?: any[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + releaseEvents(): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + stop(): void; + webkitCancelAnimationFrame(handle: number): void; + webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; + webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; + webkitRequestAnimationFrame(callback: FrameRequestCallback): number; + createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; + createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; + scroll(options?: ScrollToOptions): void; + scrollTo(options?: ScrollToOptions): void; + scrollBy(options?: ScrollToOptions): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Window: { + prototype: Window; + new(): Window; +}; + +interface WorkerEventMap extends AbstractWorkerEventMap { + "message": MessageEvent; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: (this: Worker, ev: MessageEvent) => any; + postMessage(message: any, transfer?: any[]): void; + terminate(): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string): Worker; +}; + +interface XMLDocument extends Document { + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLDocument: { + prototype: XMLDocument; + new(): XMLDocument; +}; + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + onreadystatechange: (this: XMLHttpRequest, ev: Event) => any; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: XMLHttpRequestResponseType; + readonly responseURL: string; + readonly responseXML: Document | null; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + msCaching?: string; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + overrideMimeType(mime: string): void; + send(data?: Document): void; + send(data?: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; +}; + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +}; + +interface XMLSerializer { + serializeToString(target: Node): string; +} + +declare var XMLSerializer: { + prototype: XMLSerializer; + new(): XMLSerializer; +}; + +interface XPathEvaluator { + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver?: Node): XPathNSResolver; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathEvaluator: { + prototype: XPathEvaluator; + new(): XPathEvaluator; +}; + +interface XPathExpression { + evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; +} + +declare var XPathExpression: { + prototype: XPathExpression; + new(): XPathExpression; +}; + +interface XPathNSResolver { + lookupNamespaceURI(prefix: string): string; +} + +declare var XPathNSResolver: { + prototype: XPathNSResolver; + new(): XPathNSResolver; +}; + +interface XPathResult { + readonly booleanValue: boolean; + readonly invalidIteratorState: boolean; + readonly numberValue: number; + readonly resultType: number; + readonly singleNodeValue: Node; + readonly snapshotLength: number; + readonly stringValue: string; + iterateNext(): Node; + snapshotItem(index: number): Node; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +declare var XPathResult: { + prototype: XPathResult; + new(): XPathResult; + readonly ANY_TYPE: number; + readonly ANY_UNORDERED_NODE_TYPE: number; + readonly BOOLEAN_TYPE: number; + readonly FIRST_ORDERED_NODE_TYPE: number; + readonly NUMBER_TYPE: number; + readonly ORDERED_NODE_ITERATOR_TYPE: number; + readonly ORDERED_NODE_SNAPSHOT_TYPE: number; + readonly STRING_TYPE: number; + readonly UNORDERED_NODE_ITERATOR_TYPE: number; + readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; +}; + +interface XSLTProcessor { + clearParameters(): void; + getParameter(namespaceURI: string, localName: string): any; + importStylesheet(style: Node): void; + removeParameter(namespaceURI: string, localName: string): void; + reset(): void; + setParameter(namespaceURI: string, localName: string, value: any): void; + transformToDocument(source: Node): Document; + transformToFragment(source: Node, document: Document): DocumentFragment; +} + +declare var XSLTProcessor: { + prototype: XSLTProcessor; + new(): XSLTProcessor; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + onerror: (this: AbstractWorker, ev: ErrorEvent) => any; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface Body { + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + json(): Promise; + text(): Promise; + formData(): Promise; +} + +interface CanvasPathMethods { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface ChildNode { + remove(): void; +} + +interface DocumentEvent { + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface: "NavigationEvent"): NavigationEvent; + createEvent(eventInterface: "NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface ElementTraversal { + readonly childElementCount: number; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly nextElementSibling: Element | null; + readonly previousElementSibling: Element | null; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +interface GlobalEventHandlersEventMap { + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "wheel": WheelEvent; +} + +interface GlobalEventHandlers { + onpointercancel: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerdown: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerenter: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerleave: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointermove: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerout: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; + onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface GlobalFetch { + fetch(input: RequestInfo, init?: RequestInit): Promise; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; +} + +interface IDBEnvironment { + readonly indexedDB: IDBFactory; +} + +interface LinkStyle { + readonly sheet: StyleSheet; +} + +interface MSBaseReaderEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; +} + +interface MSBaseReader { + onabort: (this: MSBaseReader, ev: Event) => any; + onerror: (this: MSBaseReader, ev: ErrorEvent) => any; + onload: (this: MSBaseReader, ev: Event) => any; + onloadend: (this: MSBaseReader, ev: ProgressEvent) => any; + onloadstart: (this: MSBaseReader, ev: Event) => any; + onprogress: (this: MSBaseReader, ev: ProgressEvent) => any; + readonly readyState: number; + readonly result: any; + abort(): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSNavigatorDoNotTrack { + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; +} + +interface NavigatorBeacon { + sendBeacon(url: USVString, data?: BodyInit): boolean; +} + +interface NavigatorConcurrentHardware { + readonly hardwareConcurrency: number; +} + +interface NavigatorContentUtils { +} + +interface NavigatorGeolocation { + readonly geolocation: Geolocation; +} + +interface NavigatorID { + readonly appCodeName: string; + readonly appName: string; + readonly appVersion: string; + readonly platform: string; + readonly product: string; + readonly productSub: string; + readonly userAgent: string; + readonly vendor: string; + readonly vendorSub: string; +} + +interface NavigatorOnLine { + readonly onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NavigatorUserMedia { + readonly mediaDevices: MediaDevices; + getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void; +} + +interface NodeSelector { + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; + querySelector(selectors: string): E | null; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; +} + +interface RandomSource { + getRandomValues(array: T): T; +} + +interface SVGAnimatedPoints { + readonly animatedPoints: SVGPointList; + readonly points: SVGPointList; +} + +interface SVGFilterPrimitiveStandardAttributes { + readonly height: SVGAnimatedLength; + readonly result: SVGAnimatedString; + readonly width: SVGAnimatedLength; + readonly x: SVGAnimatedLength; + readonly y: SVGAnimatedLength; +} + +interface SVGFitToViewBox { + readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + readonly viewBox: SVGAnimatedRect; +} + +interface SVGTests { + readonly requiredExtensions: SVGStringList; + readonly requiredFeatures: SVGStringList; + readonly systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface SVGURIReference { + readonly href: SVGAnimatedString; +} + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + readonly console: Console; +} + +interface WindowLocalStorage { + readonly localStorage: Storage; +} + +interface WindowSessionStorage { + readonly sessionStorage: Storage; +} + +interface WindowTimers extends Object, WindowTimersExtension { + clearInterval(handle: number): void; + clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; + setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; + setTimeout(handler: any, timeout?: any, ...args: any[]): number; +} + +interface WindowTimersExtension { + clearImmediate(handle: number): void; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; +} + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": ErrorEvent; + "load": Event; + "loadend": ProgressEvent; + "loadstart": Event; + "progress": ProgressEvent; + "timeout": ProgressEvent; +} + +interface XMLHttpRequestEventTarget { + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + +interface ErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + conlno?: number; + error?: any; +} + +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + storageArea?: Storage; +} + +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + +interface ImageBitmapOptions { + imageOrientation?: "none" | "flipY"; + premultiplyAlpha?: "none" | "premultiply" | "default"; + colorSpaceConversion?: "none" | "default"; + resizeWidth?: number; + resizeHeight?: number; + resizeQuality?: "pixelated" | "low" | "medium" | "high"; +} + +interface ImageBitmap { + readonly width: number; + readonly height: number; + close(): void; +} + +interface URLSearchParams { + /** + * Appends a specified key/value pair as a new search parameter. + */ + append(name: string, value: string): void; + /** + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ + delete(name: string): void; + /** + * Returns the first value associated to the given search parameter. + */ + get(name: string): string | null; + /** + * Returns all the values association with a given search parameter. + */ + getAll(name: string): string[]; + /** + * Returns a Boolean indicating if such a search parameter exists. + */ + has(name: string): boolean; + /** + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ + set(name: string, value: string): void; +} + +declare var URLSearchParams: { + prototype: URLSearchParams; + /** + * Constructor returning a URLSearchParams object. + */ + new (init?: string | URLSearchParams): URLSearchParams; +}; + +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +interface HTMLCollectionOf extends HTMLCollection { + item(index: number): T; + namedItem(name: string): T; + [index: number]: T; +} + +interface BlobPropertyBag { + type?: string; + endings?: string; +} + +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface IDBArrayKey extends Array { +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + +interface ParentNode { + readonly children: HTMLCollection; + readonly firstElementChild: Element | null; + readonly lastElementChild: Element | null; + readonly childElementCount: number; +} + +interface DocumentOrShadowRoot { + readonly activeElement: Element | null; + readonly stylesheets: StyleSheetList; + getSelection(): Selection | null; + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; +} + +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { + readonly host: Element; + innerHTML: string; +} + +interface ShadowRootInit { + mode: "open" | "closed"; + delegatesFocus?: boolean; +} + +interface HTMLSlotElement extends HTMLElement { + name: string; + assignedNodes(options?: AssignedNodesOptions): Node[]; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + +interface ElementDefinitionOptions { + extends: string; +} + +interface CustomElementRegistry { + define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; + get(name: string): any; + whenDefined(name: string): PromiseLike; +} + +interface PromiseRejectionEvent extends Event { + readonly promise: PromiseLike; + readonly reason: any; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: PromiseLike; + reason?: any; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + passive?: boolean; + once?: boolean; +} + +interface TouchEventInit extends EventModifierInit { + touches?: Touch[]; + targetTouches?: Touch[]; + changedTouches?: Touch[]; +} + +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} +interface ErrorEventHandler { + (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; +} +interface ForEachCallback { + (keyId: any, status: MediaKeyStatus): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface FunctionStringCallback { + (data: string): void; +} +interface IntersectionObserverCallback { + (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MSLaunchUriCallback { + (): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface NavigatorUserMediaErrorCallback { + (error: MediaStreamError): void; +} +interface NavigatorUserMediaSuccessCallback { + (stream: MediaStream): void; +} +interface NotificationPermissionCallback { + (permission: NotificationPermission): void; +} +interface PositionCallback { + (position: Position): void; +} +interface PositionErrorCallback { + (error: PositionError): void; +} +interface RTCPeerConnectionErrorCallback { + (error: DOMError): void; +} +interface RTCSessionDescriptionCallback { + (sdp: RTCSessionDescription): void; +} +interface RTCStatsCallback { + (report: RTCStatsReport): void; +} +interface VoidFunction { + (): void; +} +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; + "audio": HTMLAudioElement; + "b": HTMLElement; + "base": HTMLBaseElement; + "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; + "blockquote": HTMLQuoteElement; + "body": HTMLBodyElement; + "br": HTMLBRElement; + "button": HTMLButtonElement; + "canvas": HTMLCanvasElement; + "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; + "col": HTMLTableColElement; + "colgroup": HTMLTableColElement; + "data": HTMLDataElement; + "datalist": HTMLDataListElement; + "dd": HTMLElement; + "del": HTMLModElement; + "dfn": HTMLElement; + "dir": HTMLDirectoryElement; + "div": HTMLDivElement; + "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; + "embed": HTMLEmbedElement; + "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; + "font": HTMLFontElement; + "footer": HTMLElement; + "form": HTMLFormElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "h1": HTMLHeadingElement; + "h2": HTMLHeadingElement; + "h3": HTMLHeadingElement; + "h4": HTMLHeadingElement; + "h5": HTMLHeadingElement; + "h6": HTMLHeadingElement; + "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; + "hr": HTMLHRElement; + "html": HTMLHtmlElement; + "i": HTMLElement; + "iframe": HTMLIFrameElement; + "img": HTMLImageElement; + "input": HTMLInputElement; + "ins": HTMLModElement; + "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; + "label": HTMLLabelElement; + "legend": HTMLLegendElement; + "li": HTMLLIElement; + "link": HTMLLinkElement; + "listing": HTMLPreElement; + "map": HTMLMapElement; + "mark": HTMLElement; + "marquee": HTMLMarqueeElement; + "menu": HTMLMenuElement; + "meta": HTMLMetaElement; + "meter": HTMLMeterElement; + "nav": HTMLElement; + "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; + "object": HTMLObjectElement; + "ol": HTMLOListElement; + "optgroup": HTMLOptGroupElement; + "option": HTMLOptionElement; + "output": HTMLOutputElement; + "p": HTMLParagraphElement; + "param": HTMLParamElement; + "picture": HTMLPictureElement; + "plaintext": HTMLElement; + "pre": HTMLPreElement; + "progress": HTMLProgressElement; + "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; + "script": HTMLScriptElement; + "section": HTMLElement; + "select": HTMLSelectElement; + "small": HTMLElement; + "source": HTMLSourceElement; + "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; + "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; + "table": HTMLTableElement; + "tbody": HTMLTableSectionElement; + "td": HTMLTableDataCellElement; + "template": HTMLTemplateElement; + "textarea": HTMLTextAreaElement; + "tfoot": HTMLTableSectionElement; + "th": HTMLTableHeaderCellElement; + "thead": HTMLTableSectionElement; + "time": HTMLTimeElement; + "title": HTMLTitleElement; + "tr": HTMLTableRowElement; + "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; + "ul": HTMLUListElement; + "var": HTMLElement; + "video": HTMLVideoElement; + "wbr": HTMLElement; + "x-ms-webview": MSHTMLWebViewElement; + "xmp": HTMLPreElement; +} + +interface SVGElementTagNameMap { + "circle": SVGCircleElement; + "clippath": SVGClipPathElement; + "defs": SVGDefsElement; + "desc": SVGDescElement; + "ellipse": SVGEllipseElement; + "feblend": SVGFEBlendElement; + "fecolormatrix": SVGFEColorMatrixElement; + "fecomponenttransfer": SVGFEComponentTransferElement; + "fecomposite": SVGFECompositeElement; + "feconvolvematrix": SVGFEConvolveMatrixElement; + "fediffuselighting": SVGFEDiffuseLightingElement; + "fedisplacementmap": SVGFEDisplacementMapElement; + "fedistantlight": SVGFEDistantLightElement; + "feflood": SVGFEFloodElement; + "fefunca": SVGFEFuncAElement; + "fefuncb": SVGFEFuncBElement; + "fefuncg": SVGFEFuncGElement; + "fefuncr": SVGFEFuncRElement; + "fegaussianblur": SVGFEGaussianBlurElement; + "feimage": SVGFEImageElement; + "femerge": SVGFEMergeElement; + "femergenode": SVGFEMergeNodeElement; + "femorphology": SVGFEMorphologyElement; + "feoffset": SVGFEOffsetElement; + "fepointlight": SVGFEPointLightElement; + "fespecularlighting": SVGFESpecularLightingElement; + "fespotlight": SVGFESpotLightElement; + "fetile": SVGFETileElement; + "feturbulence": SVGFETurbulenceElement; + "filter": SVGFilterElement; + "foreignobject": SVGForeignObjectElement; + "g": SVGGElement; + "image": SVGImageElement; + "line": SVGLineElement; + "lineargradient": SVGLinearGradientElement; + "marker": SVGMarkerElement; + "mask": SVGMaskElement; + "metadata": SVGMetadataElement; + "path": SVGPathElement; + "pattern": SVGPatternElement; + "polygon": SVGPolygonElement; + "polyline": SVGPolylineElement; + "radialgradient": SVGRadialGradientElement; + "rect": SVGRectElement; + "stop": SVGStopElement; + "svg": SVGSVGElement; + "switch": SVGSwitchElement; + "symbol": SVGSymbolElement; + "text": SVGTextElement; + "textpath": SVGTextPathElement; + "tspan": SVGTSpanElement; + "use": SVGUseElement; + "view": SVGViewElement; +} + +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } + +declare var Audio: { new(src?: string): HTMLAudioElement; }; +declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: { new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var applicationCache: ApplicationCache; +declare var caches: CacheStorage; +declare var clientInformation: Navigator; +declare var closed: boolean; +declare var crypto: Crypto; +declare var defaultStatus: string; +declare var devicePixelRatio: number; +declare var document: Document; +declare var doNotTrack: string; +declare var event: Event | undefined; +declare var external: External; +declare var frameElement: Element; +declare var frames: Window; +declare var history: History; +declare var innerHeight: number; +declare var innerWidth: number; +declare var isSecureContext: boolean; +declare var length: number; +declare var location: Location; +declare var locationbar: BarProp; +declare var menubar: BarProp; +declare var msContentScript: ExtensionScriptApis; +declare var msCredentials: MSCredentials; +declare const name: never; +declare var navigator: Navigator; +declare var offscreenBuffering: string | boolean; +declare var onabort: (this: Window, ev: UIEvent) => any; +declare var onafterprint: (this: Window, ev: Event) => any; +declare var onbeforeprint: (this: Window, ev: Event) => any; +declare var onbeforeunload: (this: Window, ev: BeforeUnloadEvent) => any; +declare var onblur: (this: Window, ev: FocusEvent) => any; +declare var oncanplay: (this: Window, ev: Event) => any; +declare var oncanplaythrough: (this: Window, ev: Event) => any; +declare var onchange: (this: Window, ev: Event) => any; +declare var onclick: (this: Window, ev: MouseEvent) => any; +declare var oncompassneedscalibration: (this: Window, ev: Event) => any; +declare var oncontextmenu: (this: Window, ev: PointerEvent) => any; +declare var ondblclick: (this: Window, ev: MouseEvent) => any; +declare var ondevicelight: (this: Window, ev: DeviceLightEvent) => any; +declare var ondevicemotion: (this: Window, ev: DeviceMotionEvent) => any; +declare var ondeviceorientation: (this: Window, ev: DeviceOrientationEvent) => any; +declare var ondrag: (this: Window, ev: DragEvent) => any; +declare var ondragend: (this: Window, ev: DragEvent) => any; +declare var ondragenter: (this: Window, ev: DragEvent) => any; +declare var ondragleave: (this: Window, ev: DragEvent) => any; +declare var ondragover: (this: Window, ev: DragEvent) => any; +declare var ondragstart: (this: Window, ev: DragEvent) => any; +declare var ondrop: (this: Window, ev: DragEvent) => any; +declare var ondurationchange: (this: Window, ev: Event) => any; +declare var onemptied: (this: Window, ev: Event) => any; +declare var onended: (this: Window, ev: MediaStreamErrorEvent) => any; +declare var onerror: ErrorEventHandler; +declare var onfocus: (this: Window, ev: FocusEvent) => any; +declare var onhashchange: (this: Window, ev: HashChangeEvent) => any; +declare var oninput: (this: Window, ev: Event) => any; +declare var oninvalid: (this: Window, ev: Event) => any; +declare var onkeydown: (this: Window, ev: KeyboardEvent) => any; +declare var onkeypress: (this: Window, ev: KeyboardEvent) => any; +declare var onkeyup: (this: Window, ev: KeyboardEvent) => any; +declare var onload: (this: Window, ev: Event) => any; +declare var onloadeddata: (this: Window, ev: Event) => any; +declare var onloadedmetadata: (this: Window, ev: Event) => any; +declare var onloadstart: (this: Window, ev: Event) => any; +declare var onmessage: (this: Window, ev: MessageEvent) => any; +declare var onmousedown: (this: Window, ev: MouseEvent) => any; +declare var onmouseenter: (this: Window, ev: MouseEvent) => any; +declare var onmouseleave: (this: Window, ev: MouseEvent) => any; +declare var onmousemove: (this: Window, ev: MouseEvent) => any; +declare var onmouseout: (this: Window, ev: MouseEvent) => any; +declare var onmouseover: (this: Window, ev: MouseEvent) => any; +declare var onmouseup: (this: Window, ev: MouseEvent) => any; +declare var onmousewheel: (this: Window, ev: WheelEvent) => any; +declare var onmsgesturechange: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturedoubletap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgestureend: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturehold: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturestart: (this: Window, ev: MSGestureEvent) => any; +declare var onmsgesturetap: (this: Window, ev: MSGestureEvent) => any; +declare var onmsinertiastart: (this: Window, ev: MSGestureEvent) => any; +declare var onmspointercancel: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerdown: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerenter: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerleave: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointermove: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerout: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerover: (this: Window, ev: MSPointerEvent) => any; +declare var onmspointerup: (this: Window, ev: MSPointerEvent) => any; +declare var onoffline: (this: Window, ev: Event) => any; +declare var ononline: (this: Window, ev: Event) => any; +declare var onorientationchange: (this: Window, ev: Event) => any; +declare var onpagehide: (this: Window, ev: PageTransitionEvent) => any; +declare var onpageshow: (this: Window, ev: PageTransitionEvent) => any; +declare var onpause: (this: Window, ev: Event) => any; +declare var onplay: (this: Window, ev: Event) => any; +declare var onplaying: (this: Window, ev: Event) => any; +declare var onpopstate: (this: Window, ev: PopStateEvent) => any; +declare var onprogress: (this: Window, ev: ProgressEvent) => any; +declare var onratechange: (this: Window, ev: Event) => any; +declare var onreadystatechange: (this: Window, ev: ProgressEvent) => any; +declare var onreset: (this: Window, ev: Event) => any; +declare var onresize: (this: Window, ev: UIEvent) => any; +declare var onscroll: (this: Window, ev: UIEvent) => any; +declare var onseeked: (this: Window, ev: Event) => any; +declare var onseeking: (this: Window, ev: Event) => any; +declare var onselect: (this: Window, ev: UIEvent) => any; +declare var onstalled: (this: Window, ev: Event) => any; +declare var onstorage: (this: Window, ev: StorageEvent) => any; +declare var onsubmit: (this: Window, ev: Event) => any; +declare var onsuspend: (this: Window, ev: Event) => any; +declare var ontimeupdate: (this: Window, ev: Event) => any; +declare var ontouchcancel: (ev: TouchEvent) => any; +declare var ontouchend: (ev: TouchEvent) => any; +declare var ontouchmove: (ev: TouchEvent) => any; +declare var ontouchstart: (ev: TouchEvent) => any; +declare var onunload: (this: Window, ev: Event) => any; +declare var onvolumechange: (this: Window, ev: Event) => any; +declare var onwaiting: (this: Window, ev: Event) => any; +declare var opener: any; +declare var orientation: string | number; +declare var outerHeight: number; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var pageYOffset: number; +declare var parent: Window; +declare var performance: Performance; +declare var personalbar: BarProp; +declare var screen: Screen; +declare var screenLeft: number; +declare var screenTop: number; +declare var screenX: number; +declare var screenY: number; +declare var scrollbars: BarProp; +declare var scrollX: number; +declare var scrollY: number; +declare var self: Window; +declare var speechSynthesis: SpeechSynthesis; +declare var status: string; +declare var statusbar: BarProp; +declare var styleMedia: StyleMedia; +declare var toolbar: BarProp; +declare var top: Window; +declare var window: Window; +declare var customElements: CustomElementRegistry; +declare function alert(message?: any): void; +declare function blur(): void; +declare function cancelAnimationFrame(handle: number): void; +declare function captureEvents(): void; +declare function close(): void; +declare function confirm(message?: string): boolean; +declare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; +declare function focus(): void; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; +declare function getSelection(): Selection; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function moveBy(x?: number, y?: number): void; +declare function moveTo(x?: number, y?: number): void; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; +declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; +declare function print(): void; +declare function prompt(message?: string, _default?: string): string | null; +declare function releaseEvents(): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function resizeBy(x?: number, y?: number): void; +declare function resizeTo(x?: number, y?: number): void; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare function stop(): void; +declare function webkitCancelAnimationFrame(handle: number): void; +declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; +declare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; +declare function scroll(options?: ScrollToOptions): void; +declare function scrollTo(options?: ScrollToOptions): void; +declare function scrollBy(options?: ScrollToOptions): void; +declare function toString(): string; +declare function dispatchEvent(evt: Event): boolean; +declare function clearInterval(handle: number): void; +declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; +declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; +declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; +declare function clearImmediate(handle: number): void; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; +declare var sessionStorage: Storage; +declare var localStorage: Storage; +declare var console: Console; +declare var onpointercancel: (this: Window, ev: PointerEvent) => any; +declare var onpointerdown: (this: Window, ev: PointerEvent) => any; +declare var onpointerenter: (this: Window, ev: PointerEvent) => any; +declare var onpointerleave: (this: Window, ev: PointerEvent) => any; +declare var onpointermove: (this: Window, ev: PointerEvent) => any; +declare var onpointerout: (this: Window, ev: PointerEvent) => any; +declare var onpointerover: (this: Window, ev: PointerEvent) => any; +declare var onpointerup: (this: Window, ev: PointerEvent) => any; +declare var onwheel: (this: Window, ev: WheelEvent) => any; +declare var indexedDB: IDBFactory; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +type AAGUID = string; +type AlgorithmIdentifier = string | Algorithm; +type BodyInit = any; +type ByteString = string; +type ConstrainBoolean = boolean | ConstrainBooleanParameters; +type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; +type ConstrainDouble = number | ConstrainDoubleRange; +type ConstrainLong = number | ConstrainLongRange; +type CryptoOperationData = ArrayBufferView; +type GLbitfield = number; +type GLboolean = boolean; +type GLbyte = number; +type GLclampf = number; +type GLenum = number; +type GLfloat = number; +type GLint = number; +type GLintptr = number; +type GLshort = number; +type GLsizei = number; +type GLsizeiptr = number; +type GLubyte = number; +type GLuint = number; +type GLushort = number; +type IDBKeyPath = string; +type KeyFormat = string; +type KeyType = string; +type KeyUsage = string; +type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; +type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; +type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; +type RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete; +type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; +type RequestInfo = Request | string; +type USVString = string; +type payloadtype = number; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; +type FormDataEntryValue = string | File; +type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; +type AppendMode = "segments" | "sequence"; +type AudioContextState = "suspended" | "running" | "closed"; +type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; +type CanvasFillRule = "nonzero" | "evenodd"; +type ChannelCountMode = "max" | "clamped-max" | "explicit"; +type ChannelInterpretation = "speakers" | "discrete"; +type DistanceModelType = "linear" | "inverse" | "exponential"; +type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; +type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad"; +type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; +type IDBRequestReadyState = "pending" | "done"; +type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type ListeningState = "inactive" | "active" | "disambiguation"; +type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; +type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request"; +type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message"; +type MediaKeysRequirement = "required" | "optional" | "not-allowed"; +type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error"; +type MediaStreamTrackState = "live" | "ended"; +type MSCredentialType = "FIDO_2_0"; +type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; +type MSIceType = "failed" | "direct" | "relay"; +type MSStatsType = "description" | "localclientevent" | "inbound-network" | "outbound-network" | "inbound-payload" | "outbound-payload" | "transportdiagnostics"; +type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; +type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; +type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; +type NavigationReason = "up" | "down" | "left" | "right"; +type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; +type NotificationDirection = "auto" | "ltr" | "rtl"; +type NotificationPermission = "default" | "denied" | "granted"; +type OscillatorType = "sine" | "square" | "sawtooth" | "triangle" | "custom"; +type OverSampleType = "none" | "2x" | "4x"; +type PanningModelType = "equalpower"; +type PaymentComplete = "success" | "fail" | ""; +type PaymentShippingType = "shipping" | "delivery" | "pickup"; +type PushEncryptionKeyName = "p256dh" | "auth"; +type PushPermissionState = "granted" | "denied" | "prompt"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; +type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; +type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced"; +type RTCDtlsRole = "auto" | "client" | "server"; +type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed"; +type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay"; +type RTCIceComponent = "RTP" | "RTCP"; +type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed"; +type RTCIceGathererState = "new" | "gathering" | "complete"; +type RTCIceGatheringState = "new" | "gathering" | "complete"; +type RTCIceGatherPolicy = "all" | "nohost" | "relay"; +type RTCIceProtocol = "udp" | "tcp"; +type RTCIceRole = "controlling" | "controlled"; +type RTCIceTcpCandidateType = "active" | "passive" | "so"; +type RTCIceTransportPolicy = "none" | "relay" | "all"; +type RTCIceTransportState = "new" | "checking" | "connected" | "completed" | "disconnected" | "closed"; +type RTCSdpType = "offer" | "pranswer" | "answer"; +type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | "have-local-pranswer" | "have-remote-pranswer" | "closed"; +type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; +type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed"; +type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate"; +type ScopedCredentialType = "ScopedCred"; +type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; +type Transport = "usb" | "nfc" | "ble"; +type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; +type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// These are only available in a Web Worker +declare function importScripts(...urls: string[]): void; + + + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// + + +interface ActiveXObject { + new (s: string): any; +} +declare var ActiveXObject: ActiveXObject; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +interface TextStreamBase { + /** + * The column number of the current character position in an input stream. + */ + Column: number; + + /** + * The current line number in an input stream. + */ + Line: number; + + /** + * Closes a text stream. + * It is not necessary to close standard streams; they close automatically when the process ends. If + * you close a standard stream, be aware that any other pointers to that standard stream become invalid. + */ + Close(): void; +} + +interface TextStreamWriter extends TextStreamBase { + /** + * Sends a string to an output stream. + */ + Write(s: string): void; + + /** + * Sends a specified number of blank lines (newline characters) to an output stream. + */ + WriteBlankLines(intLines: number): void; + + /** + * Sends a string followed by a newline character to an output stream. + */ + WriteLine(s: string): void; +} + +interface TextStreamReader extends TextStreamBase { + /** + * Returns a specified number of characters from an input stream, starting at the current pointer position. + * Does not return until the ENTER key is pressed. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + Read(characters: number): string; + + /** + * Returns all characters from an input stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadAll(): string; + + /** + * Returns an entire line from an input stream. + * Although this method extracts the newline character, it does not add it to the returned string. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadLine(): string; + + /** + * Skips a specified number of characters when reading from an input text stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) + */ + Skip(characters: number): void; + + /** + * Skips the next line when reading from an input text stream. + * Can only be used on a stream in reading mode, not writing or appending mode. + */ + SkipLine(): void; + + /** + * Indicates whether the stream pointer position is at the end of a line. + */ + AtEndOfLine: boolean; + + /** + * Indicates whether the stream pointer position is at the end of a stream. + */ + AtEndOfStream: boolean; +} + +declare var WScript: { + /** + * Outputs text to either a message box (under WScript.exe) or the command console window followed by + * a newline (under CScript.exe). + */ + Echo(s: any): void; + + /** + * Exposes the write-only error output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdErr: TextStreamWriter; + + /** + * Exposes the write-only output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdOut: TextStreamWriter; + Arguments: { length: number; Item(n: number): string; }; + + /** + * The full path of the currently running script. + */ + ScriptFullName: string; + + /** + * Forces the script to stop immediately, with an optional exit code. + */ + Quit(exitCode?: number): number; + + /** + * The Windows Script Host build version number. + */ + BuildVersion: number; + + /** + * Fully qualified path of the host executable. + */ + FullName: string; + + /** + * Gets/sets the script mode - interactive(true) or batch(false). + */ + Interactive: boolean; + + /** + * The name of the host executable (WScript.exe or CScript.exe). + */ + Name: string; + + /** + * Path of the directory containing the host executable. + */ + Path: string; + + /** + * The filename of the currently running script. + */ + ScriptName: string; + + /** + * Exposes the read-only input stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdIn: TextStreamReader; + + /** + * Windows Script Host version + */ + Version: string; + + /** + * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. + */ + ConnectObject(objEventSource: any, strPrefix: string): void; + + /** + * Creates a COM object. + * @param strProgiID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + CreateObject(strProgID: string, strPrefix?: string): any; + + /** + * Disconnects a COM object from its event sources. + */ + DisconnectObject(obj: any): void; + + /** + * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. + * @param strPathname Fully qualified path to the file containing the object persisted to disk. + * For objects in memory, pass a zero-length string. + * @param strProgID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; + + /** + * Suspends script execution for a specified length of time, then continues execution. + * @param intTime Interval (in milliseconds) to suspend script execution. + */ + Sleep(intTime: number): void; +}; + +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + +/** + * Allows enumerating over a COM collection, which may not have indexed item access. + */ +interface Enumerator { + /** + * Returns true if the current item is the last one in the collection, or the collection is empty, + * or the current item is undefined. + */ + atEnd(): boolean; + + /** + * Returns the current item in the collection + */ + item(): T; + + /** + * Resets the current item in the collection to the first item. If there are no items in the collection, + * the current item is set to undefined. + */ + moveFirst(): void; + + /** + * Moves the current item to the next item in the collection. If the enumerator is at the end of + * the collection or the collection is empty, the current item is set to undefined. + */ + moveNext(): void; +} + +interface EnumeratorConstructor { + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; +} + +declare var Enumerator: EnumeratorConstructor; + +/** + * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. + */ +interface VBArray { + /** + * Returns the number of dimensions (1-based). + */ + dimensions(): number; + + /** + * Takes an index for each dimension in the array, and returns the item at the corresponding location. + */ + getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; + + /** + * Returns the smallest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + lbound(dimension?: number): number; + + /** + * Returns the largest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + ubound(dimension?: number): number; + + /** + * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, + * each successive dimension is appended to the end of the array. + * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] + */ + toArray(): T[]; +} + +interface VBArrayConstructor { + new (safeArray: SafeArray): VBArray; +} + +declare var VBArray: VBArrayConstructor; + +/** + * Automation date (VT_DATE) + */ +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} + +interface DateConstructor { + new (vd: VarDate): Date; +} + +interface Date { + getVarDate: () => VarDate; +} + + +/// + +interface DOMTokenList { + [Symbol.iterator](): IterableIterator; +} + +interface Headers { + [Symbol.iterator](): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all key/value pairs contained in this object. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns an iterator allowing to go through all keys f the key/value pairs contained in this object. + */ + keys(): IterableIterator; + /** + * Returns an iterator allowing to go through all values of the key/value pairs contained in this object. + */ + values(): IterableIterator; +} + +interface NodeList { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[number, Node]>; + /** + * Performs the specified action for each node in an list. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void; + /** + * Returns an list of keys in the list + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the list + */ + values(): IterableIterator; + + + [Symbol.iterator](): IterableIterator; +} + +interface NodeListOf { + + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[number, TNode]>; + + /** + * Performs the specified action for each node in an list. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: TNode, index: number, listObj: NodeListOf) => void, thisArg?: any): void; + /** + * Returns an list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns an list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[string, string | File]>; + /** + * Returns a list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + +interface URLSearchParams { + /** + * Returns an array of key, value pairs for every entry in the search params + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns a list of keys in the search params + */ + keys(): IterableIterator; + /** + * Returns a list of values in the search params + */ + values(): IterableIterator; + /** + * iterate over key/value pairs + */ + [Symbol.iterator](): IterableIterator<[string, string]>; +} diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 73aa450927d8b..3f495ed40a92c 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -82,6 +82,18 @@ declare function encodeURI(uri: string): string; */ declare function encodeURIComponent(uriComponent: string): string; +/** + * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. + * @param string A string value + */ +declare function escape(string: string): string; + +/** + * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. + * @param string A string value + */ +declare function unescape(string: string): string; + interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; @@ -1070,7 +1082,8 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1082,7 +1095,8 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1220,7 +1234,8 @@ interface Array { * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1232,7 +1247,8 @@ interface Array { * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1667,7 +1683,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1691,7 +1708,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -1934,7 +1952,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1958,7 +1977,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2201,7 +2221,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2225,7 +2246,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2466,7 +2488,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2490,7 +2513,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2734,7 +2758,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2758,7 +2783,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3001,7 +3027,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3025,7 +3052,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3267,7 +3295,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3291,7 +3320,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3534,7 +3564,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3558,7 +3589,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3802,7 +3834,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3826,7 +3859,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index a84a66e1293e1..9d6b6b345fad1 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -82,6 +82,18 @@ declare function encodeURI(uri: string): string; */ declare function encodeURIComponent(uriComponent: string): string; +/** + * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. + * @param string A string value + */ +declare function escape(string: string): string; + +/** + * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. + * @param string A string value + */ +declare function unescape(string: string): string; + interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; @@ -1070,7 +1082,8 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1082,7 +1095,8 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1220,7 +1234,8 @@ interface Array { * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1232,7 +1247,8 @@ interface Array { * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1667,7 +1683,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1691,7 +1708,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -1934,7 +1952,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1958,7 +1977,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2201,7 +2221,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2225,7 +2246,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2466,7 +2488,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2490,7 +2513,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2734,7 +2758,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2758,7 +2783,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3001,7 +3027,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3025,7 +3052,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3267,7 +3295,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3291,7 +3320,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3534,7 +3564,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3558,7 +3589,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3802,7 +3834,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3826,7 +3859,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4094,6 +4128,7 @@ interface Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ + find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** @@ -4133,10 +4168,16 @@ interface ArrayConstructor { /** * Creates an array from an array-like object. * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): T[]; + + /** + * Creates an array from an iterable object. + * @param arrayLike An array-like object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. @@ -4246,7 +4287,7 @@ interface Math { * If any argument is NaN, the result is NaN. * If all arguments are either +0 or −0, the result is +0. */ - hypot(...values: number[] ): number; + hypot(...values: number[]): number; /** * Returns the integral part of the a numeric expression, x, removing any fractional digits. @@ -4434,6 +4475,7 @@ interface ReadonlyArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ + find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** @@ -4525,7 +4567,7 @@ interface String { /** * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. + * the empty string is returned. * @param count number of copies to append */ repeat(count: number): string; @@ -4779,13 +4821,19 @@ interface Array { } interface ArrayConstructor { + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): T[]; + /** * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -5632,7 +5680,7 @@ interface Promise { } interface PromiseConstructor { - readonly [Symbol.species]: Function; + readonly [Symbol.species]: PromiseConstructor; } interface RegExp { @@ -5684,7 +5732,7 @@ interface RegExp { } interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; + readonly [Symbol.species]: RegExpConstructor; } interface String { @@ -5766,6 +5814,18 @@ interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } +interface ArrayConstructor { + readonly [Symbol.species]: ArrayConstructor; +} +interface MapConstructor { + readonly [Symbol.species]: MapConstructor; +} +interface SetConstructor { + readonly [Symbol.species]: SetConstructor; +} +interface ArrayBufferConstructor { + readonly [Symbol.species]: ArrayBufferConstructor; +} ///////////////////////////// @@ -5851,8 +5911,8 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } -interface CustomEventInit extends EventInit { - detail?: any; +interface CustomEventInit extends EventInit { + detail?: T; } interface DeviceAccelerationDict { @@ -5972,7 +6032,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface IntersectionObserverEntryInit { @@ -6465,7 +6525,7 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; total?: PaymentItem; } @@ -6477,7 +6537,7 @@ interface PaymentItem { interface PaymentMethodData { data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; } interface PaymentOptions { @@ -6542,7 +6602,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -6554,7 +6614,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -7024,8 +7084,10 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ApplicationCache: { @@ -7081,8 +7143,10 @@ interface AudioBufferSourceNode extends AudioNode { readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AudioBufferSourceNode: { @@ -7123,8 +7187,10 @@ interface AudioContextBase extends EventTarget { createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; resume(): Promise; - addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface AudioContext extends AudioContextBase { @@ -7231,8 +7297,10 @@ interface AudioTrackList extends EventTarget { onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: AudioTrack; } @@ -7358,6 +7426,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { beginPath(): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; @@ -7367,11 +7436,13 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; restore(): void; @@ -8135,20 +8206,22 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } declare var CustomEvent: { prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; interface DataCue extends TextTrackCue { data: ArrayBuffer; - addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DataCue: { @@ -8999,7 +9072,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -9070,8 +9144,10 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Document: { @@ -9354,7 +9430,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -9383,6 +9460,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scroll(options?: ScrollToOptions): void; @@ -9395,8 +9474,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; - addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Element: { @@ -9532,8 +9613,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -9654,7 +9737,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface History { @@ -9765,8 +9848,10 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAnchorElement: { @@ -9839,8 +9924,10 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; - addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAppletElement: { @@ -9907,8 +9994,10 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAreaElement: { @@ -9925,8 +10014,10 @@ declare var HTMLAreasCollection: { }; interface HTMLAudioElement extends HTMLMediaElement { - addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAudioElement: { @@ -9943,8 +10034,10 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseElement: { @@ -9961,8 +10054,10 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseFontElement: { @@ -10002,11 +10097,7 @@ interface HTMLBodyElement extends HTMLElement { onafterprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; - onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; - onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; - onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; - onload: (this: HTMLBodyElement, ev: Event) => any; onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; onoffline: (this: HTMLBodyElement, ev: Event) => any; ononline: (this: HTMLBodyElement, ev: Event) => any; @@ -10015,13 +10106,14 @@ interface HTMLBodyElement extends HTMLElement { onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; onresize: (this: HTMLBodyElement, ev: UIEvent) => any; - onscroll: (this: HTMLBodyElement, ev: UIEvent) => any; onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBodyElement: { @@ -10034,8 +10126,10 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBRElement: { @@ -10107,8 +10201,10 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLButtonElement: { @@ -10142,8 +10238,10 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; - addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLCanvasElement: { @@ -10177,8 +10275,10 @@ declare var HTMLCollection: { interface HTMLDataElement extends HTMLElement { value: string; - addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataElement: { @@ -10188,8 +10288,10 @@ declare var HTMLDataElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; - addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataListElement: { @@ -10199,8 +10301,10 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDirectoryElement: { @@ -10217,8 +10321,10 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; - addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDivElement: { @@ -10228,8 +10334,10 @@ declare var HTMLDivElement: { interface HTMLDListElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDListElement: { @@ -10238,8 +10346,10 @@ declare var HTMLDListElement: { }; interface HTMLDocument extends Document { - addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDocument: { @@ -10411,8 +10521,10 @@ interface HTMLElement extends Element { dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLElement: { @@ -10467,8 +10579,10 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLEmbedElement: { @@ -10508,8 +10622,10 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFieldSetElement: { @@ -10522,8 +10638,10 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; - addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFontElement: { @@ -10607,8 +10725,11 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; - addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -10670,10 +10791,6 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -10686,8 +10803,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameElement: { @@ -10739,17 +10858,7 @@ interface HTMLFrameSetElement extends HTMLElement { onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; - onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; - onload: (this: HTMLFrameSetElement, ev: Event) => any; onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; onoffline: (this: HTMLFrameSetElement, ev: Event) => any; ononline: (this: HTMLFrameSetElement, ev: Event) => any; @@ -10758,15 +10867,16 @@ interface HTMLFrameSetElement extends HTMLElement { onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; - onscroll: (this: HTMLFrameSetElement, ev: UIEvent) => any; onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameSetElement: { @@ -10776,8 +10886,10 @@ declare var HTMLFrameSetElement: { interface HTMLHeadElement extends HTMLElement { profile: string; - addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadElement: { @@ -10790,8 +10902,10 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; - addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadingElement: { @@ -10812,8 +10926,10 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHRElement: { @@ -10826,8 +10942,10 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; - addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHtmlElement: { @@ -10894,10 +11012,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -10915,8 +11029,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLIFrameElement: { @@ -11006,8 +11122,10 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; - addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLImageElement: { @@ -11218,8 +11336,10 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; - addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLInputElement: { @@ -11236,8 +11356,11 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; - addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLabelElement: { @@ -11254,8 +11377,10 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement | null; - addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLegendElement: { @@ -11269,8 +11394,10 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLIElement: { @@ -11314,8 +11441,10 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; - addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLinkElement: { @@ -11332,8 +11461,10 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMapElement: { @@ -11364,8 +11495,10 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMarqueeElement: { @@ -11546,8 +11679,10 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMediaElement: { @@ -11567,8 +11702,10 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMenuElement: { @@ -11601,8 +11738,10 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; - addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMetaElement: { @@ -11617,8 +11756,10 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; - addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMeterElement: { @@ -11635,8 +11776,10 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; - addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLModElement: { @@ -11752,8 +11895,10 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLObjectElement: { @@ -11768,8 +11913,10 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; - addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOListElement: { @@ -11807,8 +11954,10 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptGroupElement: { @@ -11846,8 +11995,10 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptionElement: { @@ -11880,8 +12031,10 @@ interface HTMLOutputElement extends HTMLElement { checkValidity(): boolean; reportValidity(): boolean; setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOutputElement: { @@ -11895,8 +12048,10 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; - addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParagraphElement: { @@ -11921,8 +12076,10 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; - addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParamElement: { @@ -11931,8 +12088,10 @@ declare var HTMLParamElement: { }; interface HTMLPictureElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPictureElement: { @@ -11945,8 +12104,10 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPreElement: { @@ -11971,8 +12132,10 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; - addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLProgressElement: { @@ -11985,8 +12148,10 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; - addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLQuoteElement: { @@ -12026,8 +12191,10 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; - addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLScriptElement: { @@ -12122,8 +12289,10 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -12148,8 +12317,10 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; - addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSourceElement: { @@ -12158,8 +12329,10 @@ declare var HTMLSourceElement: { }; interface HTMLSpanElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSpanElement: { @@ -12177,8 +12350,10 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; - addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLStyleElement: { @@ -12195,8 +12370,10 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; - addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCaptionElement: { @@ -12250,8 +12427,10 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCellElement: { @@ -12272,8 +12451,10 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; - addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableColElement: { @@ -12282,8 +12463,10 @@ declare var HTMLTableColElement: { }; interface HTMLTableDataCellElement extends HTMLTableCellElement { - addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableDataCellElement: { @@ -12395,8 +12578,10 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableElement: { @@ -12409,8 +12594,10 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; - addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableHeaderCellElement: { @@ -12450,8 +12637,10 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableRowElement: { @@ -12478,8 +12667,10 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableSectionElement: { @@ -12489,8 +12680,10 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; - addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTemplateElement: { @@ -12596,8 +12789,10 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; - addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTextAreaElement: { @@ -12607,8 +12802,10 @@ declare var HTMLTextAreaElement: { interface HTMLTimeElement extends HTMLElement { dateTime: string; - addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTimeElement: { @@ -12621,8 +12818,10 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; - addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTitleElement: { @@ -12642,8 +12841,10 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; - addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTrackElement: { @@ -12658,8 +12859,10 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUListElement: { @@ -12668,8 +12871,10 @@ declare var HTMLUListElement: { }; interface HTMLUnknownElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUnknownElement: { @@ -12723,8 +12928,10 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullScreen(): void; webkitExitFullscreen(): void; webkitExitFullScreen(): void; - addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLVideoElement: { @@ -12781,9 +12988,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -12867,8 +13077,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -12889,8 +13101,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -12916,8 +13130,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -13086,8 +13302,10 @@ interface MediaDevices extends EventTarget { enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaDevices: { @@ -13258,8 +13476,10 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStream: { @@ -13330,8 +13550,10 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStreamTrack: { @@ -13380,8 +13602,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -13485,8 +13709,10 @@ interface MSAppAsyncOperation extends EventTarget { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSAppAsyncOperation: { @@ -13641,8 +13867,10 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; - addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSHTMLWebViewElement: { @@ -13667,8 +13895,10 @@ interface MSInputMethodContext extends EventTarget { getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSInputMethodContext: { @@ -13833,8 +14063,10 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSStreamReader: { @@ -13862,8 +14094,10 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSWebViewAsyncOperation: { @@ -13994,6 +14228,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly pointerEnabled: boolean; readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; + readonly doNotTrack: string | null; readonly hardwareConcurrency: number; readonly languages: string[]; getGamepads(): Gamepad[]; @@ -14152,8 +14387,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -14232,8 +14469,10 @@ interface OfflineAudioContext extends AudioContextBase { oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; startRendering(): Promise; suspend(suspendTime: number): Promise; - addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OfflineAudioContext: { @@ -14253,8 +14492,10 @@ interface OscillatorNode extends AudioNode { setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OscillatorNode: { @@ -14348,8 +14589,10 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; show(): Promise; - addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentRequest: { @@ -14855,8 +15098,10 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtlsTransport: { @@ -14885,8 +15130,10 @@ interface RTCDtmfSender extends EventTarget { readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtmfSender: { @@ -14936,8 +15183,10 @@ interface RTCIceGatherer extends RTCStatsProvider { createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidateDictionary[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceGatherer: { @@ -14974,8 +15223,10 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; stop(): void; - addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceTransport: { @@ -15029,8 +15280,10 @@ interface RTCPeerConnection extends EventTarget { removeStream(stream: MediaStream): void; setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCPeerConnection: { @@ -15061,8 +15314,10 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpReceiver: { @@ -15086,8 +15341,10 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpSender: { @@ -15114,8 +15371,10 @@ interface RTCSrtpSdesTransportEventMap { interface RTCSrtpSdesTransport extends EventTarget { onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCSrtpSdesTransport: { @@ -15186,8 +15445,10 @@ interface Screen extends EventTarget { readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -15212,8 +15473,10 @@ interface ScriptProcessorNodeEventMap { interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ScriptProcessorNode: { @@ -15264,8 +15527,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -15283,11 +15548,13 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(): Promise; + getRegistration(clientURL?: USVString): Promise; getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerContainer: { @@ -15324,8 +15591,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -15378,8 +15647,10 @@ interface SpeechSynthesis extends EventTarget { pause(): void; resume(): void; speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesis: { @@ -15423,8 +15694,10 @@ interface SpeechSynthesisUtterance extends EventTarget { text: string; voice: SpeechSynthesisVoice; volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesisUtterance: { @@ -15558,8 +15831,10 @@ declare var SubtleCrypto: { interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGAElement: { @@ -15715,8 +15990,10 @@ interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGCircleElement: { @@ -15726,8 +16003,10 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGClipPathElement: { @@ -15749,8 +16028,10 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGComponentTransferFunctionElement: { @@ -15765,8 +16046,10 @@ declare var SVGComponentTransferFunctionElement: { }; interface SVGDefsElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDefsElement: { @@ -15775,8 +16058,10 @@ declare var SVGDefsElement: { }; interface SVGDescElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDescElement: { @@ -15813,8 +16098,10 @@ interface SVGElement extends Element { readonly style: CSSStyleDeclaration; readonly viewportElement: SVGElement; xmlbase: string; - addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGElement: { @@ -15853,8 +16140,10 @@ interface SVGEllipseElement extends SVGGraphicsElement { readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGEllipseElement: { @@ -15883,8 +16172,10 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEBlendElement: { @@ -15918,8 +16209,10 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEColorMatrixElement: { @@ -15934,8 +16227,10 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEComponentTransferElement: { @@ -15958,8 +16253,10 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFECompositeElement: { @@ -15991,8 +16288,10 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEConvolveMatrixElement: { @@ -16010,8 +16309,10 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDiffuseLightingElement: { @@ -16030,8 +16331,10 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDisplacementMapElement: { @@ -16047,8 +16350,10 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDistantLightElement: { @@ -16057,8 +16362,10 @@ declare var SVGFEDistantLightElement: { }; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFloodElement: { @@ -16067,8 +16374,10 @@ declare var SVGFEFloodElement: { }; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncAElement: { @@ -16077,8 +16386,10 @@ declare var SVGFEFuncAElement: { }; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncBElement: { @@ -16087,8 +16398,10 @@ declare var SVGFEFuncBElement: { }; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncGElement: { @@ -16097,8 +16410,10 @@ declare var SVGFEFuncGElement: { }; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncRElement: { @@ -16111,8 +16426,10 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEGaussianBlurElement: { @@ -16122,8 +16439,10 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEImageElement: { @@ -16132,8 +16451,10 @@ declare var SVGFEImageElement: { }; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeElement: { @@ -16143,8 +16464,10 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeNodeElement: { @@ -16160,8 +16483,10 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMorphologyElement: { @@ -16176,8 +16501,10 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEOffsetElement: { @@ -16189,8 +16516,10 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEPointLightElement: { @@ -16205,8 +16534,10 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpecularLightingElement: { @@ -16223,8 +16554,10 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpotLightElement: { @@ -16234,8 +16567,10 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETileElement: { @@ -16256,8 +16591,10 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETurbulenceElement: { @@ -16281,8 +16618,10 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFilterElement: { @@ -16295,8 +16634,10 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGForeignObjectElement: { @@ -16305,8 +16646,10 @@ declare var SVGForeignObjectElement: { }; interface SVGGElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGElement: { @@ -16322,8 +16665,10 @@ interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGradientElement: { @@ -16343,8 +16688,10 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; - addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGraphicsElement: { @@ -16358,8 +16705,10 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGImageElement: { @@ -16424,8 +16773,10 @@ interface SVGLinearGradientElement extends SVGGradientElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLinearGradientElement: { @@ -16438,8 +16789,10 @@ interface SVGLineElement extends SVGGraphicsElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLineElement: { @@ -16463,8 +16816,10 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly SVG_MARKERUNITS_STROKEWIDTH: number; readonly SVG_MARKERUNITS_UNKNOWN: number; readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMarkerElement: { @@ -16485,8 +16840,10 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMaskElement: { @@ -16520,8 +16877,10 @@ declare var SVGMatrix: { }; interface SVGMetadataElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMetadataElement: { @@ -16578,8 +16937,10 @@ interface SVGPathElement extends SVGGraphicsElement { getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; - addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPathElement: { @@ -16871,8 +17232,10 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPatternElement: { @@ -16908,8 +17271,10 @@ declare var SVGPointList: { }; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolygonElement: { @@ -16918,8 +17283,10 @@ declare var SVGPolygonElement: { }; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolylineElement: { @@ -16971,8 +17338,10 @@ interface SVGRadialGradientElement extends SVGGradientElement { readonly fx: SVGAnimatedLength; readonly fy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRadialGradientElement: { @@ -16999,8 +17368,10 @@ interface SVGRectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRectElement: { @@ -17010,8 +17381,10 @@ declare var SVGRectElement: { interface SVGScriptElement extends SVGElement, SVGURIReference { type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGScriptElement: { @@ -17021,8 +17394,10 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement { readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStopElement: { @@ -17051,8 +17426,10 @@ interface SVGStyleElement extends SVGElement { media: string; title: string; type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStyleElement: { @@ -17112,8 +17489,10 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSVGElement: { @@ -17122,8 +17501,10 @@ declare var SVGSVGElement: { }; interface SVGSwitchElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSwitchElement: { @@ -17132,8 +17513,10 @@ declare var SVGSwitchElement: { }; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { - addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSymbolElement: { @@ -17156,8 +17539,10 @@ interface SVGTextContentElement extends SVGGraphicsElement { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextContentElement: { @@ -17169,8 +17554,10 @@ declare var SVGTextContentElement: { }; interface SVGTextElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextElement: { @@ -17188,8 +17575,10 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPathElement: { @@ -17209,8 +17598,10 @@ interface SVGTextPositioningElement extends SVGTextContentElement { readonly rotate: SVGAnimatedNumberList; readonly x: SVGAnimatedLengthList; readonly y: SVGAnimatedLengthList; - addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPositioningElement: { @@ -17219,8 +17610,10 @@ declare var SVGTextPositioningElement: { }; interface SVGTitleElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTitleElement: { @@ -17278,8 +17671,10 @@ declare var SVGTransformList: { }; interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTSpanElement: { @@ -17301,8 +17696,10 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGUseElement: { @@ -17312,8 +17709,10 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; - addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGViewElement: { @@ -17433,8 +17832,10 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrack: { @@ -17464,8 +17865,10 @@ interface TextTrackCue extends EventTarget { text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrackCue: { @@ -17493,8 +17896,10 @@ interface TextTrackList extends EventTarget { readonly length: number; onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: TextTrack; } @@ -17702,8 +18107,10 @@ interface VideoTrackList extends EventTarget { readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: VideoTrack; } @@ -17907,7 +18314,29 @@ interface WebGLRenderingContext { getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; - getExtension(name: string): any; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram | null): string | null; @@ -18721,8 +19150,10 @@ declare var WebKitPoint: { }; interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var webkitRTCPeerConnection: { @@ -18754,8 +19185,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -19046,7 +19479,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; postMessage(message: any, targetOrigin: string, transfer?: any[]): void; print(): void; prompt(message?: string, _default?: string): string | null; @@ -19067,8 +19500,10 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Window: { @@ -19084,8 +19519,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -19094,8 +19531,10 @@ declare var Worker: { }; interface XMLDocument extends Document { - addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLDocument: { @@ -19136,8 +19575,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -19151,8 +19592,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -19257,8 +19700,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -19403,8 +19848,10 @@ interface GlobalEventHandlers { onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; - addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface GlobalFetch { @@ -19456,8 +19903,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface MSFileSaver { @@ -19514,9 +19963,11 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; - querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -19603,8 +20054,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface BroadcastChannel extends EventTarget { @@ -19613,8 +20066,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -19795,7 +20250,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -20031,6 +20486,128 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -20098,28 +20675,46 @@ interface VoidFunction { } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; "audio": HTMLAudioElement; + "b": HTMLElement; "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; "col": HTMLTableColElement; "colgroup": HTMLTableColElement; "data": HTMLDataElement; "datalist": HTMLDataListElement; + "dd": HTMLElement; "del": HTMLModElement; + "dfn": HTMLElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; "embed": HTMLEmbedElement; "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; "font": HTMLFontElement; + "footer": HTMLElement; "form": HTMLFormElement; "frame": HTMLFrameElement; "frameset": HTMLFrameSetElement; @@ -20130,24 +20725,34 @@ interface HTMLElementTagNameMap { "h5": HTMLHeadingElement; "h6": HTMLHeadingElement; "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; "hr": HTMLHRElement; "html": HTMLHtmlElement; + "i": HTMLElement; "iframe": HTMLIFrameElement; "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; "listing": HTMLPreElement; "map": HTMLMapElement; + "mark": HTMLElement; "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; + "nav": HTMLElement; "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; "optgroup": HTMLOptGroupElement; @@ -20156,14 +20761,25 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; + "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; "script": HTMLScriptElement; + "section": HTMLElement; "select": HTMLSelectElement; + "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; "table": HTMLTableElement; "tbody": HTMLTableSectionElement; "td": HTMLTableDataCellElement; @@ -20176,33 +20792,22 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; "ul": HTMLUListElement; + "var": HTMLElement; "video": HTMLVideoElement; + "wbr": HTMLElement; "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } -interface ElementTagNameMap extends HTMLElementTagNameMap { - "abbr": HTMLElement; - "acronym": HTMLElement; - "address": HTMLElement; - "article": HTMLElement; - "aside": HTMLElement; - "b": HTMLElement; - "bdo": HTMLElement; - "big": HTMLElement; - "center": HTMLElement; +interface SVGElementTagNameMap { "circle": SVGCircleElement; - "cite": HTMLElement; "clippath": SVGClipPathElement; - "code": HTMLElement; - "dd": HTMLElement; "defs": SVGDefsElement; "desc": SVGDescElement; - "dfn": HTMLElement; - "dt": HTMLElement; "ellipse": SVGEllipseElement; - "em": HTMLElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -20227,63 +20832,33 @@ interface ElementTagNameMap extends HTMLElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "figcaption": HTMLElement; - "figure": HTMLElement; "filter": SVGFilterElement; - "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; "g": SVGGElement; - "header": HTMLElement; - "hgroup": HTMLElement; - "i": HTMLElement; "image": SVGImageElement; - "kbd": HTMLElement; - "keygen": HTMLElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "mark": HTMLElement; "marker": SVGMarkerElement; "mask": SVGMaskElement; "metadata": SVGMetadataElement; - "nav": HTMLElement; - "nobr": HTMLElement; - "noframes": HTMLElement; - "noscript": HTMLElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; - "rt": HTMLElement; - "ruby": HTMLElement; - "s": HTMLElement; - "samp": HTMLElement; - "section": HTMLElement; - "small": HTMLElement; "stop": SVGStopElement; - "strike": HTMLElement; - "strong": HTMLElement; - "sub": HTMLElement; - "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; "text": SVGTextElement; "textpath": SVGTextPathElement; "tspan": SVGTSpanElement; - "tt": HTMLElement; - "u": HTMLElement; "use": SVGUseElement; - "var": HTMLElement; "view": SVGViewElement; - "wbr": HTMLElement; } -type ElementListTagNameMap = { - [key in keyof ElementTagNameMap]: NodeListOf -}; +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; @@ -20446,7 +21021,7 @@ declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; @@ -20469,7 +21044,6 @@ declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; @@ -20495,8 +21069,10 @@ declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; -declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; @@ -20520,7 +21096,6 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -20541,6 +21116,7 @@ type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -20931,23 +21507,6 @@ interface DOMTokenList { [Symbol.iterator](): IterableIterator; } -interface FormData { - /** - * Returns an array of key, value pairs for every entry in the list - */ - entries(): IterableIterator<[string, string | File]>; - /** - * Returns a list of keys in the list - */ - keys(): IterableIterator; - /** - * Returns a list of values in the list - */ - values(): IterableIterator; - - [Symbol.iterator](): IterableIterator; -} - interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** @@ -21014,6 +21573,31 @@ interface NodeListOf { [Symbol.iterator](): IterableIterator; } +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[string, string | File]>; + /** + * Returns a list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + interface URLSearchParams { /** * Returns an array of key, value pairs for every entry in the search params diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index 4ee476dfd1a42..cb83c656085fc 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -22,1691 +22,6 @@ and limitations under the License. /// -declare type PropertyKey = string | number | symbol; - -interface Array { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): this; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): T[]; -} - -interface DateConstructor { - new (value: Date): Date; -} - -interface Function { - /** - * Returns the name of the function. Function names are read-only and can not be changed. - */ - readonly name: string; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[] ): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - readonly EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - readonly MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - readonly MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface Object { - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean; -} - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source The source object from which to copy properties. - */ - assign(target: T, source: U): T & U; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V): T & U & V; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - * @param source3 The third source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects from which to copy properties - */ - assign(target: object, ...sources: any[]): any; - - /** - * Returns an array of all symbol properties found directly on object o. - * @param o Object to retrieve the symbols from. - */ - getOwnPropertySymbols(o: any): symbol[]; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - */ - setPrototypeOf(o: any, proto: object | null): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not - * inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript - * object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor - * property. - */ - defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; -} - -interface ReadonlyArray { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - readonly flags: string; - - /** - * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular - * expression. Default is false. Read-only. - */ - readonly sticky: boolean; - - /** - * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular - * expression. Default is false. Read-only. - */ - readonly unicode: boolean; -} - -interface RegExpConstructor { - new (pattern: RegExp, flags?: string): RegExp; - (pattern: RegExp, flags?: string): RegExp; -} - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number | undefined; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; - - /** - * Returns the String value result of normalizing the string into the normalization form - * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. - * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default - * is "NFC" - */ - normalize(form?: string): string; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; - - /** - * Returns an HTML anchor element and sets the name attribute to the text value - * @param name - */ - anchor(name: string): string; - - /** Returns a HTML element */ - big(): string; - - /** Returns a HTML element */ - blink(): string; - - /** Returns a HTML element */ - bold(): string; - - /** Returns a HTML element */ - fixed(): string; - - /** Returns a HTML element and sets the color attribute value */ - fontcolor(color: string): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: number): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: string): string; - - /** Returns an HTML element */ - italics(): string; - - /** Returns an HTML element and sets the href attribute value */ - link(url: string): string; - - /** Returns a HTML element */ - small(): string; - - /** Returns a HTML element */ - strike(): string; - - /** Returns a HTML element */ - sub(): string; - - /** Returns a HTML element */ - sup(): string; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} - - -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value: V): this; - readonly size: number; -} - -interface MapConstructor { - new (): Map; - new (entries?: [K, V][]): Map; - readonly prototype: Map; -} -declare var Map: MapConstructor; - -interface ReadonlyMap { - forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; - get(key: K): V | undefined; - has(key: K): boolean; - readonly size: number; -} - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V | undefined; - has(key: K): boolean; - set(key: K, value: V): this; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (entries?: [K, V][]): WeakMap; - readonly prototype: WeakMap; -} -declare var WeakMap: WeakMapConstructor; - -interface Set { - add(value: T): this; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface SetConstructor { - new (): Set; - new (values?: T[]): Set; - readonly prototype: Set; -} -declare var Set: SetConstructor; - -interface ReadonlySet { - forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; - has(value: T): boolean; - readonly size: number; -} - -interface WeakSet { - add(value: T): this; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (values?: T[]): WeakSet; - readonly prototype: WeakSet; -} -declare var WeakSet: WeakSetConstructor; - - -interface Generator extends Iterator { } - -interface GeneratorFunction { - /** - * Creates a new Generator object. - * @param args A list of arguments the function accepts. - */ - new (...args: any[]): Generator; - /** - * Creates a new Generator object. - * @param args A list of arguments the function accepts. - */ - (...args: any[]): Generator; - /** - * The length of the arguments. - */ - readonly length: number; - /** - * Returns the name of the function. - */ - readonly name: string; - /** - * A reference to the prototype. - */ - readonly prototype: Generator; -} - -interface GeneratorFunctionConstructor { - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): GeneratorFunction; - /** - * Creates a new Generator function. - * @param args A list of arguments the function accepts. - */ - (...args: string[]): GeneratorFunction; - /** - * The length of the arguments. - */ - readonly length: number; - /** - * Returns the name of the function. - */ - readonly name: string; - /** - * A reference to the prototype. - */ - readonly prototype: GeneratorFunction; -} -declare var GeneratorFunction: GeneratorFunctionConstructor; - - -/// - -interface SymbolConstructor { - /** - * A method that returns the default iterator for an object. Called by the semantics of the - * for-of statement. - */ - readonly iterator: symbol; -} - -interface IteratorResult { - done: boolean; - value: T; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface Iterable { - [Symbol.iterator](): Iterator; -} - -interface IterableIterator extends Iterator { - [Symbol.iterator](): IterableIterator; -} - -interface Array { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an iterable of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the array - */ - values(): IterableIterator; -} - -interface ArrayConstructor { - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; -} - -interface ReadonlyArray { - /** Iterator of values in the array. */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an iterable of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the array - */ - values(): IterableIterator; -} - -interface IArguments { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Map { - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](): IterableIterator<[K, V]>; - - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - entries(): IterableIterator<[K, V]>; - - /** - * Returns an iterable of keys in the map - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the map - */ - values(): IterableIterator; -} - -interface ReadonlyMap { - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](): IterableIterator<[K, V]>; - - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - entries(): IterableIterator<[K, V]>; - - /** - * Returns an iterable of keys in the map - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the map - */ - values(): IterableIterator; -} - -interface MapConstructor { - new (iterable: Iterable<[K, V]>): Map; -} - -interface WeakMap { } - -interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; -} - -interface Set { - /** Iterates over values in the set. */ - [Symbol.iterator](): IterableIterator; - /** - * Returns an iterable of [v,v] pairs for every value `v` in the set. - */ - entries(): IterableIterator<[T, T]>; - /** - * Despite its name, returns an iterable of the values in the set, - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the set. - */ - values(): IterableIterator; -} - -interface ReadonlySet { - /** Iterates over values in the set. */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an iterable of [v,v] pairs for every value `v` in the set. - */ - entries(): IterableIterator<[T, T]>; - - /** - * Despite its name, returns an iterable of the values in the set, - */ - keys(): IterableIterator; - - /** - * Returns an iterable of values in the set. - */ - values(): IterableIterator; -} - -interface SetConstructor { - new (iterable: Iterable): Set; -} - -interface WeakSet { } - -interface WeakSetConstructor { - new (iterable: Iterable): WeakSet; -} - -interface Promise { } - -interface PromiseConstructor { - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: Iterable>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: Iterable>): Promise; -} - -declare namespace Reflect { - function enumerate(target: object): IterableIterator; -} - -interface String { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Int8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int8ArrayConstructor { - new (elements: Iterable): Int8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; -} - -interface Uint8Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ArrayConstructor { - new (elements: Iterable): Uint8Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; -} - -interface Uint8ClampedArray { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint8ClampedArrayConstructor { - new (elements: Iterable): Uint8ClampedArray; - - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; -} - -interface Int16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int16ArrayConstructor { - new (elements: Iterable): Int16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; -} - -interface Uint16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint16ArrayConstructor { - new (elements: Iterable): Uint16Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; -} - -interface Int32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Int32ArrayConstructor { - new (elements: Iterable): Int32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; -} - -interface Uint32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Uint32ArrayConstructor { - new (elements: Iterable): Uint32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; -} - -interface Float32Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float32ArrayConstructor { - new (elements: Iterable): Float32Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; -} - -interface Float64Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Float64ArrayConstructor { - new (elements: Iterable): Float64Array; - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; -} - - -interface PromiseConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Promise; - - /** - * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, - * and a reject callback used to reject the promise with a provided reason or error. - */ - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: (T | PromiseLike)[]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: (T | PromiseLike)[]): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor; - -interface ProxyHandler { - getPrototypeOf? (target: T): object | null; - setPrototypeOf? (target: T, v: any): boolean; - isExtensible? (target: T): boolean; - preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; - has? (target: T, p: PropertyKey): boolean; - get? (target: T, p: PropertyKey, receiver: any): any; - set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; - deleteProperty? (target: T, p: PropertyKey): boolean; - defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; - enumerate? (target: T): PropertyKey[]; - ownKeys? (target: T): PropertyKey[]; - apply? (target: T, thisArg: any, argArray?: any): any; - construct? (target: T, argArray: any, newTarget?: any): object; -} - -interface ProxyConstructor { - revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; - new (target: T, handler: ProxyHandler): T; -} -declare var Proxy: ProxyConstructor; - - -declare namespace Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; - function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: object, propertyKey: PropertyKey): boolean; - function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; - function getPrototypeOf(target: object): object; - function has(target: object, propertyKey: PropertyKey): boolean; - function isExtensible(target: object): boolean; - function ownKeys(target: object): PropertyKey[]; - function preventExtensions(target: object): boolean; - function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: object, proto: any): boolean; -} - - -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): symbol; -} - -interface SymbolConstructor { - /** - * A reference to the prototype. - */ - readonly prototype: Symbol; - - /** - * Returns a new unique Symbol value. - * @param description Description of the new Symbol object. - */ - (description?: string | number): symbol; - - /** - * Returns a Symbol object from the global symbol registry matching the given key if found. - * Otherwise, returns a new symbol with this key. - * @param key key to search for. - */ - for(key: string): symbol; - - /** - * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. - * @param sym Symbol to find the key for. - */ - keyFor(sym: symbol): string | undefined; -} - -declare var Symbol: SymbolConstructor; - -/// - -interface SymbolConstructor { - /** - * A method that determines if a constructor object recognizes an object as one of the - * constructor’s instances. Called by the semantics of the instanceof operator. - */ - readonly hasInstance: symbol; - - /** - * A Boolean value that if true indicates that an object should flatten to its array elements - * by Array.prototype.concat. - */ - readonly isConcatSpreadable: symbol; - - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.match method. - */ - readonly match: symbol; - - /** - * A regular expression method that replaces matched substrings of a string. Called by the - * String.prototype.replace method. - */ - readonly replace: symbol; - - /** - * A regular expression method that returns the index within a string that matches the - * regular expression. Called by the String.prototype.search method. - */ - readonly search: symbol; - - /** - * A function valued property that is the constructor function that is used to create - * derived objects. - */ - readonly species: symbol; - - /** - * A regular expression method that splits a string at the indices that match the regular - * expression. Called by the String.prototype.split method. - */ - readonly split: symbol; - - /** - * A method that converts an object to a corresponding primitive value. - * Called by the ToPrimitive abstract operation. - */ - readonly toPrimitive: symbol; - - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - readonly toStringTag: symbol; - - /** - * An Object whose own property names are property names that are excluded from the 'with' - * environment bindings of the associated objects. - */ - readonly unscopables: symbol; -} - -interface Symbol { - readonly [Symbol.toStringTag]: "Symbol"; -} - -interface Array { - /** - * Returns an object whose properties have the value 'true' - * when they will be absent when used in a 'with' statement. - */ - [Symbol.unscopables](): { - copyWithin: boolean; - entries: boolean; - fill: boolean; - find: boolean; - findIndex: boolean; - keys: boolean; - values: boolean; - }; -} - -interface Date { - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "default"): string; - /** - * Converts a Date object to a string. - */ - [Symbol.toPrimitive](hint: "string"): string; - /** - * Converts a Date object to a number. - */ - [Symbol.toPrimitive](hint: "number"): number; - /** - * Converts a Date object to a string or number. - * - * @param hint The strings "number", "string", or "default" to specify what primitive to return. - * - * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". - * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". - */ - [Symbol.toPrimitive](hint: string): string | number; -} - -interface Map { - readonly [Symbol.toStringTag]: "Map"; -} - -interface WeakMap { - readonly [Symbol.toStringTag]: "WeakMap"; -} - -interface Set { - readonly [Symbol.toStringTag]: "Set"; -} - -interface WeakSet { - readonly [Symbol.toStringTag]: "WeakSet"; -} - -interface JSON { - readonly [Symbol.toStringTag]: "JSON"; -} - -interface Function { - /** - * Determines whether the given value inherits from this function if this function was used - * as a constructor function. - * - * A constructor function can control which objects are recognized as its instances by - * 'instanceof' by overriding this method. - */ - [Symbol.hasInstance](value: any): boolean; -} - -interface GeneratorFunction { - readonly [Symbol.toStringTag]: "GeneratorFunction"; -} - -interface Math { - readonly [Symbol.toStringTag]: "Math"; -} - -interface Promise { - readonly [Symbol.toStringTag]: "Promise"; -} - -interface PromiseConstructor { - readonly [Symbol.species]: Function; -} - -interface RegExp { - /** - * Matches a string with this regular expression, and returns an array containing the results of - * that search. - * @param string A string to search within. - */ - [Symbol.match](string: string): RegExpMatchArray | null; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replaceValue A String object or string literal containing the text to replace for every - * successful match of this regular expression. - */ - [Symbol.replace](string: string, replaceValue: string): string; - - /** - * Replaces text in a string, using this regular expression. - * @param string A String object or string literal whose contents matching against - * this regular expression will be replaced - * @param replacer A function that returns the replacement text. - */ - [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the position beginning first substring match in a regular expression search - * using this regular expression. - * - * @param string The string to search within. - */ - [Symbol.search](string: string): number; - - /** - * Returns an array of substrings that were delimited by strings in the original input that - * match against this regular expression. - * - * If the regular expression contains capturing parentheses, then each time this - * regular expression matches, the results (including any undefined results) of the - * capturing parentheses are spliced. - * - * @param string string value to split - * @param limit if not undefined, the output array is truncated so that it contains no more - * than 'limit' elements. - */ - [Symbol.split](string: string, limit?: number): string[]; -} - -interface RegExpConstructor { - [Symbol.species](): RegExpConstructor; -} - -interface String { - /** - * Matches a string an object that supports being matched against, and returns an array containing the results of that search. - * @param matcher An object that supports being matched against. - */ - match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; - - /** - * Replaces text in a string, using an object that supports replacement within a string. - * @param searchValue A object can search for and replace matches within a string. - * @param replacer A function that returns the replacement text. - */ - replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param searcher An object which supports searching within a string. - */ - search(searcher: { [Symbol.search](string: string): number; }): number; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param splitter An object that can split a string. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; -} - -interface ArrayBuffer { - readonly [Symbol.toStringTag]: "ArrayBuffer"; -} - -interface DataView { - readonly [Symbol.toStringTag]: "DataView"; -} - -interface Int8Array { - readonly [Symbol.toStringTag]: "Int8Array"; -} - -interface Uint8Array { - readonly [Symbol.toStringTag]: "UInt8Array"; -} - -interface Uint8ClampedArray { - readonly [Symbol.toStringTag]: "Uint8ClampedArray"; -} - -interface Int16Array { - readonly [Symbol.toStringTag]: "Int16Array"; -} - -interface Uint16Array { - readonly [Symbol.toStringTag]: "Uint16Array"; -} - -interface Int32Array { - readonly [Symbol.toStringTag]: "Int32Array"; -} - -interface Uint32Array { - readonly [Symbol.toStringTag]: "Uint32Array"; -} - -interface Float32Array { - readonly [Symbol.toStringTag]: "Float32Array"; -} - -interface Float64Array { - readonly [Symbol.toStringTag]: "Float64Array"; -} - - ///////////////////////////// /// DOM APIs @@ -1791,8 +106,8 @@ interface ConstrainVideoFacingModeParameters { ideal?: VideoFacingModeEnum | VideoFacingModeEnum[]; } -interface CustomEventInit extends EventInit { - detail?: any; +interface CustomEventInit extends EventInit { + detail?: T; } interface DeviceAccelerationDict { @@ -1912,7 +227,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface IntersectionObserverEntryInit { @@ -2405,7 +720,7 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; total?: PaymentItem; } @@ -2417,7 +732,7 @@ interface PaymentItem { interface PaymentMethodData { data?: any; - supportedMethods: string[]; + supportedMethods: string | string[]; } interface PaymentOptions { @@ -2482,7 +797,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -2494,7 +809,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -2964,8 +1279,10 @@ interface ApplicationCache extends EventTarget { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; - addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ApplicationCache: { @@ -3021,8 +1338,10 @@ interface AudioBufferSourceNode extends AudioNode { readonly playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AudioBufferSourceNode: { @@ -3063,8 +1382,10 @@ interface AudioContextBase extends EventTarget { createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; resume(): Promise; - addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface AudioContext extends AudioContextBase { @@ -3171,8 +1492,10 @@ interface AudioTrackList extends EventTarget { onremovetrack: (this: AudioTrackList, ev: TrackEvent) => any; getTrackById(id: string): AudioTrack | null; item(index: number): AudioTrack; - addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: AudioTrack; } @@ -3298,6 +1621,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { beginPath(): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; @@ -3307,11 +1631,13 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods { drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; restore(): void; @@ -4075,20 +2401,22 @@ declare var CSSSupportsRule: { new(): CSSSupportsRule; }; -interface CustomEvent extends Event { - readonly detail: any; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +interface CustomEvent extends Event { + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } declare var CustomEvent: { prototype: CustomEvent; - new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; }; interface DataCue extends TextTrackCue { data: ArrayBuffer; - addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DataCue: { @@ -4939,7 +3267,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): ElementListTagNameMap[K]; + getElementsByTagName(tagname: K): NodeListOf; + getElementsByTagName(tagname: K): NodeListOf; getElementsByTagName(tagname: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -5010,8 +3339,10 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; - addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Document: { @@ -5294,7 +3625,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec getAttributeNS(namespaceURI: string, localName: string): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; - getElementsByTagName(name: K): ElementListTagNameMap[K]; + getElementsByTagName(name: K): NodeListOf; + getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; @@ -5323,6 +3655,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scroll(options?: ScrollToOptions): void; @@ -5335,8 +3669,10 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; - addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Element: { @@ -5472,8 +3808,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -5594,7 +3932,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface History { @@ -5705,8 +4043,10 @@ interface HTMLAnchorElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAnchorElement: { @@ -5779,8 +4119,10 @@ interface HTMLAppletElement extends HTMLElement { useMap: string; vspace: number; width: number; - addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAppletElement: { @@ -5847,8 +4189,10 @@ interface HTMLAreaElement extends HTMLElement { * Returns a string representation of an object. */ toString(): string; - addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAreaElement: { @@ -5865,8 +4209,10 @@ declare var HTMLAreasCollection: { }; interface HTMLAudioElement extends HTMLMediaElement { - addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLAudioElement: { @@ -5883,8 +4229,10 @@ interface HTMLBaseElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseElement: { @@ -5901,8 +4249,10 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty * Sets or retrieves the font size of the object. */ size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBaseFontElement: { @@ -5942,11 +4292,7 @@ interface HTMLBodyElement extends HTMLElement { onafterprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeprint: (this: HTMLBodyElement, ev: Event) => any; onbeforeunload: (this: HTMLBodyElement, ev: BeforeUnloadEvent) => any; - onblur: (this: HTMLBodyElement, ev: FocusEvent) => any; - onerror: (this: HTMLBodyElement, ev: ErrorEvent) => any; - onfocus: (this: HTMLBodyElement, ev: FocusEvent) => any; onhashchange: (this: HTMLBodyElement, ev: HashChangeEvent) => any; - onload: (this: HTMLBodyElement, ev: Event) => any; onmessage: (this: HTMLBodyElement, ev: MessageEvent) => any; onoffline: (this: HTMLBodyElement, ev: Event) => any; ononline: (this: HTMLBodyElement, ev: Event) => any; @@ -5955,13 +4301,14 @@ interface HTMLBodyElement extends HTMLElement { onpageshow: (this: HTMLBodyElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLBodyElement, ev: PopStateEvent) => any; onresize: (this: HTMLBodyElement, ev: UIEvent) => any; - onscroll: (this: HTMLBodyElement, ev: UIEvent) => any; onstorage: (this: HTMLBodyElement, ev: StorageEvent) => any; onunload: (this: HTMLBodyElement, ev: Event) => any; text: any; vLink: any; - addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBodyElement: { @@ -5974,8 +4321,10 @@ interface HTMLBRElement extends HTMLElement { * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; - addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLBRElement: { @@ -6047,8 +4396,10 @@ interface HTMLButtonElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLButtonElement: { @@ -6082,8 +4433,10 @@ interface HTMLCanvasElement extends HTMLElement { */ toDataURL(type?: string, ...args: any[]): string; toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; - addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLCanvasElement: { @@ -6117,8 +4470,10 @@ declare var HTMLCollection: { interface HTMLDataElement extends HTMLElement { value: string; - addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataElement: { @@ -6128,8 +4483,10 @@ declare var HTMLDataElement: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; - addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDataListElement: { @@ -6139,8 +4496,10 @@ declare var HTMLDataListElement: { interface HTMLDirectoryElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDirectoryElement: { @@ -6157,8 +4516,10 @@ interface HTMLDivElement extends HTMLElement { * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; - addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDivElement: { @@ -6168,8 +4529,10 @@ declare var HTMLDivElement: { interface HTMLDListElement extends HTMLElement { compact: boolean; - addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDListElement: { @@ -6178,8 +4541,10 @@ declare var HTMLDListElement: { }; interface HTMLDocument extends Document { - addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLDocument: { @@ -6351,8 +4716,10 @@ interface HTMLElement extends Element { dragDrop(): boolean; focus(): void; msGetInputContext(): MSInputMethodContext; - addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLElement: { @@ -6407,8 +4774,10 @@ interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLEmbedElement: { @@ -6448,8 +4817,10 @@ interface HTMLFieldSetElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFieldSetElement: { @@ -6462,8 +4833,10 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM * Sets or retrieves the current typeface family. */ face: string; - addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFontElement: { @@ -6547,8 +4920,11 @@ interface HTMLFormElement extends HTMLElement { * Fires when a FORM is about to be submitted. */ submit(): void; - addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + reportValidity(): boolean; + addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -6610,10 +4986,6 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLFrameElement, ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ @@ -6626,8 +4998,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string | number; - addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameElement: { @@ -6679,17 +5053,7 @@ interface HTMLFrameSetElement extends HTMLElement { onafterprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeprint: (this: HTMLFrameSetElement, ev: Event) => any; onbeforeunload: (this: HTMLFrameSetElement, ev: BeforeUnloadEvent) => any; - /** - * Fires when the object loses the input focus. - */ - onblur: (this: HTMLFrameSetElement, ev: FocusEvent) => any; - onerror: (this: HTMLFrameSetElement, ev: ErrorEvent) => any; - /** - * Fires when the object receives focus. - */ - onfocus: (this: HTMLFrameSetElement, ev: FocusEvent) => any; onhashchange: (this: HTMLFrameSetElement, ev: HashChangeEvent) => any; - onload: (this: HTMLFrameSetElement, ev: Event) => any; onmessage: (this: HTMLFrameSetElement, ev: MessageEvent) => any; onoffline: (this: HTMLFrameSetElement, ev: Event) => any; ononline: (this: HTMLFrameSetElement, ev: Event) => any; @@ -6698,15 +5062,16 @@ interface HTMLFrameSetElement extends HTMLElement { onpageshow: (this: HTMLFrameSetElement, ev: PageTransitionEvent) => any; onpopstate: (this: HTMLFrameSetElement, ev: PopStateEvent) => any; onresize: (this: HTMLFrameSetElement, ev: UIEvent) => any; - onscroll: (this: HTMLFrameSetElement, ev: UIEvent) => any; onstorage: (this: HTMLFrameSetElement, ev: StorageEvent) => any; onunload: (this: HTMLFrameSetElement, ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLFrameSetElement: { @@ -6716,8 +5081,10 @@ declare var HTMLFrameSetElement: { interface HTMLHeadElement extends HTMLElement { profile: string; - addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadElement: { @@ -6730,8 +5097,10 @@ interface HTMLHeadingElement extends HTMLElement { * Sets or retrieves a value that indicates the table alignment. */ align: string; - addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHeadingElement: { @@ -6752,8 +5121,10 @@ interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2 * Sets or retrieves the width of the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHRElement: { @@ -6766,8 +5137,10 @@ interface HTMLHtmlElement extends HTMLElement { * Sets or retrieves the DTD version that governs the current document. */ version: string; - addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLHtmlElement: { @@ -6834,10 +5207,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; - /** - * Raised when the object has been completely received from the server. - */ - onload: (this: HTMLIFrameElement, ev: Event) => any; readonly sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. @@ -6855,8 +5224,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLIFrameElement: { @@ -6946,8 +5317,10 @@ interface HTMLImageElement extends HTMLElement { readonly x: number; readonly y: number; msGetAsCastingSource(): any; - addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLImageElement: { @@ -7158,8 +5531,10 @@ interface HTMLInputElement extends HTMLElement { * @param n Value to increment the value by. */ stepUp(n?: number): void; - addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLInputElement: { @@ -7176,8 +5551,11 @@ interface HTMLLabelElement extends HTMLElement { * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; - addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + readonly control: HTMLInputElement | null; + addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLabelElement: { @@ -7194,8 +5572,10 @@ interface HTMLLegendElement extends HTMLElement { * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement | null; - addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLegendElement: { @@ -7209,8 +5589,10 @@ interface HTMLLIElement extends HTMLElement { * Sets or retrieves the value of a list item. */ value: number; - addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLIElement: { @@ -7254,8 +5636,10 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { type: string; import?: Document; integrity: string; - addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLLinkElement: { @@ -7272,8 +5656,10 @@ interface HTMLMapElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMapElement: { @@ -7304,8 +5690,10 @@ interface HTMLMarqueeElement extends HTMLElement { width: string; start(): void; stop(): void; - addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMarqueeElement: { @@ -7486,8 +5874,10 @@ interface HTMLMediaElement extends HTMLElement { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; - addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMediaElement: { @@ -7507,8 +5897,10 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMenuElement: { @@ -7541,8 +5933,10 @@ interface HTMLMetaElement extends HTMLElement { * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; - addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMetaElement: { @@ -7557,8 +5951,10 @@ interface HTMLMeterElement extends HTMLElement { min: number; optimum: number; value: number; - addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLMeterElement: { @@ -7575,8 +5971,10 @@ interface HTMLModElement extends HTMLElement { * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; - addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLModElement: { @@ -7692,8 +6090,10 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLObjectElement: { @@ -7708,8 +6108,10 @@ interface HTMLOListElement extends HTMLElement { */ start: number; type: string; - addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOListElement: { @@ -7747,8 +6149,10 @@ interface HTMLOptGroupElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptGroupElement: { @@ -7786,8 +6190,10 @@ interface HTMLOptionElement extends HTMLElement { * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; - addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOptionElement: { @@ -7820,8 +6226,10 @@ interface HTMLOutputElement extends HTMLElement { checkValidity(): boolean; reportValidity(): boolean; setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLOutputElement: { @@ -7835,8 +6243,10 @@ interface HTMLParagraphElement extends HTMLElement { */ align: string; clear: string; - addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParagraphElement: { @@ -7861,8 +6271,10 @@ interface HTMLParamElement extends HTMLElement { * Sets or retrieves the data type of the value attribute. */ valueType: string; - addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLParamElement: { @@ -7871,8 +6283,10 @@ declare var HTMLParamElement: { }; interface HTMLPictureElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPictureElement: { @@ -7885,8 +6299,10 @@ interface HTMLPreElement extends HTMLElement { * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; - addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLPreElement: { @@ -7911,8 +6327,10 @@ interface HTMLProgressElement extends HTMLElement { * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; - addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLProgressElement: { @@ -7925,8 +6343,10 @@ interface HTMLQuoteElement extends HTMLElement { * Sets or retrieves reference information about the object. */ cite: string; - addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLQuoteElement: { @@ -7966,8 +6386,10 @@ interface HTMLScriptElement extends HTMLElement { */ type: string; integrity: string; - addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLScriptElement: { @@ -8062,8 +6484,10 @@ interface HTMLSelectElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; - addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [name: string]: any; } @@ -8088,8 +6512,10 @@ interface HTMLSourceElement extends HTMLElement { * Gets or sets the MIME type of a media resource. */ type: string; - addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSourceElement: { @@ -8098,8 +6524,10 @@ declare var HTMLSourceElement: { }; interface HTMLSpanElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLSpanElement: { @@ -8117,8 +6545,10 @@ interface HTMLStyleElement extends HTMLElement, LinkStyle { * Retrieves the CSS language in which the style sheet is written. */ type: string; - addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLStyleElement: { @@ -8135,8 +6565,10 @@ interface HTMLTableCaptionElement extends HTMLElement { * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; - addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCaptionElement: { @@ -8190,8 +6622,10 @@ interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableCellElement: { @@ -8212,8 +6646,10 @@ interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { * Sets or retrieves the width of the object. */ width: any; - addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableColElement: { @@ -8222,8 +6658,10 @@ declare var HTMLTableColElement: { }; interface HTMLTableDataCellElement extends HTMLTableCellElement { - addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableDataCellElement: { @@ -8335,8 +6773,10 @@ interface HTMLTableElement extends HTMLElement { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableElement: { @@ -8349,8 +6789,10 @@ interface HTMLTableHeaderCellElement extends HTMLTableCellElement { * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; - addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableHeaderCellElement: { @@ -8390,8 +6832,10 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableDataCellElement; - addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableRowElement: { @@ -8418,8 +6862,10 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; - addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTableSectionElement: { @@ -8429,8 +6875,10 @@ declare var HTMLTableSectionElement: { interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; - addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTemplateElement: { @@ -8536,8 +6984,10 @@ interface HTMLTextAreaElement extends HTMLElement { * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; - addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTextAreaElement: { @@ -8547,8 +6997,10 @@ declare var HTMLTextAreaElement: { interface HTMLTimeElement extends HTMLElement { dateTime: string; - addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTimeElement: { @@ -8561,8 +7013,10 @@ interface HTMLTitleElement extends HTMLElement { * Retrieves or sets the text of the object as a string. */ text: string; - addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTitleElement: { @@ -8582,8 +7036,10 @@ interface HTMLTrackElement extends HTMLElement { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; - addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLTrackElement: { @@ -8598,8 +7054,10 @@ declare var HTMLTrackElement: { interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; - addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUListElement: { @@ -8608,8 +7066,10 @@ declare var HTMLUListElement: { }; interface HTMLUnknownElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLUnknownElement: { @@ -8663,8 +7123,10 @@ interface HTMLVideoElement extends HTMLMediaElement { webkitEnterFullScreen(): void; webkitExitFullscreen(): void; webkitExitFullScreen(): void; - addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var HTMLVideoElement: { @@ -8721,9 +7183,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -8807,8 +7272,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -8829,8 +7296,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -8856,8 +7325,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -9026,8 +7497,10 @@ interface MediaDevices extends EventTarget { enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; - addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaDevices: { @@ -9198,8 +7671,10 @@ interface MediaStream extends EventTarget { getVideoTracks(): MediaStreamTrack[]; removeTrack(track: MediaStreamTrack): void; stop(): void; - addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStream: { @@ -9270,8 +7745,10 @@ interface MediaStreamTrack extends EventTarget { getConstraints(): MediaTrackConstraints; getSettings(): MediaTrackSettings; stop(): void; - addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaStreamTrack: { @@ -9320,8 +7797,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -9425,8 +7904,10 @@ interface MSAppAsyncOperation extends EventTarget { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; - addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSAppAsyncOperation, ev: MSAppAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSAppAsyncOperation: { @@ -9581,8 +8062,10 @@ interface MSHTMLWebViewElement extends HTMLElement { navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; - addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSHTMLWebViewElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSHTMLWebViewElement: { @@ -9607,8 +8090,10 @@ interface MSInputMethodContext extends EventTarget { getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSInputMethodContext: { @@ -9773,8 +8258,10 @@ interface MSStreamReader extends EventTarget, MSBaseReader { readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; - addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSStreamReader: { @@ -9802,8 +8289,10 @@ interface MSWebViewAsyncOperation extends EventTarget { readonly TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; readonly TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; readonly TYPE_INVOKE_SCRIPT: number; - addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSWebViewAsyncOperation, ev: MSWebViewAsyncOperationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MSWebViewAsyncOperation: { @@ -9934,6 +8423,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly pointerEnabled: boolean; readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; + readonly doNotTrack: string | null; readonly hardwareConcurrency: number; readonly languages: string[]; getGamepads(): Gamepad[]; @@ -10092,8 +8582,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -10172,8 +8664,10 @@ interface OfflineAudioContext extends AudioContextBase { oncomplete: (this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any; startRendering(): Promise; suspend(suspendTime: number): Promise; - addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OfflineAudioContext: { @@ -10193,8 +8687,10 @@ interface OscillatorNode extends AudioNode { setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; - addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var OscillatorNode: { @@ -10288,8 +8784,10 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; show(): Promise; - addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentRequest: { @@ -10795,8 +9293,10 @@ interface RTCDtlsTransport extends RTCStatsProvider { getRemoteParameters(): RTCDtlsParameters | null; start(remoteParameters: RTCDtlsParameters): void; stop(): void; - addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtlsTransport: { @@ -10825,8 +9325,10 @@ interface RTCDtmfSender extends EventTarget { readonly sender: RTCRtpSender; readonly toneBuffer: string; insertDTMF(tones: string, duration?: number, interToneGap?: number): void; - addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCDtmfSender: { @@ -10876,8 +9378,10 @@ interface RTCIceGatherer extends RTCStatsProvider { createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidateDictionary[]; getLocalParameters(): RTCIceParameters; - addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceGatherer: { @@ -10914,8 +9418,10 @@ interface RTCIceTransport extends RTCStatsProvider { setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void; start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void; stop(): void; - addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCIceTransport: { @@ -10969,8 +9475,10 @@ interface RTCPeerConnection extends EventTarget { removeStream(stream: MediaStream): void; setLocalDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; setRemoteDescription(description: RTCSessionDescription, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise; - addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCPeerConnection: { @@ -11001,8 +9509,10 @@ interface RTCRtpReceiver extends RTCStatsProvider { requestSendCSRC(csrc: number): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpReceiver: { @@ -11026,8 +9536,10 @@ interface RTCRtpSender extends RTCStatsProvider { setTrack(track: MediaStreamTrack): void; setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void; stop(): void; - addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCRtpSender: { @@ -11054,8 +9566,10 @@ interface RTCSrtpSdesTransportEventMap { interface RTCSrtpSdesTransport extends EventTarget { onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null; readonly transport: RTCIceTransport; - addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var RTCSrtpSdesTransport: { @@ -11126,8 +9640,10 @@ interface Screen extends EventTarget { readonly width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -11152,8 +9668,10 @@ interface ScriptProcessorNodeEventMap { interface ScriptProcessorNode extends AudioNode { readonly bufferSize: number; onaudioprocess: (this: ScriptProcessorNode, ev: AudioProcessingEvent) => any; - addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ScriptProcessorNode: { @@ -11204,8 +9722,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -11223,11 +9743,13 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(): Promise; + getRegistration(clientURL?: USVString): Promise; getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerContainer: { @@ -11264,8 +9786,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -11318,8 +9842,10 @@ interface SpeechSynthesis extends EventTarget { pause(): void; resume(): void; speak(utterance: SpeechSynthesisUtterance): void; - addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesis: { @@ -11363,8 +9889,10 @@ interface SpeechSynthesisUtterance extends EventTarget { text: string; voice: SpeechSynthesisVoice; volume: number; - addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SpeechSynthesisUtterance: { @@ -11498,8 +10026,10 @@ declare var SubtleCrypto: { interface SVGAElement extends SVGGraphicsElement, SVGURIReference { readonly target: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGAElement: { @@ -11655,8 +10185,10 @@ interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; readonly cy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGCircleElement: { @@ -11666,8 +10198,10 @@ declare var SVGCircleElement: { interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; - addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGClipPathElement: { @@ -11689,8 +10223,10 @@ interface SVGComponentTransferFunctionElement extends SVGElement { readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGComponentTransferFunctionElement: { @@ -11705,8 +10241,10 @@ declare var SVGComponentTransferFunctionElement: { }; interface SVGDefsElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDefsElement: { @@ -11715,8 +10253,10 @@ declare var SVGDefsElement: { }; interface SVGDescElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGDescElement: { @@ -11753,8 +10293,10 @@ interface SVGElement extends Element { readonly style: CSSStyleDeclaration; readonly viewportElement: SVGElement; xmlbase: string; - addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGElement: { @@ -11793,8 +10335,10 @@ interface SVGEllipseElement extends SVGGraphicsElement { readonly cy: SVGAnimatedLength; readonly rx: SVGAnimatedLength; readonly ry: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGEllipseElement: { @@ -11823,8 +10367,10 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib readonly SVG_FEBLEND_MODE_SCREEN: number; readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number; readonly SVG_FEBLEND_MODE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEBlendElement: { @@ -11858,8 +10404,10 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number; readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number; readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEColorMatrixElement: { @@ -11874,8 +10422,10 @@ declare var SVGFEColorMatrixElement: { interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEComponentTransferElement: { @@ -11898,8 +10448,10 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt readonly SVG_FECOMPOSITE_OPERATOR_OVER: number; readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; readonly SVG_FECOMPOSITE_OPERATOR_XOR: number; - addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFECompositeElement: { @@ -11931,8 +10483,10 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand readonly SVG_EDGEMODE_NONE: number; readonly SVG_EDGEMODE_UNKNOWN: number; readonly SVG_EDGEMODE_WRAP: number; - addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEConvolveMatrixElement: { @@ -11950,8 +10504,10 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan readonly kernelUnitLengthX: SVGAnimatedNumber; readonly kernelUnitLengthY: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDiffuseLightingElement: { @@ -11970,8 +10526,10 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan readonly SVG_CHANNEL_G: number; readonly SVG_CHANNEL_R: number; readonly SVG_CHANNEL_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDisplacementMapElement: { @@ -11987,8 +10545,10 @@ declare var SVGFEDisplacementMapElement: { interface SVGFEDistantLightElement extends SVGElement { readonly azimuth: SVGAnimatedNumber; readonly elevation: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEDistantLightElement: { @@ -11997,8 +10557,10 @@ declare var SVGFEDistantLightElement: { }; interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFloodElement: { @@ -12007,8 +10569,10 @@ declare var SVGFEFloodElement: { }; interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncAElement: { @@ -12017,8 +10581,10 @@ declare var SVGFEFuncAElement: { }; interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncBElement: { @@ -12027,8 +10593,10 @@ declare var SVGFEFuncBElement: { }; interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncGElement: { @@ -12037,8 +10605,10 @@ declare var SVGFEFuncGElement: { }; interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { - addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEFuncRElement: { @@ -12051,8 +10621,10 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; - addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEGaussianBlurElement: { @@ -12062,8 +10634,10 @@ declare var SVGFEGaussianBlurElement: { interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEImageElement: { @@ -12072,8 +10646,10 @@ declare var SVGFEImageElement: { }; interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeElement: { @@ -12083,8 +10659,10 @@ declare var SVGFEMergeElement: { interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMergeNodeElement: { @@ -12100,8 +10678,10 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number; readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number; readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEMorphologyElement: { @@ -12116,8 +10696,10 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEOffsetElement: { @@ -12129,8 +10711,10 @@ interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFEPointLightElement: { @@ -12145,8 +10729,10 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta readonly specularConstant: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; readonly surfaceScale: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpecularLightingElement: { @@ -12163,8 +10749,10 @@ interface SVGFESpotLightElement extends SVGElement { readonly x: SVGAnimatedNumber; readonly y: SVGAnimatedNumber; readonly z: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFESpotLightElement: { @@ -12174,8 +10762,10 @@ declare var SVGFESpotLightElement: { interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; - addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETileElement: { @@ -12196,8 +10786,10 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number; readonly SVG_TURBULENCE_TYPE_TURBULENCE: number; readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFETurbulenceElement: { @@ -12221,8 +10813,10 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; - addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGFilterElement: { @@ -12235,8 +10829,10 @@ interface SVGForeignObjectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGForeignObjectElement: { @@ -12245,8 +10841,10 @@ declare var SVGForeignObjectElement: { }; interface SVGGElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGElement: { @@ -12262,8 +10860,10 @@ interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly SVG_SPREADMETHOD_REFLECT: number; readonly SVG_SPREADMETHOD_REPEAT: number; readonly SVG_SPREADMETHOD_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGradientElement: { @@ -12283,8 +10883,10 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; - addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGGraphicsElement: { @@ -12298,8 +10900,10 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGImageElement: { @@ -12364,8 +10968,10 @@ interface SVGLinearGradientElement extends SVGGradientElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLinearGradientElement: { @@ -12378,8 +10984,10 @@ interface SVGLineElement extends SVGGraphicsElement { readonly x2: SVGAnimatedLength; readonly y1: SVGAnimatedLength; readonly y2: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGLineElement: { @@ -12403,8 +11011,10 @@ interface SVGMarkerElement extends SVGElement, SVGFitToViewBox { readonly SVG_MARKERUNITS_STROKEWIDTH: number; readonly SVG_MARKERUNITS_UNKNOWN: number; readonly SVG_MARKERUNITS_USERSPACEONUSE: number; - addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMarkerElement: { @@ -12425,8 +11035,10 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMaskElement: { @@ -12460,8 +11072,10 @@ declare var SVGMatrix: { }; interface SVGMetadataElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGMetadataElement: { @@ -12518,8 +11132,10 @@ interface SVGPathElement extends SVGGraphicsElement { getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; - addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPathElement: { @@ -12811,8 +11427,10 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPatternElement: { @@ -12848,8 +11466,10 @@ declare var SVGPointList: { }; interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolygonElement: { @@ -12858,8 +11478,10 @@ declare var SVGPolygonElement: { }; interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { - addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGPolylineElement: { @@ -12911,8 +11533,10 @@ interface SVGRadialGradientElement extends SVGGradientElement { readonly fx: SVGAnimatedLength; readonly fy: SVGAnimatedLength; readonly r: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRadialGradientElement: { @@ -12939,8 +11563,10 @@ interface SVGRectElement extends SVGGraphicsElement { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGRectElement: { @@ -12950,8 +11576,10 @@ declare var SVGRectElement: { interface SVGScriptElement extends SVGElement, SVGURIReference { type: string; - addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGScriptElement: { @@ -12961,8 +11589,10 @@ declare var SVGScriptElement: { interface SVGStopElement extends SVGElement { readonly offset: SVGAnimatedNumber; - addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStopElement: { @@ -12991,8 +11621,10 @@ interface SVGStyleElement extends SVGElement { media: string; title: string; type: string; - addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGStyleElement: { @@ -13052,8 +11684,10 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; - addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSVGElement: { @@ -13062,8 +11696,10 @@ declare var SVGSVGElement: { }; interface SVGSwitchElement extends SVGGraphicsElement { - addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSwitchElement: { @@ -13072,8 +11708,10 @@ declare var SVGSwitchElement: { }; interface SVGSymbolElement extends SVGElement, SVGFitToViewBox { - addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGSymbolElement: { @@ -13096,8 +11734,10 @@ interface SVGTextContentElement extends SVGGraphicsElement { readonly LENGTHADJUST_SPACING: number; readonly LENGTHADJUST_SPACINGANDGLYPHS: number; readonly LENGTHADJUST_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextContentElement: { @@ -13109,8 +11749,10 @@ declare var SVGTextContentElement: { }; interface SVGTextElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextElement: { @@ -13128,8 +11770,10 @@ interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly TEXTPATH_SPACINGTYPE_AUTO: number; readonly TEXTPATH_SPACINGTYPE_EXACT: number; readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number; - addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPathElement: { @@ -13149,8 +11793,10 @@ interface SVGTextPositioningElement extends SVGTextContentElement { readonly rotate: SVGAnimatedNumberList; readonly x: SVGAnimatedLengthList; readonly y: SVGAnimatedLengthList; - addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTextPositioningElement: { @@ -13159,8 +11805,10 @@ declare var SVGTextPositioningElement: { }; interface SVGTitleElement extends SVGElement { - addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTitleElement: { @@ -13218,8 +11866,10 @@ declare var SVGTransformList: { }; interface SVGTSpanElement extends SVGTextPositioningElement { - addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGTSpanElement: { @@ -13241,8 +11891,10 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; - addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGUseElement: { @@ -13252,8 +11904,10 @@ declare var SVGUseElement: { interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; - addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var SVGViewElement: { @@ -13373,8 +12027,10 @@ interface TextTrack extends EventTarget { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; - addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrack: { @@ -13404,8 +12060,10 @@ interface TextTrackCue extends EventTarget { text: string; readonly track: TextTrack; getCueAsHTML(): DocumentFragment; - addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var TextTrackCue: { @@ -13433,8 +12091,10 @@ interface TextTrackList extends EventTarget { readonly length: number; onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; item(index: number): TextTrack; - addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: TextTrack; } @@ -13642,8 +12302,10 @@ interface VideoTrackList extends EventTarget { readonly selectedIndex: number; getTrackById(id: string): VideoTrack | null; item(index: number): VideoTrack; - addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; [index: number]: VideoTrack; } @@ -13847,7 +12509,29 @@ interface WebGLRenderingContext { getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; - getExtension(name: string): any; + getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; + getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; + getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; + getExtension(extensionName: "EXT_shader_texture_lod"): EXT_shader_texture_lod | null; + getExtension(extensionName: "EXT_sRGB"): EXT_sRGB | null; + getExtension(extensionName: "OES_vertex_array_object"): OES_vertex_array_object | null; + getExtension(extensionName: "WEBGL_color_buffer_float"): WEBGL_color_buffer_float | null; + getExtension(extensionName: "WEBGL_compressed_texture_astc"): WEBGL_compressed_texture_astc | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc_srgb"): WEBGL_compressed_texture_s3tc_srgb | null; + getExtension(extensionName: "WEBGL_debug_shaders"): WEBGL_debug_shaders | null; + getExtension(extensionName: "WEBGL_draw_buffers"): WEBGL_draw_buffers | null; + getExtension(extensionName: "WEBGL_lose_context"): WEBGL_lose_context | null; + getExtension(extensionName: "WEBGL_depth_texture"): WEBGL_depth_texture | null; + getExtension(extensionName: "WEBGL_debug_renderer_info"): WEBGL_debug_renderer_info | null; + getExtension(extensionName: "WEBGL_compressed_texture_s3tc"): WEBGL_compressed_texture_s3tc | null; + getExtension(extensionName: "OES_texture_half_float_linear"): OES_texture_half_float_linear | null; + getExtension(extensionName: "OES_texture_half_float"): OES_texture_half_float | null; + getExtension(extensionName: "OES_texture_float_linear"): OES_texture_float_linear | null; + getExtension(extensionName: "OES_texture_float"): OES_texture_float | null; + getExtension(extensionName: "OES_standard_derivatives"): OES_standard_derivatives | null; + getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; + getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; + getExtension(extensionName: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram | null): string | null; @@ -14661,8 +13345,10 @@ declare var WebKitPoint: { }; interface webkitRTCPeerConnection extends RTCPeerConnection { - addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var webkitRTCPeerConnection: { @@ -14694,8 +13380,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -14986,7 +13674,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; postMessage(message: any, targetOrigin: string, transfer?: any[]): void; print(): void; prompt(message?: string, _default?: string): string | null; @@ -15007,8 +13695,10 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window scroll(options?: ScrollToOptions): void; scrollTo(options?: ScrollToOptions): void; scrollBy(options?: ScrollToOptions): void; - addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Window: { @@ -15024,8 +13714,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -15034,8 +13726,10 @@ declare var Worker: { }; interface XMLDocument extends Document { - addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLDocument: { @@ -15076,8 +13770,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -15091,8 +13787,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -15197,8 +13895,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -15343,8 +14043,10 @@ interface GlobalEventHandlers { onpointerover: (this: GlobalEventHandlers, ev: PointerEvent) => any; onpointerup: (this: GlobalEventHandlers, ev: PointerEvent) => any; onwheel: (this: GlobalEventHandlers, ev: WheelEvent) => any; - addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface GlobalFetch { @@ -15396,8 +14098,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface MSFileSaver { @@ -15454,9 +14158,11 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: K): HTMLElementTagNameMap[K] | null; + querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; - querySelectorAll(selectors: K): ElementListTagNameMap[K]; + querySelectorAll(selectors: K): NodeListOf; + querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -15543,8 +14249,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface BroadcastChannel extends EventTarget { @@ -15553,8 +14261,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -15735,7 +14445,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -15971,6 +14681,128 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface EXT_blend_minmax { + readonly MIN_EXT: number; + readonly MAX_EXT: number; +} + +interface EXT_frag_depth { +} + +interface EXT_shader_texture_lod { +} + +interface EXT_sRGB { + readonly SRGB_EXT: number; + readonly SRGB_ALPHA_EXT: number; + readonly SRGB8_ALPHA8_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; +} + +interface OES_vertex_array_object { + readonly VERTEX_ARRAY_BINDING_OES: number; + createVertexArrayOES(): WebGLVertexArrayObjectOES; + deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; + isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES; + bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void; +} + +interface WebGLVertexArrayObjectOES { +} + +interface WEBGL_color_buffer_float { + readonly RGBA32F_EXT: number; + readonly RGB32F_EXT: number; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number; + readonly UNSIGNED_NORMALIZED_EXT: number; +} + +interface WEBGL_compressed_texture_astc { + readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number; + readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number; + readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number; + readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number; + readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number; + getSupportedProfiles(): string[]; +} + +interface WEBGL_compressed_texture_s3tc_srgb { + readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number; + readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number; +} + +interface WEBGL_debug_shaders { + getTranslatedShaderSource(shader: WebGLShader): string; +} + +interface WEBGL_draw_buffers { + readonly COLOR_ATTACHMENT0_WEBGL: number; + readonly COLOR_ATTACHMENT1_WEBGL: number; + readonly COLOR_ATTACHMENT2_WEBGL: number; + readonly COLOR_ATTACHMENT3_WEBGL: number; + readonly COLOR_ATTACHMENT4_WEBGL: number; + readonly COLOR_ATTACHMENT5_WEBGL: number; + readonly COLOR_ATTACHMENT6_WEBGL: number; + readonly COLOR_ATTACHMENT7_WEBGL: number; + readonly COLOR_ATTACHMENT8_WEBGL: number; + readonly COLOR_ATTACHMENT9_WEBGL: number; + readonly COLOR_ATTACHMENT10_WEBGL: number; + readonly COLOR_ATTACHMENT11_WEBGL: number; + readonly COLOR_ATTACHMENT12_WEBGL: number; + readonly COLOR_ATTACHMENT13_WEBGL: number; + readonly COLOR_ATTACHMENT14_WEBGL: number; + readonly COLOR_ATTACHMENT15_WEBGL: number; + readonly DRAW_BUFFER0_WEBGL: number; + readonly DRAW_BUFFER1_WEBGL: number; + readonly DRAW_BUFFER2_WEBGL: number; + readonly DRAW_BUFFER3_WEBGL: number; + readonly DRAW_BUFFER4_WEBGL: number; + readonly DRAW_BUFFER5_WEBGL: number; + readonly DRAW_BUFFER6_WEBGL: number; + readonly DRAW_BUFFER7_WEBGL: number; + readonly DRAW_BUFFER8_WEBGL: number; + readonly DRAW_BUFFER9_WEBGL: number; + readonly DRAW_BUFFER10_WEBGL: number; + readonly DRAW_BUFFER11_WEBGL: number; + readonly DRAW_BUFFER12_WEBGL: number; + readonly DRAW_BUFFER13_WEBGL: number; + readonly DRAW_BUFFER14_WEBGL: number; + readonly DRAW_BUFFER15_WEBGL: number; + readonly MAX_COLOR_ATTACHMENTS_WEBGL: number; + readonly MAX_DRAW_BUFFERS_WEBGL: number; + drawBuffersWEBGL(buffers: number[]): void; +} + +interface WEBGL_lose_context { + loseContext(): void; + restoreContext(): void; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -16038,28 +14870,46 @@ interface VoidFunction { } interface HTMLElementTagNameMap { "a": HTMLAnchorElement; + "abbr": HTMLElement; + "acronym": HTMLElement; + "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; + "article": HTMLElement; + "aside": HTMLElement; "audio": HTMLAudioElement; + "b": HTMLElement; "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; + "bdo": HTMLElement; + "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; + "center": HTMLElement; + "cite": HTMLElement; + "code": HTMLElement; "col": HTMLTableColElement; "colgroup": HTMLTableColElement; "data": HTMLDataElement; "datalist": HTMLDataListElement; + "dd": HTMLElement; "del": HTMLModElement; + "dfn": HTMLElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; + "dt": HTMLElement; + "em": HTMLElement; "embed": HTMLEmbedElement; "fieldset": HTMLFieldSetElement; + "figcaption": HTMLElement; + "figure": HTMLElement; "font": HTMLFontElement; + "footer": HTMLElement; "form": HTMLFormElement; "frame": HTMLFrameElement; "frameset": HTMLFrameSetElement; @@ -16070,24 +14920,34 @@ interface HTMLElementTagNameMap { "h5": HTMLHeadingElement; "h6": HTMLHeadingElement; "head": HTMLHeadElement; + "header": HTMLElement; + "hgroup": HTMLElement; "hr": HTMLHRElement; "html": HTMLHtmlElement; + "i": HTMLElement; "iframe": HTMLIFrameElement; "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; "isindex": HTMLUnknownElement; + "kbd": HTMLElement; + "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; "listing": HTMLPreElement; "map": HTMLMapElement; + "mark": HTMLElement; "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; + "nav": HTMLElement; "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noframes": HTMLElement; + "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; "optgroup": HTMLOptGroupElement; @@ -16096,14 +14956,25 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; + "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; + "rt": HTMLElement; + "ruby": HTMLElement; + "s": HTMLElement; + "samp": HTMLElement; "script": HTMLScriptElement; + "section": HTMLElement; "select": HTMLSelectElement; + "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; + "strike": HTMLElement; + "strong": HTMLElement; "style": HTMLStyleElement; + "sub": HTMLElement; + "sup": HTMLElement; "table": HTMLTableElement; "tbody": HTMLTableSectionElement; "td": HTMLTableDataCellElement; @@ -16116,33 +14987,22 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; + "tt": HTMLElement; + "u": HTMLElement; "ul": HTMLUListElement; + "var": HTMLElement; "video": HTMLVideoElement; + "wbr": HTMLElement; "x-ms-webview": MSHTMLWebViewElement; "xmp": HTMLPreElement; } -interface ElementTagNameMap extends HTMLElementTagNameMap { - "abbr": HTMLElement; - "acronym": HTMLElement; - "address": HTMLElement; - "article": HTMLElement; - "aside": HTMLElement; - "b": HTMLElement; - "bdo": HTMLElement; - "big": HTMLElement; - "center": HTMLElement; +interface SVGElementTagNameMap { "circle": SVGCircleElement; - "cite": HTMLElement; "clippath": SVGClipPathElement; - "code": HTMLElement; - "dd": HTMLElement; "defs": SVGDefsElement; "desc": SVGDescElement; - "dfn": HTMLElement; - "dt": HTMLElement; "ellipse": SVGEllipseElement; - "em": HTMLElement; "feblend": SVGFEBlendElement; "fecolormatrix": SVGFEColorMatrixElement; "fecomponenttransfer": SVGFEComponentTransferElement; @@ -16167,63 +15027,33 @@ interface ElementTagNameMap extends HTMLElementTagNameMap { "fespotlight": SVGFESpotLightElement; "fetile": SVGFETileElement; "feturbulence": SVGFETurbulenceElement; - "figcaption": HTMLElement; - "figure": HTMLElement; "filter": SVGFilterElement; - "footer": HTMLElement; "foreignobject": SVGForeignObjectElement; "g": SVGGElement; - "header": HTMLElement; - "hgroup": HTMLElement; - "i": HTMLElement; "image": SVGImageElement; - "kbd": HTMLElement; - "keygen": HTMLElement; "line": SVGLineElement; "lineargradient": SVGLinearGradientElement; - "mark": HTMLElement; "marker": SVGMarkerElement; "mask": SVGMaskElement; "metadata": SVGMetadataElement; - "nav": HTMLElement; - "nobr": HTMLElement; - "noframes": HTMLElement; - "noscript": HTMLElement; "path": SVGPathElement; "pattern": SVGPatternElement; - "plaintext": HTMLElement; "polygon": SVGPolygonElement; "polyline": SVGPolylineElement; "radialgradient": SVGRadialGradientElement; "rect": SVGRectElement; - "rt": HTMLElement; - "ruby": HTMLElement; - "s": HTMLElement; - "samp": HTMLElement; - "section": HTMLElement; - "small": HTMLElement; "stop": SVGStopElement; - "strike": HTMLElement; - "strong": HTMLElement; - "sub": HTMLElement; - "sup": HTMLElement; "svg": SVGSVGElement; "switch": SVGSwitchElement; "symbol": SVGSymbolElement; "text": SVGTextElement; "textpath": SVGTextPathElement; "tspan": SVGTSpanElement; - "tt": HTMLElement; - "u": HTMLElement; "use": SVGUseElement; - "var": HTMLElement; "view": SVGViewElement; - "wbr": HTMLElement; } -type ElementListTagNameMap = { - [key in keyof ElementTagNameMap]: NodeListOf -}; +interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; @@ -16386,7 +15216,7 @@ declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; @@ -16409,7 +15239,6 @@ declare function scrollTo(options?: ScrollToOptions): void; declare function scrollBy(options?: ScrollToOptions): void; declare function toString(): string; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; @@ -16435,8 +15264,10 @@ declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; -declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; @@ -16460,7 +15291,6 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -16481,6 +15311,7 @@ type MouseWheelEvent = WheelEvent; type ScrollRestoration = "auto" | "manual"; type FormDataEntryValue = string | File; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type AppendMode = "segments" | "sequence"; type AudioContextState = "suspended" | "running" | "closed"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; @@ -16871,23 +15702,6 @@ interface DOMTokenList { [Symbol.iterator](): IterableIterator; } -interface FormData { - /** - * Returns an array of key, value pairs for every entry in the list - */ - entries(): IterableIterator<[string, string | File]>; - /** - * Returns a list of keys in the list - */ - keys(): IterableIterator; - /** - * Returns a list of values in the list - */ - values(): IterableIterator; - - [Symbol.iterator](): IterableIterator; -} - interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** @@ -16954,6 +15768,31 @@ interface NodeListOf { [Symbol.iterator](): IterableIterator; } +interface HTMLCollectionBase { + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollectionOf { + [Symbol.iterator](): IterableIterator; +} + +interface FormData { + /** + * Returns an array of key, value pairs for every entry in the list + */ + entries(): IterableIterator<[string, string | File]>; + /** + * Returns a list of keys in the list + */ + keys(): IterableIterator; + /** + * Returns a list of values in the list + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; +} + interface URLSearchParams { /** * Returns an array of key, value pairs for every entry in the search params diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index f87d32110a64e..cf7eea74c3c70 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -57,7 +57,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath | null; + keyPath?: string | string[]; } interface KeyAlgorithm { @@ -94,7 +94,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: Headers | string[][]; + headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; @@ -106,7 +106,7 @@ interface RequestInit { } interface ResponseInit { - headers?: Headers | string[][]; + headers?: HeadersInit; status?: number; statusText?: string; } @@ -461,8 +461,10 @@ interface FileReader extends EventTarget, MSBaseReader { readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; - addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var FileReader: { @@ -490,7 +492,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: Headers | string[][] | object): Headers; + new(init?: HeadersInit): Headers; }; interface IDBCursor { @@ -542,9 +544,12 @@ interface IDBDatabase extends EventTarget { createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; - addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; - addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: "versionchange", listener: (this: IDBDatabase, ev: IDBVersionChangeEvent) => any, options?: boolean | EventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBDatabase: { @@ -628,8 +633,10 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { interface IDBOpenDBRequest extends IDBRequest { onblocked: (this: IDBOpenDBRequest, ev: Event) => any; onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any; - addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBOpenDBRequest: { @@ -650,8 +657,10 @@ interface IDBRequest extends EventTarget { readonly result: any; source: IDBObjectStore | IDBIndex | IDBCursor; readonly transaction: IDBTransaction; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBRequest: { @@ -677,8 +686,10 @@ interface IDBTransaction extends EventTarget { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; - addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var IDBTransaction: { @@ -743,8 +754,10 @@ interface MessagePort extends EventTarget { close(): void; postMessage(message?: any, transfer?: any[]): void; start(): void; - addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { @@ -772,8 +785,10 @@ interface Notification extends EventTarget { readonly tag: string; readonly title: string; close(): void; - addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { @@ -1000,8 +1015,10 @@ interface ServiceWorker extends EventTarget, AbstractWorker { readonly scriptURL: USVString; readonly state: ServiceWorkerState; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorker: { @@ -1025,8 +1042,10 @@ interface ServiceWorkerRegistration extends EventTarget { showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerRegistration: { @@ -1091,8 +1110,10 @@ interface WebSocket extends EventTarget { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; - addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WebSocket: { @@ -1112,8 +1133,10 @@ interface Worker extends EventTarget, AbstractWorker { onmessage: (this: Worker, ev: MessageEvent) => any; postMessage(message: any, transfer?: any[]): void; terminate(): void; - addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Worker: { @@ -1153,8 +1176,10 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequest: { @@ -1168,8 +1193,10 @@ declare var XMLHttpRequest: { }; interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { - addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var XMLHttpRequestUpload: { @@ -1183,8 +1210,10 @@ interface AbstractWorkerEventMap { interface AbstractWorker { onerror: (this: AbstractWorker, ev: ErrorEvent) => any; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Body { @@ -1221,8 +1250,10 @@ interface MSBaseReader { readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; - addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface NavigatorBeacon { @@ -1276,8 +1307,10 @@ interface XMLHttpRequestEventTarget { onloadstart: (this: XMLHttpRequest, ev: Event) => any; onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; - addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } interface Client { @@ -1312,8 +1345,10 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any; close(): void; postMessage(message: any, transfer?: any[]): void; - addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var DedicatedWorkerGlobalScope: { @@ -1423,8 +1458,10 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { onsync: (this: ServiceWorkerGlobalScope, ev: SyncEvent) => any; readonly registration: ServiceWorkerRegistration; skipWaiting(): Promise; - addEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var ServiceWorkerGlobalScope: { @@ -1468,8 +1505,10 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo msWriteProfilerMark(profilerMarkName: string): void; createImageBitmap(image: ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; createImageBitmap(image: ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; - addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var WorkerGlobalScope: { @@ -1526,8 +1565,10 @@ interface BroadcastChannel extends EventTarget { onmessageerror: (ev: MessageEvent) => any; close(): void; postMessage(message: any): void; - addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var BroadcastChannel: { @@ -1662,7 +1703,7 @@ interface EcKeyAlgorithm extends KeyAlgorithm { typedCurve: string; } -interface EcKeyImportParams { +interface EcKeyImportParams extends Algorithm { namedCurve: string; } @@ -1839,7 +1880,6 @@ declare function msWriteProfilerMark(profilerMarkName: string): void; declare function createImageBitmap(image: ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; declare function createImageBitmap(image: ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; declare var indexedDB: IDBFactory; declare var msIndexedDB: IDBFactory; declare var navigator: WorkerNavigator; @@ -1858,9 +1898,10 @@ declare function btoa(rawString: string): string; declare var console: Console; declare function fetch(input: RequestInfo, init?: RequestInit): Promise; declare function dispatchEvent(evt: Event): boolean; -declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -declare function addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; +declare function removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AlgorithmIdentifier = string | Algorithm; type BodyInit = any; type IDBKeyPath = string; @@ -1869,6 +1910,7 @@ type USVString = string; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type FormDataEntryValue = string | File; +type HeadersInit = Headers | string[][] | { [key: string]: string }; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..03c7be6149bad --- /dev/null +++ b/lib/pl/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Modyfikatora „{0}” nie można używać z deklaracją importu.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Modyfikatora „{0}” nie można używać z deklaracją interfejsu.", + "A_0_parameter_must_be_the_first_parameter_2680": "Parametr „{0}” musi być pierwszym parametrem.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Parametr wzorca wiązania nie może być opcjonalny w sygnaturze implementacji.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Instrukcji „break” można użyć tylko w ramach otaczającej instrukcji iteracji lub switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Instrukcja „break” może wykonać skok tylko do etykiety otaczającej instrukcji.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Klasa może zawierać implementację tylko identyfikatora/nazwy kwalifikowanej z opcjonalnymi argumentami typu.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Deklaracja klasy bez modyfikatora „default” musi mieć nazwę.", + "A_class_may_only_extend_another_class_2311": "Klasa może rozszerzać tylko inną klasę.", + "A_class_may_only_implement_another_class_or_interface_2422": "Klasa może zawierać implementację tylko innej klasy lub innego interfejsu.", + "A_class_member_cannot_have_the_0_keyword_1248": "Składowa klasy nie może zawierać słowa kluczowego „{0}”.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Wyrażenie przecinkowe nie jest dozwolone w obliczonej nazwie właściwości.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Obliczona nazwa właściwości nie może odwoływać się do parametru typu z zawierającego go typu.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Nazwa właściwości obliczanej w deklaracji właściwości klasy musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Nazwa właściwości obliczanej w przeciążeniu metody musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Nazwa właściwości obliczanej w typie literału musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Nazwa właściwości obliczanej w otaczającym kontekście musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Nazwa właściwości obliczanej w interfejsie musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Obliczona nazwa właściwości musi być typu „string”, „number”, „symbol” lub „any”.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Obliczona nazwa właściwości w postaci „{0}” musi być typu „symbol”.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Dostęp do składowej wyliczenia ze specyfikatorem const można uzyskać tylko za pomocą literału ciągu.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Inicjator „const” w otaczającym kontekście musi być ciągiem lub literałem numerycznym.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Konstruktor nie może zawierać wywołania „super”, gdy jego klasa rozszerza wartość „null”.", + "A_constructor_cannot_have_a_this_parameter_2681": "Konstruktor nie może zawierać parametru „this”.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Instrukcji „continue” można użyć tylko w otaczającej instrukcji iteracji.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Instrukcja „continue” może wykonać skok tylko do etykiety otaczającej instrukcji iteracji.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Nie można użyć modyfikatora „declare” w otaczającym kontekście.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Wymagany jest modyfikator „declare” dla deklaracji najwyższego poziomu w pliku d.ts.", + "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_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”.", + "A_file_cannot_have_a_reference_to_itself_1006": "Plik nie może przywoływać samego siebie.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Instrukcja „for-await-of” jest dozwolona jedynie w funkcji asynchronicznej lub generatorze asynchronicznym.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Funkcja zwracająca wartość „never” nie może mieć osiągalnego punktu końcowego.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Funkcja wywoływana ze słowem kluczowym „new” nie może mieć typu „this” o wartości „void”.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Funkcja, której deklarowany typ jest inny niż „void” lub „any”, musi zwracać wartość.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Generator nie może mieć adnotacji typu „void”.", + "A_get_accessor_cannot_have_parameters_1054": "Metoda dostępu „get” nie może mieć parametrów.", + "A_get_accessor_must_return_a_value_2378": "Metoda dostępu „get” musi zwracać wartość.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicjator składowej w deklaracji wyliczenia nie może przywoływać składowych zadeklarowanych po nim, w tym składowych zdefiniowanych w innych wyliczeniach.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Klasa mixin musi mieć konstruktor z pojedynczym parametrem rest o typie „any[]”.", + "A_module_cannot_have_multiple_default_exports_2528": "Moduł nie może mieć wielu eksportów domyślnych.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklaracja przestrzeni nazw nie może znajdować się w innym pliku niż klasa lub funkcja, z którą ją scalono.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklaracja przestrzeni nazw nie może występować przed klasą lub funkcją, z którą ją scalono.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklaracja przestrzeni nazw jest dozwolona tylko w przestrzeni nazw lub module.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicjator parametru jest dozwolony tylko w implementacji funkcji lub konstruktora.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Właściwości parametru nie można zadeklarować za pomocą parametru rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Właściwość parametru jest dozwolona tylko w implementacji konstruktora.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Właściwości parametru nie można zadeklarować za pomocą wzorca wiązania.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Ścieżka w opcji „extends” musi być względna lub bezwzględna, lecz element „{0}” nie spełnia tego wymagania.", + "A_promise_must_have_a_then_method_1059": "Obietnica musi mieć metodę „then”.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Właściwość klasy, której typem jest typ „unikatowy symbol”, musi być „static” i „readonly”.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Właściwość interfejsu lub typu, którego typem jest typ „unikatowy symbol”, musi być „readonly”.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Wymagany parametr nie może występować po opcjonalnym parametrze.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nie może zawierać wzorca wiązania.", + "A_rest_element_cannot_have_an_initializer_1186": "Element rest nie może mieć inicjatora.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Element rest musi być ostatni we wzorcu usuwającym strukturę.", + "A_rest_parameter_cannot_be_optional_1047": "Parametr rest nie może być opcjonalny.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Parametr rest nie może mieć inicjatora.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Parametr rest musi występować na końcu listy parametrów.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Parametr rest musi być typu tablicowego.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Instrukcji „return” można użyć tylko w treści funkcji.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Seria wpisów, które ponownie mapują importowane dane na lokalizacje wyszukiwania względne wobec adresu „baseUrl”.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Metoda dostępu „set” nie może mieć adnotacji zwracanego typu.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Metoda dostępu „set” nie może mieć parametru opcjonalnego.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Metoda dostępu „set” nie może mieć parametru rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Metoda dostępu „set” musi mieć dokładnie jeden parametr.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Parametr metody dostępu „set” nie może mieć inicjatora.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Sygnatura z implementacją nie może używać typu literału ciągu.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Wywołanie „super” musi być pierwszą instrukcją konstruktora, jeśli klasa zawiera zainicjowane właściwości lub ma właściwości parametrów.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ochrona typu oparta na elemencie „this” nie jest zgodna z ochroną typu opartą na parametrze.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ „this” jest dostępny tylko w niestatycznej składowej klasy lub interfejsu.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Plik „tsconfig.json” jest już zdefiniowany w: „{0}”.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Lista elementów typu krotki nie może być pusta.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Wyrażenie asercji typu jest niedozwolone po lewej stronie wyrażenia potęgowania. Zastanów się nad zamknięciem wyrażenia w nawiasach.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Właściwość literału typu nie może mieć inicjatora.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Predykat typów nie może zawierać odwołania do parametru rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predykat typów nie może zawierać odwołania do elementu „{0}” we wzorcu wiązania.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predykat typów jest dozwolony tylko w położeniu zwracanego typu dla funkcji i metod.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Musi być możliwe przypisanie typu predykatu typów do typu jego parametru.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Zmienna, której typem jest typ „unikatowy symbol”, musi być „const”.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Wyrażenie „yield” jest dozwolone tylko w treści generatora.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Nie można uzyskać dostępu do metody abstrakcyjnej „{0}” w klasie „{1}” za pomocą wyrażenia super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Metody abstrakcyjne mogą występować tylko w klasie abstrakcyjnej.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Właściwość abstrakcyjna „{0}” w klasie „{1}” jest niedostępna w konstruktorze.", + "Accessibility_modifier_already_seen_1028": "Napotkano już modyfikator dostępności.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Metody dostępu są dostępne tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.", + "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”.", + "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”.", + "Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”.", + "Add_this_to_unresolved_variable_90008": "Dodaj „this.” do nierozpoznanej zmiennej.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Dodanie pliku tsconfig.json pomoże w organizowaniu projektów, które zawierają pliki TypeScript i JavaScript. Dowiedz się więcej: https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Dodatkowe kontrole", + "Advanced_Options_6178": "Opcje zaawansowane", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Wszystkie deklaracje elementu „{0}” muszą mieć identyczne modyfikatory.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Wszystkie deklaracje „{0}” muszą mieć identyczne parametry typu.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Wszystkie deklaracje metody abstrakcyjnej muszą występować obok siebie.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.", + "Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Otaczające wyliczenia ze specyfikacją const nie są dozwolone w przypadku podania flagi „--isolatedModules”.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Deklaracja otaczającego modułu nie może określać względnej nazwy modułu.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Moduły otoczenia nie mogą być zagnieżdżone w innych modułach ani przestrzeniach nazw.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Moduł AMD nie może mieć wielu przypisań nazw.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Abstrakcyjna metoda dostępu nie może mieć implementacji.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Metoda dostępu nie może być zadeklarowana w otaczającym kontekście.", + "An_accessor_cannot_have_type_parameters_1094": "Metoda dostępu nie może mieć parametrów typu.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Deklaracja otaczającego modułu jest dozwolona tylko na najwyższym poziomie pliku.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Arytmetyczny operand musi być typu „any”, „number” lub typu wyliczeniowego.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Asynchroniczna funkcja lub metoda w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Funkcja lub metoda asynchroniczna musi mieć prawidłowy oczekujący zwracany typ.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Metoda lub funkcja asynchroniczna musi zwrócić element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.", + "An_async_iterator_must_have_a_next_method_2519": "Iterator asynchroniczny musi mieć metodę „next()”.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Składowa wyliczenia nie może mieć nazwy liczbowej.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Przypisanie eksportu może być używane tylko w module.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Nie można użyć przypisania eksportu w module z innymi eksportowanymi elementami.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Nie można użyć przypisania eksportu w przestrzeni nazw.", + "An_export_assignment_cannot_have_modifiers_1120": "Przypisanie eksportu nie może mieć modyfikatorów.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Deklaracja eksportu może być używana tylko w module.", + "An_export_declaration_cannot_have_modifiers_1193": "Deklaracja eksportu nie może mieć modyfikatorów.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Rozszerzona wartość znaku ucieczki Unicode musi należeć do zakresu od 0x0 do 0x10FFFF (włącznie).", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementacja nie może być zadeklarowana w otaczających kontekstach.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Deklaracja importu może być używana tylko w przestrzeni nazw lub module.", + "An_import_declaration_cannot_have_modifiers_1191": "Deklaracja importu nie może mieć modyfikatorów.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ścieżka importu nie może kończyć się rozszerzeniem „{0}”. Rozważ zaimportowanie „{1}”.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Argument wyrażenia indeksu musi być typu „string”, „number”, „symbol” lub „any”.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Sygnatura indeksu nie może mieć parametru rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Sygnatura indeksu musi mieć adnotację typu.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Sygnatura indeksu musi mieć dokładnie jeden parametr.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Parametr sygnatury indeksu nie może zawierać znaku zapytania.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Parametr sygnatury indeksu nie może mieć modyfikatora dostępności.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Parametr sygnatury indeksu nie może mieć inicjatora.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Parametr sygnatury indeksu musi mieć adnotację typu.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr sygnatury indeksu musi być typu „string” lub „number”.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Interfejs może rozszerzać tylko identyfikator/nazwę kwalifikowaną z opcjonalnymi argumentami typu.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Interfejs może rozszerzać tylko klasę lub inny interfejs.", + "An_interface_property_cannot_have_an_initializer_1246": "Właściwość interfejsu nie może mieć inicjatora.", + "An_iterator_must_have_a_next_method_2489": "Iterator musi zawierać metodę „next()”.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Literał obiektu nie może mieć wielu metod dostępu pobierania/ustawiania o takiej samej nazwie.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Literał obiektu nie może mieć wielu właściwości o takiej samej nazwie w trybie z ograniczeniami.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Literał obiektu nie może mieć właściwości i metody dostępu o takiej samej nazwie.", + "An_object_member_cannot_be_declared_optional_1162": "Składowa obiektu nie może być zadeklarowana jako opcjonalna.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Sygnatura przeciążenia nie może być zadeklarowana jako generator.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Wyrażenie jednoargumentowe z operatorem „{0}” jest niedozwolone po lewej stronie wyrażenia potęgowania. Zastanów się nad zamknięciem wyrażenia w nawiasach.", + "Annotate_with_type_from_JSDoc_95009": "Dodaj adnotację przy użyciu typu z JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Dodaj adnotację przy użyciu typów z JSDoc", + "Argument_expression_expected_1135": "Oczekiwano wyrażenia argumentu.", + "Argument_for_0_option_must_be_Colon_1_6046": "Argumentem opcji „{0}” musi być: {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Nie można przypisać argumentu typu „{0}” do parametru typu „{1}”.", + "Array_element_destructuring_pattern_expected_1181": "Oczekiwano wzorca usuwającego strukturę elementu tablicy.", + "Asterisk_Slash_expected_1010": "Oczekiwano znaków „*/”.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Rozszerzenia zakresu globalnego mogą być zagnieżdżane bezpośrednio jedynie w modułach zewnętrznych lub deklaracjach modułów otoczenia.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Rozszerzenia zakresu globalnego muszą mieć modyfikator „declare”, chyba że znajdują się w już otaczającym kontekście.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Automatyczne odnajdowanie operacji wpisywania zostało włączone w projekcie „{0}”. Trwa uruchamianie dodatkowego przejścia rozwiązania dla modułu „{1}” przy użyciu lokalizacji pamięci podręcznej „{2}”.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Wyrażenia klasy bazowej nie mogą odwoływać się do parametrów typu klasy.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Zwracany typ konstruktora bazowego „{0}” nie jest typem klasy ani interfejsu.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Wszystkie konstruktory podstawowe muszą mieć ten sam zwracany typ.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Katalog podstawowy do rozpoznawania innych niż bezwzględne nazw modułów.", + "Basic_Options_6172": "Opcje podstawowe", + "Binary_digit_expected_1177": "Oczekiwano bitu.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Dla elementu powiązania „{0}” niejawnie określono typ „{1}”.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Zmienna „{0}” o zakresie bloku została użyta przed jej deklaracją.", + "Call_decorator_expression_90028": "Wywołaj wyrażenie dekoratora.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Dla sygnatury wywołania bez adnotacji zwracanego typu niejawnie określono zwracany typ „any”.", + "Call_target_does_not_contain_any_signatures_2346": "Cel wywołania nie zawiera żadnych podpisów.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Nie można uzyskać dostępu do elementu „{0}.{1}”, ponieważ element „{0}” jest typem, ale nie przestrzenią nazw. Czy chcesz pobrać typ właściwości „{1}” w lokalizacji „{0}” za pomocą elementu „{0}[„{1}”]”?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Nie można przypisać typu konstruktora „{0}” do typu konstruktora „{1}”.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Nie można przypisać abstrakcyjnego typu konstruktora do nieabstrakcyjnego typu konstruktora.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Nie można przydzielić do elementu „{0}”, ponieważ jest to stała lub właściwość tylko do odczytu.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Nie można przydzielić do elementu „{0}”, ponieważ nie jest to zmienna.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Nie można rozszerzyć modułu „{0}”, ponieważ rozpoznawany jest obiekt inny niż moduł.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Nie można rozszerzyć modułu „{0}” za pośrednictwem operacji eksportu wartości, ponieważ jest on rozpoznawany jako jednostka inna niż moduł.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Nie można skompilować modułów za pomocą opcji „{0}”, chyba że flaga „--module” ma wartość „amd” lub „system”.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Nie można skompilować przestrzeni nazw, jeśli podano flagę „--isolatedModules”.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Nie można utworzyć wystąpienia klasy abstrakcyjnej.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Nie można wyeksportować elementu „{0}”. Z modułu można eksportować jedynie lokalne deklaracje.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Nie można rozszerzyć klasy „{0}”. Konstruktor klasy jest oznaczony jako prywatny.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Nie można rozszerzyć interfejsu „{0}”. Czy chodziło Ci o „implements”?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Nie można znaleźć pliku tsconfig.json w określonym katalogu: „{0}”.", + "Cannot_find_global_type_0_2318": "Nie można odnaleźć typu globalnego „{0}”.", + "Cannot_find_global_value_0_2468": "Nie można odnaleźć wartości globalnej „{0}”.", + "Cannot_find_module_0_2307": "Nie można odnaleźć modułu „{0}”.", + "Cannot_find_name_0_2304": "Nie można odnaleźć nazwy „{0}”.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Nie można znaleźć nazwy „{0}”. Czy chodziło Ci o „{1}”?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Nie można znaleźć nazwy „{0}”. Czy chodziło o składową wystąpienia „this.{0}”?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Nie można znaleźć nazwy „{0}”. Czy chodziło o statyczną składową „{1}.{0}”?", + "Cannot_find_namespace_0_2503": "Nie można odnaleźć przestrzeni nazw „{0}”.", + "Cannot_find_parameter_0_1225": "Nie można odnaleźć parametru „{0}”.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nie można odnaleźć wspólnej ścieżki podkatalogu dla plików wejściowych.", + "Cannot_find_type_definition_file_for_0_2688": "Nie można znaleźć pliku definicji typu dla elementu „{0}”.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Nie można zaimportować plików deklaracji typu. Rozważ zaimportowanie „{0}” zamiast „{1}”.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Nie można zainicjować zmiennej „{0}” z zakresu zewnętrznego w tym samym zakresie co deklaracja „{1}” należąca do zakresu bloku.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nie można wywołać wyrażenia, w którego typie nie ma sygnatury wywołania. Typ „{0}” nie ma zgodnych sygnatur wywołań.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Nie można ponownie wyeksportować typu, jeśli podano flagę „--isolatedModules”", + "Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.", + "Cannot_redeclare_exported_variable_0_2323": "Nie można zadeklarować ponownie wyeksportowanej zmiennej „{0}”.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Nie można ponownie zadeklarować identyfikatora „{0}” w klauzuli catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Nie można użyć kodu JSX, jeśli nie podano flagi „--jsx”.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Nie można używać importów, eksportów lub rozszerzeń modułów, jeśli flaga „--module” ma wartość „none”.", + "Cannot_use_namespace_0_as_a_type_2709": "Nie można używać przestrzeni nazw „{0}” jako typu.", + "Cannot_use_namespace_0_as_a_value_2708": "Nie można używać przestrzeni nazw „{0}” jako wartości.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Nie można użyć elementu „new” z wyrażeniem, którego typ nie ma sygnatury wywołania lub konstrukcji.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Nie można zapisać pliku „{0}”, ponieważ zostałby nadpisany przez wiele plików wejściowych.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Nie można zapisać pliku „{0}”, ponieważ nadpisałby plik wejściowy.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Zmienna klauzuli catch nie może mieć adnotacji typu.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Zmienna klauzuli catch nie może mieć inicjatora.", + "Change_0_to_1_90014": "Zmień element „{0}” na „{1}”.", + "Change_extends_to_implements_90003": "Zmień atrybut „extends” na „implements”.", + "Change_spelling_to_0_90022": "Zmiana pisowni na „{0}”.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Sprawdzanie, czy „{0}” to najdłuższy zgodny prefiks dla „{1}” — „{2}”.", + "Circular_definition_of_import_alias_0_2303": "Definicja cykliczna aliasu importu „{0}”.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Wykryto cykliczność podczas rozpoznawania konfiguracji: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Klasa „{0}” definiuje metodę dostępu do składowej wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako funkcję składową wystąpienia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Klasa „{0}” definiuje funkcję składową wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako metodę dostępu do składowej wystąpienia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Klasa „{0}” definiuje funkcję składową wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako właściwość składowej wystąpienia.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Klasa „{0}” definiuje właściwość składowej wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako funkcję składową wystąpienia.", + "Class_0_incorrectly_extends_base_class_1_2415": "Klasa „{0}” niepoprawnie rozszerza klasę bazową „{1}”.", + "Class_0_incorrectly_implements_interface_1_2420": "Klasa „{0}” zawiera niepoprawną implementację interfejsu „{1}”.", + "Class_0_used_before_its_declaration_2449": "Klasa „{0}” została użyta przed zadeklarowaniem.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklaracje klas nie mogą mieć więcej niż jeden tag „@augments” lub „@extends”.", + "Class_name_cannot_be_0_2414": "Klasa nie może mieć nazwy „{0}”.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Strona statyczna klasy „{0}” niepoprawnie rozszerza stronę statyczną klasy bazowej „{1}”.", + "Classes_can_only_extend_a_single_class_1174": "Klasy mogą rozszerzać tylko pojedynczą klasę.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Klasy zawierające metody abstrakcyjne muszą być oznaczone jako abstrakcyjne.", + "Command_line_Options_6171": "Opcje wiersza polecenia", + "Compilation_complete_Watching_for_file_changes_6042": "Ukończono kompilację. Wyszukiwanie zmian plików.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Skompiluj projekt z uwzględnieniem ścieżki jego pliku konfiguracji lub folderu z plikiem „tsconfig.json”.", + "Compiler_option_0_expects_an_argument_6044": "Opcja kompilatora „{0}” oczekuje argumentu.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Opcja kompilatora „{0}” wymaga wartości typu {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Obliczone wartości nie są dozwolone w wyliczeniu ze składowymi o wartości ciągu.", + "Concatenate_and_emit_output_to_single_file_6001": "Połącz i wyemituj dane wyjściowe do pojedynczego pliku.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Znaleziono sprzeczne definicje dla „{0}” w „{1}” i „{2}”. Rozważ zainstalowanie konkretnej wersji tej biblioteki, aby rozwiązać problem.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Dla sygnatury konstrukcji bez adnotacji zwracanego typu niejawnie określono zwracany typ „any”.", + "Constructor_implementation_is_missing_2390": "Brak implementacji konstruktora.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Konstruktor klasy „{0}” jest prywatny i dostępny tylko w ramach deklaracji klasy.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor klasy „{0}” jest chroniony i dostępny tylko w ramach deklaracji klasy.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory klas pochodnych muszą zawierać wywołanie „super”.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Nie podano pliku zawierającego i nie można określić katalogu głównego. Pomijanie wyszukiwania w folderze „node_modules”.", + "Convert_function_0_to_class_95002": "Konwertuj funkcję „{0}” na klasę", + "Convert_function_to_an_ES2015_class_95001": "Konwertuj funkcję na klasę ES2015", + "Convert_to_default_import_95013": "Konwertuj na import domyślny", + "Corrupted_locale_file_0_6051": "Uszkodzony plik ustawień regionalnych {0}.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nie można znaleźć pliku deklaracji dla modułu „{0}”. Element „{1}” ma niejawnie typ „any”.", + "Could_not_write_file_0_Colon_1_5033": "Nie można zapisać pliku „{0}”: {1}.", + "DIRECTORY_6038": "KATALOG", + "Declaration_expected_1146": "Oczekiwano deklaracji.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Nazwa deklaracji powoduje konflikt z wbudowanym identyfikatorem globalnym „{0}”.", + "Declaration_or_statement_expected_1128": "Oczekiwano deklaracji lub instrukcji.", + "Declare_method_0_90023": "Zadeklaruj metodę „{0}”.", + "Declare_property_0_90016": "Zadeklaruj właściwość „{0}”.", + "Declare_static_method_0_90024": "Zadeklaruj metodę statyczną „{0}”.", + "Declare_static_property_0_90027": "Zadeklaruj właściwość statyczną „{0}”.", + "Decorators_are_not_valid_here_1206": "Elementy Decorator nie są tutaj prawidłowe.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Nie można stosować elementów Decorator do wielu metod dostępu pobierania/ustawiania o takiej samej nazwie.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Domyślny eksport modułu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Przestarzałe] Użyj w zastępstwie opcji „--jsxFactory”. Określ obiekt wywoływany dla elementu createElement przy określaniu jako celu emisji JSX „react”", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Przestarzałe] Użyj w zastępstwie opcji „--outFile”. Połącz dane wyjściowe i wyemituj jako jeden plik", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Przestarzałe] Użyj w zastępstwie opcji „--skipLibCheck”. Pomiń sprawdzanie typów domyślnych plików deklaracji biblioteki.", + "Digit_expected_1124": "Oczekiwano cyfry.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Katalog „{0}” nie istnieje. Operacje wyszukiwania w nim zostaną pominięte.", + "Disable_checking_for_this_file_90018": "Wyłącz sprawdzanie dla tego pliku.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Wyłącz ograniczenia rozmiarów dla projektów JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Wyłącz dokładne sprawdzanie sygnatur ogólnych w typach funkcji.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Nie zezwalaj na przywoływanie tego samego pliku za pomocą nazw różniących się wielkością liter.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Nie dodawaj odwołań z trzema ukośnikami ani zaimportowanych modułów do listy skompilowanych plików.", + "Do_not_emit_comments_to_output_6009": "Nie emituj komentarzy do danych wyjściowych.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Nie emituj deklaracji dla kodu z adnotacją „@internal”.", + "Do_not_emit_outputs_6010": "Nie emituj danych wyjściowych.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Nie emituj danych wyjściowych w przypadku zgłoszenia błędów.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Nie emituj dyrektyw „use strict” w danych wyjściowych modułu.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Nie wymazuj deklaracji wyliczeń ze specyfikacją const w wygenerowanym kodzie.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Nie generuj w skompilowanych danych wyjściowych niestandardowych funkcji pomocy, takich jak „__extends”.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Nie uwzględniaj domyślnego pliku biblioteki (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Nie zgłaszaj błędów dla nieosiągalnego kodu.", + "Do_not_report_errors_on_unused_labels_6074": "Nie zgłaszaj błędów dla nieużywanych etykiet.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Nie rozpoznawaj rzeczywistej ścieżki linków symbolicznych.", + "Do_not_truncate_error_messages_6165": "Nie obcinaj komunikatów o błędach.", + "Duplicate_declaration_0_2718": "Zduplikowana deklaracja „{0}”.", + "Duplicate_function_implementation_2393": "Zduplikowana implementacja funkcji.", + "Duplicate_identifier_0_2300": "Zduplikowany identyfikator „{0}”.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Zduplikowany identyfikator „{0}”. Kompilator rezerwuje nazwę „{1}” w zakresie najwyższego poziomu modułu.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Zduplikowany identyfikator „{0}”. Kompilator rezerwuje nazwę „{1}” w zakresie najwyższego poziomu modułu zawierającego funkcje asynchroniczne.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Zduplikowany identyfikator „{0}”. Kompilator używa deklaracji „{1}” do obsługi funkcji asynchronicznych.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Zduplikowany identyfikator „arguments”. Kompilator używa ciągu „arguments” do zainicjowania parametrów rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Powielony identyfikator „_newTarget”. Kompilator używa deklaracji zmiennej „_newTarget” do przechwytywania odwołania do metawłaściwości „new.target”.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Zduplikowany identyfikator „_super”. Kompilator używa ciągu „_super” do przechwycenia odwołania do klasy bazowej.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Zduplikowany identyfikator „_this”. Kompilator używa deklaracji zmiennej „_this” do przechwycenia odwołania do elementu „this”.", + "Duplicate_label_0_1114": "Zduplikowana etykieta „{0}”.", + "Duplicate_number_index_signature_2375": "Zduplikowana sygnatura indeksu liczbowego.", + "Duplicate_string_index_signature_2374": "Zduplikowana sygnatura indeksu ciągu.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Nie można użyć dynamicznego importowania, gdy celem są moduły ECMAScript 2015.", + "Dynamic_import_cannot_have_type_arguments_1326": "Dynamiczne importowanie nie może mieć argumentów typu", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamiczne importowanie musi mieć jeden specyfikator jako argument.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specyfikator dynamicznego importowania musi być typu „string”, ale określono typ „{0}”.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element niejawnie przyjmuje typ „any”, ponieważ wyrażenie indeksu ma typ inny niż „number”.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Element ma niejawnie typ „any”, ponieważ typ „{0}” nie ma sygnatury indeksu.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Emituj znacznik kolejności bajtów UTF-8 na początku plików wyjściowych.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emituj pojedynczy plik z mapami źródeł zamiast oddzielnego pliku.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emituj źródło razem z mapami źródłowymi w pojedynczym pliku; wymaga ustawienia opcji „--inlineSourceMap” lub „--sourceMap”.", + "Enable_all_strict_type_checking_options_6180": "Włącz wszystkie opcje ścisłego sprawdzania typów.", + "Enable_strict_checking_of_function_types_6186": "Włącz dokładne sprawdzanie typów funkcji.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Włącz dokładne sprawdzanie inicjowania właściwości w klasach.", + "Enable_strict_null_checks_6113": "Włącz dokładne sprawdzanie wartości null.", + "Enable_tracing_of_the_name_resolution_process_6085": "Włącz śledzenie procesu rozpoznawania nazw.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Umożliwia obsługę eksperymentalną funkcji asynchronicznych języka ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Umożliwia obsługę eksperymentalną elementów Decorator języka ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Umożliwia obsługę eksperymentalną emitowania metadanych typów elementów Decorator.", + "Enum_0_used_before_its_declaration_2450": "Wyliczenie „{0}” zostało użyte przed zadeklarowaniem.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Wszystkie deklaracje wyliczeń muszą być elementami const lub żadna nie może być elementem const.", + "Enum_member_expected_1132": "Oczekiwano składowych wyliczenia.", + "Enum_member_must_have_initializer_1061": "Składowa wyliczenia musi mieć inicjator.", + "Enum_name_cannot_be_0_2431": "Wyliczenie nie może mieć nazwy „{0}”.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Typ wyliczenia „{0}” ma składowe z inicjatorami niebędącymi literałami.", + "Examples_Colon_0_6026": "Przykłady: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Nadmierna głębokość stosu podczas porównywania typów „{0}” i „{1}”.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Oczekiwano argumentów typu {0}-{1}; podaj je z tagiem „@extends”.", + "Expected_0_arguments_but_got_1_2554": "Oczekiwane argumenty: {0}, uzyskano: {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Oczekiwano {0} argumentów, ale otrzymano {1} lub więcej.", + "Expected_0_type_arguments_but_got_1_2558": "Oczekiwane argumenty typu: {0}, uzyskano: {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Oczekiwano argumentów typu {0}; podaj je z tagiem „@extends”.", + "Expected_at_least_0_arguments_but_got_1_2555": "Oczekiwane argumenty: co najmniej {0}, uzyskano: {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Oczekiwano co najmniej {0} argumentów, ale otrzymano {1} lub więcej.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Oczekiwano odpowiadającego tagu zamykającego kodu JSX dla elementu „{0}”.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Oczekiwano odpowiedniego tagu zamykającego dla fragmentu kodu JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Oczekiwany typ pola „{0}” w pliku „package.json” to „string”, a uzyskano typ „{1}”.", + "Experimental_Options_6177": "Opcje eksperymentalne", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Obsługa eksperymentalna dekoratorów to funkcja, która może ulec zmianie w nowszych wersjach. Ustaw opcję „experimentalDecorators”, aby usunąć to ostrzeżenie.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Jawnie określony rodzaj rozpoznawania modułów: „{0}”.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Nie można użyć przypisania eksportu, gdy są używane moduły języka ECMAScript. Zamiast tego rozważ użycie elementu „export default” lub innego formatu modułu.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Przypisanie eksportu nie jest obsługiwane, gdy flaga „--module” ma postać „system”.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Deklaracja eksportu powoduje konflikt z wyeksportowaną deklaracją „{0}”.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Deklaracje eksportu są niedozwolone w przestrzeni nazw.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Plik typów wyeksportowanych pakietów zewnętrznych „{0}” nie jest modułem. Skontaktuj się z autorem pakietu, aby zaktualizować definicję pakietu.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Plik typów wyeksportowanych pakietów zewnętrznych nie może zawierać odwołań z potrójnym ukośnikiem. Skontaktuj się z autorem pakietu, aby zaktualizować definicję pakietu.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Alias „{0}” wyeksportowanego typu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Wyeksportowana zmienna „{0}” ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Wyeksportowana zmienna „{0}” ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Wyeksportowana zmienna „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Eksporty i przypisania eksportów nie są dozwolone w rozszerzeniach modułów.", + "Expression_expected_1109": "Oczekiwano wyrażenia.", + "Expression_or_comma_expected_1137": "Oczekiwano wyrażenia lub przecinka.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Wynikiem rozpoznania wyrażenia jest element „_super” używany przez kompilator do przechwycenia odwołania do klasy bazowej.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Wynikiem rozpoznania wyrażenia jest deklaracja zmiennej „{0}” używana przez kompilator do obsługi funkcji asynchronicznych.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Wynikiem rozpoznania wyrażenia jest deklaracja zmiennej „_newTarget” używana przez kompilator do przechwytywania odwołania do metawłaściwości „new.target”.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Wynikiem rozpoznania wyrażenia jest deklaracja zmiennej „_this” używana przez kompilator do przechwycenia odwołania do elementu „this”.", + "Extract_constant_95006": "Wyodrębnij stałą", + "Extract_function_95005": "Wyodrębnij funkcję", + "Extract_symbol_95003": "Wyodrębnij symbol", + "Extract_to_0_in_1_95004": "Wyodrębnij do {0} w {1}", + "Extract_to_0_in_1_scope_95008": "Wyodrębnij do {0} w zakresie {1}", + "Extract_to_0_in_enclosing_scope_95007": "Wyodrębnij do {0} w zakresie otaczającym", + "FILE_6035": "PLIK", + "FILE_OR_DIRECTORY_6040": "PLIK LUB KATALOG", + "Failed_to_parse_file_0_Colon_1_5014": "Nie można przeanalizować pliku „{0}”: {1}.", + "Fallthrough_case_in_switch_7029": "Przepuszczająca klauzula case w instrukcji switch.", + "File_0_does_not_exist_6096": "Plik „{0}” nie istnieje.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Plik „{0}” istnieje — użyj go jako wyniku rozpoznawania nazw.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Plik „{0}” ma nieobsługiwane rozszerzenie, dlatego zostanie pominięty.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Plik „{0}” ma nieobsługiwane rozszerzenie. Obsługiwane są tylko rozszerzenia {1}.", + "File_0_is_not_a_module_2306": "Plik „{0}” nie jest modułem.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Plik „{0}” nie znajduje się w katalogu „rootDir” „{1}”. Katalog „rootDir” powinien zawierać wszystkie pliki źródłowe.", + "File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.", + "File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Nazwa pliku „{0}” różni się od już dołączonej nazwy pliku „{1}” tylko wielkością liter.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Nazwa pliku „{0}” ma rozszerzenie „{1}” — zostanie ono usunięte.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specyfikacja pliku nie może zawierać katalogu nadrzędnego („..”) wyświetlanego po symbolu wieloznacznym katalogu rekursywnego („**”): „{0}”.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Specyfikacja pliku nie może zawierać wielu cyklicznych symboli wieloznacznych katalogu („**”): „{0}”.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specyfikacja pliku nie może kończyć się cyklicznym symbolem wieloznacznym katalogu („**”): „{0}”.", + "Found_package_json_at_0_6099": "Znaleziono plik „package.json” w lokalizacji „{0}”.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”. Definicje klas automatycznie używają trybu z ograniczeniami.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”. Moduły automatycznie używają trybu z ograniczeniami.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Dla wyrażenia funkcji bez adnotacji zwracanego typu jest niejawnie określony zwracany typ „{0}”.", + "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_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.", + "Generates_corresponding_d_ts_file_6002": "Generuje odpowiadający plik „d.ts”.", + "Generates_corresponding_map_file_6043": "Generuje odpowiadający plik „map”.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Dla generatora niejawnie określono typ „{0}”, ponieważ nie przekazuje on żadnych wartości. Rozważ podanie zwracanego typu.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generatory nie są dozwolone w otaczającym kontekście.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Generatory są dostępne tylko wtedy, gdy jest używany język ECMAScript 2015 lub nowszy.", + "Generic_type_0_requires_1_type_argument_s_2314": "Typ ogólny „{0}” wymaga następującej liczby argumentów typu: {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Typ ogólny „{0}” wymaga od {1} do {2} argumentów typu.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Tworzenie wystąpienia typu ogólnego jest nadmiernie szczegółowe i prawdopodobnie nieskończone.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Widoczności metod dostępu pobierającej i ustawiającej są niezgodne.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Globalne eksporty modułu mogą występować tylko na najwyższym poziomie.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Globalne eksporty modułu mogą występować tylko w plikach deklaracji.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Globalne eksporty modułu mogą występować tylko w plikach modułów.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Typ globalny „{0}” musi być typem klasy lub interfejsu.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Typ globalny „{0}” musi mieć następującą liczbę parametrów typu: {1}.", + "Hexadecimal_digit_expected_1125": "Oczekiwano cyfry szesnastkowej.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Oczekiwano identyfikatora. „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Oczekiwano identyfikatora. „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami. Definicje klas są określane automatycznie w trybie z ograniczeniami.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Oczekiwano identyfikatora. Element „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami. Moduły są określane automatycznie w trybie z ograniczeniami.", + "Identifier_expected_1003": "Oczekiwano identyfikatora.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Oczekiwano identyfikatora. Ciąg „__esModule” jest zastrzeżony jako eksportowany znacznik podczas transformowania modułów ECMAScript.", + "Ignore_this_error_message_90019": "Ignoruj ten komunikat o błędzie.", + "Implement_inherited_abstract_class_90007": "Implementuj odziedziczoną klasę abstrakcyjną.", + "Implement_interface_0_90006": "Implementuj interfejs „{0}”.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzula implements wyeksportowanej klasy „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Import_0_from_module_1_90013": "Import „{0}” z modułu „{1}”.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Nie można użyć przypisania importu, gdy są używane moduły języka ECMAScript. Zamiast tego rozważ użycie elementu „import * as ns from \"mod\"”, „import {a} from \"mod\"” lub „import d from \"mod\"” albo innego formatu modułu.", + "Import_declaration_0_is_using_private_name_1_4000": "Deklaracja importu „{0}” używa nazwy prywatnej „{1}”.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklaracja importu powoduje konflikt z deklaracją lokalną „{0}”.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Deklaracje importu w przestrzeni nazw nie mogą odwoływać się do modułu.", + "Import_emit_helpers_from_tslib_6139": "Importuj pomocników emitowania z elementu „tslib”.", + "Import_name_cannot_be_0_2438": "Import nie może mieć nazwy „{0}”.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Deklaracja importu lub eksportu w deklaracji otaczającego modułu nie może przywoływać modułu za pomocą jego nazwy względnej.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importy nie są dozwolone w rozszerzeniach modułów. Rozważ przeniesienie ich do obejmującego modułu zewnętrznego.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "W deklaracjach wyliczenia otoczenia inicjator składowej musi być wyrażeniem stałym.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "W przypadku wyliczenia z wieloma deklaracjami tylko jedna deklaracja może pominąć inicjator dla pierwszego elementu wyliczenia.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "W deklaracjach wyliczeń ze specyfikatorem „const” inicjator składowej musi być wyrażeniem stałym.", + "Index_signature_in_type_0_only_permits_reading_2542": "Sygnatura indeksu w typie „{0}” zezwala tylko na odczytywanie.", + "Index_signature_is_missing_in_type_0_2329": "Brak sygnatury indeksu w typie „{0}”.", + "Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Wszystkie poszczególne deklaracje w scalonej deklaracji „{0}” muszą być wyeksportowane lub lokalne.", + "Infer_parameter_types_from_usage_95012": "Wywnioskuj typy parametrów na podstawie użycia.", + "Infer_type_of_0_from_usage_95011": "Wywnioskuj typ elementu „{0}” na podstawie użycia.", + "Initialize_property_0_in_the_constructor_90020": "Zainicjuj właściwość „{0}” w konstruktorze.", + "Initialize_static_property_0_90021": "Zainicjuj właściwość statyczną „{0}”.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicjator zmiennej składowej wystąpienia „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego w konstruktorze.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicjator parametru „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego po nim.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicjator nie określa żadnej wartości dla tego elementu powiązania, a element powiązania nie ma wartości domyślnej.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicjatory są niedozwolone w otaczających kontekstach.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicjuje projekt TypeScript i tworzy plik tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Wstaw opcje wiersza polecenia i pliki z pliku.", + "Install_0_95014": "Zainstaluj składnik „{0}”", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Interfejs „{0}” nie może jednocześnie rozszerzać typów „{1}” i „{2}”.", + "Interface_0_incorrectly_extends_interface_1_2430": "Interfejs „{0}” niepoprawnie rozszerza interfejs „{1}”.", + "Interface_declaration_cannot_have_implements_clause_1176": "Deklaracja interfejsu nie może mieć klauzuli „implements”.", + "Interface_name_cannot_be_0_2427": "Interfejs nie może mieć nazwy „{0}”.", + "Invalid_character_1127": "Nieprawidłowy znak.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nieprawidłowa nazwa modułu w rozszerzeniu. Moduł „{0}” jest rozpoznawany jako moduł bez typu na poziomie „{1}”, którego nie można rozszerzyć.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nieprawidłowa nazwa modułu w rozszerzeniu. Nie można znaleźć modułu „{0}”.", + "Invalid_reference_directive_syntax_1084": "Nieprawidłowa składnia dyrektywy „reference”.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Nieprawidłowe użycie elementu „{0}”. Definicje klas są określane automatycznie w trybie z ograniczeniami.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Nieprawidłowe użycie elementu „{0}”. Moduły są określane automatycznie w trybie z ograniczeniami.", + "Invalid_use_of_0_in_strict_mode_1100": "Nieprawidłowe użycie elementu „{0}” w trybie z ograniczeniami.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Nieprawidłowa wartość elementu „jsxFactory”. „{0}” to nie jest prawidłowy identyfikator ani kwalifikowana nazwa.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Nieprawidłowa wartość opcji „--reactNamespace”. Element „{0}” nie jest prawidłowym identyfikatorem.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Element JSDoc „@{0} {1}” nie pasuje do klauzuli „extends {2}”.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Element JSDoc „@{0}” nie został dołączony do klasy.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Element „...” JSDoc może występować tylko w ostatnim parametrze sygnatury.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Tag JSDoc „@param” tag ma nazwę „{0}”, ale nie ma parametru o tej nazwie.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Tag „@typedef” JSDoc powinien mieć adnotację typu lub powinien po nim następować tag „@property” lub „@member”.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc mogą być używane wyłącznie w komentarzach dokumentacji.", + "JSX_attribute_expected_17003": "Oczekiwano atrybutu JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atrybuty JSX muszą mieć przypisane wyrażenie, które nie jest puste.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX „{0}” nie ma odpowiedniego tagu zamykającego.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Typ atrybutów elementu JSX „{0}” nie może być typem unii.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Klasa elementów JSX nie obsługuje atrybutów, ponieważ nie ma właściwości „{0}”.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Dla elementu JSX niejawnie określono typ „any”, ponieważ interfejs „JSX.{0}” nie istnieje.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Dla elementu JSX niejawnie określono typ „any”, ponieważ typ globalny „JSX.Element” nie istnieje.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Typ elementu JSX „{0}” nie ma sygnatury konstrukcji ani wywołania.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Typ elementu JSX „{0}” nie jest funkcją konstruktora dla elementów JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementy JSX nie mogą mieć wielu atrybutów o tej samej nazwie.", + "JSX_expressions_must_have_one_parent_element_2657": "Wyrażenia JSX muszą mieć jeden element nadrzędny.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Fragment kodu JSX nie ma odpowiedniego tagu zamykającego.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "W przypadku korzystania z opcji --jsxFactory fragment kodu JSX nie jest obsługiwany", + "JSX_spread_child_must_be_an_array_type_2609": "Element podrzędny rozkładu JSX musi być typem tablicy.", + "Jump_target_cannot_cross_function_boundary_1107": "Cel skoku nie może przekraczać granicy funkcji.", + "KIND_6034": "RODZAJ", + "LOCATION_6037": "LOKALIZACJA", + "Language_service_is_disabled_9004": "Usługa języka jest wyłączona.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Lewa strona operatora „przecinek” jest nieużywana i nie ma żadnych efektów ubocznych.", + "Line_break_not_permitted_here_1142": "Podział wiersza nie jest tutaj dozwolony.", + "Line_terminator_not_permitted_before_arrow_1200": "Terminator wiersza nie jest dozwolony przed strzałką.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista folderów, z których mają być uwzględnione definicje typów.", + "List_of_language_service_plugins_6181": "Lista wtyczek usługi języka.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Lista folderów głównych, których połączona zawartość reprezentuje strukturę projektu w czasie wykonywania.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Ładowanie elementu „{0}” z katalogu głównego „{1}”, lokalizacja kandydata: „{2}”.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Ładowanie modułu „{0}” z folderu „node_modules”, docelowy typ pliku: „{1}”.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Ładowanie modułu jako pliku/folderu, lokalizacja modułu kandydata: „{0}”, docelowy typ pliku: „{1}”.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Ustawienia regionalne muszą mieć postać lub -. Na przykład „{0}” lub „{1}”.", + "Longest_matching_prefix_for_0_is_1_6108": "Najdłuższy zgodny prefiks dla „{0}” to „{1}”.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Wyszukiwanie w folderze „node_modules”, początkowa lokalizacja: „{0}”.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Ustaw wywołanie „super()” jako pierwszą instrukcję w konstruktorze.", + "Member_0_implicitly_has_an_1_type_7008": "Dla składowej „{0}” niejawnie określono typ „{1}”.", + "Merge_conflict_marker_encountered_1185": "Napotkano znacznik konfliktu scalania.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Scalona deklaracja „{0}” nie może zawierać domyślnej deklaracji eksportu. Rozważ dodanie oddzielnej deklaracji „export default {0}” zamiast niej.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Metawłaściwość „{0}” jest dozwolona tylko w treści deklaracji funkcji, wyrażeniu funkcji lub konstruktorze.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Metoda „{0}” nie może mieć implementacji, ponieważ jest oznaczona jako abstrakcyjna.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Metoda „{0}” wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Metoda „{0}” wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Modifiers_cannot_appear_here_1184": "Modyfikatory nie mogą występować w tym miejscu.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Moduł {0} już wyeksportował składową o nazwie „{1}”. Zastanów się nad jawnym ponownym eksportem, aby rozstrzygnąć niejednoznaczność.", + "Module_0_has_no_default_export_1192": "Moduł „{0}” nie ma eksportu domyślnego.", + "Module_0_has_no_exported_member_1_2305": "Moduł „{0}” nie ma wyeksportowanej składowej „{1}”.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Moduł „{0}” został ukryty przez deklarację lokalną o takiej samej nazwie.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Wynikiem rozpoznania modułu „{0}” jest jednostka niebędąca modułem i nie można zaimportować tego modułu przy użyciu tej konstrukcji.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Moduł „{0}” używa elementu „export =” i nie może być używany z elementem „export *”.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Moduł „{0}” został rozpoznany jako otaczający moduł zadeklarowany w elemencie „{1}”, ponieważ nie zmodyfikowano tego pliku.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Moduł „{0}” został rozpoznany jako otaczający moduł zadeklarowany lokalnie w pliku „{1}”.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Moduł „{0}” został rozpoznany jako „{1}”, ale nie jest ustawiona opcja „--jsx”.", + "Module_Resolution_Options_6174": "Opcje rozpoznawania modułu", + "Module_name_0_matched_pattern_1_6092": "Nazwa modułu: „{0}”, dopasowany wzorzec: „{1}”.", + "Module_name_0_was_not_resolved_6090": "======== Nazwa modułu „{0}” nie została rozpoznana. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nazwa modułu „{0}” została pomyślnie rozpoznana jako „{1}”. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Rodzaj rozpoznawania modułów nie został podany. Zostanie użyty rodzaj „{0}”.", + "Module_resolution_using_rootDirs_has_failed_6111": "Nie można rozpoznać modułów przy użyciu opcji „rootDirs”.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Konstruktor nie może mieć wielu implementacji.", + "NEWLINE_6061": "NOWY WIERSZ", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Nazwane właściwości „{0}” typów „{1}” i „{2}” nie są identyczne.", + "Namespace_0_has_no_exported_member_1_2694": "Przestrzeń nazw „{0}” nie ma wyeksportowanej składowej „{1}”.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Żaden z konstruktorów podstawowych nie ma określonej liczby argumentów typu.", + "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ść.", + "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}”.", + "Object_is_possibly_null_2531": "Obiekt ma prawdopodobnie wartość „null”.", + "Object_is_possibly_null_or_undefined_2533": "Obiekt ma prawdopodobnie wartość „null” lub „undefined”.", + "Object_is_possibly_undefined_2532": "Obiekt ma prawdopodobnie wartość „undefined”.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Dla literału obiektu można określić tylko znane właściwości, a właściwość „{0}” nie istnieje w typie „{1}”.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Literał obiektu może określać wyłącznie znane właściwości, ale element „{0}” nie istnieje w typie „{1}”. Czy chodziło Ci o „{2}”?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Dla właściwości „{0}” literału obiektu niejawnie określono typ „{1}”.", + "Octal_digit_expected_1178": "Oczekiwano cyfry ósemkowej.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Typy literałów ósemkowych muszą korzystać ze składni ES2015. Użyj składni „{0}”.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Literały ósemkowe są niedozwolone w inicjatorze składowych wyliczeń. Użyj składni „{0}”.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Literały ósemkowe są niedozwolone w trybie z ograniczeniami.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Literały ósemkowe są niedostępne, jeśli językiem docelowym jest ECMAScript 5 lub nowszy. Użyj składni „{0}”.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "W instrukcji „for...in” jest dozwolona tylko pojedyncza deklaracja zmiennej.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "W instrukcji „for...of” jest dozwolona tylko pojedyncza deklaracja zmiennej.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Tylko funkcja typu void może być wywoływana za pomocą słowa kluczowego „new”.", + "Only_ambient_modules_can_use_quoted_names_1035": "Tylko otaczające moduły mogą używać nazw w cudzysłowie.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Tylko moduły „amd” i „system” są obsługiwane razem z parametrem --{0}.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Klauzula „extends” klasy obsługuje obecnie tylko identyfikatory/nazwy kwalifikowane z opcjonalnymi argumentami typu.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Tylko publiczne i chronione metody klasy bazowej są dostępne przy użyciu słowa kluczowego „super”.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Nie można zastosować operatora „{0}” do typów „{1}” i „{2}”.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Opcję „{0}” można określić jedynie w pliku „tsconfig.json”.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Opcja „{0}” może być używana tylko w przypadku podania opcji „--inlineSourceMap” lub „--sourceMap”.", + "Option_0_cannot_be_specified_with_option_1_5053": "Opcji „{0}” nie można określić razem z opcją „{1}”.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Opcji „{0}” nie można określić bez opcji „{1}”.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Wartość opcji „{0}” powinna być tablicą łańcuchów.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Opcji „isolatedModules” można użyć tylko wtedy, gdy podano opcję „--module” lub opcja „target” określa cel „ES2015” lub wyższy.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Opcji „paths” nie można użyć bez podawania opcji „--baseUrl”.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Nie można mieszać opcji „project” z plikami źródłowymi w wierszu polecenia.", + "Options_Colon_6027": "Opcje:", + "Output_directory_for_generated_declaration_files_6166": "Katalog wyjściowy dla wygenerowanych plików deklaracji.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Sygnatura przeciążenia nie jest zgodna z implementacją funkcji.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Wszystkie sygnatury przeciążeń muszą być abstrakcyjne lub nieabstrakcyjne.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Wszystkie sygnatury przeciążeń muszą być otaczającymi sygnaturami lub żadna nie może być otaczającą sygnaturą.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Wszystkie sygnatury przeciążeń muszą być wyeksportowane lub żadna nie może być wyeksportowana.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Wszystkie sygnatury przeciążeń muszą być opcjonalne lub wymagane.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Wszystkie sygnatury przeciążeń muszą być publiczne, prywatne lub chronione.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Parametr „{0}” nie może być przywoływany w swoim inicjatorze.", + "Parameter_0_implicitly_has_an_1_type_7006": "Dla parametru „{0}” niejawnie określono typ „{1}”.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr „{0}” nie znajduje się w tym samym położeniu co parametr „{1}”.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Parametr „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Parametr „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Parametr „{0}” konstruktora z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Parametr „{0}” konstruktora z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Parametr „{0}” konstruktora z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Parametr „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Parametr „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Parametr „{0}” wyeksportowanej funkcji ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Parametr „{0}” wyeksportowanej funkcji ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Parametr „{0}” wyeksportowanej funkcji ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Parametr „{0}” sygnatury indeksu z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Parametr „{0}” sygnatury indeksu z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Parametr „{0}” metody z wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Parametr „{0}” metody z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Parametr „{0}” metody publicznej z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Parametr „{0}” metody publicznej z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Parametr „{0}” metody publicznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Parametr „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Parametr „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Parametr „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametr nie może mieć znaku zapytania i inicjatora.", + "Parameter_declaration_expected_1138": "Oczekiwano deklaracji parametru.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Typ parametru publicznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Typ parametru publicznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Typ parametru publicznej statycznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Typ parametru publicznej statycznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analizuj w trybie z ograniczeniami i emituj ciąg „use strict” dla każdego pliku źródłowego.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Wzorzec „{0}” może zawierać maksymalnie jeden znak „*”.", + "Prefix_0_with_an_underscore_90025": "Prefiks „{0}” z podkreśleniem.", + "Print_names_of_files_part_of_the_compilation_6155": "Drukuj nazwy plików będących częścią kompilacji.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Drukuj nazwy wygenerowanych plików będących częścią kompilacji.", + "Print_the_compiler_s_version_6019": "Wypisz wersję kompilatora.", + "Print_this_message_6017": "Wypisz ten komunikat.", + "Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.", + "Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy chodziło Ci o „{2}”?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Właściwość „{0}” ma deklaracje będące w konflikcie i jest niedostępna w typie „{1}”.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Właściwość „{0}” nie ma inicjatora i nie jest na pewno przypisana w konstruktorze.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „get” nie ma adnotacji zwracanego typu.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „set” nie ma adnotacji typu parametru.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Właściwości „{0}” w typie „{1}” nie można przypisać do typu „{2}”.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Właściwość „{0}” jest zadeklarowana, ale jej wartość nie jest nigdy odczytywana.", + "Property_0_is_incompatible_with_index_signature_2530": "Właściwość „{0}” jest niezgodna z sygnaturą indeksu.", + "Property_0_is_missing_in_type_1_2324": "W typie „{1}” brakuje właściwości „{0}”.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Właściwość „{0}” jest opcjonalna w typie „{1}”, ale jest wymagana w typie „{2}”.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Właściwość „{0}” jest prywatna i dostępna tylko w klasie „{1}”.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Właściwość „{0}” jest prywatna w typie „{1}”, ale nie w typie „{2}”.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Właściwość „{0}” jest chroniona i dostępna tylko za pośrednictwem wystąpienia klasy „{1}”.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Właściwość „{0}” jest chroniona i dostępna tylko w klasie „{1}” oraz w jej podklasach.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Właściwość „{0}” jest chroniona, ale typ „{1}” nie jest klasą pochodną elementu „{2}”.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Właściwość „{0}” jest chroniona w typie „{1}”, ale jest publiczna w typie „{2}”.", + "Property_0_is_used_before_being_assigned_2565": "Właściwość „{0}” jest używana przed przypisaniem.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Właściwości „{0}” atrybutu rozkładu JSX nie można przypisać do właściwości docelowej.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Właściwość „{0}” wyeksportowanego wyrażenia klasy nie może być prywatna ani chroniona.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Właściwość „{0}” wyeksportowanego interfejsu ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Właściwość „{0}” wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Nie można przypisać właściwości „{0}” typu „{1}” do typu indeksu numerycznego „{2}”.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Nie można przypisać właściwości „{0}” typu „{1}” do typu indeksu ciągu „{2}”.", + "Property_assignment_expected_1136": "Oczekiwano przypisania właściwości.", + "Property_destructuring_pattern_expected_1180": "Oczekiwano wzorca usuwającego strukturę właściwości.", + "Property_or_signature_expected_1131": "Oczekiwano właściwości lub sygnatury.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Wartością właściwości może być jedynie literał ciągu, literał numeryczny, wartości „true”, „false” i „null”, literał obiektu i literał tablicy.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Udostępnij pełne wsparcie dla elementów iterowanych w elementach „for-of”, rozpiętości i usuwania, gdy elementem docelowym jest „ES5” lub „ES3”.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Metoda publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Metoda publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Metoda publiczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Właściwość publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Właściwość publiczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Właściwość publiczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Publiczna metoda statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Publiczna metoda statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Publiczna metoda statyczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Publiczna właściwość statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można jej nazwać.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Publiczna właściwość statyczna „{0}” wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Publiczna właściwość statyczna „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Zgłaszaj błąd w przypadku wyrażeń i deklaracji z implikowanym typem „any”.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.", + "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", + "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", + "Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.", + "Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.", + "Report_errors_on_unused_parameters_6135": "Raportuj błędy dla nieużywanych parametrów.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Wymagane parametry typu mogą nie być zgodne z opcjonalnymi parametrami typu.", + "Resolution_for_module_0_was_found_in_cache_6147": "Znaleziono rozwiązanie dla modułu „{0}” w pamięci podręcznej.", + "Resolving_from_node_modules_folder_6118": "Trwa rozpoznawanie na podstawie folderu node_modules...", + "Resolving_module_0_from_1_6086": "======== Rozpoznawanie modułu „{0}” na podstawie „{1}”. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Rozpoznawanie nazwy modułu „{0}” względem podstawowego adresu URL „{1}” — „{2}”.", + "Resolving_real_path_for_0_result_1_6130": "Rozpoznawanie rzeczywistej ścieżki elementu ƒ„{0}”, wynik: „{1}”.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający: „{1}”, katalog główny: „{2}”. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający: „{1}”, katalog główny nie został ustawiony. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający nie został ustawiony, katalog główny: „{1}”. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Rozpoznawanie dyrektywy odwołania do typu „{0}”, plik zawierający nie został ustawiony, katalog główny nie został ustawiony. ========", + "Resolving_using_primary_search_paths_6117": "Trwa rozpoznawanie przy użyciu ścieżek wyszukiwania podstawowego...", + "Resolving_with_primary_search_path_0_6121": "Rozpoznawanie przy użyciu ścieżki wyszukiwania podstawowego „{0}”.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Dla parametru rest „{0}” niejawnie określono typ „any[]”.", + "Rest_types_may_only_be_created_from_object_types_2700": "Typy rest można tworzyć tylko na podstawie typów obiektu.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Zwracany typ sygnatury wywołania z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Zwracany typ sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Zwracany typ sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Zwracany typ sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Musi istnieć możliwość przypisania zwracanego typu sygnatury konstruktora do typu wystąpienia klasy.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Zwracany typ wyeksportowanej funkcji ma nazwę „{0}” z modułu zewnętrznego {1} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Zwracany typ wyeksportowanej funkcji ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Zwracany typ wyeksportowanej funkcji ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Zwracany typ sygnatury indeksu z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Zwracany typ sygnatury indeksu z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Zwracany typ metody z wyeksportowanego interfejsu ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Zwracany typ metody z wyeksportowanego interfejsu ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Zwracany typ publicznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Zwracany typ publicznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Zwracany typ publicznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Zwracany typ metody publicznej z wyeksportowanej klasy ma nazwę „{0}” z modułu zewnętrznego {1} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Zwracany typ metody publicznej z wyeksportowanej klasy ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Zwracany typ metody publicznej z wyeksportowanej klasy ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Zwracany typ publicznej statycznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu zewnętrznego {2} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Zwracany typ publicznej statycznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę „{1}” z modułu prywatnego „{2}” lub używa tej nazwy.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Zwracany typ publicznej statycznej metody pobierającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{0}” z modułu zewnętrznego {1} lub używa tej nazwy, ale nie można go nazwać.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę „{0}” z modułu prywatnego „{1}” lub używa tej nazwy.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{0}” lub używa tej nazwy.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Ponownie używane są rozwiązania modułu pochodzące z programu „{0}”, ponieważ rozwiązania nie zmieniły się w stosunku do starej wersji programu.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Ponownie używane jest rozwiązanie modułu „{0}” do pliku „{1}” ze starej wersji programu.", + "Rewrite_as_the_indexed_access_type_0_90026": "Zapisz ponownie jako typ dostępu indeksowanego „{0}”.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nie można określić katalogu głównego. Pomijanie ścieżek wyszukiwania podstawowego.", + "STRATEGY_6039": "STRATEGIA", + "Scoped_package_detected_looking_in_0_6182": "Wykryto pakiet w zakresie, wyszukiwanie w „{0}”", + "Setters_cannot_return_a_value_2408": "Metody ustawiające nie mogą zwracać wartości.", + "Show_all_compiler_options_6169": "Pokaż wszystkie opcje kompilatora.", + "Show_diagnostic_information_6149": "Pokaż informacje diagnostyczne.", + "Show_verbose_diagnostic_information_6150": "Pokaż pełne informacje diagnostyczne.", + "Signature_0_must_be_a_type_predicate_1224": "Sygnatura „{0}” musi być predykatem typów.", + "Skip_type_checking_of_declaration_files_6012": "Pomiń sprawdzanie typu plików deklaracji.", + "Source_Map_Options_6175": "Opcje mapy źródła", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Nie można przypisać specjalizowanej sygnatury przeciążenia do żadnej sygnatury niespecjalizowanej.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Specyfikator dynamicznego importowania nie może być elementem spread.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Podaj wersję docelową języka ECMAScript: „ES3” (domyślna), „ES5”, „ES2015”, „ES2016”, „ES2017” lub „ESNEXT”.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Wybierz sposób generowania kodu JSX: „preserve”, „react-native” lub „react”.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Określ pliki biblioteki do uwzględnienia w kompilacji: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Określ sposób generowania kodu modułu: „none”, „commonjs”, „amd”, „system”, „umd”, „es2015” lub „ESNext”.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Określ strategię rozpoznawania modułów: „node” (Node.js) lub „classic” (TypeScript w wersji wcześniejszej niż 1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Określ funkcję fabryki JSX do użycia, gdy elementem docelowym jest emisja elementu JSX „react”, np. „React.createElement” lub „h”.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Określ sekwencję końca wiersza, która ma być używana podczas emitowania plików: „CRLF” (dos) lub „LF” (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Określ lokalizację, w której debuger ma szukać plików TypeScript zamiast szukania w lokalizacjach źródłowych.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Określ lokalizację, w której debuger ma szukać plików map zamiast szukania w wygenerowanych lokalizacjach.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Określ katalog główny plików wejściowych. Strukturą katalogów wyjściowych można sterować przy użyciu opcji --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operator rozpiętości w wyrażeniach „new” jest dostępny tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", + "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread można tworzyć tylko z typów obiektu.", + "Statement_expected_1129": "Oczekiwano instrukcji.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Instrukcje są niedozwolone w otaczających kontekstach.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statyczne składowe nie mogą przywoływać parametrów typu klasy.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Właściwość statyczna „{0}” jest w konflikcie z właściwością wbudowaną „Function.{0}” funkcji konstruktora „{1}”.", + "Strict_Type_Checking_Options_6173": "Opcje ścisłego sprawdzania typów", + "String_literal_expected_1141": "Oczekiwano literału ciągu.", + "String_literal_with_double_quotes_expected_1327": "Oczekiwano literału ciągu z podwójnymi cudzysłowami.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stosuj styl dla błędów i komunikatów za pomocą koloru i kontekstu. (eksperymentalne).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Kolejne deklaracje zmiennej muszą być tego samego typu. Zmienna „{0}” musi być typu „{1}”, ale w tym miejscu jest typu „{2}”.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Podstawienie „{0}” dla wzorca „{1}” ma nieprawidłowy typ. Oczekiwano typu „string”, a uzyskano typ „{2}”.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Podstawienie „{0}” we wzorcu „{1}” może zawierać maksymalnie jeden znak „*”.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Podstawieniami wzorca „{0}” powinna być tablica.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Podstawienia dla wzorca „{0}” nie powinny być pustą tablicą.", + "Successfully_created_a_tsconfig_json_file_6071": "Pomyślnie utworzono plik tsconfig.json.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Wywołania super są niedozwolone poza konstruktorami i zagnieżdżonymi funkcjami wewnątrz konstruktorów.", + "Suppress_excess_property_checks_for_object_literals_6072": "Pomiń nadmiarowe sprawdzenia właściwości dla literałów obiektu.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Pomiń błędy noImplicitAny dotyczące obiektów indeksowania bez sygnatur indeksów.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Odwołanie do elementu „Symbol” nie zawiera odwołania do globalnego obiektu konstruktora symboli.", + "Syntax_Colon_0_6023": "Składnia: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Nie można zastosować operatora „{0}” do typu „symbol”.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Operator „{0}” nie jest dozwolony w przypadku typów logicznych. Zamiast tego rozważ użycie operatora „{1}”.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Typ „Object” można przypisać do niewielu innych typów. Czy zamiast tego typu miał zostać użyty typ „any”?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Obiekt „arguments” nie może być przywoływany w funkcji strzałkowej w językach ES3 i ES5. Rozważ użycie standardowego wyrażenia funkcji.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Obiekt „arguments” nie może być przywoływany w asynchronicznej funkcji lub metodzie w języku ES3 i ES5. Rozważ użycie standardowej funkcji lub metody.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Treść instrukcji „if” nie może być pustą instrukcją.", + "The_character_set_of_the_input_files_6163": "Zestaw znaków plików wejściowych.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Treść zawierającej funkcji lub modułu jest za duża do analizy przepływu sterowania.", + "The_current_host_does_not_support_the_0_option_5001": "Bieżący host nie obsługuje opcji „{0}”.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Wyrażenie przypisania eksportu musi być identyfikatorem lub kwalifikowaną nazwą w otaczającym kontekście.", + "The_files_list_in_config_file_0_is_empty_18002": "Lista „files” w pliku konfiguracji „{0}” jest pusta.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Pierwszym parametrem metody „then” obietnicy musi być wywołanie zwrotne.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Dla typu globalnego „JSX.{0}” nie można określić więcej niż jednej właściwości.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Lewa strona instrukcji „for...in” nie może być wzorcem usuwającym strukturę.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Lewa strona instrukcji „for...in” nie może używać adnotacji typu.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Lewa strona instrukcji „for...in” musi być zmienną lub dostępem do właściwości.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Lewa strona instrukcji „for...in” musi być typu „string” lub „any”.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Lewa strona instrukcji „for...of” nie może używać adnotacji typu.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Lewa strona instrukcji „for...of” musi być zmienną lub dostępem do właściwości.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Lewa strona operacji arytmetycznej musi być typu „any”, „number” lub typu wyliczeniowego.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Lewa strona wyrażenia przypisania musi być zmienną lub dostępem do właściwości.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Lewa strona wyrażenia „in” musi być typu „any”, „string”, „number” lub „symbol”.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Lewa strona wyrażenia „instanceof” musi być typu „any”, typu obiektu lub parametrem typu.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Ustawienia regionalne używane przy wyświetlaniu komunikatów użytkownikowi (np. „pl-pl”)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maksymalna głębokość zależności na potrzeby wyszukiwania w elemencie node_modules i ładownia plików JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Argument operacji dla operatora delete nie może być właściwością tylko do odczytu.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Argument operacji dla operatora delete musi być odwołaniem do właściwości.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operatora inkrementacji lub dekrementacji musi być zmienną lub dostępem do właściwości.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Zwracany typ konstruktora elementu JSX musi zwracać typ obiektu.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Zwracany typ funkcji dekoratora parametrów musi mieć postać „void” lub „any”.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Zwracany typ funkcji dekoratora właściwości musi mieć postać „void” lub „any”.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Zwracany typ funkcji asynchronicznej musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Zwracany typ metody lub funkcji asynchronicznej musi być globalnym typem Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "Prawa strona instrukcji „for...in” musi być typu „any”, typu obiektu lub parametrem typu.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Prawa strona operacji arytmetycznej musi być typu „any”, „number” lub typu wyliczeniowego.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Prawa strona wyrażenia „in” musi być typu „any”, typu obiektu lub parametrem typu.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Prawa strona wyrażenia „instanceof” musi być typu „any” lub typu, który można przypisać do typu interfejsu „Function”.", + "The_specified_path_does_not_exist_Colon_0_5058": "Wybrana ścieżka nie istnieje: „{0}”.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Cel przypisania musi być zmienną lub dostępem do właściwości.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Cel przypisania rest obiektu musi stanowić dostęp do zmiennej lub właściwości.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Kontekstu „this” typu „{0}” nie można przypisać do elementu „this” metody typu „{1}”.", + "The_this_types_of_each_signature_are_incompatible_2685": "Typy „this” sygnatur nie są zgodne.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Nie można wywnioskować argumentu typu dla parametru typu „{0}” na podstawie użycia. Rozważ jawne określenie argumentów typu.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Typ zwracany przez metodę „next()” iteratora asynchronicznego musi być obietnicą dla typu z właściwością „value”.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Typ zwracany przez metodę „next()” iteratora musi mieć właściwość „value”.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Deklaracja zmiennej instrukcji „for...in” nie może mieć inicjatora.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Deklaracja zmiennej instrukcji „for...of” nie może mieć inicjatora.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Instrukcja „with” nie jest obsługiwana. Wszystkie symbole w bloku „with” będą mieć typ „any”.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Ta składnia wymaga zaimportowanego pomocnika, ale nie można znaleźć modułu „{0}”.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Ta składnia wymaga zaimportowanego pomocnika o nazwie „{1}”, ale moduł „{0}” nie ma wyeksportowanej składowej „{1}”.", + "Trailing_comma_not_allowed_1009": "Końcowy przecinek jest niedozwolony.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluj każdy plik jako oddzielny moduł (podobne do „ts.transpileModule”).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Spróbuj użyć polecenia „npm install @types/{0}”, jeśli istnieje, lub dodać nowy plik deklaracji (.d.ts) zawierający ciąg „declare module '{0}';”", + "Trying_other_entries_in_rootDirs_6110": "Wykonywanie prób przy użyciu innych pozycji opcji „rootDirs”.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Wykonywanie próby przeprowadzenia podstawienia „{0}”, lokalizacja modułu kandydata: „{1}”.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Nie można przypisać typu krotki „{0}” o długości „{1}” do krotki o długości „{2}”.", + "Type_0_cannot_be_converted_to_type_1_2352": "Typu „{0}” nie można przekonwertować na typ „{1}”.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Typu „{0}” nie można używać jako typu indeksu.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Typu „{0}” nie można użyć do indeksowania typu „{1}”.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Typ „{0}” nie spełnia warunków ograniczenia „{1}”.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Typ „{0}” nie ma pasującej sygnatury indeksu dla typu „{1}”.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Typy „{0}” i „{1}” nie mają żadnych wspólnych właściwości.", + "Type_0_has_no_property_1_2460": "Typ „{0}” nie ma właściwości „{1}”.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Typ „{0}” nie ma właściwości „{1}” i sygnatury indeksu ciągu.", + "Type_0_is_not_a_constructor_function_type_2507": "Typ „{0}” nie jest typem funkcji konstruktora.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Typ „{0}” nie jest prawidłowym zwracanym typem funkcji asynchronicznej w wersji ES5/ES3, ponieważ nie odwołuje się do wartości konstruktora zgodnej z elementem Promise.", + "Type_0_is_not_an_array_type_2461": "Typ „{0}” nie jest typem tablicowym.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Typ „{0}” nie jest typem tablicowym ani typem ciągu.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ „{0}” nie jest typem tablicy ani ciągu lub nie ma metody „[Symbol.iterator]()” zwracającej iterator.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ „{0}” nie jest typem tablicy lub nie ma metody „[Symbol.iterator]()” zwracającej iterator.", + "Type_0_is_not_assignable_to_type_1_2322": "Typu „{0}” nie można przypisać do typu „{1}”.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Typu „{0}” nie można przypisać do typu „{1}”. Istnieją dwa różne typy o tej nazwie, lecz są ze sobą niezwiązane.", + "Type_0_is_not_comparable_to_type_1_2678": "Typu „{0}” nie można porównać z typem „{1}”.", + "Type_0_is_not_generic_2315": "Typ „{0}” nie jest ogólny.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Typ „{0}” nie udostępnia dopasowania dla sygnatury „{1}”.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Typ „{0}” rekursywnie przywołuje sam siebie jako typ podstawowy.", + "Type_alias_0_circularly_references_itself_2456": "Alias typu „{0}” cyklicznie przywołuje sam siebie.", + "Type_alias_name_cannot_be_0_2457": "Alias typu nie może mieć nazwy „{0}”.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Adnotacja typu nie może występować w deklaracji konstruktora.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Kandydujący argument typu „{1}” nie jest prawidłowym argumentem typu, ponieważ nie jest nadtypem kandydata „{0}”.", + "Type_argument_expected_1140": "Oczekiwano argumentu typu.", + "Type_argument_list_cannot_be_empty_1099": "Lista argumentów typu nie może być pusta.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Pliki deklaracji typu do uwzględnienia w kompilacji.", + "Type_expected_1110": "Oczekiwano typu.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Typ jest przywoływany bezpośrednio lub pośrednio w wywołaniu zwrotnym realizacji jego własnej metody „then”.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ musi mieć metodę „[Symbol.asyncIterator]()” zwracającą iterator asynchroniczny.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ musi zawierać metodę „[Symbol.iterator]()” zwracającą iterator.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu „await” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterowanych elementów operandu „yield*” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu „yield” w generatorze asynchronicznym musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", + "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu „{0}” zawiera ograniczenie cykliczne.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu „{0}” ma cykliczną wartość domyślną.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Parametr typu „{0}” wyeksportowanej funkcji ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Parametr typu „{0}” wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Parametr typu „{0}” wyeksportowanego aliasu typu ma nazwę prywatną „{1}” lub jej używa.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Parametr typu „{0}” metody z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Parametr typu „{0}” metody publicznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Parametr typu „{0}” publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", + "Type_parameter_declaration_expected_1139": "Oczekiwano deklaracji parametru typu.", + "Type_parameter_list_cannot_be_empty_1098": "Lista parametrów typu nie może być pusta.", + "Type_parameter_name_cannot_be_0_2368": "Parametr typu nie może mieć nazwy „{0}”.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Parametry typu nie mogą występować w deklaracji konstruktora.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Predykatu typów „{0}” nie można przypisać do elementu „{1}”.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Dyrektywa odwołania do typu „{0}” nie została rozpoznana. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Dyrektywa odwołania do typu „{0}” została pomyślnie rozpoznana jako „{1}”, podstawowe: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mają osobne deklaracje właściwości prywatnej „{0}”.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrów „{0}” i „{1}” są niezgodne.", + "Types_of_property_0_are_incompatible_2326": "Typy właściwości „{0}” są niezgodne.", + "Unable_to_open_file_0_6050": "Nie można otworzyć pliku „{0}”.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Nie można rozpoznać sygnatury dekoratora klasy wywołanego jako wyrażenie.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Nie można rozpoznać sygnatury dekoratora metody wywołanego jako wyrażenie.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Nie można rozpoznać sygnatury dekoratora parametru wywołanego jako wyrażenie.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Nie można rozpoznać sygnatury dekoratora właściwości wywołanego jako wyrażenie.", + "Unexpected_end_of_text_1126": "Nieoczekiwany koniec tekstu.", + "Unexpected_token_1012": "Nieoczekiwany token.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Nieoczekiwany token. Oczekiwano konstruktora, metody, metody dostępu lub właściwości.", + "Unexpected_token_expected_1179": "Nieoczekiwany token. Oczekiwano znaku „{”.", + "Unknown_compiler_option_0_5023": "Nieznana opcja kompilatora „{0}”.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Nieznana opcja „excludes”. Czy chodziło o „exclude”?", + "Unknown_type_acquisition_option_0_17010": "Opcja pozyskania nieznanego typu „{0}”.", + "Unreachable_code_detected_7027": "Wykryto nieosiągalny kod.", + "Unsupported_locale_0_6049": "Nieobsługiwane ustawienia regionalne „{0}”.", + "Unterminated_Unicode_escape_sequence_1199": "Niezakończona sekwencja ucieczki kodu Unicode.", + "Unterminated_quoted_string_in_response_file_0_6045": "Niezakończony ciąg ujęty w cudzysłów w pliku odpowiedzi „{0}”.", + "Unterminated_regular_expression_literal_1161": "Niezakończony literał wyrażenia regularnego.", + "Unterminated_string_literal_1002": "Niezakończony literał ciągu znaków.", + "Unterminated_template_literal_1160": "Niezakończony literał szablonu.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Wywołania funkcji bez typu nie mogą przyjmować argumentów typu.", + "Unused_label_7028": "Nieużywana etykieta.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", + "VERSION_6036": "WERSJA", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Wartość typu „{0}” nie ma żadnych wspólnych właściwości z typem „{1}”. Czy jej wywołanie było zamierzone?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Nie można wywołać wartości typu „{0}”. Czy miał zostać użyty operator „new”?", + "Variable_0_implicitly_has_an_1_type_7005": "Dla zmiennej „{0}” niejawnie określono typ „{1}”.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Zmienna „{0}” ma niejawnie typ „{1}” w niektórych lokalizacjach, w których nie można określić jej typu.", + "Variable_0_is_used_before_being_assigned_2454": "Zmienna „{0}” jest używana przed przypisaniem.", + "Variable_declaration_expected_1134": "Oczekiwano deklaracji zmiennej.", + "Variable_declaration_list_cannot_be_empty_1123": "Lista deklaracji zmiennych nie może być pusta.", + "Version_0_6029": "Wersja {0}", + "Watch_input_files_6005": "Obserwuj pliki wejściowe.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nie można zmienić nazw elementów zdefiniowanych w standardowej bibliotece TypeScript.", + "You_cannot_rename_this_element_8000": "Nie można zmienić nazwy tego elementu.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Element „{0}” akceptuje za mało argumentów, aby można go było użyć w tym miejscu jako dekorator. Czy chcesz najpierw go wywołać i zapisać tag „@{0}()”?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Element „{0}” został określony dwa razy. Atrybut o nazwie „{0}” zostanie przesłonięty.", + "_0_can_only_be_used_in_a_ts_file_8009": "Elementu „{0}” można użyć tylko w pliku .ts.", + "_0_expected_1005": "Oczekiwano elementu „{0}”.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "Dla elementu „{0}” niejawnie określono zwracany typ „any”, ponieważ nie zawiera on adnotacji zwracanego typu i jest przywoływany bezpośrednio lub pośrednio w jednym z jego zwracanych wyrażeń.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Dla elementu „{0}” niejawnie określono typ „any”, ponieważ nie zawiera on adnotacji typu i jest przywoływany bezpośrednio lub pośrednio w jego własnym inicjatorze.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "Element „{0}” jest elementem podstawowym, ale element „{1}” jest obiektem otoki. Preferuje się użycie elementu „{0}”, jeśli jest to możliwe.", + "_0_is_declared_but_its_value_is_never_read_6133": "Element „{0}” jest zadeklarowany, ale jego wartość nie jest nigdy odczytywana.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "„{0}” nie jest prawidłową metawłaściwością słowa kluczowego „{1}”. Czy miał to być element „{2}”?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Element „{0}” jest przywoływany bezpośrednio lub pośrednio w jego własnym wyrażeniu podstawowym.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Element „{0}” jest przywoływany bezpośrednio lub pośrednio w jego własnej adnotacji typu.", + "_0_list_cannot_be_empty_1097": "Lista „{0}” nie może być pusta.", + "_0_modifier_already_seen_1030": "Napotkano już modyfikator „{0}”.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "Modyfikator „{0}” nie może występować w elemencie klasy.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Modyfikator „{0}” nie może występować w deklaracji konstruktora.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "Modyfikator „{0}” nie może występować we właściwości danych.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Modyfikator „{0}” nie może być stosowany w przypadku elementu przestrzeni nazw lub modułu.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Modyfikator „{0}” nie może występować w parametrze.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Modyfikator „{0}” nie może być stosowany w przypadku składowej typu.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Modyfikator „{0}” nie może być stosowany w przypadku sygnatury indeksu.", + "_0_modifier_cannot_be_used_here_1042": "Modyfikatora „{0}” nie można użyć w tym miejscu.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Modyfikatora „{0}” nie można użyć w otaczającym kontekście.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Modyfikatora „{0}” nie można używać z modyfikatorem „{1}”.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "Modyfikatora „{0}” nie można używać z deklaracją klasy.", + "_0_modifier_must_precede_1_modifier_1029": "Modyfikator „{0}” musi występować przed modyfikatorem „{1}”.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "Element „{0}” odwołuje się tylko do typu, ale jest używany tutaj jako przestrzeń nazw.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "Element „{0}” odwołuje się jedynie do typu, ale jest używany w tym miejscu jako wartość.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "„{0}” odnosi się do globalnego formatu UMD, ale bieżący plik jest modułem. Rozważ zamiast tego dodanie importu.", + "_0_tag_already_specified_1223": "Tag „{0}” jest już określony.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "Tag „{0}” nie może być użyty niezależnie jako tag JSDoc najwyższego poziomu.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "Dla elementu „{0}” bez adnotacji zwracanego typu niejawnie określono zwracany typ „{1}”.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Modyfikator „abstract” może być stosowany jedynie w przypadku deklaracji klasy, metody lub właściwości.", + "await_expression_is_only_allowed_within_an_async_function_1308": "Wyrażenie „await” jest dozwolone tylko w funkcji asynchronicznej.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Wyrażeń „await” nie można używać w inicjatorze parametru.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Opcja „baseUrl” ma ustawioną wartość „{0}”. Ta wartość zostanie użyta do rozpoznania innej niż względna nazwy modułu „{1}”.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "Znaku „=” można użyć tylko we właściwości literału obiektu wewnątrz przypisania usuwającego strukturę.", + "case_or_default_expected_1130": "Oczekiwano elementu „case” lub „default”.", + "class_expressions_are_not_currently_supported_9003": "Wyrażenia „class” nie są obecnie obsługiwane.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Deklaracje „const” mogą być deklarowane tylko w bloku.", + "const_declarations_must_be_initialized_1155": "Konieczne jest zainicjowanie deklaracji „const”.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest wartość nieskończona.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest niedozwolona wartość „NaN”.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Wyliczenia ze specyfikatorem „const” mogą być używane tylko w wyrażeniach dostępu do indeksu lub właściwości albo po prawej stronie deklaracji importu lub przypisania eksportu.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Nie można wywołać elementu „delete” dla identyfikatora w trybie z ograniczeniami.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklaracji wyliczeń można używać tylko w pliku ts.", + "export_can_only_be_used_in_a_ts_file_8003": "Ciągu „export=” można użyć tylko w pliku ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modyfikator „export” nie może być stosowany do modułów otoczenia ani rozszerzeń modułów, ponieważ są one zawsze widoczne.", + "extends_clause_already_seen_1172": "Napotkano już klauzulę „extends”.", + "extends_clause_must_precede_implements_clause_1173": "Klauzula „extends” musi poprzedzać klauzulę „implements”.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Klauzula „extends” wyeksportowanej klasy „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Klauzula „extends” wyeksportowanego interfejsu „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", + "file_6025": "plik", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Metody dostępu „get” i „set” muszą mieć ten sam typ „this”.", + "get_and_set_accessor_must_have_the_same_type_2380": "Metody dostępu „get” i „set” muszą być tego samego typu.", + "implements_clause_already_seen_1175": "Napotkano już klauzulę „implements”.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Klauzul implements można używać tylko w pliku ts.", + "import_can_only_be_used_in_a_ts_file_8002": "Ciągu „export ... =” można użyć tylko w pliku ts.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Deklaracji interfejsów można używać tylko w pliku ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Deklaracje „let” mogą być deklarowane tylko w bloku.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Element „let” nie może być używany jako nazwa w deklaracjach „let” ani „const”.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Deklaracji modułów można używać tylko w pliku ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Nie można użyć instrukcji „new T[]” do utworzenia tablicy. Zamiast tego użyj instrukcji „new Array()”.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Wyrażenie „new”, którego element docelowy nie ma sygnatury konstrukcji, jest niejawnie typu „any”.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Asercje o wartości innej niż null mogą być używane tylko w pliku ts.", + "options_6024": "opcje", + "or_expected_1144": "Oczekiwano znaku „{” lub „;”.", + "package_json_does_not_have_a_0_field_6100": "Plik „package.json” nie zawiera pola „{0}”.", + "package_json_has_0_field_1_that_references_2_6101": "Plik „package.json” zawiera pole „{0}” „{1}” odwołujące się do elementu „{2}”.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modyfikatorów parametrów można używać tylko w pliku ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Opcja „paths” została określona. Wyszukiwanie wzorca zgodnego z nazwą modułu „{0}”.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modyfikator „readonly” może występować jedynie w deklaracji właściwości lub sygnaturze indeksu.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Opcja „rootDirs” została ustawiona. Zostanie ona użyta do rozpoznania względnej nazwy modułu „{0}”.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Element „super” może być przywoływany tylko w klasie pochodnej.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Element „super” może być przywoływany jedynie w składowych klas pochodnych lub wyrażeń literałów obiektów.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Nie można przywołać elementu „super” w obliczonej nazwie właściwości.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Nie można przywoływać elementu „super” w argumentach konstruktora.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Element „super” jest dozwolony w składowych wyrażeń literałów obiektów tylko wtedy, gdy opcja „target” ma wartość „ES2015” lub wyższą.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Element „super” należy wywołać przed uzyskaniem dostępu do właściwości elementu „super” w konstruktorze klasy pochodnej.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Element „super” musi być wywoływany przed uzyskaniem dostępu do elementu „this” w konstruktorze klasy pochodnej.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Po elemencie „super” musi występować lista argumentów lub metoda dostępu do składowej.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Dostęp do właściwości „super” jest dozwolony tylko w konstruktorze, funkcji składowej lub metodzie dostępu składowej klasy pochodnej.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Nie można przywołać elementu „this” w obliczonej nazwie właściwości.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Nie można przywołać elementu „this” w treści modułu ani przestrzeni nazw.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Nie można przywołać elementu „this” w inicjatorze właściwości statycznej.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "Nie można przywołać elementu „this” w argumentach konstruktora.", + "this_cannot_be_referenced_in_current_location_2332": "Nie można przywołać elementu „this” w bieżącej lokalizacji.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "Element „this” niejawnie przyjmuje typ „any”, ponieważ nie ma adnotacji typu.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Aliasów typów można używać tylko w pliku ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Argumentów typu można używać tylko w pliku ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Wyrażeń asercji typów można używać tylko w pliku ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Deklaracji parametru typu można używać tylko w pliku ts.", + "types_can_only_be_used_in_a_ts_file_8010": "Typów można używać tylko w pliku ts.", + "unique_symbol_types_are_not_allowed_here_1335": "Typy „unikatowy symbol” nie są dozwolone w tym miejscu.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy „unikatowy symbol” są dozwolone tylko w zmiennych w instrukcji zmiennej.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typów „unikatowy symbol” nie można używać w deklaracji zmiennej z nazwą powiązania.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Instrukcje „with” są niedozwolone w bloku funkcji asynchronicznej.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Instrukcje „with” są niedozwolone w trybie z ograniczeniami.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Wyrażeń „yield” nie można używać w inicjatorze parametru." +} \ No newline at end of file diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 7b4bdfe4718c6..2bf4ae59f070d 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -5,6 +5,7 @@ declare namespace ts.server.protocol { const enum CommandTypes { Brace = "brace", BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", Change = "change", Close = "close", Completions = "completions", @@ -13,6 +14,7 @@ declare namespace ts.server.protocol { CompileOnSaveEmitFile = "compileOnSaveEmitFile", Configure = "configure", Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", Implementation = "implementation", Exit = "exit", Format = "format", @@ -46,6 +48,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", @@ -67,6 +70,7 @@ declare namespace ts.server.protocol { * Client-initiated request message */ interface Request extends Message { + type: "request"; /** * The command to execute */ @@ -86,6 +90,7 @@ declare namespace ts.server.protocol { * Server-initiated event message */ interface Event extends Message { + type: "event"; /** * Name of event */ @@ -99,6 +104,7 @@ declare namespace ts.server.protocol { * Response by server to client request message. */ interface Response extends Message { + type: "response"; /** * Sequence number of the request message. */ @@ -112,7 +118,8 @@ declare namespace ts.server.protocol { */ command: string; /** - * Contains error message if success === false. + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. */ message?: string; /** @@ -164,6 +171,19 @@ declare namespace ts.server.protocol { interface TodoCommentsResponse extends Response { body?: TodoComment[]; } + /** + * A request to determine if the caret is inside a comment. + */ + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ + onlyMultiLine: boolean; + } /** * A request to get indentation for a location in file */ @@ -332,7 +352,7 @@ declare namespace ts.server.protocol { * Represents a single refactoring action - for example, the "Extract Method..." refactor might * offer several actions, each corresponding to a surround class or closure to extract into. */ - type RefactorActionInfo = { + interface RefactorActionInfo { /** * The programmatic name of the refactoring action */ @@ -343,7 +363,7 @@ declare namespace ts.server.protocol { * so this description should make sense by itself if the parent is inlineable=true */ description: string; - }; + } interface GetEditsForRefactorRequest extends Request { command: CommandTypes.GetEditsForRefactor; arguments: GetEditsForRefactorRequestArgs; @@ -359,7 +379,7 @@ declare namespace ts.server.protocol { interface GetEditsForRefactorResponse extends Response { body?: RefactorEditInfo; } - type RefactorEditInfo = { + interface RefactorEditInfo { edits: FileCodeEdits[]; /** * An optional location where the editor should start a rename operation once @@ -367,7 +387,7 @@ declare namespace ts.server.protocol { */ renameLocation?: Location; renameFilename?: string; - }; + } /** * Request for the available codefixes at a specific position. */ @@ -375,6 +395,12 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). @@ -402,6 +428,10 @@ declare namespace ts.server.protocol { */ errorCodes?: number[]; } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } /** * Response for GetCodeFixes request. */ @@ -505,12 +535,19 @@ declare namespace ts.server.protocol { */ file: string; } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } /** * Definition response message. Gives text range for definition. */ interface DefinitionResponse extends Response { body?: FileSpan[]; } + interface DefinitionInfoAndBoundSpanReponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } /** * Definition response message. Gives text range for definition. */ @@ -714,7 +751,7 @@ declare namespace ts.server.protocol { /** * An array of span groups (one per file) that refer to the item to be renamed. */ - locs: SpanGroup[]; + locs: ReadonlyArray; } /** * Rename response message. @@ -953,6 +990,12 @@ declare namespace ts.server.protocol { * Compiler options to be used with inferred projects. */ options: ExternalProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ + projectRootPath?: string; } /** * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so @@ -1134,6 +1177,8 @@ declare namespace ts.server.protocol { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; } /** * Format and format on key response message. @@ -1171,6 +1216,11 @@ declare namespace ts.server.protocol { * Optional prefix to apply to possible completions. */ prefix?: string; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + includeExternalModuleExports: boolean; } /** * Completions request; value of command field is "completions". @@ -1189,7 +1239,11 @@ declare namespace ts.server.protocol { /** * Names of one or more entries for which to obtain details. */ - entryNames: string[]; + entryNames: (string | CompletionEntryIdentifier)[]; + } + interface CompletionEntryIdentifier { + name: string; + source: string; } /** * Completion entry details request; value of command field is @@ -1236,10 +1290,26 @@ declare namespace ts.server.protocol { */ sortText: string; /** - * An optional span that indicates the text to be replaced by this completion item. If present, - * this span should be used instead of the default one. + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; } /** * Additional completion entry details, available on demand @@ -1269,6 +1339,14 @@ declare namespace ts.server.protocol { * JSDoc tags for the symbol. */ tags: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + source?: SymbolDisplayPart[]; } interface CompletionsResponse extends Response { body?: CompletionEntry[]; @@ -1563,6 +1641,17 @@ declare namespace ts.server.protocol { */ languageServiceEnabled: boolean; } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } /** * Arguments for reload request. */ @@ -1922,6 +2011,7 @@ declare namespace ts.server.protocol { paths?: MapLike; plugins?: PluginImport[]; preserveConstEnums?: boolean; + preserveSymlinks?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; @@ -1956,6 +2046,7 @@ declare namespace ts.server.protocol { System = "System", ES6 = "ES6", ES2015 = "ES2015", + ESNext = "ESNext", } const enum ModuleResolutionKind { Classic = "Classic", @@ -1970,6 +2061,9 @@ declare namespace ts.server.protocol { ES5 = "ES5", ES6 = "ES6", ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ESNext = "ESNext", } } declare namespace ts.server.protocol { @@ -1991,6 +2085,81 @@ declare namespace ts.server.protocol { position: number; } + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference", + } + + enum ScriptElementKind { + unknown = "", + warning = "warning", + /** predefined type (void) or keyword (class) */ + keyword = "keyword", + /** top level script node */ + scriptElement = "script", + /** module foo {} */ + moduleElement = "module", + /** class X {} */ + classElement = "class", + /** var x = class X {} */ + localClassElement = "local class", + /** interface Y {} */ + interfaceElement = "interface", + /** type T = ... */ + typeElement = "type", + /** enum E */ + enumElement = "enum", + enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ + variableElement = "var", + /** Inside function */ + localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ + functionElement = "function", + /** Inside function */ + localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ + memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ + memberVariableElement = "property", + /** class X { constructor() { } } */ + constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ + callSignatureElement = "call", + /** interface Y { []:number; } */ + indexSignatureElement = "index", + /** interface Y { new():Y; } */ + constructSignatureElement = "construct", + /** function foo(*Y*: string) */ + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + /** + * + */ + jsxAttribute = "JSX attribute", + } + interface TypeAcquisition { enableAutoDiscovery?: boolean; enable?: boolean; @@ -2002,6 +2171,7 @@ declare namespace ts.server.protocol { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface JSDocTagInfo { @@ -2022,12 +2192,10 @@ declare namespace ts.server.protocol { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[]; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; } declare namespace ts { // these types are empty stubs for types from services and should not be used directly - export type HighlightSpanKind = never; - export type ScriptElementKind = never; export type ScriptKind = never; export type IndentStyle = never; export type JsxEmit = never; diff --git a/lib/pt-BR/diagnosticMessages.generated.json b/lib/pt-BR/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..37f410337acbf --- /dev/null +++ b/lib/pt-BR/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Um modificador '{0}' não pode ser usado com uma declaração de importação.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Um modificador '{0}' não pode ser usado com uma declaração de interface.", + "A_0_parameter_must_be_the_first_parameter_2680": "Um parâmetro '{0}' deve ser o primeiro parâmetro.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Um parâmetro de padrão de associação não pode ser opcional em uma assinatura de implementação.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Uma instrução 'break' só pode ser usada em uma iteração de circunscrição ou instrução switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Uma instrução 'break' só pode saltar para um rótulo de uma instrução de circunscrição.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Uma classe pode implementar apenas um identificador/nome qualificado com argumentos de tipo opcionais.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Uma declaração de classe sem o modificador 'default' deve ter um nome.", + "A_class_may_only_extend_another_class_2311": "Uma classe somente pode estender-se para outra classe.", + "A_class_may_only_implement_another_class_or_interface_2422": "Uma classe somente pode implementar outra classe ou interface.", + "A_class_member_cannot_have_the_0_keyword_1248": "Um membro de classe não pode ter a palavra-chave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Uma expressão de vírgula não é permitida em um nome de propriedade calculado.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Um nome de propriedade calculado não pode fazer referência a um parâmetro de tipo no seu tipo recipiente.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Um nome de propriedade computado em uma declaração de propriedade de classe deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Um nome de propriedade computado em uma sobrecarga do método deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Um nome de propriedade computado em um tipo literal deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Um nome de propriedade computado em um contexto de ambiente deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Um nome de propriedade computado em uma interface deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Um nome de propriedade calculado deve ser do tipo 'string', 'number', 'symbol' ou 'any'.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Um nome de propriedade calculado do formulário '{0}' deve ser do tipo 'symbol'.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Um membro const enum só pode ser acessado usando um literal de cadeia de caracteres.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Um inicializador \"const\" em um contexto de ambiente deve ser uma cadeia ou um literal numérico.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Um construtor não pode conter uma chamada 'super' quando sua classe estende 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Um construtor não pode ter um parâmetro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Uma instrução 'continue' só pode ser usada em uma instrução de iteração de circunscrição.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Uma instrução 'continue' só pode saltar para um rótulo de uma instrução de iteração de circunscrição.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Um modificador 'declare' não pode ser usado em um contexto de ambiente.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Um modificador 'declare' é necessário para uma declaração de nível superior em um arquivo .d.ts.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Um decorador pode decoras somente uma implementação de método, não uma sobrecarga.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Uma cláusula 'default' não pode aparecer mais de uma vez em uma instrução 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Uma exportação padrão só pode ser usada em um módulo do estilo ECMAScript.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Uma declaração de atribuição definitiva '!' não é permitida neste contexto.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Uma declaração de desestruturação deve ter um inicializador.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Uma chamada de importação dinâmica em ES5/ES3 exige o construtor 'Promise'. Verifique se você tem uma declaração para o construtor 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Uma chamada de importação dinâmica retorna um 'Promise'. Verifique se você tem uma declaração para 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", + "A_file_cannot_have_a_reference_to_itself_1006": "Um arquivo não pode fazer referência a si mesmo.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Uma instrução 'for-await-of' é permitida somente na função assíncrona ou no gerador assíncrono.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Uma função que retorna 'never' não pode ter um ponto de extremidade acessível.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Uma função chamada com a palavra-chave 'new' não pode ter um tipo 'this' que seja 'void'.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "A função cujo tipo declarado não é 'void' nem 'any' deve retornar um valor.", + "A_generator_cannot_have_a_void_type_annotation_2505": "O gerador não pode ter uma anotação de tipo 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Um acessador 'get' não pode ter parâmetros.", + "A_get_accessor_must_return_a_value_2378": "Um acessador 'get' deve retornar um valor.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "O inicializador de um membro em uma declaração enum não pode referenciar membros declarados depois dele, inclusive membros definidos em outros enums.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Uma classe mixin deve ter um construtor um único parâmetro rest do tipo 'any[]'.", + "A_module_cannot_have_multiple_default_exports_2528": "Um módulo não pode ter várias exportações padrão.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Uma declaração de namespace não pode estar em um arquivo diferente de uma classe ou função com a qual ela é mesclada.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Uma declaração de namespace não pode estar localizada antes de uma classe ou função com a qual ela é mesclada.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Uma declaração de namespace só é permitida e um namespace ou módulo.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Um inicializador de parâmetro só é permitido em uma implementação de função ou de construtor.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Uma propriedade de parâmetro não pode ser declarada usando um parâmetro rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Uma propriedade de parâmetro somente é permitida em uma implementação de construtor.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Uma propriedade de parâmetro pode não ser declarada usando um padrão de associação.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Um caminho em uma opção 'extends' deve ser relativo ou ter raiz, mas o '{0}' não é.", + "A_promise_must_have_a_then_method_1059": "Uma promessa deve ter um método 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Uma propriedade de uma classe cujo tipo é um tipo de 'símbolo exclusivo' deve ser 'estática' e 'somente leitura'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'símbolo exclusivo' deve ser 'somente leitura'.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", + "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Um elemento rest deve ser o último em um padrão de desestruturação.", + "A_rest_parameter_cannot_be_optional_1047": "Um parâmetro rest não pode ser opcional.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Um parâmetro rest não pode ter um inicializador.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Um parâmetro rest deve ser o último em uma lista de parâmetros.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Um parâmetro rest deve ser de um tipo de matriz.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Uma instrução 'return' só pode ser usada dentro de um corpo de função.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Uma série de entradas que o remapeamento importa para pesquisar locais relativos a 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Um acessador 'set' não pode ter uma anotação de tipo de retorno.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Um acessador 'set' não pode ter um parâmetro opcional.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Um acessador 'set' não pode ter um parâmetro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Um acessador 'set' deve ter exatamente um parâmetro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Um parâmetro de acessador 'set' não pode ter um inicializador.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Uma assinatura com uma implementação não pode usar um tipo de cadeia de caracteres literal.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Uma chamada 'super' deve ser a primeira instrução no construtor quando uma classe contiver propriedades inicializadas ou propriedades de parâmetro.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Uma proteção de tipo baseado em 'this não é compatível com uma proteção de tipo baseado em parâmetro.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Um tipo 'this' está disponível somente em um membro não estático de uma classe ou interface.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Um arquivo 'tsconfig.json' já está definido em: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Uma lista de elementos do tipo tupla não pode estar vazia.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Uma expressão de asserção de tipo não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Uma propriedade literal de tipo não pode ter um inicializador.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "O predicado de tipo não pode fazer referência a um parâmetro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "O predicado de tipo não pode fazer referência ao elemento '{0}' em um padrão de associação.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "O predicado de tipo só é permitido na posição de tipo de retorno para funções e métodos.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "O tipo de um predicado de tipo deve ser atribuível para o tipo de seu parâmetro.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Uma variável cujo tipo é um tipo de 'símbolo exclusivo' deve ser 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "A expressão 'yield' só é permitida em um corpo gerador.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "O método abstrato '{0}' na classe '{1}' não pode ser acessado por meio da expressão super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Os métodos abstratos só podem aparecer dentro de uma classe abstrata.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "A propriedade abstrata '{0}' na classe '{1}' não pode ser acessada no construtor.", + "Accessibility_modifier_already_seen_1028": "O modificador de acessibilidade já foi visto.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Os acessadores somente estão disponíveis no direcionamento para ECMAScript 5 e superior.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.", + "Add_0_to_existing_import_declaration_from_1_90015": "Adicione \"{0}\" à declaração de importação existente de \"{1}\".", + "Add_index_signature_for_property_0_90017": "Adicione assinatura de índice para a propriedade '{0}'.", + "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente.", + "Add_this_to_unresolved_variable_90008": "Adicione 'this.' a uma variável não resolvida.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Adicionar um arquivo tsconfig.json ajuda a organizar projetos que contêm arquivos TypeScript e JavaScript. Saiba mais em https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Verificações Adicionais", + "Advanced_Options_6178": "Opções Avançadas", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas as declarações de '{0}' devem ter modificadores idênticos.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas as declarações de '{0}' devem ter parâmetros de tipo idênticos.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas as declarações de um método abstrato devem ser consecutivas.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.", + "Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "As enumerações de constante de ambiente não são permitidas quando o sinalizador '--isolatedModules' é fornecido.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "A declaração de módulo de ambiente não pode especificar o nome do módulo relativo.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Módulos de ambiente não podem ser aninhados em outros módulos ou namespaces.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Um módulo AMD não pode ter várias atribuições de nome.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Um acessador abstrato não pode ter uma implementação.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Um acessador não pode ser declarado em um contexto de ambiente.", + "An_accessor_cannot_have_type_parameters_1094": "Um acessador não pode ter parâmetros de tipo.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Uma declaração de módulo de ambiente só é permitida no nível superior em um arquivo.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Um operando aritmético deve ser do tipo 'any', 'number' ou um tipo enum.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Uma função ou método assíncrono em ES5/ES3 requer o construtor 'Promise'. Verifique se você tem a declaração para o construtor 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Um método ou função assíncrona deve ter um tipo de retorno válido que é possível aguardar.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Um método ou função assíncrona deve retornar uma 'Promessa'. Certifique-se de ter uma declaração para 'Promessa' ou inclua 'ES2015' na sua opção `--lib`.", + "An_async_iterator_must_have_a_next_method_2519": "O iterador assíncrono deve ter um método 'next()'.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Um membro enum não pode ter um nome numérico.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Uma atribuição de exportação só pode ser usada em um módulo.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Uma atribuição de exportação não pode ser usada em um módulo com outros elementos exportados.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Uma atribuição de exportação não pode ser usada em um namespace.", + "An_export_assignment_cannot_have_modifiers_1120": "Uma atribuição de exportação não pode ter modificadores.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Uma declaração de exportação só pode ser usada em um módulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Uma declaração de exportação não pode ter modificadores.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Um valor de escape Unicode estendido deve estar entre 0x0 e 0x10FFFF, inclusive.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Uma implementação não pode ser declarada em contextos de ambiente.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Uma declaração de importação só pode ser usada em um namespace ou módulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Uma declaração de importação não pode ter modificadores.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Um caminho de importação não pode terminar com uma extensão '{0}'. Considere importar '{1}'.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Um argumento de expressão de índice deve ser do tipo 'string', 'number', 'symbol' ou 'any'.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Uma assinatura de índice não pode ter um parâmetro rest.", + "An_index_signature_must_have_a_type_annotation_1021": "Uma assinatura de índice deve ter uma anotação de tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Uma assinatura de índice deve ter exatamente um parâmetro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Um parâmetro de assinatura de índice não pode ter um ponto de interrogação.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Um parâmetro de assinatura de índice não pode ter um modificador de acessibilidade.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Um parâmetro de assinatura de índice não pode ter um inicializador.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Um parâmetro de assinatura de índice deve ter uma anotação de tipo.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Um tipo de parâmetro de assinatura de índice deve ser 'string' ou 'number'.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Uma interface só pode estender um identificador/nome qualificado com argumentos de tipo opcionais.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Uma interface só pode estender uma classe ou outra interface.", + "An_interface_property_cannot_have_an_initializer_1246": "Uma propriedade de interface não pode ter um inicializador.", + "An_iterator_must_have_a_next_method_2489": "Um iterador deve ter um método 'next()'.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Um literal de objeto não pode ter vários acessadores get/set com o mesmo nome.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Um literal de objeto não pode ter várias propriedades com o mesmo nome no modo estrito.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Um literal de objeto não pode ter propriedade e acessador com o mesmo nome.", + "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", + "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", + "Argument_expression_expected_1135": "Expressão de argumento esperada.", + "Argument_for_0_option_must_be_Colon_1_6046": "O argumento para a opção '{0}' deve ser: {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "O argumento do tipo '{0}' não é atribuível ao parâmetro do tipo '{1}'.", + "Array_element_destructuring_pattern_expected_1181": "Padrão de desestruturação de elemento da matriz esperado.", + "Asterisk_Slash_expected_1010": "'*/' esperado.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Acréscimos de escopo global somente podem ser diretamente aninhados em módulos externos ou declarações de módulo de ambiente.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Acréscimos de escopo global devem ter o modificador 'declare' a menos que apareçam em contexto já ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "A descoberta automática para digitações está habilitada no projeto '{0}'. Executando o passe de resolução extra para o módulo '{1}' usando o local do cache '{2}'.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "As expressões de classe base não podem referenciar parâmetros de tipo de classe.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "O tipo de retorno do construtor base '{0}' não é um tipo de interface ou classe.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Todos os construtores base devem ter o mesmo tipo de retorno.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Diretório base para resolver nomes de módulo não absolutos.", + "Basic_Options_6172": "Opções Básicas", + "Binary_digit_expected_1177": "Dígito binário esperado.", + "Binding_element_0_implicitly_has_an_1_type_7031": "O elemento de associação '{0}' tem implicitamente um tipo '{1}'.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variável de escopo de bloco '{0}' usada antes da sua declaração.", + "Call_decorator_expression_90028": "Chamar expressão decoradora.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Assinatura de chamada, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno 'any'.", + "Call_target_does_not_contain_any_signatures_2346": "O destino da chamada não contém nenhuma assinatura.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Não foi possível acessar '{0}.{1}' porque '{0}' é um tipo, mas não um namespace. Você quis dizer recuperar o tipo da propriedade '{1}' em '{0}' com '{0}[\"{1}\"]'?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Não é possível atribuir um tipo de construtor '{0}' para um tipo de construtor '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Não é possível atribuir um tipo de construtor abstrato a um tipo de construtor não abstrato.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Não é possível atribuir a '{0}' porque é uma constante ou uma propriedade de somente leitura.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Não é possível atribuir a '{0}' porque não é uma variável.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Não é possível aumentar o módulo '{0}' porque ele resolve para uma entidade não módulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Não é possível aumentar o módulo '{0}' com as exportações do valor, porque ele resolve para uma entidade sem módulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Não é possível compilar módulos usando a opção '{0}', a menos que o sinalizador '--module' seja 'amd' ou 'system'.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Não é possível compilar namespaces quando o sinalizador '--isolatedModules' é fornecido.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Não é possível criar uma instância de uma classe abstrata.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Não é possível exportar '{0}'. Somente declarações locais podem ser exportadas de um módulo.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Não é possível estender uma classe '{0}'. O construtor de classe está marcado como privado.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Não é possível estender uma interface '{0}'. Você quis dizer 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Não é possível encontrar um arquivo tsconfig.json no diretório especificado: '{0}'.", + "Cannot_find_global_type_0_2318": "Não é possível encontrar o tipo global '{0}'.", + "Cannot_find_global_value_0_2468": "Não é possível encontrar o valor global '{0}'.", + "Cannot_find_module_0_2307": "Não é possível encontrar o módulo '{0}'.", + "Cannot_find_name_0_2304": "Não é possível encontrar o nome '{0}'.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Não é possível localizar o nome '{0}'. Você quis dizer '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Não foi possível localizar o nome '{0}'. Você quis dizer o membro de instância 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Não foi possível encontrar o nome '{0}'. Você quis dizer o membro estático '{1}.{0}'?", + "Cannot_find_namespace_0_2503": "Não é possível encontrar o namespace '{0}'.", + "Cannot_find_parameter_0_1225": "Não é possível encontrar o parâmetro '{0}'.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Não é possível encontrar o caminho do subdiretório comum para os arquivos de entrada.", + "Cannot_find_type_definition_file_for_0_2688": "Não é possível encontrar o arquivo de definição de tipo para '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Não é possível importar arquivos de declaração de tipo. Considere a possibilidade de importar '{0}' em vez de '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Não é possível inicializar a variável com escopo externo '{0}' no mesmo escopo que a declaração de escopo de bloco '{1}'.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Não é possível invocar uma expressão cujo tipo não tem uma assinatura de chamada. O tipo '{0}' não tem assinaturas de chamada compatíveis.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Não será possível reexportar um tipo quando o sinalizador '--isolatedModules' for fornecido.", + "Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Não é possível redeclarar a variável exportada '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Não é possível declarar novamente o identificador '{0}' na cláusula catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Não é possível usar JSX, a menos que o sinalizador '--jsx' seja fornecido.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Não será possível usar importações, exportações ou acréscimos de módulo quando '--module' for 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Não é possível usar o namespace '{0}' como um tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "Não é possível usar o namespace '{0}' como um valor.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Não é possível usar 'new' com uma expressão cujo tipo não tem uma chamada ou assinatura de constructo.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Não é possível gravar o arquivo '{0}' porque ele seria substituído por diversos arquivos de entrada.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Não é possível gravar o arquivo '{0}' porque ele substituiria o arquivo de entrada.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "A variável de cláusula catch não pode ter uma anotação de tipo.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "A variável de cláusula catch não pode ter um inicializador.", + "Change_0_to_1_90014": "Alterar '{0}' para '{1}'.", + "Change_extends_to_implements_90003": "Altere 'extends' para 'implements'.", + "Change_spelling_to_0_90022": "Alterar ortografia para '{0}'.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verificando se '{0}' é o maior prefixo correspondente para '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definição circular do alias de importação '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularidade detectada ao resolver a configuração: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "A classe '{0}' define o acessador de membro de instância '{1}', mas a classe estendida '{2}' o define como uma função de membro de instância.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "A classe '{0}' define a função de membro de instância '{1}', mas a classe estendida '{2}' a define como um acessador de membro de instância.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "A classe '{0}' define a função de membro de instância '{1}', mas a classe estendida '{2}' a define como uma propriedade de membro de instância.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "A classe '{0}' define a propriedade de membro de instância '{1}', mas a classe estendida '{2}' a define como uma função de membro de instância.", + "Class_0_incorrectly_extends_base_class_1_2415": "A classe '{0}' estende incorretamente a classe base '{1}'.", + "Class_0_incorrectly_implements_interface_1_2420": "A classe '{0}' implementa incorretamente a interface '{1}'.", + "Class_0_used_before_its_declaration_2449": "Classe '{0}' usada antes de sua declaração.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Declarações de classe não podem ter mais de uma marca `@augments` ou `@extends`.", + "Class_name_cannot_be_0_2414": "O nome de classe não pode ser '{0}'.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "O lado estático da classe '{0}' incorretamente estende o lado estático da classe base '{1}'.", + "Classes_can_only_extend_a_single_class_1174": "Classes só podem estender uma única classe.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "As classes que contêm métodos abstratos devem ser marcadas como abstratas.", + "Command_line_Options_6171": "Opções da Linha de Comando", + "Compilation_complete_Watching_for_file_changes_6042": "Compilação concluída. Monitorando alterações de arquivo.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compile o projeto dando o caminho para seu arquivo de configuração ou para uma pasta com um 'tsconfig.json'.", + "Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em um enum com membros de valor de cadeia de caracteres.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatenar e emitir saída para um arquivo único.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Foram encontradas definições em conflito para '{0}' em '{1}' e em '{2}'. Considere instalar uma versão específica desta biblioteca para solucionar o conflito.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Assinatura de constructo, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno 'any'.", + "Constructor_implementation_is_missing_2390": "Implementação do construtor ausente.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "O construtor de classe '{0}' é privado e somente acessível na declaração de classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "O construtor de classe '{0}' é protegido e somente acessível na declaração de classe.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Construtores para classes derivadas devem conter uma chamada 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "O arquivo contido não foi especificado e o diretório raiz não pode ser determinado, ignorando a pesquisa na pasta 'node_modules'.", + "Convert_function_0_to_class_95002": "Converter função '{0}' em classe", + "Convert_function_to_an_ES2015_class_95001": "Converter função em uma classe ES2015", + "Convert_to_default_import_95013": "Converter para importação padrão", + "Corrupted_locale_file_0_6051": "Arquivo de localidade {0} corrompido.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Não foi possível localizar o arquivo de declaração para o módulo '{0}'. '{1}' tem implicitamente um tipo 'any'.", + "Could_not_write_file_0_Colon_1_5033": "Não foi possível gravar o arquivo '{0}': {1}.", + "DIRECTORY_6038": "DIRETÓRIO", + "Declaration_expected_1146": "Declaração esperada.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "O nome de declaração entra em conflito com o identificador global integrado '{0}'.", + "Declaration_or_statement_expected_1128": "Declaração ou instrução esperada.", + "Declare_method_0_90023": "Declare o método '{0}'.", + "Declare_property_0_90016": "Declare a propriedade '{0}'.", + "Declare_static_method_0_90024": "Declare o método estático '{0}'.", + "Declare_static_property_0_90027": "Declare a propriedade estática \"{0}\".", + "Decorators_are_not_valid_here_1206": "Os decoradores não são válidos aqui.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Os decoradores não podem ser aplicados a vários acessadores get/set de mesmo nome.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "A exportação padrão do módulo tem ou está usando o nome particular '{0}'.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Preterido] Use '--jsxFactory' no lugar. Especifique o objeto invocado para createElement ao direcionar uma emissão de JSX 'react'", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Preterido] Use '--outFile' no lugar. Concatene e emita uma saída para um arquivo único", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Preterido] Use '--skipLibCheck' no lugar. Ignore a verificação de tipo dos arquivos de declaração de biblioteca padrão.", + "Digit_expected_1124": "Dígito esperado.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "O diretório '{0}' não existe; ignorando todas as pesquisas nele.", + "Disable_checking_for_this_file_90018": "Desabilitar a verificação para esse arquivo.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Desabilitar as limitações de tamanho nos projetos JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Desabilitar verificação estrita de assinaturas genéricas em tipos de função.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Não permitir referências com maiúsculas de minúsculas inconsistentes no mesmo arquivo.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Não adicionar as referências de barra tripla nem os módulos importados à lista de arquivos compilados.", + "Do_not_emit_comments_to_output_6009": "Não emita comentários para a saída.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Não emita declarações de código que contenham uma anotação '@internal'.", + "Do_not_emit_outputs_6010": "Não emita saídas.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Não emita saídas se erros forem reportados.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Não emita diretivas 'use strict' na saída de módulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Não apague declarações const enum no código gerado.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Não gerar funções auxiliares personalizadas como '__extends' nas saídas compiladas.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Não incluir o arquivo de biblioteca padrão (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Não relate erros sobre código inacessível.", + "Do_not_report_errors_on_unused_labels_6074": "Não relate erros sobre rótulos não utilizados.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Não resolver o real caminho de symlinks.", + "Do_not_truncate_error_messages_6165": "Não truncar as mensagens de erro.", + "Duplicate_declaration_0_2718": "Declaração duplicada '{0}'.", + "Duplicate_function_implementation_2393": "Implementação de função duplicada.", + "Duplicate_identifier_0_2300": "Identificador '{0}' duplicado.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificador duplicado '{0}'. O compilador reserva o nome '{1}' no escopo de nível superior de um módulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Duplicar o identificador '{0}'. O compilador reserva o nome '{1}' em escopo de alto nível de um módulo que contém funções assíncronas.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificador '{0}' duplicado. O compilador usa a declaração '{1}' para dar suporte a funções assíncronas.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificador 'arguments' duplicado. O compilador usa 'arguments' para inicializar os parâmetros rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificador duplicado '_newTarget'. O compilador usa a declaração de variável '_newTarget' para capturar a referência de metapropriedade 'new.target'.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Identificador '_super' duplicado. O compilador usa '_super' para capturar a referência da classe base.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificador '_this' duplicado. O compilador usa a declaração de variável '_this' para capturar a referência 'this'.", + "Duplicate_label_0_1114": "Rótulo '{0}' duplicado.", + "Duplicate_number_index_signature_2375": "Assinatura de índice de número duplicado.", + "Duplicate_string_index_signature_2374": "Assinatura de índice de cadeia de caracteres duplicada.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "A importação dinâmica não pode ser usada ao destinar módulos de ECMAScript 2015.", + "Dynamic_import_cannot_have_type_arguments_1326": "A importação dinâmica não pode ter argumentos de tipo", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "A importação dinâmica deve ter um especificador como um argumento.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "O especificador da importação dinâmica deve ser do tipo 'string', mas aqui tem o tipo '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "O elemento implicitamente tem um tipo 'any' porque a expressão de índice não é do tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "O elemento tem, implicitamente, 'qualquer' tipo, pois o tipo '{0}' não tem assinatura de índice.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Emitir uma Marca de Ordem de Byte (BOM) UTF-8 no início dos arquivos de saída.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir um arquivo único com os mapas de origem em vez de arquivos separados.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir a origem ao lado dos sourcemaps em um arquivo único; a definição requer '--inlineSourceMap' ou '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Habilitar todas as opções estritas de verificação de tipo.", + "Enable_strict_checking_of_function_types_6186": "Habilitar verificação estrita de tipos de função.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite a verificação estrita de inicialização de propriedade nas classes.", + "Enable_strict_null_checks_6113": "Habilite verificações nulas estritas.", + "Enable_tracing_of_the_name_resolution_process_6085": "Habilite o rastreio do processo de resolução de nome.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita o suporte experimental para funções assíncronas de ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", + "Enum_0_used_before_its_declaration_2450": "Enum '{0}' usada antes de sua declaração.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações enum devem ser const ou não const.", + "Enum_member_expected_1132": "Membro enum esperado.", + "Enum_member_must_have_initializer_1061": "O membro enum deve ter um inicializador.", + "Enum_name_cannot_be_0_2431": "O nome de enum não pode ser '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "O tipo Enum '{0}' tem membros com inicializadores que não são literais.", + "Examples_Colon_0_6026": "Exemplos: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidade da pilha excessiva ao comparar tipos '{0}' e '{1}'.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Espera-se {0}-{1} argumentos de tipo; forneça esses recursos com uma marca \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "{0} argumentos eram esperados, mas {1} foram obtidos.", + "Expected_0_arguments_but_got_1_or_more_2556": "Eram {0} argumentos esperados, mas {1} ou mais foram obtidos.", + "Expected_0_type_arguments_but_got_1_2558": "{0} argumentos de tipo eram esperados, mas {1} foram obtidos.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Espera-se {0} argumentos de tipo; forneça esses recursos com uma marca \"@extends\".", + "Expected_at_least_0_arguments_but_got_1_2555": "Pelo menos {0} argumentos eram esperados, mas {1} foram obtidos.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Pelo menos {0} argumentos eram esperados, mas {1} ou mais foram obtidos.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Marca de fechamento de JSX correspondente esperada para '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Marca de fechamento correspondente esperada para fragmento JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "O tipo esperado do campo '{0}' em 'package.json' como 'string', obteve '{1}'.", + "Experimental_Options_6177": "Opções Experimentais", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "O suporte experimental de decorador é um recurso que está sujeito a alterações em uma liberação futura. Configure a opção 'experimentalDecorators' para remover este aviso.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolução de módulo especificado explicitamente: '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Não é possível usar a atribuição de exportação durante o direcionamento para módulos de ECMAScript. Use a 'exportação padrão' ou outro formato de módulo em vez disso.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "A atribuição de exportação não tem suporte quando o sinalizador '--module' é 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Exportar conflitos de declaração com declaração exportada de '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "As declarações de exportação não são permitidas em um namespace.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "O arquivo de digitação '{0}' do pacote externo exportado não é um módulo. Entre em contato com o autor do pacote para atualizar a definição de pacote.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "O arquivo de digitação do pacote externo exportado não pode conter referências de barra tripla. Entre em contato com o autor do pacote para atualizar a definição de pacote.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "O alias de tipo exportado '{0}' tem ou está usando o nome particular '{1}'.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "A variável exportada '{0}' tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeada.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "A variável exportada '{0}' tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "A variável exportada '{0}' tem ou está usando o nome particular '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exportações e designações de exportações não são permitidas em acréscimos de módulo.", + "Expression_expected_1109": "Expressão esperada.", + "Expression_or_comma_expected_1137": "Expressão ou vírgula esperada.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "A expressão é resolvida como '_super', que o compilador utiliza para capturar a referência da classe base.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "A expressão é resolvida como uma declaração de variável '{0}' que o compilador usa para dar suporte a funções assíncronas.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "A expressão é resolvida para a declaração de variável '_newTarget' que o compilador usa para capturar a referência de metapropriedade 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "A expressão é resolvida como a declaração de variável '_this' que o compilador utiliza para capturar a referência 'this'.", + "Extract_constant_95006": "Extrair constante", + "Extract_function_95005": "Extrair função", + "Extract_symbol_95003": "Extrair símbolo", + "Extract_to_0_in_1_95004": "Extrair para {0} em {1}", + "Extract_to_0_in_1_scope_95008": "Extrair para {0} no escopo {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extrair para {0} no escopo de delimitação", + "FILE_6035": "ARQUIVO", + "FILE_OR_DIRECTORY_6040": "ARQUIVO OU DIRETÓRIO", + "Failed_to_parse_file_0_Colon_1_5014": "Falha ao analisar arquivo '{0}': {1}.", + "Fallthrough_case_in_switch_7029": "Caso de fallthrough no comutador.", + "File_0_does_not_exist_6096": "O arquivo '{0}' não existe.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "O arquivo '{0}' existe; use-o como um resultado de resolução de nome.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "O arquivo '{0}' tem uma extensão sem suporte, portanto ele será ignorado.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "O arquivo '{0}' tem extensão sem suporte. As únicas extensões com suporte são {1}.", + "File_0_is_not_a_module_2306": "O arquivo '{0}' não é um módulo.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "O arquivo '{0}' não está em 'rootDir' '{1}'. Espera-se que 'rootDir' contenha todos os arquivos de origem.", + "File_0_not_found_6053": "Arquivo '{0}' não encontrado.", + "File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "O nome do arquivo '{0}' difere do nome de arquivo '{1}' já incluído somente em maiúsculas e minúsculas.", + "File_name_0_has_a_1_extension_stripping_it_6132": "O nome do arquivo '{0}' tem uma extensão '{1}' – remoção.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "A especificação de arquivo não pode conter um diretório pai ('..') que aparece após um curinga de diretório recursivo ('**'): '{0}'.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "A especificação de arquivo não pode conter vários curingas do diretório recursivo ('**'): '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "A especificação de arquivo não pode terminar em um curinga do diretório recursivo ('**'): '{0}'.", + "Found_package_json_at_0_6099": "'package.json' encontrado em '{0}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Decorações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Declarações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'. Definições de classe estão automaticamente em modo estrito.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Declarações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'. Módulos estão automaticamente em modo estrito.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "A expressão de função, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno '{0}'.", + "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_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.", + "Generates_corresponding_d_ts_file_6002": "Gera o arquivo '.d.ts' correspondente.", + "Generates_corresponding_map_file_6043": "Gera o arquivo '.map' correspondente.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Implicitamente, o gerador tem o tipo '{0}' porque não produz nenhum valor. Considere fornecer um tipo de retorno.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Os geradores não são permitidos em um contexto de ambiente.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Geradores só estão disponíveis ao direcionar para o ECMAScript 2015 ou superior.", + "Generic_type_0_requires_1_type_argument_s_2314": "O tipo genérico '{0}' exige {1} argumento(s) de tipo.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "O tipo genérico '{0}' exige argumentos de tipo entre {1} e {2}.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "A instanciação de tipo genérico é muito profunda e possivelmente infinita.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Acessadores getter e setter não concordam quanto à visibilidade.", + "Global_module_exports_may_only_appear_at_top_level_1316": "As exportações de módulo global podem somente aparecer no nível superior.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "As exportações de módulo global podem somente aparecer em arquivos de declaração.", + "Global_module_exports_may_only_appear_in_module_files_1314": "As exportações de módulo global podem somente aparecer em arquivos de módulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "O tipo global '{0}' deve ser um tipo de classe ou interface.", + "Global_type_0_must_have_1_type_parameter_s_2317": "O tipo global '{0}' deve ter {1} parâmetro(s) de tipo.", + "Hexadecimal_digit_expected_1125": "Dígito hexadecimal esperado.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Identificador esperado. '{0}' é uma palavra reservada no modo estrito.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Identificador esperado. '{0}' é uma palavra reservada no modo estrito. Definições de classe estão automaticamente no modo estrito.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificador esperado. '{0}' é uma palavra reservada em modo estrito. Os módulos ficam automaticamente em modo estrito.", + "Identifier_expected_1003": "Identificador esperado.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. '__esModule' é reservado como um marcador exportado ao transformar os módulos ECMAScript.", + "Ignore_this_error_message_90019": "Ignore essa mensagem de erro.", + "Implement_inherited_abstract_class_90007": "Implemente a classe abstrata herdada.", + "Implement_interface_0_90006": "Implemente a interface '{0}'.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "A cláusula implements da classe exportada '{0}' tem ou está usando o nome particular '{1}'.", + "Import_0_from_module_1_90013": "Importar '{0}' do módulo \"{1}\".", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Não é possível usar a atribuição de importação durante o direcionamento para módulos de ECMAScript. Use 'importar * como ns de \"mod\"', 'importar {a} de \"mod\"', 'importar d de \"mod\"' ou outro formato de módulo em vez disso.", + "Import_declaration_0_is_using_private_name_1_4000": "A declaração da importação '{0}' está usando o nome particular '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "A declaração da importação está em conflito com a declaração local '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "As declarações de importação em um namespace não podem fazer referência a um módulo.", + "Import_emit_helpers_from_tslib_6139": "Importar auxiliares de emissão de 'tslib'.", + "Import_name_cannot_be_0_2438": "O nome da importação não pode ser '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "A declaração de importação e exportação em uma declaração de módulo de ambiente não pode fazer referência ao módulo por meio do nome do módulo relativo.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importações não são permitidas em acréscimos de módulo. Considere movê-las para o módulo externo delimitador.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações enum de ambiente, o inicializador de membro deve ser uma expressão de constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em um enum com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento enum.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações enum 'const', o inicializador de membro deve ser uma expressão de constante.", + "Index_signature_in_type_0_only_permits_reading_2542": "Assinatura de índice no tipo '{0}' permite somente leitura.", + "Index_signature_is_missing_in_type_0_2329": "Assinatura de índice ausente no tipo '{0}'.", + "Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Todas as declarações individuais na declaração mesclada '{0}' devem ser exportadas ou ficar no local.", + "Infer_parameter_types_from_usage_95012": "Inferir os tipos de parâmetro do uso.", + "Infer_type_of_0_from_usage_95011": "Inferir o tipo de '{0}' do uso.", + "Initialize_property_0_in_the_constructor_90020": "Inicializar a propriedade '{0}' no construtor.", + "Initialize_static_property_0_90021": "Inicializar a propriedade estática '{0}'.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "O inicializador da variável de membro de instância '{0}' não pode referenciar o identificador '{1}' declarado no construtor.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "O inicializador do parâmetro '{0}' não pode referenciar o identificador '{1}' declarado depois dele.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "O inicializador não fornece um valor para esse elemento de associação e o elemento de associação não tem valor padrão.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializadores não são permitidos em contextos de ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa um projeto TypeScript e cria um arquivo tsconfig.json.", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserir opções e arquivos de linha de comando de um arquivo.", + "Install_0_95014": "Instalar '{0}'", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "A interface '{0}' não pode estender os tipos '{1}' e '{2}' simultaneamente.", + "Interface_0_incorrectly_extends_interface_1_2430": "A interface '{0}' estende incorretamente a interface '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "A declaração de interface não pode ter a cláusula 'implements'.", + "Interface_name_cannot_be_0_2427": "O nome da interface não pode ser '{0}'.", + "Invalid_character_1127": "Caractere inválido.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nome de módulo inválido no aumento. O módulo '{0}' resolve para um módulo não tipado em '{1}', que não pode ser aumentado.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nome de módulo inválido em acréscimo, o módulo '{0}' não pôde ser encontrado.", + "Invalid_reference_directive_syntax_1084": "Sintaxe de diretiva 'reference' inválida.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Uso inválido de '{0}'. Definições de classe estão automaticamente no modo estrito.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso inválido de '{0}'. Os módulos ficam automaticamente em modo estrito.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso inválido de '{0}' no modo estrito.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor inválido para 'jsxFactory'. '{0}' não é um identificador válido ou nome qualificado.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor inválido para '--reactNamespace'. '{0}' não é um identificador válido.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "O '@{0} {1}' do JSDoc não corresponde à cláusula 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "O '@{0}' do JSDoc não está anexado a uma classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' só pode aparecer no último parâmetro de uma assinatura.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "A marcação do JSDoc \"@param\" tem o nome \"{0}\", mas não há nenhum parâmetro com esse nome.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "A marca JSDoc \"@typedef\" deve ter uma anotação de tipo ou ser seguida pelas marcas \"@property\" or \"@member\".", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Os tipos de JSDoc podem ser usados somente dentro dos comentários de documentação.", + "JSX_attribute_expected_17003": "Atributo JSX esperado.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Os atributos JSX só devem ser atribuídos a 'expressões' que não estejam vazias.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "O elemento JSX '{0}' não tem uma marcação de fechamento correspondente.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "O tipo de atributos de elemento JSX '{0}' não pode ser um tipo de união.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "A classe do elemento JSX não dá suporte a atributos porque não tem uma propriedade '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "O elemento JSX implicitamente tem o tipo 'any' porque não há uma interface de 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "O elemento JSX implicitamente tem tipo 'any' porque o tipo global \"JSX.Element\" não existe.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "O tipo de elemento JSX '{0}' não tem nenhum constructo nem assinaturas de chamadas.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "O tipo de elemento JSX '{0}' não é uma função de construtor para elementos JSX.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementos JSX não podem ter vários atributos com o mesmo nome.", + "JSX_expressions_must_have_one_parent_element_2657": "As expressões JSX devem ter um elemento pai.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "O fragmento JSX não tem uma marcação de fechamento correspondente.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "O fragmento JSX não é compatível com o uso de --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "O filho do espalhamento JSX deve ser um tipo de matriz.", + "Jump_target_cannot_cross_function_boundary_1107": "O destino do salto não pode ultrapassar o limite de função.", + "KIND_6034": "TIPO", + "LOCATION_6037": "LOCAL", + "Language_service_is_disabled_9004": "O serviço de linguagem está desabilitado.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "O operador antes da vírgula não é usado e não tem efeitos colaterais.", + "Line_break_not_permitted_here_1142": "Quebra de linha não permitida aqui.", + "Line_terminator_not_permitted_before_arrow_1200": "Terminador de linha não permitido antes de seta.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista de pastas das quais são incluídas as definições de tipo.", + "List_of_language_service_plugins_6181": "Lista de plug-ins de serviço de linguagem.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Listas das pastas raiz cujo conteúdo combinado representa a estrutura do projeto no tempo de execução.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Carregando '{0}' do diretório raiz '{1}', local candidato '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Carregando o módulo '{0}' da pasta 'node_modules', tipo de arquivo de destino '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Carregando módulo como arquivo/pasta, local do módulo candidato '{0}', tipo de arquivo de destino '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "A localidade deve estar no formato ou -. Por exemplo '{0}' ou '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "O maior prefixo correspondente para '{0}' é '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Pesquisando na pasta 'node_modules', local inicial '{0}'.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Tornar a chamada 'super()' a primeira instrução no construtor.", + "Member_0_implicitly_has_an_1_type_7008": "O membro '{0}' implicitamente tem um tipo '{1}'.", + "Merge_conflict_marker_encountered_1185": "Marcador de conflito de mesclagem encontrado.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "A declaração mesclada '{0}' não pode conter uma declaração de exportação padrão. Considere adicionar uma declaração 'export default {0}' independente.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "A metapropriedade '{0}' só é permitida no corpo de uma declaração de função, expressão de função ou construtor.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "O método '{0}' não pode ter uma implementação, pois está marcado como abstrato.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "O método '{0}' da interface exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "O método '{0}' da interface exportada tem ou está usando o nome privado '{1}'.", + "Modifiers_cannot_appear_here_1184": "Modificadores não podem aparecer aqui.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "O módulo {0} já exportou um membro denominado '{1}'. Considere reexportar explicitamente para resolver a ambiguidade.", + "Module_0_has_no_default_export_1192": "O módulo '{0}' não tem padrão de exportação.", + "Module_0_has_no_exported_member_1_2305": "O módulo '{0}' não tem nenhum membro exportado '{1}'.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "O módulo '{0}' está oculto por uma declaração de local com o mesmo nome.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "O módulo '{0}' resolve para uma entidade sem módulo e não pode ser importado usando este constructo.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "O módulo '{0}' usa 'export =' e não pode ser usado com 'export *'.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "O módulo '{0}' foi resolvido como um módulo de ambiente declarado em '{1}', já que este arquivo não foi modificado.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "O módulo '{0}' foi resolvido como módulo de ambiente declarado localmente no arquivo '{1}'.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "O módulo '{0}' foi resolvido para '{1}', mas '--jsx' não está configurado.", + "Module_Resolution_Options_6174": "Opções da Resolução de Módulo", + "Module_name_0_matched_pattern_1_6092": "Nome do módulo '{0}', padrão correspondido '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Nome do módulo '{0}' não foi resolvido. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nome do módulo '{0}' foi resolvido com sucesso '{1}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Resolução de tipo não foi especificado, usando '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "Falha na resolução de módulo usando 'rootDirs'.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Não são permitidas várias implementações de construtor.", + "NEWLINE_6061": "NEWLINE", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "As propriedades com nome '{0}' dos tipos '{1}' e '{2}' não são idênticas.", + "Namespace_0_has_no_exported_member_1_2694": "O namespace '{0}' não tem o membro exportado '{1}'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Nenhum construtor base tem o número especificado de argumentos de tipo.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nenhuma entrada foi localizada no arquivo de configuração '{0}'. Os caminhos especificados foram 'incluir' '{1}' e 'excluir' '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "A classe não abstrata '{0}' não implementa o membro abstrato herdado '{1}' da classe '{2}'.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "A expressão da classe não abstrata não implementa o membro abstrato herdado '{0}' da classe '{1}'.", + "Not_all_code_paths_return_a_value_7030": "Nem todos os caminhos de código retornam um valor.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "O tipo de índice numérico '{0}' não é atribuível ao tipo de índice de cadeia de caracteres '{1}'.", + "Object_is_possibly_null_2531": "Possivelmente, o objeto é 'nulo'.", + "Object_is_possibly_null_or_undefined_2533": "Possivelmente, o objeto é 'nulo' ou 'indefinido'.", + "Object_is_possibly_undefined_2532": "Possivelmente, o objeto é 'nulo'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "O literal de objeto pode especificar apenas propriedades conhecidas e '{0}' não existe no tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "O literal de objeto pode especificar somente propriedades conhecidas, mas o '{0}' não existe no tipo '{1}'. Você queria ter escrito '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "A propriedade '{0}' do literal de objeto implicitamente tem um tipo '{1}'.", + "Octal_digit_expected_1178": "Dígito octal esperado.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Tipos de literais octais devem usar a sintaxe ES2015. Use a sintaxe '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Literais octais não são permitidos em inicializador de membros de enumerações. Use a sintaxe '{0}'.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Literais octais não são permitidos no modo estrito.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Literais octais não estão disponíveis quando se tem como destino ECMAScript 5 e superiores. Use a sintaxe '{0}'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "É permitida apenas uma única declaração de variável em uma instrução 'for...in'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "É permitida apenas uma única declaração de variável em uma instrução 'for...of'.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Apenas uma função void pode ser chamada com a palavra-chave 'new'.", + "Only_ambient_modules_can_use_quoted_names_1035": "Somente os módulos de ambiente podem usar nomes entre aspas.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Há suporte somente aos módulos 'amd' e 'system' ao lado de --{0}.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Somente os identificadores/nomes qualificados com argumentos de tipo opcionais tem suporte atualmente nas cláusulas de classe 'extends'.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Somente métodos protegidos e públicos da classe base são acessíveis pela palavra-chave 'super'.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "O operador '{0}' não pode ser aplicado aos tipos '{1}' e '{2}'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "A opção '{0}' só pode ser especificada no arquivo 'tsconfig.json'.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", + "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}'.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "A opção '{0}' deve ter matriz de cadeias de um valor.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "A opção 'paths' não pode ser usada sem se especificar a opção '--baseUrl'.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "A opção 'project' não pode ser mesclada com arquivos de origem em uma linha de comando.", + "Options_Colon_6027": "Opções:", + "Output_directory_for_generated_declaration_files_6166": "Diretório de saída para os arquivos de declaração gerados.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "A assinatura de sobrecarga não é compatível com a implementação da função.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Assinaturas de sobrecarga devem todas ser abstratas ou não abstratas.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Todas as assinaturas de sobrecarga devem ser ambiente ou não ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Assinaturas de sobrecarga devem todas ser exportadas ou não exportadas.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Todas as assinaturas de sobrecarga devem ser opcionais ou obrigatórias.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Todas as assinaturas de sobrecarga devem ser protegidas, privadas ou públicas.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "O parâmetro '{0}' não pode ser referenciado em seu inicializador.", + "Parameter_0_implicitly_has_an_1_type_7006": "O parâmetro '{0}' implicitamente tem um tipo '{1}'.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "O parâmetro '{0}' não está na mesma posição que o parâmetro '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "O parâmetro '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "O parâmetro '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "O parâmetro '{0}' do construtor da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "O parâmetro '{0}' do construtor da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "O parâmetro '{0}' do construtor da classe exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "O parâmetro '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "O parâmetro '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "O parâmetro '{0}' da função exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "O parâmetro '{0}' da função exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "O parâmetro '{0}' da função exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "O parâmetro '{0}' da assinatura de índice da interface exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "O parâmetro '{0}' da assinatura de índice da interface exportadas tem ou está usando o nome privado '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "O parâmetro '{0}' do método da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "O parâmetro '{0}' do método da interface exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "O parâmetro '{0}' do método público da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "O parâmetro '{0}' do método público da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "O parâmetro '{0}' do método público da classe exportada tem ou está usando o nome particular '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "O parâmetro '{0}' do método estático público da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "O parâmetro '{0}' do método estático público da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "O parâmetro '{0}' do método estático público da classe exportada tem ou está usando o nome particular '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "O parâmetro não pode ter inicializador e ponto de interrogação.", + "Parameter_declaration_expected_1138": "Declaração de parâmetro esperada.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "O tipo de parâmetro do setter público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "O tipo de parâmetro do setter público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "O tipo de parâmetro do setter estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "O tipo de parâmetro do setter estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analisar em modo estrito e emitir \"usar estrito\" para cada arquivo de origem.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "O padrão '{0}' pode ter no máximo um caractere '*'.", + "Prefix_0_with_an_underscore_90025": "Prefixo '{0}' com um sublinhado.", + "Print_names_of_files_part_of_the_compilation_6155": "Nomes de impressão das partes dos arquivos da compilação.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.", + "Print_the_compiler_s_version_6019": "Imprima a versão do compilador.", + "Print_this_message_6017": "Imprima esta mensagem.", + "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe no enum 'const' '{1}'.", + "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "A propriedade '{0}' não existe no tipo '{1}'. Você quis dizer '{2}'?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "A propriedade '{0}' tem declarações conflitantes e é inacessível no tipo '{1}'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "A propriedade '{0}' não tem nenhum inicializador e não está definitivamente atribuída no construtor.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador get não tem uma anotação de tipo de retorno.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador set não tem uma anotação de tipo de parâmetro.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída ao tipo '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "A propriedade '{0}' é declarada, mas seu valor nunca é lido.", + "Property_0_is_incompatible_with_index_signature_2530": "A propriedade '{0}' é incompatível com a assinatura de índice.", + "Property_0_is_missing_in_type_1_2324": "A propriedade '{0}' está ausente no tipo '{1}'.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "A propriedade '{0}' é opcional no tipo '{1}', mas obrigatória no tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "A propriedade '{0}' é particular e somente é acessível na classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "A propriedade '{0}' é particular no tipo '{1}', mas não no tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "A propriedade '{0}' é protegida e somente é acessível por meio de uma instância da classe '{1}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "A propriedade '{0}' é protegida e somente é acessível na classe '{1}' e em suas subclasses.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "A propriedade '{0}' é protegida, mas o tipo '{1}' não é uma classe derivada de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "A propriedade '{0}' é protegida no tipo '{1}', mas pública no tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "A propriedade '{0}' é usada antes de ser atribuída.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "A propriedade \"{0}\" do atributo de espalhamento JSX não pode ser atribuída à propriedade de destino.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "A propriedade '{0}' da expressão de classe exportada não pode ser privada nem protegida.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "A propriedade '{0}' da interface exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "A propriedade '{0}' da interface exportada tem ou está usando o nome particular '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "A propriedade '{0}' do tipo '{1}' não é atribuível ao tipo de índice numérico '{2}'.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "A propriedade '{0}' do tipo '{1}' não é atribuível ao tipo de índice de cadeia de caracteres '{2}'.", + "Property_assignment_expected_1136": "Atribuição de propriedade esperada.", + "Property_destructuring_pattern_expected_1180": "Padrão de desestruturação de propriedade esperado.", + "Property_or_signature_expected_1131": "Propriedade ou assinatura esperada.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "O valor da propriedade pode ser somente um literal de cadeia, um literal numérico, 'true', 'false', 'null', literal de objeto ou literal de matriz.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Fornecer suporte completo para os iteráveis em 'for-of', espalhamento e desestruturação ao direcionar 'ES5' ou 'ES3'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "O método público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "O método público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "O método público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "A propriedade pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeada.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "A propriedade pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "A propriedade pública '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "O método estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "O método estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "O método estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "A propriedade estática pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeada.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "A propriedade estática pública '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo particular '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "A propriedade estática pública '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Gerar erro em expressões e declarações com um tipo 'any' implícito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.", + "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", + "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.", + "Report_errors_in_js_files_8019": "Relatar erros em arquivos .js.", + "Report_errors_on_unused_locals_6134": "Relatar erros nos locais não utilizados.", + "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", + "Resolution_for_module_0_was_found_in_cache_6147": "A resolução para o modo '{0}' foi encontrada no cache.", + "Resolving_from_node_modules_folder_6118": "Resolvendo na pasta node_modules...", + "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Resolvendo o caminho real de '{0}', resultado '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido '{1}', diretório raiz '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido '{1}', diretório raiz não configurado. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido não configurado, diretório raiz '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Resolvendo diretiva de referência de tipo '{0}', arquivo contido não configurado, diretório raiz não configurado. ========", + "Resolving_using_primary_search_paths_6117": "Resolvendo usando caminhos de pesquisa primários...", + "Resolving_with_primary_search_path_0_6121": "Resolvendo com caminho de pesquisa primário '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "O parâmetro rest '{0}' implicitamente tem um tipo 'any[]'.", + "Rest_types_may_only_be_created_from_object_types_2700": "Os tipos de rest podem ser criado somente de tipos de objeto.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "O tipo de retorno da assinatura de chamada da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "O tipo de retorno da assinatura de chamada da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "O tipo de retorno da assinatura de construtor da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "O tipo de retorno da assinatura de construtor da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "O tipo de retorno da assinatura de construtor deve ser atribuível ao tipo de instância da classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "O tipo de retorno da função exportada tem ou está usando o nome '{0}' do módulo externo {1}, mas não pode ser nomeado.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "O tipo de retorno da função exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "O tipo de retorno da função exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "O tipo de retorno da assinatura de índice da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "O tipo de retorno da assinatura de índice da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "O tipo de retorno do método da interface exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "O tipo de retorno do método da interface exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "O tipo de retorno do getter público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo {2}, mas não pode ser nomeado.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "O tipo de retorno do getter público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "O tipo de retorno do getter público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "O tipo de retorno do método público da classe exportada tem ou está usando o nome '{0}' do módulo externo {1}, mas não pode ser nomeado.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "O tipo de retorno do método público da classe exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "O tipo de retorno do método público da classe exportada tem ou está usando o nome particular '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "O tipo de retorno do getter estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo externo '{2}', mas não pode ser nomeado.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "O tipo de retorno do getter estático público '{0}' da classe exportada tem ou está usando o nome '{1}' do módulo privado '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "O tipo de retorno do getter estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome '{0}' do módulo externo {1}, mas não pode ser nomeado.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome '{0}' do módulo particular '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome particular '{0}'.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Reutilizando resoluções de módulo originados em '{0}', já que as resoluções do programa antigo estão inalteradas.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Reutilizando a resolução do módulo '{0}' para o arquivo '{1}' do programa antigo.", + "Rewrite_as_the_indexed_access_type_0_90026": "Regravar como o tipo de acesso indexado '{0}'.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Diretório raiz não pode ser determinado, ignorando caminhos de pesquisa primários.", + "STRATEGY_6039": "ESTRATÉGIA", + "Scoped_package_detected_looking_in_0_6182": "Pacote com escopo detectado, procurando no '{0}'", + "Setters_cannot_return_a_value_2408": "Setters não podem retornar um valor.", + "Show_all_compiler_options_6169": "Mostrar todas as opções do compilador.", + "Show_diagnostic_information_6149": "Mostras as informações de diagnóstico.", + "Show_verbose_diagnostic_information_6150": "Mostras as informações detalhadas de diagnóstico.", + "Signature_0_must_be_a_type_predicate_1224": "A assinatura '{0}' deve ser um predicado de tipo.", + "Skip_type_checking_of_declaration_files_6012": "Ignorar a verificação de tipo dos arquivos de declaração.", + "Source_Map_Options_6175": "Opções do Sourcemap", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Especifique a versão de destino do ECMAScript: 'ES3' (padrão), 'ES5', 'ES2015', 'ES2016', 'ES2017' ou 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Especifique a geração de código JSX: 'preserve', 'react-native' ou 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Especifique os arquivos de biblioteca a serem incluídos na compilação: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Especifique a geração de código de módulo: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' ou 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Especifique a estratégia de resolução de módulo: 'node' (Node.js) ou 'classic' (TypeScript pré-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Especifique a função de fábrica JSX a ser usada ao direcionar a emissão 'react' do JSX, por ex., 'React.createElement' ou 'h'.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Especifique o fim da sequência de linha a ser usado ao emitir arquivos: 'CRLF' (dos) ou 'LF' (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Especifique o local onde o depurador deve localizar arquivos TypeScript em vez de locais de origem.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Especifique o local onde o depurador deve localizar arquivos de mapa em vez de locais gerados.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique o diretório raiz de arquivos de entrada. Use para controlar a estrutura do diretório de saída com --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "O operador de espalhamento só está disponível em expressões 'new' no direcionamento a ECMAScript 5 e superior.", + "Spread_types_may_only_be_created_from_object_types_2698": "Os tipos de espalhamento podem ser criados apenas de tipos de objeto.", + "Statement_expected_1129": "Instrução esperada.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Instruções não são permitidas em contextos de ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "Membros estáticos não podem fazer referência a parâmetros de tipo de classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Conflitos de propriedade estática '{0}' com propriedade interna 'Function.{0}' da função de construtor '{1}'.", + "Strict_Type_Checking_Options_6173": "Opções Estritas da Verificação de Tipo", + "String_literal_expected_1141": "Literal de cadeia de caracteres esperado.", + "String_literal_with_double_quotes_expected_1327": "Literal de cadeia com aspas duplas é esperado.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Estilizar erros e mensagens usando cor e contexto (experimental).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Declarações de variável subsequentes devem ter o mesmo tipo. A variável '{0}' deve ser do tipo '{1}', mas aqui tem o tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "A substituição '{0}' para o padrão '{1}' tem um tipo incorreto, 'string' esperada, obteve '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "A substituição '{0}' no padrão '{1}' pode ter no máximo um caractere '*'.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "As substituições para o padrão '{0}' devem ser uma matriz.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Substituições para o padrão '{0}' não devem ser uma matriz vazia.", + "Successfully_created_a_tsconfig_json_file_6071": "Arquivo tsconfig.json criado com êxito.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "As chamadas super não são permitidas fora dos construtores ou em funções aninhadas dentro dos construtores.", + "Suppress_excess_property_checks_for_object_literals_6072": "Verificações de propriedade de excesso de compactação para literais de objeto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Suprimir erros de noImplicitAny para objetos de indexação sem assinaturas de índice.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "A referência 'symbol' não se refere ao objeto global do construtor Symbol.", + "Syntax_Colon_0_6023": "Sintaxe: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "O operador '{0}' não pode ser aplicado ao tipo 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "O operador '{0}' não é permitido para tipos boolianos. Considere usar '{1}'.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "O tipo 'Objeto' pode ser atribuído para muito poucos outros tipos. Você desejava usar o tipo 'qualquer' ao invés disso?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "O objeto 'arguments' não pode ser referenciado em uma função de seta em ES3 e ES5. Considere usar uma expressão de função padrão.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "O objeto 'arguments' não pode ser referenciado em uma função assíncrona ou o método no ES3 e ES5. Considere usar uma função ou um método padrão.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "O corpo de uma instrução 'if' não pode ser uma instrução vazia.", + "The_character_set_of_the_input_files_6163": "O conjunto de caracteres dos arquivos de entrada.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "O corpo da função ou do módulo contido é muito grande para a análise de fluxo de controle.", + "The_current_host_does_not_support_the_0_option_5001": "O host atual não dá suporte à opção '{0}'.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "A expressão de uma atribuição de exportação deve ser um identificador ou nome qualificado em um contexto de ambiente.", + "The_files_list_in_config_file_0_is_empty_18002": "A lista de 'arquivos' no arquivo de configuração '{0}' está vazia.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "O primeiro parâmetro do método 'then' de uma promessa deve ser um retorno de chamada.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "O tipo global 'JSX.{0}' não pode ter mais de uma propriedade.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "O tipo inferido de '{0}' faz referência a um tipo '{1}' inacessível. Uma anotação de tipo é necessária.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "O lado esquerdo de uma instrução 'for...in' não pode ser um padrão de desestruturação.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "O lado esquerdo de uma instrução 'for...in' não pode usar uma anotação de tipo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "O lado esquerdo de uma instrução 'for...in' deve ser uma variável ou um acesso à propriedade.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "O lado esquerdo de uma instrução de 'for...in' deve ser do tipo 'string' ou 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "O lado esquerdo de uma instrução 'for...of' não pode usar uma anotação de tipo.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "O lado esquerdo de uma instrução 'for...of' deve ser uma variável ou um acesso à propriedade.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "O lado esquerdo de uma operação aritmética deve ser do tipo 'any', 'number' ou enum.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "O lado esquerdo de uma expressão de atribuição deve ser uma variável ou um acesso à propriedade.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "O lado esquerdo de uma expressão 'in' deve ser do tipo 'any', 'string', 'number' ou 'symbol'.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "O lado esquerdo de uma expressão 'instanceof' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "O local usado ao exibir mensagens ao usuário (por exemplo, 'en-us')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "A profundidade máxima de dependência a ser pesquisada em arquivos node_modules e de carregamento de JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "O operando de um operador delete não pode ser uma propriedade somente leitura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "O operando de um operador delete deve ser uma referência de propriedade.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "O operando de um operador de incremento ou decremento deve ser uma variável ou um acesso à propriedade.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "O tipo de retorno de um construtor de elemento JSX deve retornar um tipo de objeto.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "O tipo de retorno de uma função de decorador de parâmetro deve ser 'void' ou 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "O tipo de retorno de uma função de decorador de propriedade deve ser 'void' ou 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "O tipo de retorno de uma função assíncrona deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "O tipo de retorno de uma função assíncrona ou método deve ser o tipo Promessa global.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "O lado direito de uma instrução 'for...in' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "O lado direito de uma operação aritmética deve ser do tipo 'any', 'number' ou enum.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "O lado direito de uma expressão 'in' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "O lado direito de uma expressão 'instanceof' deve ser do tipo 'any' ou de um tipo que pode ser atribuído ao tipo de interface 'Function'.", + "The_specified_path_does_not_exist_Colon_0_5058": "O caminho especificado não existe: '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "O destino de uma atribuição deve ser uma variável ou um acesso à propriedade.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "O destino de uma atribuição rest de objeto deve ser uma variável ou um acesso de propriedade.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "O contexto 'this' de tipo '{0}' não é atribuível para o 'this' do método de tipo '{1}'.", + "The_this_types_of_each_signature_are_incompatible_2685": "Os tipos 'this' de cada assinatura são incompatíveis.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "O argumento de tipo para o parâmetro de tipo '{0}' não pode ser inferido com base no uso. Considere especificar os argumentos de tipo explicitamente.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "O tipo retornado pelo método 'next()' de um iterador assíncrono deve ser uma promessa para um tipo com a propriedade 'value'.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "O tipo retornado pelo método 'next()' de um iterador deve ter uma propriedade 'value'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "A declaração de variável de uma instrução 'for...in' não pode ter um inicializador.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "A declaração de variável de uma instrução 'for...of' não pode ter um inicializador.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "A instrução \"with\" não tem suporte. Todos os símbolos em um bloco \"with\" terão o tipo \"any\".", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Essa sintaxe requer um auxiliar importado, mas o módulo '{0}' não pode ser encontrado.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Essa sintaxe requer um auxiliar importado chamado '{1}', mas o módulo '{0}' não tem nenhum membro exportado '{1}'.", + "Trailing_comma_not_allowed_1009": "Vírgula à direita não permitida.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transcompilar cada arquivo como um módulo separado (do mesmo modo que 'ts.transpileModule').", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Tente `npm install @types/{0}`, se existir, ou adicione um novo arquivo de declaração (.d.ts) que contenha `declare module '{0}';`", + "Trying_other_entries_in_rootDirs_6110": "Tentando outras entradas em 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Tentando substituição '{0}', local de módulo candidato: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "O tipo de tupla '{0}' com comprimento '{1}' não pode ser atribuído à tupla com comprimento '{2}'.", + "Type_0_cannot_be_converted_to_type_1_2352": "O tipo '{0}' não pode ser convertido para o tipo '{1}'.", + "Type_0_cannot_be_used_as_an_index_type_2538": "O tipo '{0}' não pode ser usado como um tipo de índice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "O tipo '{0}' não pode ser usado para indexar o tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "O tipo '{0}' não satisfaz a restrição '{1}'.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "O tipo '{0}' não tem assinatura de índice correspondente para o tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "O tipo '{0}' não tem propriedades em comum com o tipo '{1}'.", + "Type_0_has_no_property_1_2460": "O tipo '{0}' não tem nenhuma propriedade '{1}'.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "O tipo '{0}' não tem nenhuma propriedade '{1}' e nenhuma assinatura de índice da cadeia de caracteres.", + "Type_0_is_not_a_constructor_function_type_2507": "O tipo '{0}' não é um tipo de função de construtor.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "O tipo '{0}' não é um tipo de retorno de função assíncrona válido no ES5/ES3, pois não se refere ao valor construtor compatível com a Promessa.", + "Type_0_is_not_an_array_type_2461": "O tipo '{0}' não é um tipo de matriz.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "O tipo '{0}' não é um tipo de matriz ou de cadeia de caracteres.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "O tipo '{0}' não é um tipo de matriz de um tipo de cadeia ou não tem um método '[Symbol.iterator]()' que retorna um iterador.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "O tipo '{0}' não é um tipo de matriz ou não tem um método '[Symbol.iterator]()' que retorna um iterador.", + "Type_0_is_not_assignable_to_type_1_2322": "O tipo '{0}' não pode ser atribuído ao tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "O tipo '{0}' não é atribuível ao tipo '{1}'. Dois tipos diferentes com esse nome existem, mas eles não são relacionados.", + "Type_0_is_not_comparable_to_type_1_2678": "O tipo '{0}' não pode ser comparável ao tipo '{1}'.", + "Type_0_is_not_generic_2315": "O tipo '{0}' não é genérico.", + "Type_0_provides_no_match_for_the_signature_1_2658": "O tipo '{0}' fornece nenhuma correspondência para a assinatura '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "O tipo '{0}' referencia recursivamente a si próprio como um tipo base.", + "Type_alias_0_circularly_references_itself_2456": "O alias de tipo '{0}' referencia circulamente a si próprio.", + "Type_alias_name_cannot_be_0_2457": "O nome do alias de tipo não pode ser '{0}'.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Uma anotação de tipo não pode aparecer em uma declaração de construtor.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "O candidato de argumento de tipo '{1}' não é um argumento de tipo válido porque ele não é um supertipo do candidato '{0}'.", + "Type_argument_expected_1140": "Argumento de tipo esperado.", + "Type_argument_list_cannot_be_empty_1099": "A lista de argumentos de tipo não pode estar vazia.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Arquivos de declaração de tipo a serem incluídos em compilação.", + "Type_expected_1110": "Tipo esperado.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "O tipo é referenciado diretamente ou indiretamente em um retorno de chamada de preenchimento do seu próprio método 'then'.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "O tipo deve ter um método '[Symbol.asyncIterator]()' que retorna um iterador assíncrono.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "O tipo deve ter um método '[Symbol.iterator]()' que retorna um iterador.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "O tipo de operando \"await\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "O tipo de elementos iterados de um operando \"yield*\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "O tipo do operando \"yield\" em um gerador assíncrono deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", + "Type_parameter_0_has_a_circular_constraint_2313": "O parâmetro de tipo '{0}' tem uma restrição circular.", + "Type_parameter_0_has_a_circular_default_2716": "O parâmetro de tipo '{0}' tem um padrão circular.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "O parâmetro de tipo '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "O parâmetro de tipo '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "O parâmetro de tipo '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "O parâmetro de tipo '{0}' da função exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "O parâmetro de tipo '{0}' da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "O parâmetro de tipo '{0}' do alias de tipo exportado tem ou está usando o nome privado '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "O parâmetro de tipo '{0}' do método da interface exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "O parâmetro de tipo '{0}' do método público da classe exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "O parâmetro de tipo '{0}' do método estático público da classe exportada tem ou está usando o nome particular '{1}'.", + "Type_parameter_declaration_expected_1139": "Declaração de parâmetro de tipo esperada.", + "Type_parameter_list_cannot_be_empty_1098": "A lista de parâmetros de tipo não pode estar vazia.", + "Type_parameter_name_cannot_be_0_2368": "O nome do parâmetro de tipo não pode ser '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Os parâmetros de tipo não podem aparecer em uma declaração de construtor.", + "Type_predicate_0_is_not_assignable_to_1_1226": "O predicado de tipo '{0}' não pode ser atribuído a '{1}'.", + "Type_reference_directive_0_was_not_resolved_6120": "======== A diretiva de referência de tipo '{0}' não foi resolvida. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== A diretiva de referência de tipo '{0}' foi resolvida com sucesso para '{1}', primário: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Tipos têm declarações separadas de uma propriedade privada '{0}'.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Os tipos de parâmetros '{0}' e '{1}' são incompatíveis.", + "Types_of_property_0_are_incompatible_2326": "Tipos de propriedade '{0}' são incompatíveis.", + "Unable_to_open_file_0_6050": "Não é possível abrir o arquivo '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Não é possível resolver a assinatura do decorador de classe quando ele é chamado como uma expressão.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Não é possível resolver a assinatura do decorador de método quando ele é chamado como uma expressão.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Não é possível resolver a assinatura do decorador de parâmetro quando ele é chamado como uma expressão.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Não é possível resolver a assinatura do decorador de propriedade quando ele é chamado como uma expressão.", + "Unexpected_end_of_text_1126": "Fim inesperado do texto.", + "Unexpected_token_1012": "Token inesperado.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Um construtor, método, acessador ou propriedade era esperado.", + "Unexpected_token_expected_1179": "Token inesperado. '{' esperado.", + "Unknown_compiler_option_0_5023": "Opção do compilador '{0}' desconhecida.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opção desconhecida 'excludes'. Você quis dizer 'exclude'?", + "Unknown_type_acquisition_option_0_17010": "Opção de aquisição de tipo desconhecido '{0}'.", + "Unreachable_code_detected_7027": "Código inacessível detectado.", + "Unsupported_locale_0_6049": "Localidade '{0}' sem suporte.", + "Unterminated_Unicode_escape_sequence_1199": "Sequência de escape Unicode não finalizada.", + "Unterminated_quoted_string_in_response_file_0_6045": "Cadeia de caracteres entre aspas não finalizada no arquivo de resposta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Literal de expressão regular não finalizado.", + "Unterminated_string_literal_1002": "Literal de cadeia de caracteres não finalizado.", + "Unterminated_template_literal_1160": "Literal de modelo não finalizado.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Chamadas de função não tipadas não podem aceitar argumentos de tipo.", + "Unused_label_7028": "Rótulo não utilizado.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", + "VERSION_6036": "VERSÃO", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "O valor do tipo '{0}' não tem propriedades em comum com o tipo '{1}'. Você queria chamá-lo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "O valor do tipo '{0}' não pode ser chamado. Você pretendia incluir 'new'?", + "Variable_0_implicitly_has_an_1_type_7005": "A variável '{0}' implicitamente tem um tipo '{1}'.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "A variável '{0}' tem implicitamente o tipo '{1}' em alguns locais onde o tipo não pode ser determinado.", + "Variable_0_is_used_before_being_assigned_2454": "A variável '{0}' é usada antes de ser atribuída.", + "Variable_declaration_expected_1134": "Declaração de variável esperada.", + "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", + "Version_0_6029": "Versão {0}", + "Watch_input_files_6005": "Observe os arquivos de entrada.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", + "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' são especificados duas vezes. O atributo chamado '{0}' será substituído.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' só pode ser usado em um arquivo .ts.", + "_0_expected_1005": "'{0}' esperado.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "Implicitamente, '{0}' tem um retorno tipo 'any' porque ele não tem uma anotação de tipo de retorno e é referenciado direta ou indiretamente em uma das suas expressões de retorno.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Implicitamente, '{0}' tem o tipo 'any' porque não tem uma anotação de tipo e é referenciado direta ou indiretamente em seu próprio inicializador.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' é um primitivo, mas '{1}' é um objeto de wrapper. Prefira usar '{0}' quando possível.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' é declarado, mas seu valor nunca é lido.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' não é uma metapropriedade para a palavra-chave '{1}'. Você quis dizer '{2}'?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' é referenciado direta ou indiretamente em sua própria expressão base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' é referenciado direta ou indiretamente em sua própria anotação de tipo.", + "_0_list_cannot_be_empty_1097": "A lista '{0}' não pode estar vazia.", + "_0_modifier_already_seen_1030": "O modificador '{0}' já foi visto.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "O modificador '{0}' não pode aparecer em um elemento de classe.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "O modificador '{0}' não pode aparecer em uma declaração de construtor.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "O modificador '{0}' não pode aparecer nas propriedades dos dados.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "O modificador '{0}' não pode aparecer em um módulo ou elemento de namespace.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "O modificador '{0}' não pode aparecer em um parâmetro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "O modificador '{0}' não pode aparecer em um membro de tipo.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "O modificador '{0}' não pode aparecer em uma assinatura de índice.", + "_0_modifier_cannot_be_used_here_1042": "O modificador '{0}' não pode ser usado aqui.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "O modificador '{0}' não pode ser usado em um contexto de ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "O modificador '{0}' não pode ser usado com um modificador '{1}'.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "O modificador '{0}' não pode ser usado com declarações de classes.", + "_0_modifier_must_precede_1_modifier_1029": "O modificador '{0}' deve preceder o modificador '{1}'.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' refere-se apenas a um tipo, mas está sendo usado como um namespace aqui.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' só faz referência a um tipo, mas está sendo usado como valor no momento.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' refere-se a uma UMD global, mas o arquivo atual é um módulo. Considere adicionar uma importação.", + "_0_tag_already_specified_1223": "A marca '{0}' já foi especificada.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "A marcação '{0}' não pode ser usada independentemente como uma marcação de JSDoc de nível superior.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "O modificador 'abstract' pode aparecer somente em uma declaração de classe, método ou propriedade.", + "await_expression_is_only_allowed_within_an_async_function_1308": "A expressão 'await' só é permitida em funções assíncronas.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "As expressões 'await' não podem ser usadas em inicializadores de parâmetros.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "A opção 'baseUrl' é configurada para '{0}', usando este valor para resolver o nome de módulo não relativo '{1}'.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' só pode ser usado em uma propriedade literal de objeto dentro de uma atribuição de desestruturação.", + "case_or_default_expected_1130": "'case' ou 'default' esperado.", + "class_expressions_are_not_currently_supported_9003": "No momento, não há suporte para expressões 'class'.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "declarações 'const' só podem ser declaradas dentro de um bloco.", + "const_declarations_must_be_initialized_1155": "As declarações 'const' devem ser inicializadas.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "O inicializador de membro enum 'const' foi avaliado como um valor não finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "O inicializador de membro enum 'const' foi avaliado como o valor não permitido 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Enums 'const' só podem ser usados em expressões de acesso de índice ou propriedade, ou do lado direito de uma declaração de importação ou atribuição de exportação.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' não pode ser chamado em um identificador no modo estrito.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' só podem ser usadas em um arquivo .ts.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' só pode ser usado em um arquivo .ts.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "O modificador 'export' não pode ser aplicado a módulos de ambiente e acréscimos de módulo, pois eles estão sempre visíveis.", + "extends_clause_already_seen_1172": "A cláusula 'extends' já foi vista.", + "extends_clause_must_precede_implements_clause_1173": "A cláusula 'extends' deve preceder a cláusula 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "A cláusula 'extends' da classe exportada '{0}' tem ou está usando o nome particular '{1}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "A cláusula 'extends' da interface exportada '{0}' tem ou está usando o nome particular '{1}'.", + "file_6025": "arquivo", + "get_and_set_accessor_must_have_the_same_this_type_2682": "os assessores 'set' e 'get' devem ter o mesmo tipo 'this'.", + "get_and_set_accessor_must_have_the_same_type_2380": "Os acessadores 'get' e 'set' devem ser do mesmo tipo.", + "implements_clause_already_seen_1175": "A cláusula 'implements' já foi vista.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' só podem ser usadas em um arquivo .ts.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' só pode ser usado em um arquivo .ts.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' só podem ser usadas em um arquivo .ts.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Declarações 'let' só podem ser declaradas dentro de um bloco.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "O uso de 'let' não é permitido como um nome em declarações 'let' ou 'const'.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' só podem ser usadas em um arquivo .ts.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "'new T[]' não pode ser usado para criar uma matriz. Use 'new Array()' em vez disso.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "A expressão 'new', cujo destino não tem uma assinatura de constructo, implicitamente tem um tipo 'any'.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' só podem ser usados em um arquivo .ts.", + "options_6024": "opções", + "or_expected_1144": "'{' ou ';' esperado.", + "package_json_does_not_have_a_0_field_6100": "'package.json' não tem um campo '{0}'.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' tem '{0}' campo '{1}' que faz referência a '{2}'.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' só podem ser usados em um arquivo .ts.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "A opção 'paths' é especificada, procurando por um padrão para corresponder ao nome do módulo '{0}'.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "O modificador 'readonly' pode aparecer somente em uma declaração de propriedade ou assinatura de índice.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "A opção 'rootDirs' está configurada, usando-a para resolver o nome de módulo relativo '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' só pode ser referenciado em uma classe derivada.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' pode ser referido somente em membros de classes derivadas ou expressões literais de objeto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' não pode ser referenciado em um nome de propriedade calculado.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' não pode ser referenciado nos argumentos do construtor.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' é permitido somente em membros de expressões literais de objeto quando a opção 'target' é 'ES2015' ou maior.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "'super' deve ser chamado antes de acessar uma propriedade de 'super' no construtor de uma classe derivada.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "'super' deve ser chamado antes de acessar 'this' no construtor de uma classe derivada.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' deve ser seguido por um acesso de membro ou lista de argumentos.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "O acesso à propriedade 'super' só é permitido em um construtor, em funções de membros ou acessadores de membros de uma classe derivada.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' não pode ser referenciado em um nome de propriedade calculado.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' não pode ser referenciado em um corpo de módulo ou de namespace.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' não pode ser referenciado em um inicializador de propriedade estática.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "'this' não pode ser referenciado em argumentos de construtor.", + "this_cannot_be_referenced_in_current_location_2332": "'this' não pode ser referenciado no local atual.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' implicitamente tem o tipo 'any' porque não tem uma anotação de tipo.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' só podem ser usados em um arquivo .ts.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' só podem ser usados em um arquivo .ts.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' só podem ser usadas em um arquivo .ts.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' só podem ser usadas em um arquivo .ts.", + "types_can_only_be_used_in_a_ts_file_8010": "'types' só podem ser usados em um arquivo .ts.", + "unique_symbol_types_are_not_allowed_here_1335": "tipos de 'símbolo exclusivo' não são permitidos aqui.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "tipos de 'símbolo exclusivo' são permitidos apenas em variáveis em uma declaração de variável.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "tipos de 'símbolo exclusivo' não podem ser usados em uma declaração de variável com um nome associado.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "As declarações 'with' não são permitidas em blocos de funções assíncronas.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Instruções 'with' não são permitidas no modo estrito.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "As expressões 'yield' não podem ser usadas em inicializadores de parâmetros." +} \ No newline at end of file diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..87c1a2224221d --- /dev/null +++ b/lib/ru/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "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_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}\".", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Выражение с запятой запрещено в имени вычисляемого свойства.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Имя вычисляемого свойства не может ссылаться на параметр типа из содержащего его типа.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Имя вычисляемого свойства в объявлении свойств класса должно ссылаться на выражение, тип которого — литерал или уникальный символ.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Имя вычисляемого свойства в перегрузке метода должно ссылаться на выражение, тип которого — литерал или уникальный символ.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Имя вычисляемого свойства в литерале должно ссылаться на выражение, тип которого — литерал или уникальный символ.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Имя вычисляемого свойства в окружающем контексте должно ссылаться на выражение, тип которого — литерал или уникальный символ.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Имя вычисляемого свойства в интерфейсе должно ссылаться на выражение, тип которого — литерал или уникальный символ.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Имя вычисляемого свойства должно иметь тип string, number, symbol или any.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Имя вычисляемого свойства в форме \"{0}\" должно иметь тип symbol.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Доступ к элементу перечисления констант может осуществляться только с использованием строкового литерала.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Инициализатор const в окружающем контексте должен быть строковым или цифровым литералом.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Конструктор не может содержать вызов \"super\", если его класс расширяет \"null\".", + "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": "Модификатор declare необходим для объявления верхнего уровня в D.TS-файле.", + "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_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\".", + "A_file_cannot_have_a_reference_to_itself_1006": "Файл не может содержать ссылку на самого себя.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Оператор for-await-of разрешено использовать только в асинхронной функции или в асинхронном генераторе.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Функция, возвращающая \"never\", не может иметь доступную конечную точку.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Функция, которая вызывается с ключевым словом new, не может иметь тип this со значением void.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Функция, объявленный тип которой не является void или any, должна возвращать значение.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Генератор не может иметь аннотацию типа void.", + "A_get_accessor_cannot_have_parameters_1054": "Метод доступа get не может иметь параметров.", + "A_get_accessor_must_return_a_value_2378": "Метод доступа get должен возвращать значение.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Инициализатор элемента в объявлении перечисления не может ссылаться на элементы, объявленные после него, включая элементы, определенные в других перечислениях.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Класс примеси должен иметь конструктор с одиночным параметром REST типа any[].", + "A_module_cannot_have_multiple_default_exports_2528": "Модуль не может иметь несколько импортов по умолчанию.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Объявление пространства имен и класс или функция, с которыми оно объединено, не могут находится в разных файлах.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Объявление пространства имен не может располагаться раньше класса или функции, с которыми оно объединено.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Объявление пространства имен разрешено использовать только в пространстве имен или модуле.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Инициализатор параметра разрешено использовать только в реализации функции или конструктора.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Свойство параметра невозможно объявить с помощью параметра REST.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Свойство параметра допускается только в реализации конструктора.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Свойство параметра невозможно объявить с помощью шаблона привязки.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Путь в параметре extends должен быть относительным или указанным от корня, но \"{0}\" не является ни тем ни другим.", + "A_promise_must_have_a_then_method_1059": "Класс promise должен содержать метод then.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Свойство класса, тип которого — уникальный символ, должно быть задано как \"static\" и \"readonly\".", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Свойство интерфейса или литерала, тип которого — уникальный символ, должно быть задано как \"readonly\".", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Обязательный параметр не должен следовать за необязательным.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Элемент rest не может содержать шаблон привязки.", + "A_rest_element_cannot_have_an_initializer_1186": "Элемент rest не может содержать инициализатор.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Элемент REST должен быть последним в шаблоне деструктуризации.", + "A_rest_parameter_cannot_be_optional_1047": "Параметр rest не может быть необязательным.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Параметр rest не может иметь инициализатор.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Параметр rest должен стоять на последнем месте в списке параметров.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Параметр rest должен иметь тип массива.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Оператор return можно использовать только в теле функции.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Серия записей, которая повторно сопоставляет импорты с расположениями поиска, заданными относительно baseUrl.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Метод доступа set не может иметь заметку с типом возвращаемого значения.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Метод доступа set не может иметь необязательный параметр.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Метод доступа set не может иметь параметр rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "У метода доступа set должен быть ровно один параметр.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Параметр метода доступа set не может иметь инициализатор.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Сигнатура с реализацией не может использовать тип строкового литерала.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Вызов super должен быть первой инструкцией в конструкторе, если класс содержит инициализированные свойства или свойства параметров.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Условие типа this несовместимо с условием типа на основе параметров.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Тип this доступен только в нестатическом элементе класса или интерфейса.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Файл tsconfig.json уже определен в \"{0}\".", + "A_tuple_type_element_list_cannot_be_empty_1122": "Список элементов типа кортежа не может быть пустым.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Выражение утверждения типа не допускается в левой части выражения, возводимого в степень. Попробуйте заключить выражение в скобки.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Свойство литерала типа не может иметь инициализатор.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Предикат типов не может ссылаться на параметр rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Предикат типов не может ссылаться на элемент \"{0}\" в шаблоне привязки.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Предикат типов разрешено использовать только в позиции типа возвращаемого значения для функций и методов.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Тип предиката типа должен быть доступным для назначения этому типу параметра.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Переменная типа \"уникальный символ\" должна быть задана как \"const\".", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Выражение yield разрешено использовать только в теле генератора.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Невозможно получить доступ к абстрактному методу \"{0}\" класса \"{1}\" с помощью выражения super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Абстрактные методы могут использоваться только в абстрактных классах.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Абстрактное свойство \"{0}\" в классе \"{1}\" недоступно в конструкторе.", + "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": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\".", + "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\".", + "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\".", + "Add_this_to_unresolved_variable_90008": "Добавление \"this.\" к неразрешенной переменной.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Добавление файла 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_type_parameters_2428": "Все объявления \"{0}\" должны иметь одинаковые параметры типа.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.", + "Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.", + "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_abstract_accessor_cannot_have_an_implementation_1318": "У абстрактного метода доступа не может быть реализации.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Метод доступа нельзя объявить в окружающем контексте.", + "An_accessor_cannot_have_type_parameters_1094": "Метод доступа не может иметь параметры типа.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Объявление окружающего модуля разрешено использовать только в рамках верхнего уровня файла.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Арифметический операнд должен иметь тип any, number или тип перечисления.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Асинхронной функции или методу ES5/ES3 требуется конструктор Promise. Убедитесь, что имеется объявление для конструктора Promise или включите ES2015 в параметр \"--lib\".", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Асинхронная функция или метод должны иметь допустимый тип возвращаемого значения, поддерживающий ожидание.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Асинхронная функция или метод должны вернуть Promise. Убедитесь, что у вас есть объявление для Promise или включите ES2015 в параметр --lib.", + "An_async_iterator_must_have_a_next_method_2519": "В асинхронном итераторе должен быть метод next().", + "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_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 включительно.", + "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_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": "Сигнатура индекса не может иметь параметр rest.", + "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_initializer_1020": "Параметр сигнатуры индекса не может содержать инициализатор.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "У параметра сигнатуры индекса должна быть аннотация типа.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Параметр сигнатуры индекса должен иметь тип string или number.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Интерфейс может расширить только идентификатор или полное имя с дополнительными аргументами типа.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Интерфейс может расширять только класс или другой интерфейс.", + "An_interface_property_cannot_have_an_initializer_1246": "Свойство интерфейса не может иметь инициализатор.", + "An_iterator_must_have_a_next_method_2489": "Итератор должен иметь метод \"next()\".", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Объектный литерал не может иметь несколько методов доступа get/set с одинаковым именем.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Объектный литерал не может иметь несколько свойств с одинаковым именем в строгом режиме.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Объектный литерал не может иметь свойство и метод доступа с одинаковым именем.", + "An_object_member_cannot_be_declared_optional_1162": "Элемент объекта не может быть объявлен необязательным.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Сигнатура перегрузки не может быть объявлена в качестве генератора.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Унарное выражение с оператором \"{0}\" не допускается в левой части выражения, возводимого в степень. Попробуйте заключить выражение в скобки.", + "Annotate_with_type_from_JSDoc_95009": "Заметка с типом из JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Заметки с типами из JSDoc", + "Argument_expression_expected_1135": "Ожидалось выражение аргумента.", + "Argument_for_0_option_must_be_Colon_1_6046": "Аргумент для параметра \"{0}\" должен быть {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Аргумент типа \"{0}\" нельзя назначить параметру типа \"{1}\".", + "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, если они отображаются в окружающем контексте.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Автообнаружение для вводимых данных включено в проекте \"{0}\". Идет запуск дополнительного этапа разрешения для модуля \"{1}\" с использованием расположения кэша \"{2}\".", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Выражения базового класса не могут ссылаться на параметры типа класса.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Тип возвращаемого значения конструктора базового класса \"{0}\" не является классом или типом интерфейса.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Конструкторы базового класса должны иметь одинаковые типы возвращаемых значений.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Базовый каталог для разрешения неабсолютных имен модуля.", + "Basic_Options_6172": "Базовые параметры", + "Binary_digit_expected_1177": "Ожидался бит.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Элемент привязки \"{0}\" имеет неявный тип \"{1}\".", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Переменная \"{0}\" с областью видимости, ограниченной блоком, использована перед своим объявлением.", + "Call_decorator_expression_90028": "Вызов выражения-декоратора.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Сигнатура вызова, у которой нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения any.", + "Call_target_does_not_contain_any_signatures_2346": "Объект вызова не содержит сигнатуры.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Не удается получить доступ к {0}.{1}, так как {0} является типом, но не является пространством имен. Вы хотели получить тип свойства {1} в {0} с использованием {0}[\"{1}\"]?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Не удается назначить тип конструктора \"{0}\" для типа конструктора \"{1}\".", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Не удается назначить тип конструктора абстрактного класса для типа конструктора класса, не являющегося абстрактным.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Не удается задать значение для \"{0}\", так как это константа или свойство, доступное только для чтения.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Не удается задать значение для \"{0}\", так как это не переменная.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Не удается улучшить модуль \"{0}\", так как он разрешается в немодульную сущность.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Невозможно добавить экспорт значений в модуль \"{0}\", так как он разрешается в немодульную сущность.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Невозможно скомпилировать модули с использованием параметра \"{0}\", если флаг \"--module\" не имеет значения \"amd\" или \"system\".", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "Невозможно скомпилировать пространства имен, если задан флаг \"--isolatedModules\".", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Невозможно создать экземпляр абстрактного класса.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Не удается экспортировать \"{0}\". Только локальные объявления можно экспортировать из модуля.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Не удается расширить класс \"{0}\". Конструктор класса помечен как частный.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Не удается расширить интерфейс \"{0}\". Вы имели в виду \"реализует\"?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Не удается найти файл tsconfig.json в указанном каталоге: \"{0}\".", + "Cannot_find_global_type_0_2318": "Не удается найти глобальный тип \"{0}\".", + "Cannot_find_global_value_0_2468": "Не удается найти глобальное значение \"{0}\".", + "Cannot_find_module_0_2307": "Не удается найти модуль \"{0}\".", + "Cannot_find_name_0_2304": "Не удается найти имя \"{0}\".", + "Cannot_find_name_0_Did_you_mean_1_2552": "Не удается найти имя \"{0}\". Вы имели в виду \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Не удается найти имя \"{0}\". Возможно, вы имели в виду элемент экземпляра \"this.{0}\"?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Не удается найти имя \"{0}\". Возможно, вы имели в виду статический элемент \"{1}.{0}\"?", + "Cannot_find_namespace_0_2503": "Не удается найти пространство имен \"{0}\".", + "Cannot_find_parameter_0_1225": "Не удается найти параметр \"{0}\".", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Не удается найти общий путь к подкаталогу для входных файлов.", + "Cannot_find_type_definition_file_for_0_2688": "Не удается найти файл определения типа для \"{0}\".", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Невозможно импортировать файлы объявления типа. Рекомендуется импортировать \"{0}\" вместо \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Невозможно инициализировать переменную \"{0}\" с внешней областью видимости в той же области видимости, что и объявление \"{1}\" с областью видимости \"Блок\".", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Не удается вызвать выражение, в типе которого отсутствует сигнатура вызова. Тип \"{0}\" не содержит совместимые сигнатуры вызова.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Невозможно повторно экспортировать тип, если установлен флажок \"--isolatedModules\".", + "Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".", + "Cannot_redeclare_exported_variable_0_2323": "Не удается повторно объявить экспортированную переменную \"{0}\".", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Невозможно повторно объявить идентификатор \"{0}\" в операторе catch.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Невозможно использовать JSX, если не задан флаг \"--jsx\".", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Невозможно использовать директивы import, export или приращения модуля, если флаг \"--module\" имеет значение \"none\".", + "Cannot_use_namespace_0_as_a_type_2709": "Невозможно использовать пространство имен \"{0}\" как тип.", + "Cannot_use_namespace_0_as_a_value_2708": "Невозможно использовать пространство имен \"{0}\" как значение.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Невозможно использовать new с выражением, у типа которого нет сигнатуры вызова или конструктора.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Не удается записать файл \"{0}\", так как он будет перезаписан несколькими входными файлами.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Не удается записать файл \"{0}\", так как это привело бы к перезаписи входного файла.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Переменная оператора catch не может иметь аннотацию типа.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Переменная оператора catch не может иметь инициализатор.", + "Change_0_to_1_90014": "Замена \"{0}\" на \"{1}\".", + "Change_extends_to_implements_90003": "Измените \"extends\" на \"implements\".", + "Change_spelling_to_0_90022": "Изменить правописание на \"{0}\".", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Идет проверка того, является ли \"{0}\" самым длинным соответствующим префиксом для \"{1}\" — \"{2}\".", + "Circular_definition_of_import_alias_0_2303": "Циклическое определение псевдонима импорта \"{0}\".", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Обнаружена цикличность при разрешении конфигурации: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Класс \"{0}\" определяет метод доступа — элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет его как функцию — элемент экземпляра.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Класс \"{0}\" определяет функцию — элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет ее как метод доступа — элемент экземпляра.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Класс \"{0}\" определяет функцию-элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет ее как свойство-элемент экземпляра.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Класс \"{0}\" определяет свойство-элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет его как функцию-элемент экземпляра.", + "Class_0_incorrectly_extends_base_class_1_2415": "Класс \"{0}\" неправильно расширяет базовый класс \"{1}\".", + "Class_0_incorrectly_implements_interface_1_2420": "Класс \"{0}\" неправильно реализует интерфейс \"{1}\".", + "Class_0_used_before_its_declaration_2449": "Класс \"{0}\" использован прежде, чем объявлен.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "В объявлении класса не может использоваться более одного тега \"@augments\" или \"@extends\".", + "Class_name_cannot_be_0_2414": "Имя класса не может иметь значение \"{0}\".", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Статическая сторона класса \"{0}\" неправильно расширяет статическую сторону базового класса \"{1}\".", + "Classes_can_only_extend_a_single_class_1174": "Классы могут расширить только один класс.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Классы, содержащие абстрактные методы, должны быть отмечены как абстрактные.", + "Command_line_Options_6171": "Параметры командной строки", + "Compilation_complete_Watching_for_file_changes_6042": "Компиляция завершена. Отслеживание изменений в файлах.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Компиляция проекта по заданному пути к файлу конфигурации или папке с файлом tsconfig.json.", + "Compiler_option_0_expects_an_argument_6044": "Параметр компилятора \"{0}\" ожидает аргумент.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Параметр \"{0}\" компилятора требует значение типа {1}.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Имена вычисляемых свойств запрещены в перечислениях.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Вычисленные значения запрещены в перечислении с членами, имеющими строковые значения.", + "Concatenate_and_emit_output_to_single_file_6001": "Связать и вывести результаты в один файл.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Конфликтующие определения для \"{0}\" найдены в \"{1}\" и \"{2}\". Попробуйте установить конкретную версию этой библиотеки, чтобы устранить конфликт.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Сигнатура конструктора, у которой нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения any.", + "Constructor_implementation_is_missing_2390": "Отсутствует реализация конструктора.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Конструктор класса \"{0}\" является частным и доступным только в объявлении класса.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Конструктор класса \"{0}\" защищен и доступен только в объявлении класса.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Конструкторы производных классов должны содержать вызов super.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Содержащий файл не указан, корневой каталог невозможно определить. Выполняется пропуск поиска в папке node_modules.", + "Convert_function_0_to_class_95002": "Преобразование функции \"{0}\" в класс", + "Convert_function_to_an_ES2015_class_95001": "Преобразование функции в класс ES2015", + "Convert_to_default_import_95013": "Преобразовать в импорт по умолчанию", + "Corrupted_locale_file_0_6051": "Поврежденный файл языкового стандарта \"{0}\".", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Не удалось найти файл объявления модуля \"{0}\". \"{1}\" имеет неявный тип \"any\".", + "Could_not_write_file_0_Colon_1_5033": "Не удалось записать файл \"{0}\": \"{1}\".", + "DIRECTORY_6038": "КАТАЛОГ", + "Declaration_expected_1146": "Ожидалось объявление.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Имя объявления конфликтует со встроенным глобальным идентификатором \"{0}\".", + "Declaration_or_statement_expected_1128": "Ожидалось объявление или оператор.", + "Declare_method_0_90023": "Объявите метод \"{0}\".", + "Declare_property_0_90016": "Объявите свойство \"{0}\".", + "Declare_static_method_0_90024": "Объявите статический метод \"{0}\".", + "Declare_static_property_0_90027": "Объявление статического свойства \"{0}\".", + "Decorators_are_not_valid_here_1206": "Декораторы здесь недопустимы.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Декораторы нельзя применять к множественным методам доступа get или set с совпадающим именем.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Экспорт модуля по умолчанию использует или имеет закрытое имя \"{0}\".", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Устарело.] Используйте --jsxFactory. Укажите объект, вызываемый для createElement при целевом порождении JSX react", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Устарело.] Используйте --outFile. Сцепление и порождение выходных данных в одном файле", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Устарело.] Используйте --skipLibCheck. Пропуск проверки типов для файлов объявления библиотеки по умолчанию.", + "Digit_expected_1124": "Ожидалась цифра.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Каталога \"{0}\" не существует. Поиск в нем будет пропускаться.", + "Disable_checking_for_this_file_90018": "Отключить проверку для этого файла.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Отключение ограничений на размеры в проектах JavaScript.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Отключить строгую проверку универсальных сигнатур в типах функций.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Запретить ссылки с разным регистром, указывающие на один файл.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Не добавлять ссылки с тройной косой чертой или импортированные модули в список скомпилированных файлов.", + "Do_not_emit_comments_to_output_6009": "Не создавать комментарии в выходных данных.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Не создавать объявления для кода, имеющего аннотацию \"@internal\".", + "Do_not_emit_outputs_6010": "Не создавать выходные данные.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Не выводить выходные элементы, если есть ошибки.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Не порождать директивы use strict в выходных данных модуля.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Не удалять объявления перечислений констант из сгенерированного кода.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Не создавать вспомогательные пользовательские функции, такие как __extends, в скомпилированных выходных данных.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Не включать файл библиотеки по умолчанию (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Не сообщать об ошибках в недостижимом коде.", + "Do_not_report_errors_on_unused_labels_6074": "Не сообщать об ошибках в неиспользуемых метках.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Не разрешать реальный путь symlink.", + "Do_not_truncate_error_messages_6165": "Не усекать сообщения об ошибках.", + "Duplicate_declaration_0_2718": "Дублирующееся объявление \"{0}\".", + "Duplicate_function_implementation_2393": "Повторяющаяся реализация функции.", + "Duplicate_identifier_0_2300": "Повторяющийся идентификатор \"{0}\".", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Повторяющийся идентификатор \"{0}\". Компилятор резервирует имя \"{1}\" в области верхнего уровня модуля.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Повторяющийся идентификатор \"{0}\". Компилятор резервирует имя \"{1}\" в области верхнего уровня для асинхронных функций в модуле.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Повторяющийся идентификатор \"{0}\". Компилятор использует объявление \"{1}\" для поддержки асинхронных функций.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Повторяющийся идентификатор arguments. Компилятор использует arguments для инициализации параметров \"rest\".", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Дублирующийся идентификатор \"_newTarget\". Компилятор использует объявление переменной \"_newTarget\" для получения ссылки на метасвойство \"new.target\".", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Повторяющийся идентификатор \"_super\". Компилятор использует \"_super\" для получения ссылки на базовый класс.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Повторяющийся идентификатор \"_this\". Компилятор использует объявление переменной \"_this\" для получения ссылки this.", + "Duplicate_label_0_1114": "Повторяющаяся метка \"{0}\".", + "Duplicate_number_index_signature_2375": "Повторяющаяся сигнатура числового индекса.", + "Duplicate_string_index_signature_2374": "Повторяющаяся сигнатура строкового индекса.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Динамический импорт не может использоваться с модулями ECMAScript 2015.", + "Dynamic_import_cannot_have_type_arguments_1326": "При динамическом импорте не могут использоваться аргументы типов", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "При динамическом импорте необходимо указать один описатель в качестве аргумента.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Описатель динамического импорта должен иметь тип \"string\", но имеет тип \"{0}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Элемент неявно содержит тип any, так как выражение индекса не имеет тип number.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Элемент неявно имеет тип any, так как тип \"{0}\" не содержит сигнатуру индекса.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Порождать метку порядка байтов UTF-8 в начале выходных файлов.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Порождать один файл с сопоставлениями источников, а не создавать отдельный файл.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Порождать источник вместе с sourcemap в одном файле (нужно задать параметр --inlineSourceMap или --sourceMap).", + "Enable_all_strict_type_checking_options_6180": "Включить все параметры строгой проверки типов.", + "Enable_strict_checking_of_function_types_6186": "Включение строгой проверки типов функций.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.", + "Enable_strict_null_checks_6113": "Включить строгие проверки NULL.", + "Enable_tracing_of_the_name_resolution_process_6085": "Включить трассировку процесса разрешения имен.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Включает экспериментальную поддержку для асинхронных функций ES7.", + "Enables_experimental_support_for_ES7_decorators_6065": "Включает экспериментальную поддержку для декораторов ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Включает экспериментальную поддержку для создания метаданных типа для декораторов.", + "Enum_0_used_before_its_declaration_2450": "Перечисление \"{0}\" использовано прежде, чем объявлено.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Все объявления перечислений должны иметь значение const или отличное от const.", + "Enum_member_expected_1132": "Ожидался элемент перечисления.", + "Enum_member_must_have_initializer_1061": "У элемента перечисления должен быть инициализатор.", + "Enum_name_cannot_be_0_2431": "Имя перечисления не может иметь значение \"{0}\".", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Тип перечисления \"{0}\" имеет элементы с инициализаторами, которые не являются литералами.", + "Examples_Colon_0_6026": "Примеры: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Чрезмерная глубина стека при сравнении типов \"{0}\" и \"{1}\".", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Ожидается аргументов типа: {0}–{1}. Укажите их с тегом \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "Ожидалось аргументов: {0}, получено: {1}.", + "Expected_0_arguments_but_got_1_or_more_2556": "Ожидалось аргументов: {0}, получено: {1} или больше.", + "Expected_0_type_arguments_but_got_1_2558": "Ожидались аргументы типа {0}, получены: {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Ожидается аргументов типа: {0}. Укажите их с тегом \"@extends\".", + "Expected_at_least_0_arguments_but_got_1_2555": "Ожидалось аргументов не менее: {0}, получено: {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Ожидалось аргументов не меньше: {0}, получено: {1} или больше.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Ожидался соответствующий закрывающий тег JSX для \"{0}\".", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Ожидался соответствующий закрывающий тег фрагмента JSX.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Ожидаемый тип поля \"{0}\" в package.json должен быть string, получен \"{1}\".", + "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_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}\" не является модулем. Обратитесь к автору пакета для обновления определения пакета.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Файл экспортированных внешних типизаций пакета не может содержать ссылки с тройной косой чертой. Обратитесь к автору пакета для обновления определения пакета.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Экспортированный псевдоним типа \"{0}\" имеет или использует закрытое имя \"{1}\".", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Экспортированная переменная \"{0}\" имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именована.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Экспортированная переменная \"{0}\" имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Экспортированная переменная \"{0}\" имеет или использует закрытое имя \"{1}\".", + "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\", который используется компилятором для получения ссылки на базовый класс.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Разрешение выражения дает объявление переменной \"{0}\", которое используется компилятором для поддержки асинхронных функций.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Выражение разрешается в объявление переменной \"_newTarget\", которое компилятор использует для получения ссылки на метасвойство \"new.target\".", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Разрешение выражения дает объявление переменной \"_this\", которое используется компилятором для получения ссылки this.", + "Extract_constant_95006": "Извлечь константу", + "Extract_function_95005": "Извлечь функцию", + "Extract_symbol_95003": "Извлечь символ", + "Extract_to_0_in_1_95004": "Извлечь в {0} в {1}", + "Extract_to_0_in_1_scope_95008": "Извлечь в {0} в области {1}", + "Extract_to_0_in_enclosing_scope_95007": "Извлечь в {0} во включающей области", + "FILE_6035": "ФАЙЛ", + "FILE_OR_DIRECTORY_6040": "Файл или каталог", + "Failed_to_parse_file_0_Colon_1_5014": "Не удалось проанализировать файл \"{0}\": {1}.", + "Fallthrough_case_in_switch_7029": "Случай передачи управления в операторе switch.", + "File_0_does_not_exist_6096": "Файл \"{0}\" не существует.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "Файл \"{0}\" существует — используйте его как результат разрешения имени.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "Файл \"{0}\" имеет неподдерживаемое разрешение, поэтому будет пропущен.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Файл \"{0}\" имеет неподдерживаемое расширение. Поддерживаются только следующие расширения: {1}.", + "File_0_is_not_a_module_2306": "Файл \"{0}\" не является модулем.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Файл \"{0}\" отсутствует в \"rootDir\" \"{1}\". Все исходные файлы должны находиться в каталоге \"rootDir\".", + "File_0_not_found_6053": "Файл \"{0}\" не найден.", + "File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Файл с именем \"{0}\" отличается от уже включенного файла с именем \"{1}\" только регистром.", + "File_name_0_has_a_1_extension_stripping_it_6132": "У имени файла \"{0}\" есть расширение \"{1}\"; расширение удаляется.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Спецификация файла не может содержать родительский каталог (\"..\"), который указывается после рекурсивного подстановочного знака каталога (\"**\"): \"{0}\".", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Спецификация файла не может содержать несколько рекурсивных подстановочных знаков каталога (\"**\"): \"{0}\".", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Спецификация файла не может заканчиваться рекурсивным подстановочным знаком каталога (\"**\"): \"{0}\".", + "Found_package_json_at_0_6099": "Обнаружен package.json в \"{0}\".", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5. Определения класса автоматически появляются в строгом режиме.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5. Модули автоматически появляются в строгом режиме.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Выражение функции, у которого нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения \"{0}\".", + "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_overload_must_be_static_2387": "Перегрузка функции должна быть статической.", + "Function_overload_must_not_be_static_2388": "Перегрузка функции не должна быть статической.", + "Generates_corresponding_d_ts_file_6002": "Создает соответствующий D.TS-файл.", + "Generates_corresponding_map_file_6043": "Создает соответствующий файл с расширением \".map\".", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Генератор неявно имеет тип \"{0}\", поскольку он не предоставляет никаких значений. Рекомендуется указать тип возвращаемого значения.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Генераторы не разрешается использовать в окружающем контексте.", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Генераторы доступны только при разработке для ECMAScript 2015 или более поздних версий.", + "Generic_type_0_requires_1_type_argument_s_2314": "Универсальный тип \"{0}\" требует следующее число аргументов типа: {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Универсальный тип \"{0}\" требует аргументы типа от {1} до {2}.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Создание экземпляров универсального типа слишком глубокое и, возможно, бесконечное.", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Методы доступа get и set не согласуются с точки зрения видимости.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Глобальные операции экспорта модуля могут появиться только на верхнем уровне.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Глобальные операции экспорта модуля могут появиться только в файлах объявления.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Глобальные операции экспорта модуля могут появиться только в файлах модуля.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Глобальный тип \"{0}\" должен быть классом или интерфейсом.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Глобальный тип \"{0}\" должен иметь следующее число параметров типа: {1}.", + "Hexadecimal_digit_expected_1125": "Ожидалась шестнадцатеричная цифра.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме. Определения классов автоматически находятся в строгом режиме.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме. Модули автоматически находятся в строгом режиме.", + "Identifier_expected_1003": "Ожидался идентификатор.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Ожидался идентификатор. Значение \"__esModule\" зарезервировано как экспортируемый маркер при преобразовании модулей ECMAScript.", + "Ignore_this_error_message_90019": "Пропустить это сообщение об ошибке.", + "Implement_inherited_abstract_class_90007": "Реализуйте унаследованный абстрактный класс.", + "Implement_interface_0_90006": "Реализуйте интерфейс \"{0}\".", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Предложение Implements экспортированного класса \"{0}\" имеет или использует закрытое имя \"{1}\".", + "Import_0_from_module_1_90013": "Импорт \"{0}\" из модуля \"{1}\".", + "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": "Объявления импорта в пространстве имен не могут иметь ссылки на модуль.", + "Import_emit_helpers_from_tslib_6139": "Импорт вспомогательных объектов, участвующих в порождении, из \"tslib\".", + "Import_name_cannot_be_0_2438": "Имя импорта не может иметь значение \"{0}\".", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Объявление импорта или экспорта во объявлении окружающего модуля не может иметь ссылки на модуль через относительное имя модуля.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Операции импорта запрещены в улучшениях модуля. Попробуйте переместить их в содержащий внешний модуль.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Во внешних объявлениях перечислений инициализатор элемента должен быть константным выражением.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "В перечислении с несколькими объявлениями только одно объявление может опустить инициализатор для своего первого элемента перечисления.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "В инициализаторе элементов объявлений перечисления const должно быть константным выражением.", + "Index_signature_in_type_0_only_permits_reading_2542": "Сигнатура индекса в типе \"{0}\" разрешает только чтение.", + "Index_signature_is_missing_in_type_0_2329": "В типе \"{0}\" отсутствует сигнатура индекса.", + "Index_signatures_are_incompatible_2330": "Сигнатуры индекса несовместимы.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Все отдельные объявления в объединенном объявлении \"{0}\" должны быть экспортированными или локальными.", + "Infer_parameter_types_from_usage_95012": "Вывод типов параметров на основе использования.", + "Infer_type_of_0_from_usage_95011": "Вывод типа \"{0}\" на основе использования.", + "Initialize_property_0_in_the_constructor_90020": "Инициализировать свойство \"{0}\" в конструкторе.", + "Initialize_static_property_0_90021": "Инициализировать статическое свойство \"{0}\".", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Инициализатор переменной-элемента экземпляра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный в конструкторе.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Инициализатор параметра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный после него.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Инициализатор не предоставляет значения для элемента привязки, который не имеет значения по умолчанию.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Инициализаторы не разрешены в окружающих контекстах.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Инициализирует проект TypeScript и создает файл \"tsconfig.json\".", + "Insert_command_line_options_and_files_from_a_file_6030": "Вставка параметров командной строки и файлов из файла.", + "Install_0_95014": "Установить \"{0}\"", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Интерфейс \"{0}\" не может одновременно расширить типы \"{1}\" и \"{2}\".", + "Interface_0_incorrectly_extends_interface_1_2430": "Интерфейс \"{0}\" неправильно расширяет интерфейс \"{1}\".", + "Interface_declaration_cannot_have_implements_clause_1176": "Объявление интерфейса не может иметь предложение implements.", + "Interface_name_cannot_be_0_2427": "Имя интерфейса не может иметь значение \"{0}\".", + "Invalid_character_1127": "Недопустимый символ.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Недопустимое имя модуля в приращении. Модуль \"{0}\" разрешается в модуль без типа в \"{1}\", который невозможно дополнить.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Недопустимое имя модуля в улучшении, не удается найти модуль \"{0}\".", + "Invalid_reference_directive_syntax_1084": "Недопустимый синтаксис директивы reference.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Недопустимое использование \"{0}\". Определения классов автоматически находятся в строгом режиме.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Недопустимое использование \"{0}\". Модули автоматически находятся в строгом режиме.", + "Invalid_use_of_0_in_strict_mode_1100": "Недопустимое использование \"{0}\" в строгом режиме.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Недопустимое значение для jsxFactory. \"{0}\" не является допустимым идентификатором или полным именем.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Недопустимое значение для \"--reactNamespace\". \"{0}\" не является допустимым идентификатором.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Параметр \"@{0} {1}\" JSDoc не соответствует предложению \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "Параметр \"@{0}\" JSDoc не связан с классом.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc \"...\" может использоваться только в последнем параметре сигнатуры.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "У тега \"@param\" JSDoc есть имя \"{0}\", но параметр с таким именем отсутствует.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "У тега \"@typedef\" JSDoc должна быть аннотация типа, или после него должны стоять теги \"@property\" или \"@member\".", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Типы JSDoc можно использовать только в комментариях в документации.", + "JSX_attribute_expected_17003": "Ожидался атрибут JSX.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Атрибутам JSX должно назначаться только непустое \"expression\".", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Элемент JSX \"{0}\" не содержит соответствующий закрывающий тег.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "Тип атрибутов элемента JSX \"{0}\" не может быть типом объединения.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Класс элементов JSX не поддерживает атрибуты, так как не имеет свойства \"{0}\".", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Элемент JSX неявно имеет тип \"any\", так как интерфейс \"JSX.{0}\" не существует.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Элемент JSX неявно имеет тип any, так как глобальный тип \"JSX.Element\" не существует.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Тип элемента JSX \"{0}\" не имеет конструкций или сигнатур вызова.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "Тип элемента JSX \"{0}\" не является функцией конструктора для элементов JSX.", + "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_jsxFactory_17016": "Фрагмент JSX не поддерживается при использовании --jsxFactory", + "JSX_spread_child_must_be_an_array_type_2609": "Дочерний объект расширения JSX должен иметь тип массива.", + "Jump_target_cannot_cross_function_boundary_1107": "Целевой объект перехода не может находиться за границей функции.", + "KIND_6034": "ВИД", + "LOCATION_6037": "РАСПОЛОЖЕНИЕ", + "Language_service_is_disabled_9004": "Языковая служба отключена.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Сторона оператора слева от запятой не используется и не имеет побочных эффектов.", + "Line_break_not_permitted_here_1142": "Здесь запрещено использовать разрыв строки.", + "Line_terminator_not_permitted_before_arrow_1200": "Перед стрелкой запрещен символ завершения строки.", + "List_of_folders_to_include_type_definitions_from_6161": "Список папок, определения типов из которых будут включены.", + "List_of_language_service_plugins_6181": "Список подключаемых модулей языковой службы.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Список корневых папок, объединенное содержимое которых представляет структуру проекта во время выполнения.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Загружается \"{0}\" из корневого каталога \"{1}\"; расположение кандидата: \"{2}\".", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "Загружается модуль \"{0}\" из папки \"node_modules\", тип целевого файла: \"{1}\".", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Загружается модуль в виде файла или папки, расположение модуля-кандидата: \"{0}\", тип целевого файла: \"{1}\".", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Языковой стандарт должен иметь форму <язык> или <язык>–<территория>. Например, \"{0}\" или \"{1}\".", + "Longest_matching_prefix_for_0_is_1_6108": "Самый длинный соответствующий префикс для \"{0}\": \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Поиск в папке node_modules; первоначальное расположение: \"{0}\".", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Сделайте вызов \"super()\" первой инструкцией в конструкторе.", + "Member_0_implicitly_has_an_1_type_7008": "Элемент \"{0}\" неявно имеет тип \"{1}\".", + "Merge_conflict_marker_encountered_1185": "Встретилась отметка о конфликте слияния.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Объединенное объявление \"{0}\" не может включать объявление экспорта по умолчанию. Рекомендуется добавить вместо него отдельное объявление \"export default {0}\".", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Метасвойство \"{0}\" разрешено только в тексте объявления функции, выражения функции или конструктора.", + "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}\" экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Метод \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Modifiers_cannot_appear_here_1184": "Здесь невозможно использовать модификаторы.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Модуль {0} уже экспортировал элемент с именем \"{1}\". Попробуйте явно повторно экспортировать его, чтобы устранить неоднозначность.", + "Module_0_has_no_default_export_1192": "У модуля \"{0}\" нет экспорта по умолчанию.", + "Module_0_has_no_exported_member_1_2305": "Модуль \"{0}\" не имеет экспортированного элемента \"{1}\".", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Модуль \"{0}\" скрыт локальным объявлением с таким же именем.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "Модуль \"{0}\" разрешается в немодульную сущность и не может быть импортирован с помощью этой конструкции.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Модуль \"{0}\" использует параметр \"export =\" и не может использоваться с параметром \"export *\".", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Модуль \"{0}\" был разрешен в окружающий модуль, объявленный в \"{1}\", так как этот файл не был изменен.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Модуль \"{0}\" был разрешен как локально объявленный окружающий модуль в файле \"{1}\".", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Модуль \"{0}\" был разрешен как \"{1}\", но параметр \"--jsx\" не задан.", + "Module_Resolution_Options_6174": "Параметры разрешения модулей", + "Module_name_0_matched_pattern_1_6092": "Имя модуля \"{0}\", соответствующий шаблон \"{1}\".", + "Module_name_0_was_not_resolved_6090": "======== Имя модуля \"{0}\" не было разрешено. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Имя модуля \"{0}\" было успешно разрешено в \"{1}\". ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Тип разрешения модуля не указан, используется \"{0}\".", + "Module_resolution_using_rootDirs_has_failed_6111": "Произошел сбой при разрешении модуля с помощью \"rootDirs\".", + "Multiple_constructor_implementations_are_not_allowed_2392": "Не разрешается использование нескольких реализаций конструкторов.", + "NEWLINE_6061": "НОВАЯ СТРОКА", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Именованное свойство \"{0}\" содержит типы \"{1}\" и \"{2}\", которые не являются идентичными.", + "Namespace_0_has_no_exported_member_1_2694": "Пространство имен \"{0}\" не содержит экспортированный элемент \"{1}\".", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Ни один конструктор базового класса не имеет указанного числа аргументов типа.", + "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": "Не все пути кода возвращают значение.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".", + "Object_is_possibly_null_2531": "Возможно, объект равен null.", + "Object_is_possibly_null_or_undefined_2533": "Возможно, объект равен null или undefined.", + "Object_is_possibly_undefined_2532": "Возможно, объект равен undefined.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Объектный литерал может использовать только известные свойства. \"{0}\" не существует в типе \"{1}\".", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Объектный литерал может указывать только известные свойства, но \"{0}\" не существует в типе \"{1}\". Вы хотели записать \"{2}\"?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Свойство объектного литерала \"{0}\" неявно имеет тип \"{1}\".", + "Octal_digit_expected_1178": "Ожидалась восьмеричная цифра.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Литералы восьмеричного типа должны использовать синтаксис ES2015. Используйте синтаксис \"{0}\".", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Восьмеричные литералы запрещены в инициализаторах членов перечисления. Используйте синтаксис \"{0}\".", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Восьмеричные литералы запрещено использовать в строгом режиме.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Восьмеричные литералы недоступны при выборе целевой платформы ECMAScript 5 и более поздних. Используйте синтаксис \"{0}\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "В операторе for...in разрешено только одно объявление переменной.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "В операторе for...of разрешено только одно объявление переменной.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "С помощью ключевого слова new можно вызвать только функцию void.", + "Only_ambient_modules_can_use_quoted_names_1035": "Имена в кавычках могут использоваться только во внешних модулях.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Только модули amd и system поддерживаются вместе с --{0}.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "В предложениях extends класса сейчас поддерживаются только идентификаторы или полные имена с необязательными аргументами типа.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Через ключевое слово super доступны только общие и защищенные методы базового класса.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Оператор \"{0}\" невозможно применить к типам \"{1}\" и \"{2}\".", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "Параметр \"{0}\" можно указать только в файле tsconfig.json.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Параметр \"{0}\" можно использовать только при указании \"--inlineSourceMap\" или \"--sourceMap\".", + "Option_0_cannot_be_specified_with_option_1_5053": "Параметр \"{0}\" невозможно указать с помощью параметра \"{1}\".", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Параметр \"{0}\" невозможно указать без указания параметра \"{1}\".", + "Option_0_should_have_array_of_strings_as_a_value_6103": "Параметр \"{0}\" должен иметь массив строк в качестве значения.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Параметр isolatedModules можно использовать, только если указан параметр --module или если параметр target — ES2015 или выше.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Параметр paths невозможно использовать без указания параметра \"--baseUrl\".", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Параметр project не может быть указан вместе с исходными файлами в командной строке.", + "Options_Colon_6027": "Параметры:", + "Output_directory_for_generated_declaration_files_6166": "Выходной каталог для создаваемых файлов объявления.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Сигнатура перегрузки несовместима с реализацией функции.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Сигнатуры перегрузки должны быть абстрактными или неабстрактными.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Все сигнатуры перегрузки должны быть либо внешними, либо не внешними.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Сигнатуры перегрузки должны быть экспортированы и не экспортированы.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Все сигнатуры перегрузки должны быть либо необязательными, либо обязательными.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Все сигнатуры перегрузки должны быть либо общими, либо закрытыми, либо защищенными.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "На параметр \"{0}\" невозможно ссылаться в его инициализаторе.", + "Parameter_0_implicitly_has_an_1_type_7006": "Параметр \"{0}\" неявно имеет тип \"{1}\".", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Параметр \"{0}\" находится в позиции, отличной от позиции параметра \"{1}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Параметр \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Параметр \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Параметр \"{0}\" конструктора из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Параметр \"{0}\" конструктора из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Параметр \"{0}\" конструктора из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Параметр \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Параметр \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Параметр \"{0}\" экспортированной функции имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Параметр \"{0}\" экспортированной функции имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Параметр \"{0}\" экспортированной функции имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Параметр \"{0}\" сигнатуры индекса из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Параметр \"{0}\" сигнатуры индекса из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Параметр \"{0}\" метода из экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Параметр \"{0}\" метода из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Параметр \"{0}\" общего метода из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Параметр \"{0}\" общего метода из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Параметр \"{0}\" общего метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Параметр \"{0}\" общего статического метода из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Параметр \"{0}\" общего статического метода из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Параметр \"{0}\" общего статического метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Параметр не может содержать вопросительный знак и инициализатор.", + "Parameter_declaration_expected_1138": "Ожидалось объявление параметра.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Тип параметра открытого метода задания \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Тип параметра открытого метода задания \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Тип параметра открытого статического метода задания \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Тип параметра открытого статического метода задания \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Анализ в строгом режиме и создание директивы \"use strict\" для каждого исходного файла.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Шаблон \"{0}\" может содержать не больше одного символа \"*\".", + "Prefix_0_with_an_underscore_90025": "Добавьте к \"{0}\" префикс — символ подчеркивания.", + "Print_names_of_files_part_of_the_compilation_6155": "Печатать имена файлов, входящих в компиляцию.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Печатать имена создаваемых файлов, входящих в компиляцию.", + "Print_the_compiler_s_version_6019": "Печать версии компилятора.", + "Print_this_message_6017": "Напечатайте это сообщение.", + "Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".", + "Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Свойство \"{0}\" не существует в типе \"{1}\". Вы имели в виду \"{2}\"?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Свойство \"{0}\" содержит конфликтующие объявления и недоступно в типе \"{1}\".", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Свойство \"{0}\" не имеет инициализатора, и ему не гарантировано присваивание в конструкторе.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа get не задана заметка с типом возвращаемого значения.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа set не задана заметка с типом параметра.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Свойство \"{0}\" в типе \"{1}\" не может быть присвоено типу \"{2}\".", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", + "Property_0_is_incompatible_with_index_signature_2530": "Свойство \"{0}\" несовместимо с сигнатурой индекса.", + "Property_0_is_missing_in_type_1_2324": "Свойство \"{0}\" отсутствует в типе \"{1}\".", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Свойство \"{0}\" является необязательным в типе \"{1}\" и обязательным в типе \"{2}\".", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Свойство \"{0}\" является закрытым и доступно только в классе \"{1}\".", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Свойство \"{0}\" является закрытым в типе \"{1}\" и не является таковым в типе \"{2}\".", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "Свойство \"{0}\" является защищенным и доступно только через экземпляр класса \"{1}\".", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Свойство \"{0}\" является защищенным и доступно только в классе \"{1}\" и его подклассах.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Свойство \"{0}\" является защищенным, однако тип \"{1}\" не является классом, производным от \"{2}\".", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Свойство \"{0}\" является защищенным в типе \"{1}\" и общим в типе \"{2}\".", + "Property_0_is_used_before_being_assigned_2565": "Свойство \"{0}\" используется перед присваиванием значения.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Свойство \"{0}\" атрибута расширения JSX не может быть назначено для целевого свойства.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Свойство \"{0}\" выражения экспортированного класса не может быть частным или защищенным.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Свойство \"{0}\" экспортированного интерфейса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "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_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, объектным литералом либо литералом массива.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "Предоставление полной поддержки для итерируемых элементов в for-of, расширение и деструктуризация при выборе целевой платформы ES5 или ES3.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Открытый метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Открытый метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Открытый метод \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Общее свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именовано.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Общее свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Общее свойство \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Открытый статический метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Открытый статический метод \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Открытый статический метод \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Общее статическое свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именовано.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Общее статическое свойство \"{0}\" экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Общее статическое свойство \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Вызывать ошибку в выражениях и объявлениях с подразумеваемым типом any.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", + "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", + "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\".", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", + "Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.", + "Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.", + "Report_errors_on_unused_parameters_6135": "Сообщать об ошибках в неиспользованных параметрах.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Обязательные параметры типа не могут следовать за необязательными параметрами типа.", + "Resolution_for_module_0_was_found_in_cache_6147": "Разрешение для модуля \"{0}\" найдено в кэше.", + "Resolving_from_node_modules_folder_6118": "Идет разрешение из папки node_modules...", + "Resolving_module_0_from_1_6086": "======== Идет разрешение модуля \"{0}\" из \"{1}\". ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Идет разрешение имени модуля \"{0}\" относительного к базовому URL-адресу \"{1}\" — \"{2}\".", + "Resolving_real_path_for_0_result_1_6130": "Разрешается реальный путь для \"{0}\"; результат: \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл \"{1}\", корневой каталог \"{2}\". ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл \"{1}\", корневой каталог не задан. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл не задан, корневой каталог \"{1}\". ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Идет разрешение директивы ссылки на тип \"{0}\", содержащий файл не задан, корневой каталог не задан. ========", + "Resolving_using_primary_search_paths_6117": "Идет разрешение с помощью первичных путей поиска...", + "Resolving_with_primary_search_path_0_6121": "Разрешается с помощью первичного пути поиска \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Параметр rest \"{0}\" неявно имеет тип any[].", + "Rest_types_may_only_be_created_from_object_types_2700": "Типы REST можно создавать только из типов объектов.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Тип возвращаемого значения сигнатуры вызова из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Тип возвращаемого значения сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Тип возвращаемого значения сигнатуры конструктора из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Тип возвращаемого значения сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Тип возвращаемого значения сигнатуры конструктора должен поддерживать присваивание типу экземпляра класса.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Тип возвращаемого значения экспортированной функции имеет или использует имя \"{0}\" из внешнего модуля {1}, но не может быть именован.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Тип возвращаемого значения экспортированной функции имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Тип возвращаемого значения экспортированной функции имеет или использует закрытое имя \"{0}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Тип возвращаемого значения сигнатуры индекса из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Тип возвращаемого значения сигнатуры индекса из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Тип возвращаемого значения метода из экспортированного интерфейса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Тип возвращаемого значения метода из экспортированного интерфейса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Тип возвращаемого значения открытого метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Тип возвращаемого значения открытого метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Тип возвращаемого значения открытого метода получения \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Тип возвращаемого значения общего метода из экспортированного класса имеет или использует имя \"{0}\" из внешнего модуля {1}, но не может быть именован.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Тип возвращаемого значения общего метода из экспортированного класса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Тип возвращаемого значения общего метода из экспортированного класса имеет или использует закрытое имя \"{0}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Тип возвращаемого значения открытого статического метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из внешнего модуля {2}, но не может быть именован.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Тип возвращаемого значения открытого статического метода получения \"{0}\" из экспортированного класса имеет или использует имя \"{1}\" из закрытого модуля \"{2}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Тип возвращаемого значения открытого статического метода получения \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует имя \"{0}\" из внешнего модуля {1}, но не может быть именован.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует имя \"{0}\" из закрытого модуля \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует закрытое имя \"{0}\".", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Повторно используются разрешения модулей, унаследованные из \"{0}\", так как они не изменились со старой программы.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Повторно используется разрешение модуля \"{0}\" в файле \"{1}\" из старой программы.", + "Rewrite_as_the_indexed_access_type_0_90026": "Необходима перезапись с типом индексного доступа {0}.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Корневой каталог невозможно определить, идет пропуск первичных путей поиска.", + "STRATEGY_6039": "СТРАТЕГИЯ", + "Scoped_package_detected_looking_in_0_6182": "Обнаружен пакет, относящийся к области; поиск в \"{0}\"", + "Setters_cannot_return_a_value_2408": "Методы доступа set не могут возвращать значения.", + "Show_all_compiler_options_6169": "Отображение всех параметров компилятора.", + "Show_diagnostic_information_6149": "Отображение сведений диагностики.", + "Show_verbose_diagnostic_information_6150": "Отображение подробных сведений диагностики.", + "Signature_0_must_be_a_type_predicate_1224": "Сигнатура \"{0}\" должна быть предикатом типа.", + "Skip_type_checking_of_declaration_files_6012": "Пропустить проверку типа файлов объявления.", + "Source_Map_Options_6175": "Параметры сопоставления источников", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Специализированная сигнатура перегрузки не поддерживает назначение неспециализированной сигнатуре.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Описатель динамического импорта не может быть элементом расширения.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Укажите целевую версию ECMAScript: \"ES3\" (по умолчанию), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\" или \"ESNEXT\".", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Укажите вариант создания кода JSX: \"preserve\", \"react-native\" или \"react\".", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Укажите файлы библиотеки для включения в компиляцию: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Укажите вариант создания кода модуля: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\", или \"ESNext\".", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Укажите стратегию разрешения модуля: node (Node.js) или classic (TypeScript pre-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Укажите функцию фабрики JSX, используемую при нацеливании на вывод JSX \"react\", например \"React.createElement\" или \"h\".", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Укажите окончание последовательности строки для использования при порождении файлов: CRLF (DOS) или LF (UNIX).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Укажите расположение, в котором отладчик должен найти файлы TypeScript вместо исходных расположений.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Укажите расположение, в котором отладчик должен найти файлы карты, вместо созданных расположений.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Укажите корневой каталог входных файлов. Используйте его для управления структурой выходных каталогов с --outDir.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Оператор расширения в выражениях new доступен только при разработке для ECMAScript 5 и более поздних версий.", + "Spread_types_may_only_be_created_from_object_types_2698": "Типы расширения можно создавать только из типов объектов.", + "Statement_expected_1129": "Ожидался оператор.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Операторы не разрешены в окружающих контекстах.", + "Static_members_cannot_reference_class_type_parameters_2302": "Статические элементы не могут ссылаться на параметры типов класса.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Статическое свойство \"{0}\" конфликтует со встроенным свойством \"Function.{0}\" функции-конструктора \"{1}\".", + "Strict_Type_Checking_Options_6173": "Параметры строгой проверки типов", + "String_literal_expected_1141": "Ожидался строковый литерал.", + "String_literal_with_double_quotes_expected_1327": "Ожидается строковый литерал с двойными кавычками.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Стилизовать ошибки и сообщения с помощью цвета и контекста (экспериментальная функция).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Последующие объявления переменных должны иметь тот же тип. Переменная \"{0}\" должна иметь тип \"{1}\", однако имеет тип \"{2}\".", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Подстановка \"{0}\" для шаблона \"{1}\" содержит неправильный тип, ожидается string, получен \"{2}\".", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Подстановка \"{0}\" в шаблоне \"{1}\" может содержать не больше одного символа \"*\".", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Подстановки для шаблона \"{0}\" должны быть массивом.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Замены для шаблона \"{0}\" не должны быть пустым массивом.", + "Successfully_created_a_tsconfig_json_file_6071": "Файл tsconfig.json успешно создан.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Вызовы super не разрешены вне конструкторов или во вложенных функциях внутри конструкторов.", + "Suppress_excess_property_checks_for_object_literals_6072": "Подавлять избыточные проверки свойств для объектных литералов.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Подавлять ошибки noImplicitAny для объектов индексирования, у которых отсутствуют сигнатуры индекса.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "Ссылка Symbol не ссылается на глобальный объект конструктора Symbol.", + "Syntax_Colon_0_6023": "Синтаксис: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Оператор \"{0}\" невозможно применить к типу Symbol.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Оператор \"{0}\" не разрешен для логических типов. Попробуйте использовать \"{1}\" вместо него.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Тип Object можно назначить малому количеству других типов. Возможно, вы хотели использовать тип any?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "Нельзя ссылаться на объект типа arguments в стрелочной функции ES3 и ES5. Используйте стандартное выражение функции.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "На объект arguments невозможно указать ссылку в асинхронной функции или методе в ES3 и ES5. Попробуйте использовать стандартную функцию или метод.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Текст оператора if не может быть пустым.", + "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_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Левый операнд оператора for...in не может быть шаблоном деструктурирования.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Левый операнд оператора for...in не может использовать аннотацию типа.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "В левой части оператора \"for...in\" должна быть переменная или доступ к свойству.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Левый операнд оператора for...in должен иметь тип string или any.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Левый операнд оператора for...of не может использовать аннотацию типа.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "В левой части оператора \"for...of\" должна быть переменная или доступ к свойству.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Левый операнд арифметической операции должен иметь тип any, number или тип перечисления.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "В левой части выражения назначения должна быть переменная или доступ к свойству.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "Левый операнд выражения in должен иметь тип any, string, number или Symbol.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Левый операнд выражения instanceof должен иметь тип any, тип объекта или параметр типа.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Языковой стандарт, который используется при отображении сообщений пользователю (например, en-us)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Максимальная глубина зависимостей для поиска в папке node_modules и загрузки файлов JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Операнд оператора delete не может быть свойством только для чтения.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Операнд оператора delete должен быть ссылкой на свойство.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Операнд оператора инкремента или декремента должен быть переменной или доступом к свойству.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "Тип возвращаемого значения конструктора элемента JSX должен возвращать тип объекта.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Тип возвращаемого значения функции декоратора параметра должен быть либо void, либо any.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Тип возвращаемого значения функции декоратора свойства должен быть либо void, либо any.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Тип возвращаемого значения асинхронной функции должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Тип возвращаемого значения асинхронной функции или метода должен быть глобальным типом Promise.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "Правый операнд оператора for...in должен иметь тип any, тип объекта или быть параметром типа.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Правый операнд арифметической операции должен иметь тип any, number или тип перечисления.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Правый операнд выражения \"in\" должен иметь тип \"any\", быть типом объекта или параметром типа.", + "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_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Контекст this типа \"{0}\" не может быть назначен методу this типа \"{1}\".", + "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}\" невозможно вывести из использования. Рассмотрите возможность явного указания аргументов типа.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Возвращаемый тип метода next() асинхронного итератора должен быть классом promise (для типа со свойством value).", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Тип, возвращаемый методом \"next()\" итератора, должен содержать свойство value.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Объявление переменной оператора for...in не может содержать инициализатор.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Объявление переменной оператора for...of не может содержать инициализатор.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Оператор with не поддерживается. Все символы в блоке with получат тип any.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Для этого синтаксиса требуется импортированный вспомогательный объект, но найти модуль \"{0}\" не удается.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Для этого синтаксиса требуется импортированный вспомогательный объект \"{1}\", но у модуля \"{0}\" нет экспортированного элемента \"{1}\".", + "Trailing_comma_not_allowed_1009": "Завершающая запятая запрещена.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Транскомпиляция каждого файла как отдельного модуля (аналогично ts.transpileModule).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Попробуйте команду \"npm install @types/{0}\", если это возможно, или добавьте новый файл объявления (.d.ts), содержащий \"declare module '{0}';\"", + "Trying_other_entries_in_rootDirs_6110": "Попытка использовать другие записи в \"rootDirs\".", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Выполняется попытка замены \"{0}\", расположение модуля кандидата: \"{1}\".", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "Кортеж типа \"{0}\" с длиной \"{1}\" невозможно назначить кортежу с длиной \"{2}\".", + "Type_0_cannot_be_converted_to_type_1_2352": "Тип \"{0}\" невозможно преобразовать в тип \"{1}\".", + "Type_0_cannot_be_used_as_an_index_type_2538": "Тип \"{0}\" невозможно использовать как тип индекса.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Тип \"{0}\" не может использоваться для индексации типа \"{1}\".", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Тип \"{0}\" не удовлетворяет ограничению \"{1}\".", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Тип \"{0}\" не содержит соответствующую сигнатуру индекса для типа \"{1}\".", + "Type_0_has_no_properties_in_common_with_type_1_2559": "У типа \"{0}\" нет общих свойств с типом \"{1}\".", + "Type_0_has_no_property_1_2460": "Тип \"{0}\" не содержит свойство \"{1}\".", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "Тип \"{0}\" не содержит свойство \"{1}\" и сигнатуру строкового индекса.", + "Type_0_is_not_a_constructor_function_type_2507": "Тип \"{0}\" не является типом функции конструктора.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Тип \"{0}\" не является допустимым типом возвращаемого значения асинхронной функции в ES5/ES3, так как он не ссылается на значение конструктора, совместимое с Promise.", + "Type_0_is_not_an_array_type_2461": "Тип \"{0}\" не является типом массива.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Тип \"{0}\" не является типом массива или типом строки.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "{0} не является типом массива или строки или в нем нет метода [Symbol.iterator](), который возвращает итератор.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "{0} не является типом массива или в нем нет метода [Symbol.iterator](), который возвращает итератор.", + "Type_0_is_not_assignable_to_type_1_2322": "Тип \"{0}\" не может быть назначен для типа \"{1}\".", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Тип \"{0}\" невозможно присвоить типу \"{1}\". Существует два разных типа с таким именем, но они не связаны.", + "Type_0_is_not_comparable_to_type_1_2678": "Тип \"{0}\" невозможно сравнить с типом \"{1}\".", + "Type_0_is_not_generic_2315": "Тип \"{0}\" не является универсальным.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Тип \"{0}\" не предоставляет соответствия для сигнатуры \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Тип \"{0}\" рекурсивно ссылается сам на себя как на базовый тип.", + "Type_alias_0_circularly_references_itself_2456": "Псевдоним типа \"{0}\" циклически ссылается на себя.", + "Type_alias_name_cannot_be_0_2457": "Псевдоним типа не может иметь имя \"{0}\".", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Аннотация типа не может содержаться в объявлении конструктора.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "Кандидат аргумента типа \"{1}\" является недопустимым аргументом, так как это не супертип кандидата \"{0}\".", + "Type_argument_expected_1140": "Ожидался аргумент типа.", + "Type_argument_list_cannot_be_empty_1099": "Список аргументов типа не может быть пустым.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Файлы объявления типа, включаемые в компиляцию.", + "Type_expected_1110": "Ожидался тип.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "На тип есть прямые или непрямые ссылки в обратном вызове выполнения собственного метода then.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Тип должен иметь метод [Symbol.asyncIterator](), который возвращает асинхронный итератор.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Тип должен иметь метод \"[Symbol.iterator]()\", который возвращает итератор.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Тип операнда \"await\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Тип элементов итерации для операнда \"yield*\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Тип операнда \"yield\" в асинхронном генераторе должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", + "Type_parameter_0_has_a_circular_constraint_2313": "Параметр типа \"{0}\" содержит циклическое ограничение.", + "Type_parameter_0_has_a_circular_default_2716": "Параметр типа \"{0}\" по умолчанию является циклическим.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Параметр типа \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Параметр типа \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Параметр типа \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Параметр типа \"{0}\" экспортированной функции имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Параметр типа \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Параметр типа \"{0}\" экспортированного псевдонима типа имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Параметр типа \"{0}\" метода из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Параметр типа \"{0}\" общего метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Параметр типа \"{0}\" общего статического метода из экспортированного класса имеет или использует закрытое имя \"{1}\".", + "Type_parameter_declaration_expected_1139": "Ожидалось объявление параметра типа.", + "Type_parameter_list_cannot_be_empty_1098": "Список параметров типа не может быть пустым.", + "Type_parameter_name_cannot_be_0_2368": "Параметр типа не может иметь имя \"{0}\".", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Параметры типов не могут содержаться в объявлении конструктора.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Предикат типов \"{0}\" не может быть назначен для \"{1}\".", + "Type_reference_directive_0_was_not_resolved_6120": "======== Директива ссылки на тип \"{0}\" не разрешена. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Директива ссылки на тип \"{0}\" успешно разрешена в \"{1}\", первичный объект: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Типы имеют раздельные объявления закрытого свойства \"{0}\".", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Типы параметров \"{0}\" и \"{1}\" несовместимы.", + "Types_of_property_0_are_incompatible_2326": "Типы свойства \"{0}\" несовместимы.", + "Unable_to_open_file_0_6050": "Не удается открыть файл \"{0}\".", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Не удается разрешить сигнатуру декоратора класса при вызове в качестве выражения.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Не удается разрешить сигнатуру декоратора метода при вызове в качестве выражения.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Не удается разрешить сигнатуру декоратора параметра при вызове в качестве выражения.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Не удается разрешить сигнатуру декоратора свойства при вызове в качестве выражения.", + "Unexpected_end_of_text_1126": "Неожиданный конец текста.", + "Unexpected_token_1012": "Неожиданный токен.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Неожиданный токен. Ожидался конструктор, метод, метод доступа или свойство.", + "Unexpected_token_expected_1179": "Неожиданный токен. Ожидался символ \"{\".", + "Unknown_compiler_option_0_5023": "Неизвестный параметр компилятора \"{0}\".", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Неизвестный параметр excludes. Возможно, вы имели в виду exclude?", + "Unknown_type_acquisition_option_0_17010": "Неизвестный параметр получения типа, \"{0}\".", + "Unreachable_code_detected_7027": "Обнаружен недостижимый код.", + "Unsupported_locale_0_6049": "Неподдерживаемый языковой стандарт \"{0}\".", + "Unterminated_Unicode_escape_sequence_1199": "Незавершенная escape-последовательность Юникода.", + "Unterminated_quoted_string_in_response_file_0_6045": "Незавершенная строка в кавычках в файле ответов \"{0}\".", + "Unterminated_regular_expression_literal_1161": "Незавершенный литерал регулярного выражения.", + "Unterminated_string_literal_1002": "Строковый литерал без признака конца.", + "Unterminated_template_literal_1160": "Незавершенный литерал шаблона.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Вызовы функций без типов не могут принимать аргументы типов.", + "Unused_label_7028": "Неиспользуемая метка.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", + "VERSION_6036": "ВЕРСИЯ", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Значение типа \"{0}\" не имеет общих свойств со значением типа \"{1}\". Вы хотели вызвать его?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Значение типа \"{0}\" не может вызываться. Вы хотели использовать new?", + "Variable_0_implicitly_has_an_1_type_7005": "Переменная \"{0}\" неявно имеет тип \"{1}\".", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Переменная \"{0}\" неявным образом получает тип \"{1}\" в некоторых местах, где ее тип невозможно определить.", + "Variable_0_is_used_before_being_assigned_2454": "Переменная \"{0}\" используется перед назначением.", + "Variable_declaration_expected_1134": "Ожидалось объявление переменной.", + "Variable_declaration_list_cannot_be_empty_1123": "Список объявлений переменной не может быть пустым.", + "Version_0_6029": "Версия {0}", + "Watch_input_files_6005": "Просмотр входных файлов.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Невозможно переименовать элементы, определенные в стандартной библиотеке TypeScript.", + "You_cannot_rename_this_element_8000": "Этот элемент переименовать нельзя.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" принимает слишком мало аргументов для использования в качестве декоратора. Вы хотели сначала вызвать его и записать \"@{0}()\"?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" указаны дважды. Атрибут \"{0}\" будет перезаписан.", + "_0_can_only_be_used_in_a_ts_file_8009": "\"{0}\" может использоваться только в TS-файле.", + "_0_expected_1005": "Ожидалось \"{0}\".", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "\"{0}\" неявно имеет тип возвращаемого значения any, так как у него нет заметки с типом возвращаемого значения, а также на него прямо или косвенно указана ссылка в одном из его выражений return.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "\"{0}\" неявно имеет тип any, так как отсутствует аннотация типа и на \"{0}\" есть прямые или непрямые ссылки в его собственном инициализаторе.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" является примитивом, но \"{1}\" — объект оболочки. Предпочтительно использовать \"{0}\" по мере возможности.", + "_0_is_declared_but_its_value_is_never_read_6133": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" не является допустимым метасвойством для ключевого слова \"{1}\". Вы имели в виду \"{2}\"?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "На \"{0}\" есть прямые или непрямые ссылки в его собственном базовом выражении.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "На \"{0}\" есть прямые или непрямые ссылки в его собственной аннотации типа.", + "_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_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 может отображаться только в объявлении класса, метода или свойства.", + "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": "\"=\" можно использовать только в свойстве объектного литерала в назначении деструктурирования.", + "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 можно использовать только в выражениях доступа к свойствам или по индексу, а также в правой части объявления присваивания импорта или экспорта.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений могут использоваться только в TS-файле.", + "export_can_only_be_used_in_a_ts_file_8003": "Элемент \"export=\" может использоваться только в TS-файле.", + "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": "Предложение extends экспортированного класса \"{0}\" имеет или использует закрытое имя \"{1}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Предложение extends экспортированного интерфейса \"{0}\" имеет или использует закрытое имя \"{1}\".", + "file_6025": "файл", + "get_and_set_accessor_must_have_the_same_this_type_2682": "Методы доступа \"get\" и \"set\" должны иметь одинаковый тип \"this\".", + "get_and_set_accessor_must_have_the_same_type_2380": "Методы доступа get и set должны иметь одинаковый тип.", + "implements_clause_already_seen_1175": "Предложение implements уже существует.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "Предложения implements могут использоваться только в TS-файле.", + "import_can_only_be_used_in_a_ts_file_8002": "Элемент \"import ... =\" может использоваться только в TS-файле.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "Объявления интерфейсов могут использоваться только в TS-файле.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "Объявления let можно задать только в блоке.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Не допускается использование let в качестве имени в объявлениях let или const.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "Объявления модулей могут использоваться только в TS-файле.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "Оператор new T[] не может использоваться для создания массива. Используйте вместо него \"new Array()\".", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Выражение new, у цели которого нет сигнатуры конструктора, неявно имеет тип any.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Утверждения для проверки на null могут использоваться только в TS-файле.", + "options_6024": "параметры", + "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 содержит поле \"{0}\" \"{1}\", которое ссылается на \"{2}\".", + "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 может отображаться только в объявлении свойства или сигнатуре индекса.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Параметр \"rootDirs\" задан; он используется для разрешения относительного имени модуля \"{0}\".", + "super_can_only_be_referenced_in_a_derived_class_2335": "Ссылка на super может указываться только в производном классе.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "На super можно ссылаться только в элементах производных классов или литеральных выражениях объекта.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Не допускается ссылка на super в имени вычисляемого свойства.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "На super невозможно ссылаться в аргументах конструктора.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "super допускается только в элементах литеральных выражений объекта, если параметр target — ES2015 или выше.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Перед тем, как получить доступ к свойству \"super\" в конструкторе производного класса, необходимо вызвать \"super\".", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "super следует вызывать перед получением доступа к this в конструкторе производного класса.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "После super должен идти список аргументов или доступ к элементу.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Доступ к свойству super разрешен только в конструкторе, функции-элементе или методе доступа к элементам производного класса.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "На this не может указывать ссылка в имени вычисляемого свойства.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "На this не могут указывать ссылки в теле модуля или пространства имен.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "На this не могут указывать ссылки в инициализаторе статического свойства.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "На this не могут указывать ссылки в аргументах конструктора.", + "this_cannot_be_referenced_in_current_location_2332": "На this не могут указывать ссылки в текущем расположении.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "this неявно содержит тип any, так как он не имеет аннотации типа.", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "Псевдонимы типов могут использоваться только в TS-файле.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "Аргументы типов могут использоваться только в TS-файле.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Выражения утверждения типа могут использоваться только в TS-файле.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Объявления параметров типа могут использоваться только в TS-файле.", + "types_can_only_be_used_in_a_ts_file_8010": "Типы могут использоваться только в TS-файле.", + "unique_symbol_types_are_not_allowed_here_1335": "Типы \"уникальный символ\" здесь запрещены.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Типы \"уникальный символ\" разрешены только в переменных в операторе с переменной.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Типы \"уникальный символ\" невозможно использовать в объявлении переменной с именем привязки.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Операторы with не разрешено использовать в блоке асинхронной функции.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Операторы with не разрешено использовать в строгом режиме.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Выражения yield не могут быть использованы в инициализаторе параметра." +} \ No newline at end of file diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..73cae04049958 --- /dev/null +++ b/lib/tr/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Bir '{0}' değiştiricisi, içeri aktarma bildirimiyle birlikte kullanılamaz.", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "Bir '{0}' değiştiricisi, arabirim bildirimiyle birlikte kullanılamaz.", + "A_0_parameter_must_be_the_first_parameter_2680": "Bir '{0}' parametresi ilk parametre olmalıdır.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Uygulama imzasındaki bir bağlama deseni parametresi isteğe bağlı olamaz.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' deyimi yalnızca bir kapsayan yineleme veya switch deyimi içinde kullanılabilir.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' deyimi, yalnızca kapsayan deyimin etiketine atlayabilir.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Bir sınıf, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı uygulayabilir.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' değiştiricisi olmayan bir sınıf bildiriminin adı olmalıdır.", + "A_class_may_only_extend_another_class_2311": "Bir sınıf yalnızca başka bir sınıfı genişletebilir.", + "A_class_may_only_implement_another_class_or_interface_2422": "Bir sınıf yalnızca başka bir sınıfı veya arabirimi uygulayabilir.", + "A_class_member_cannot_have_the_0_keyword_1248": "Bir sınıf üyesi '{0}' anahtar kelimesini içeremez.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Hesaplanan özellik adında virgül ifadesine izin verilmez.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Hesaplanan özellik adı, kapsayan türündeki bir tür parametresine başvuramaz.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Bir sınıf özelliği bildirimindeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Bir metot aşırı yüklemesindeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Bir tür sabit değerindeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Bir çevresel bağlamdaki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Bir arabirimdeki hesaplanan özellik adı, sabit değer türündeki veya 'unique symbol' türündeki bir ifadeye başvurmalıdır.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Hesaplanan özellik adı 'string', 'number', 'symbol' veya 'any' türünde olmalıdır.", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "'{0}' biçimindeki hesaplanan özellik adı 'symbol' türünde olmalıdır.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const numaralandırma üyesine yalnızca dize sabit değeri kullanılarak erişilebilir.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Çevresel bağlamdaki 'const' başlatıcısı bir dize veya sayısal sabit değer olmalıdır.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Sınıfı 'null' değerini aşan bir oluşturucu 'super' çağrısını içeremez.", + "A_constructor_cannot_have_a_this_parameter_2681": "Bir oluşturucu 'this' parametresini içeremez.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' deyimi yalnızca bir kapsayan yineleme deyimi içinde kullanılabilir.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' deyimi, yalnızca kapsayan yineleme deyiminin etiketine atlayabilir.", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Çevresel bağlamda 'declare' değiştiricisi kullanılamaz.", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Bir .d.ts dosyasındaki en üst düzey bildirim için 'declare' değiştiricisi gerekir.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekoratörler yalnızca metot uygulaması dekore edebilir; aşırı yüklemeleri dekore edemez.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' yan tümcesi, 'switch' deyiminde birden fazla kez bulunamaz.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Varsayılan dışarı aktarma, yalnızca ECMAScript stili bir modülde kullanılabilir.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Bu bağlamda '!' belirli atama onayına izin verilmez.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Yok etme bildiriminin bir başlatıcısı olmalıdır.", + "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3 içindeki dinamik içeri aktarma çağrısı, 'Promise' oluşturucusu gerektirir. 'Promise' oluşturucusu için bir bildiriminizin olduğundan veya `--lib` seçeneğinize 'ES2015' eklediğinizden emin olun.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Dinamik içeri aktarma çağrısı, 'Promise' döndürür. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ekleyin.", + "A_file_cannot_have_a_reference_to_itself_1006": "Bir dosya kendine başvuramaz.", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "Bir 'for-await-of' deyimine yalnızca zaman uyumsuz işlev veya zaman uyumsuz oluşturucu içinde izin verilir.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never' döndüren bir işlev, erişilebilir bir uç noktaya sahip olamaz.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'New' anahtar kelimesiyle çağrılan bir işlev, 'void' olan bir 'this' türüne sahip olamaz.", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "Bildirilen türü 'void' veya 'any' olmayan işlevin bir değer döndürmesi gerekir.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Bir oluşturucu 'void' türündeki bir ek açıklamaya sahip olamaz.", + "A_get_accessor_cannot_have_parameters_1054": "Bir 'get' erişimcisi parametrelere sahip olamaz.", + "A_get_accessor_must_return_a_value_2378": "'get' erişimcisinin bir değer döndürmesi gerekir.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Numaralandırma bildirimdeki bir üye başlatıcısı, diğer numaralandırmalarda tanımlanan üyeler dahil olmak üzere kendinden sonra bildirilen üyelere başvuramaz.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Mixin sınıfının 'any[]' türünde tek bir rest parametresi içeren bir oluşturucusu olmalıdır.", + "A_module_cannot_have_multiple_default_exports_2528": "Modül, birden fazla varsayılan dışarı aktarmaya sahip olamaz.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden farklı bir dosyada olamaz.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Parametre özelliği, bağlama deseni kullanılarak bildirilemez.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'extends' seçeneğindeki yolun göreli veya kök olması gerekir, ancak '{0}' bu koşullara uymuyor.", + "A_promise_must_have_a_then_method_1059": "Promise'in bir 'then' metodu olmalıdır.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Bir 'unique symbol' türündeki sınıfın özelliği hem 'static' hem de 'readonly' olmalıdır.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Bir 'unique symbol' türündeki arabirimin veya tür sabit değerinin özelliği 'readonly' olmalıdır.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Gerekli parametre, isteğe bağlı parametreden sonra gelemez.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest öğesi bir bağlama deseni içeremez.", + "A_rest_element_cannot_have_an_initializer_1186": "rest öğesi bir başlatıcıya sahip olamaz.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Rest öğesi, yok etme desenindeki son öğe olmalıdır.", + "A_rest_parameter_cannot_be_optional_1047": "rest parametresi isteğe bağlı olamaz.", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest parametresi bir başlatıcıya sahip olamaz.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest parametresi, parametre listesinin sonunda bulunmalıdır.", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest parametresi dizi türünde olmalıdır.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' deyimi, yalnızca bir işlev gövdesinde kullanılabilir.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "İçeri aktarmaları, 'baseUrl' ile ilgili arama konumlarına yeniden eşleyen bir girdi dizisi.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' erişimcisi, dönüş türü ek açıklamasına sahip olamaz.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' erişimcisi isteğe bağlı bir parametreye sahip olamaz.", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' erişimcisi rest parametresine sahip olamaz.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' erişimcisi tam olarak bir parametreye sahip olmalıdır.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' erişimci parametresinin bir başlatıcısı olamaz.", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "Uygulamaya sahip bir imza, dize sabit değeri türünü kullanamaz.", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "Bir sınıf başlatılmış özellik içerdiğinde veya parametre özelliklerine sahip olduğunda 'super' çağrısı, oluşturucudaki ilk deyim olmalıdır.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'This' tabanlı tür koruması, parametre tabanlı tür koruması ile uyumlu değildir.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' türü, yalnızca bir sınıfın veya arabirimin statik olmayan bir üyesinde kullanılabilir.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' dosyası şu konumda zaten tanımlanmış: '{0}'.", + "A_tuple_type_element_list_cannot_be_empty_1122": "Demet türü öğe listesi boş olamaz.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Üs ifadesinin sol tarafında tür onaylama ifadesine izin verilmez. İfadeyi parantez içine yazmayı düşünün.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Tür sabit değeri özelliği bir başlatıcıya sahip olamaz.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Bir tür koşulu, rest parametresine başvuru yapamaz.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Bir tür koşulu, bağlama desenindeki '{0}' öğesine başvuru yapamaz.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Bir tür koşuluna yalnızca işlevlere ve metotlara ait dönüş türü konumunda izin verilir.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Bir tür koşulunun türü, parametresinin türüne atanabilir olmalıdır.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Bir 'unique symbol' türündeki değişken 'const' olmalıdır.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Bir 'yield' ifadesine yalnızca oluşturucu gövdesinde izin verilir.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "'{1}' sınıfındaki '{0}' soyut metoduna super ifadesi ile erişilemez.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Soyut metotlar yalnızca bir soyut sınıfta görüntülenebilir.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "'{1}' sınıfındaki '{0}' soyut özelliğine oluşturucuda erişilemiyor.", + "Accessibility_modifier_already_seen_1028": "Erişilebilirlik değiştiricisi zaten görüldü.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Erişimciler yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.", + "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekleyin.", + "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekleyin.", + "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekleyin.", + "Add_this_to_unresolved_variable_90008": "Çözümlenmemiş değişkene 'this.' ekleyin.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Bir tsconfig.json dosyası eklemek, hem TypeScript hem de JavaScript dosyaları içeren projeleri düzenlemenize yardımcı olur. Daha fazla bilgi edinmek için bkz. https://aka.ms/tsconfig.", + "Additional_Checks_6176": "Ek Denetimler", + "Advanced_Options_6178": "Gelişmiş Seçenekler", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", + "Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' bayrağı sağlandığında çevresel const numaralandırma değerlerine izin verilmez.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Çevresel modül bildirimi göreli modül adını belirtemez.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Çevresel modüller, diğer modüllerde veya ad alanlarında iç içe bulunamaz.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD modülü birden fazla ad atamasında sahip olamaz.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Soyut erişimcinin uygulaması olamaz.", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Erişimci, çevresel bağlamda bildirilemez.", + "An_accessor_cannot_have_type_parameters_1094": "Erişimci, tür parametrelerine sahip olamaz.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Çevresel modül bildirimine yalnızca bir dosyadaki en üst düzeyde izin verilir.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Aritmetik işlenen, 'any', 'number' veya numaralandırma türünde olmalıdır.", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 içindeki zaman uyumsuz bir fonksiyon veya metot, 'Promise' oluşturucusu gerektiriyor. 'Promise' oluşturucusu için bir bildiriminizin olduğundan veya `--lib` seçeneğinize 'ES2015' eklediğinizden emin olun.", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Zaman uyumsuz bir işlev veya metot, geçerli bir beklenebilir dönüş türüne sahip olmalıdır.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Zaman uyumsuz bir işlevin veya metodun 'Promise' döndürmesi gerekir. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ifadesini ekleyin.", + "An_async_iterator_must_have_a_next_method_2519": "Zaman uyumsuz yineleyicinin bir 'next()' metodu olmalıdır.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Numaralandırma üyesi, sayısal bir ada sahip olamaz.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Dışarı aktarma ataması yalnızca bir modülde kullanılabilir.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Dışarı aktarma ataması, dışarı aktarılmış diğer öğelere sahip bir modülde kullanılamaz.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Ad alanında dışarı aktarma ataması kullanılamaz.", + "An_export_assignment_cannot_have_modifiers_1120": "Dışarı aktarma ataması, değiştiricilere sahip olamaz.", + "An_export_declaration_can_only_be_used_in_a_module_1233": "Dışarı aktarma bildirimi yalnızca bir modülde kullanılabilir.", + "An_export_declaration_cannot_have_modifiers_1193": "Dışarı aktarma bildirimi, değiştiricilere sahip olamaz.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Genişletilmiş Unicode kaçış değeri, 0x0 ve 0x10FFFF dahil olmak üzere bu değerler arasında olmalıdır.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Uygulama, çevresel bağlamda bildirilemez.", + "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "İçeri aktarma bildirimi yalnızca bir ad alanında veya modülde kullanılabilir.", + "An_import_declaration_cannot_have_modifiers_1191": "İçeri aktarma bildirimi, değiştiricilere sahip olamaz.", + "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "İçeri aktarma yolu '{0}' uzantısıyla bitemez. Bunun yerine '{1}' öğesini içeri aktarmayı deneyin.", + "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Dizin ifadesi bağımsız değişkeni 'string', 'number', 'symbol' veya 'any' değerlerine sahip olmalıdır.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Dizin imzası bir rest parametresine sahip olamaz.", + "An_index_signature_must_have_a_type_annotation_1021": "Dizin imzası bir tür açıklamasına sahip olmalıdır.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Dizin imzası tam olarak bir parametreye sahip olmalıdır.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Dizin imzası parametresi, bir soru işareti içeremez.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Dizin imzası parametresi, bir erişilebilirlik değiştiricisine sahip olamaz.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Dizin imzası parametresi, bir başlatıcıya sahip olamaz.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Dizin imzası parametresi, bir tür ek açıklamasına sahip olmalıdır.", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "Dizin imzası parametresi, 'string' veya 'number' türünde olmalıdır.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Bir arabirim, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı genişletebilir.", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "Arabirim, yalnızca bir sınıfı veya başka bir arabirimi genişletebilir.", + "An_interface_property_cannot_have_an_initializer_1246": "Arabirim özelliği bir başlatıcıya sahip olamaz.", + "An_iterator_must_have_a_next_method_2489": "Bir yineleyici 'next()' metoduna sahip olmalıdır.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Nesne sabit değeri aynı ada sahip birden fazla get/set erişimcisine sahip olamaz.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "Nesne sabit değeri, katı modda aynı ada sahip birden fazla özelliğe sahip olamaz.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Nesne sabit değeri, aynı ada sahip bir özellik ve erişimciye sahip olamaz.", + "An_object_member_cannot_be_declared_optional_1162": "Nesne üyesi, isteğe bağlı olarak bildirilemez.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Aşırı yükleme imzası, bir oluşturucu olarak bildirilemez.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Üs ifadesinin sol tarafında '{0}' işlecine sahip bir tek terimli ifadeye izin verilmez. İfadeyi parantez içine yazmayı düşünün.", + "Annotate_with_type_from_JSDoc_95009": "JSDoc türü ile not ekle", + "Annotate_with_types_from_JSDoc_95010": "JSDoc türleri ile not ekle", + "Argument_expression_expected_1135": "Bağımsız değişken ifadesi bekleniyor.", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' seçeneğinin bağımsız değişkeni {1} olmalıdır.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "'{0}' türündeki bağımsız değişken '{1}' türündeki parametreye atanamaz.", + "Array_element_destructuring_pattern_expected_1181": "Dizi öğesi yok etme deseni bekleniyor.", + "Asterisk_Slash_expected_1010": "'*/' bekleniyor.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Genel kapsam genişletmeleri yalnızca dış modüllerde ya da çevresel modül bildirimlerinde doğrudan yuvalanabilir.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Genel kapsam genişletmeleri, zaten çevresel olan bir bağlamda göründükleri durumlar dışında 'declare' değiştiricisine sahip olmalıdır.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "'{0}' projesinde otomatik tür bulma etkinleştirildi. '{2}' önbellek konumu kullanılarak '{1}' modülü için ek çözümleme geçişi çalıştırılıyor.", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Temel sınıf ifadelerinde sınıf türü parametrelerine başvuruda bulunulamaz.", + "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "Temel oluşturucu dönüş türü '{0}', bir sınıf veya arabirim türü değil.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Tüm temel oluşturucuların aynı dönüş türüne sahip olması gerekir.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Mutlak olmayan modül adlarını çözümlemek için kullanılan temel dizin.", + "Basic_Options_6172": "Temel Seçenekler", + "Binary_digit_expected_1177": "İkili sayı bekleniyor.", + "Binding_element_0_implicitly_has_an_1_type_7031": "'{0}' bağlama öğesi, örtük olarak '{1}' türü içeriyor.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Blok kapsamlı değişken '{0}', bildirilmeden önce kullanıldı.", + "Call_decorator_expression_90028": "Dekoratör ifadesini çağırın.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Dönüş türü ek açıklaması bulunmayan çağrı imzası, örtük olarak 'any' dönüş türüne sahip.", + "Call_target_does_not_contain_any_signatures_2346": "Çağrı hedefi imza içermiyor.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}' bir ad alanı değil tür olduğundan '{0}.{1}' erişimi sağlanamıyor. '{0}[\"{1}\"]' değerini belirterek '{0}' içindeki '{1}' özelliğinin türünü almak mı istediniz?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' oluşturucu türüne '{1}' oluşturucu türü atanamaz.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Bir soyut oluşturucu türü, soyut olmayan bir oluşturucu türüne atanamaz.", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "Sabit veya salt okunur bir özellik olduğundan '{0}' özelliğine atama yapılamıyor.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Değişken olmadığından '{0}' öğesine atama yapılamıyor.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "'{0}' modülü, modül olmayan bir varlığa çözümlendiğinden genişletilemiyor.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Modül olmayan bir varlığa çözümlendiğinden '{0}' modülü, değer dışarı aktarmalarıyla genişletilemiyor.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' bayrağı 'amd' veya 'system' olmadığı sürece '{0}' seçeneği kullanılarak modül derlenemez.", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "'--isolatedModules' bayrağı sağlandığında ad alanları derlenemez.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Bir soyut sınıfın örneği oluşturulamaz.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}' dışarı aktarılamıyor. Bir modülden yalnızca yerel bildirimler dışarı aktarılabilir.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "'{0}' sınıfı genişletilemez. Sınıf oluşturucusu, özel olarak işaretlenmiş.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "'{0}' arabirimi genişletilemiyor. Bunun yerine 'implements' kullanmayı deneyin.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Belirtilen dizinde tsconfig.json dosyası bulunamıyor: '{0}'.", + "Cannot_find_global_type_0_2318": "'{0}' genel türü bulunamıyor.", + "Cannot_find_global_value_0_2468": "'{0}' genel değeri bulunamıyor.", + "Cannot_find_module_0_2307": "'{0}' modülü bulunamıyor.", + "Cannot_find_name_0_2304": "'{0}' adı bulunamıyor.", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' adı bulunamıyor. Bunu mu demek istediniz: '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "'{0}' adı bulunamıyor. 'this.{0}' örnek üyesini mi aradınız?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "'{0}' adı bulunamıyor. '{1}.{0}' statik üyesini mi aradınız?", + "Cannot_find_namespace_0_2503": "'{0}' ad alanı bulunamıyor.", + "Cannot_find_parameter_0_1225": "'{0}' parametresi bulunamıyor.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Giriş dosyalarına ait ortak alt dizin yolu bulunamıyor.", + "Cannot_find_type_definition_file_for_0_2688": "'{0}' için tür tanımı dosyası bulunamıyor.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Tür bildirim dosyaları içeri aktarılamıyor. '{1}' yerine '{0}' dosyasını içeri aktarmanız önerilir.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Dış kapsamdaki '{0}' değişkeni, blok kapsamındaki '{1}' bildirimiyle aynı kapsamda başlatılamaz.", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Türü bir çağrı imzasına sahip olmayan bir ifade çağrılamaz. '{0}' türünün uyumlu çağrı imzası yok.", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", + "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", + "Cannot_redeclare_exported_variable_0_2323": "Dışarı aktarılan '{0}' değişkeni yeniden bildirilemiyor.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Catch yan tümcesindeki '{0}' tanımlayıcısı yeniden bildirilemiyor.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' bayrağı sağlanmazsa JSX kullanılamaz.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module' değeri 'none' olduğunda içeri aktarma, dışarı aktarma veya modül genişletme kullanılamaz.", + "Cannot_use_namespace_0_as_a_type_2709": "'{0}' ad alanı, tür olarak kullanılamaz.", + "Cannot_use_namespace_0_as_a_value_2708": "'{0}' ad alanı, değer olarak kullanılamaz.", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "Türünde çağrı veya yapı imzası olmayan ifadeyle 'new' kullanılamaz.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Birden fazla giriş dosyası tarafından üzerine yazılacağı için '{0}' dosyası yazılamıyor.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Giriş dosyasının üzerine yazacağı için '{0}' dosyası yazılamıyor.", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch yan tümcesi değişkeni bir tür ek açıklamasına sahip olamaz.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch yan tümcesi değişkeni bir başlatıcıya sahip olamaz.", + "Change_0_to_1_90014": "'{0}' değerini '{1}' olarak değiştirin.", + "Change_extends_to_implements_90003": "'extends' ifadesini 'implements' olarak değiştirin.", + "Change_spelling_to_0_90022": "Yazımı '{0}' olarak değiştirin.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' ön ekinin '{1}' - '{2}' için eşleşen en uzun ön ek olup olmadığı denetleniyor.", + "Circular_definition_of_import_alias_0_2303": "'{0}' içeri aktarma diğer adının döngüsel tanımı.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Yapılandırma çözümlenirken döngüsellik algılandı: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "'{0}' sınıfı, '{1}' örnek üyesi erişimcisini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi işlevi olarak tanımlar.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "'{0}' sınıfı, '{1}' örnek üyesi işlevini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi erişimcisi olarak tanımlar.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "'{0}' sınıfı, '{1}' örnek üyesi işlevini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi özelliği olarak tanımlar.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' sınıfı, '{1}' örnek üyesi özelliğini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi işlevi olarak tanımlar.", + "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' sınıfı, '{1}' temel sınıfını yanlış genişletiyor.", + "Class_0_incorrectly_implements_interface_1_2420": "'{0}' sınıfı, '{1}' arabirimini yanlış uyguluyor.", + "Class_0_used_before_its_declaration_2449": "'{0}' sınıfı, bildiriminden önce kullanıldı.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Sınıf bildirimlerinde birden fazla `@augments` veya `@extends` etiketi olamaz.", + "Class_name_cannot_be_0_2414": "Sınıf adı '{0}' olamaz.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "'{0}' statik sınıf tarafı, '{1}' statik temel sınıf tarafını yanlış genişletiyor.", + "Classes_can_only_extend_a_single_class_1174": "Sınıflar yalnızca bir sınıfı genişletebilir.", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Soyut metotlar içeren sınıflar abstract olarak işaretlenmelidir.", + "Command_line_Options_6171": "Komut Satırı Seçenekleri", + "Compilation_complete_Watching_for_file_changes_6042": "Derleme tamamlandı. Dosya değişiklikleri izleniyor.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Yapılandırma dosyasının yolu veya 'tsconfig.json' dosyasını içeren klasörün yolu belirtilen projeyi derleyin.", + "Compiler_option_0_expects_an_argument_6044": "'{0}' derleyici seçeneği, bağımsız değişken bekliyor.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "'{0}' derleyici seçeneği, {1} türünde bir değer gerektiriyor.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Numaralandırmalarda hesaplanan özellik adına izin verilmiyor.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Dize değeri içeren üyelerin bulunduğu bir sabit listesinde hesaplanan değerlere izin verilmez.", + "Concatenate_and_emit_output_to_single_file_6001": "Çıktıyı tek dosyaya birleştirin ve yayın.", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{1}' ve '{2}' içinde '{0}' için çakışan tanımlar bulundu. Çakışmayı çözmek için bu kitaplığın belirli bir versiyonunu yüklemeniz önerilir.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Dönüş türü ek açıklaması bulunmayan yapı imzası, örtük olarak 'any' dönüş türüne sahip.", + "Constructor_implementation_is_missing_2390": "Oluşturucu uygulaması yok.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "'{0}' sınıfının oluşturucusu özel olduğundan, oluşturucuya yalnızca sınıf bildiriminden erişilebilir.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' sınıfının oluşturucusu korumalı olduğundan, oluşturucuya yalnızca sınıf bildiriminden erişilebilir.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Türetilmiş sınıflara ilişkin oluşturucular bir 'super' çağrısı içermelidir.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Kapsayıcı dosya belirtilmedi ve kök dizini belirlenemiyor; 'node_modules' klasöründe arama atlanıyor.", + "Convert_function_0_to_class_95002": "'{0}' işlevini sınıfa dönüştür", + "Convert_function_to_an_ES2015_class_95001": "İşlevi bir ES2015 sınıfına dönüştür", + "Convert_to_default_import_95013": "Varsayılan içeri aktarmaya dönüştür", + "Corrupted_locale_file_0_6051": "{0} yerel ayar dosyası bozuk.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "'{0}' modülü için bildirim dosyası bulunamadı. '{1}' örtülü olarak 'any' türüne sahip.", + "Could_not_write_file_0_Colon_1_5033": "'{0}' dosyası yazılamadı: {1}.", + "DIRECTORY_6038": "DİZİN", + "Declaration_expected_1146": "Bildirim bekleniyor.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Bildirim adı, yerleşik genel tanımlayıcı '{0}' ile çakışıyor.", + "Declaration_or_statement_expected_1128": "Bildirim veya deyim bekleniyor.", + "Declare_method_0_90023": "'{0}' metodunu bildirin.", + "Declare_property_0_90016": "'{0}' özelliğini bildirin.", + "Declare_static_method_0_90024": "'{0}' statik metodunu bildirin.", + "Declare_static_property_0_90027": "'{0}' statik özelliğini bildirin.", + "Decorators_are_not_valid_here_1206": "Buradaki dekoratörler geçerli değil.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Kullanım Dışı] Bunun yerine '--jsxFactory' kullanın. 'react' JSX gösterimi hedefleniyorsa, createElement için çağrılan nesneyi belirtin", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Kullanım Dışı] Bunun yerine '--outFile' kullanın. Çıkışı tek bir dosya olarak birleştirin ve gösterin", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", + "Digit_expected_1124": "Rakam bekleniyor.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' dizini yok, içindeki tüm aramalar atlanıyor.", + "Disable_checking_for_this_file_90018": "Bu dosya için denetimi devre dışı bırakın.", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript projelerinde boyut sınırlamalarını devre dışı bırakın.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "İşlev türlerinde genel imzalar için katı denetimi devre dışı bırakın.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Aynı dosyaya yönelik tutarsız büyük/küçük harflere sahip başvurulara izin verme.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Derlenen dosya listesine üç eğik çizgi başvuruları veya içeri aktarılan modüller eklemeyin.", + "Do_not_emit_comments_to_output_6009": "Çıktıya ait açıklamaları gösterme.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' ek açıklamasına sahip kod için bildirimleri gösterme.", + "Do_not_emit_outputs_6010": "Çıktıları gösterme.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Herhangi bir hata bildirildiyse çıkışları gösterme.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Modül çıkışında 'use strict' yönergeleri gösterme.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Oluşturulan kodda const numaralandırma bildirimlerini silme.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Derlenen çıkışta '__extends' gibi özel yardımcı işlevler oluşturmayın.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Varsayılan kitaplık dosyasını (lib.d.ts) eklemeyin.", + "Do_not_report_errors_on_unreachable_code_6077": "Erişilemeyen kod ile ilgili hataları bildirme.", + "Do_not_report_errors_on_unused_labels_6074": "Kullanılmayan etiketler ile ilgili hataları bildirme.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Simgesel bağlantıların gerçek yolunu çözümlemeyin.", + "Do_not_truncate_error_messages_6165": "Hata iletilerini kesmeyin.", + "Duplicate_declaration_0_2718": "Yinelenen '{0}' bildirimi.", + "Duplicate_function_implementation_2393": "Yinelenen işlev uygulaması.", + "Duplicate_identifier_0_2300": "Yinelenen tanımlayıcı: '{0}'.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Yinelenen tanımlayıcı: '{0}'. Derleyici, bir modülün üst düzey kapsamındaki '{1}' adını ayırır.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "'{0}' tanımlayıcısı yineleniyor. Derleyici, zaman uyumsuz işlevler içeren bir modülün en üst düzey kapsamında '{1}' adını ayırıyor.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Yinelenen tanımlayıcı: '{0}'. Derleyici, zaman uyumsuz işlevleri desteklemek için '{1}' bildirimini kullanır.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Yinelenen tanımlayıcı: 'arguments'. Derleyici, rest parametrelerini başlatmak için 'arguments' tanımlayıcısını kullanır.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Yinelenen '_newTarget' tanımlayıcısı. Derleyicide, '_newTarget' değişken bildirimi 'new.target' meta-özellik başvurusu yakalamak için kullanılıyor.", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "Yinelenen tanımlayıcı: '_super'. Derleyici, temel sınıf başvurusunu yakalamak için '_super' tanımlayıcısını kullanır.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Yinelenen tanımlayıcı: '_this'. Derleyici, 'this' başvurusunu yakalamak için '_this' değişken bildirimini kullanır.", + "Duplicate_label_0_1114": "'{0}' etiketi yineleniyor.", + "Duplicate_number_index_signature_2375": "Dizin imzasında yinelenen numara.", + "Duplicate_string_index_signature_2374": "Dizin imzasında yinelenen dize.", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 modülleri hedeflenirken dinamik içeri aktarma kullanılamaz.", + "Dynamic_import_cannot_have_type_arguments_1326": "Dinamik içeri aktarma, tür bağımsız değişkenleri içeremez", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dinamik içeri aktarma, bağımsız değişken olarak bir tanımlayıcı içermelidir.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Dinamik içeri aktarmanın tanımlayıcısı 'string' türünde olmalıdır, ancak buradaki tür: '{0}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Dizin ifadesi 'number' türünde olmadığından, öğe örtük olarak 'any' türü içeriyor.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "'{0}' türünün dizin imzası olmadığından öğe dolaylı olarak 'any' türüne sahip.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Çıkış dosyalarının başında bir UTF-8 Bayt Sırası İşareti (BOM) gösterin.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Ayrı bir dosya oluşturmak yerine, kaynak eşlemeleri içeren tek bir dosya gösterin.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Kaynağı, kaynak eşlemeleri ile birlikte tek bir dosya içinde gösterin; '--inlineSourceMap' veya '--sourceMap' öğesinin ayarlanmasını gerektirir.", + "Enable_all_strict_type_checking_options_6180": "Tüm katı tür denetleme seçeneklerini etkinleştirin.", + "Enable_strict_checking_of_function_types_6186": "İşlev türleri üzerinde katı denetimi etkinleştirin.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", + "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", + "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", + "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", + "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Numaralandırma bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", + "Enum_member_expected_1132": "Numaralandırma üyesi bekleniyor.", + "Enum_member_must_have_initializer_1061": "Numaralandırma üyesi bir başlatıcıya sahip olmalıdır.", + "Enum_name_cannot_be_0_2431": "Sabit listesi adı '{0}' olamaz.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Sabit listesi türü '{0}', sabit değer olmayan başlatıcılara sahip üyeler içeriyor.", + "Examples_Colon_0_6026": "Örnekler: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Aşırı yığın derinliği, '{0}' ve '{1}' türlerini karşılaştırıyor.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} türünde bağımsız değişkenler bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", + "Expected_0_arguments_but_got_1_2554": "{0} bağımsız değişken bekleniyordu ancak {1} alındı.", + "Expected_0_arguments_but_got_1_or_more_2556": "{0} bağımsız değişken bekleniyordu ancak {1} veya daha fazla bağımsız değişken alındı.", + "Expected_0_type_arguments_but_got_1_2558": "{0} türünde bağımsız değişkenler bekleniyordu ancak {1} alındı.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} türünde bağımsız değişkenler bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", + "Expected_at_least_0_arguments_but_got_1_2555": "En az {0} bağımsız değişken bekleniyordu ancak {1} alındı.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "En az {0} bağımsız değişken bekleniyordu ancak {1} veya daha fazla bağımsız değişken alındı.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' için ilgili JSX kapanış etiketi bekleniyor.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX parçasına karşılık gelen kapanış etiketi bekleniyordu.", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "'Package.json' öğesindeki '{0}' alanının türünün 'string' olması bekleniyordu, ancak '{1}' alındı.", + "Experimental_Options_6177": "Deneysel Seçenekler", + "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Dekoratörler için sunulan deneysel destek özelliği, sonraki sürümlerde değiştirilebilir. Bu uyarıyı kaldırmak için 'experimentalDecorators' seçeneğini ayarlayın.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Açık olarak belirtilen modül çözümleme türü: '{0}'.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript modülleri hedeflenirken dışarı aktarma ataması kullanılamaz. Bunun yerine 'export default' veya başka bir modül biçimi kullanmayı deneyin.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' bayrağı 'system' ise dışarı aktarma ataması desteklenmez.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Dışarı aktarma bildirimi, dışarı aktarılan '{0}' bildirimiyle çakışıyor.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Ad alanında dışarı aktarma bildirimlerine izin verilmez.", + "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Dışarı aktarılan dış paket yazı dosyası '{0}', bir modül değil. Paket tanımını güncelleştirmek için lütfen paket yazarı ile iletişime geçin.", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Dışarı aktarılan dış paket yazıları, üç eğik çizgili başvurular içeremez. Paket tanımını güncelleştirmek için lütfen paket yazarı ile iletişime geçin.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Dışarı aktarılan '{0}' tür diğer adı, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Dışarı aktarılan '{0}' değişkeni, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Dışarı aktarılan '{0}' değişkeni, '{2}' özel modüldeki '{1}' özel adına sahip veya bu adı kullanıyor.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Dışarı aktarılan '{0}' değişkeni, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Modül genişletmelerinde dışarı aktarmalara ve dışarı aktarma atamalarına izin verilmez.", + "Expression_expected_1109": "İfade bekleniyor.", + "Expression_or_comma_expected_1137": "İfade veya virgül bekleniyor.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "İfade, derleyicinin temel sınıf başvurusunu yakalamak için kullandığı '_super' öğesi olarak çözümleniyor.", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "İfade, derleyicinin zaman uyumsuz işlevleri desteklemek için kullandığı '{0}' değişken bildirimi olarak çözümleniyor.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "İfade, derleyicinin 'new.target' meta-özellik başvurusu yakalamak için kullandığı '_newTarget' değişken bildirimi olarak çözümleniyor.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "İfade, derleyicinin 'this' başvurusunu yakalamak için kullandığı '_this' değişken bildirimi olarak çözümleniyor.", + "Extract_constant_95006": "Sabiti ayıkla", + "Extract_function_95005": "İşlevi ayıkla", + "Extract_symbol_95003": "Sembolü ayıkla", + "Extract_to_0_in_1_95004": "{1} içindeki {0} konumuna ayıkla", + "Extract_to_0_in_1_scope_95008": "{1} kapsamındaki {0} konumuna ayıkla", + "Extract_to_0_in_enclosing_scope_95007": "Çevreleyen kapsamdaki {0} konumuna ayıkla", + "FILE_6035": "DOSYA", + "FILE_OR_DIRECTORY_6040": "DOSYA VEYA DİZİN", + "Failed_to_parse_file_0_Colon_1_5014": "'{0}' dosyası ayrıştırılamadı: {1}.", + "Fallthrough_case_in_switch_7029": "switch deyiminde sonraki ifadeye geçiş.", + "File_0_does_not_exist_6096": "'{0}' adlı dosya yok.", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "'{0}' adlı dosya yok; bunu bir çözümleme sonucu olarak kullanın.", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' dosyasının desteklenmeyen bir uzantısı olduğundan dosya atlanıyor.", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' dosyası desteklenmeyen uzantıya sahip. Yalnızca {1} uzantıları desteklenir.", + "File_0_is_not_a_module_2306": "'{0}' dosyası bir modül değil.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' dosyası, 'rootDir' '{1}' dizininde değil. 'rootDir' dizininin tüm kaynak dosyalarını içermesi bekleniyor.", + "File_0_not_found_6053": "'{0}' dosyası bulunamadı.", + "File_change_detected_Starting_incremental_compilation_6032": "Dosya değişikliği algılandı. Artımlı derleme başlatılıyor...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' dosya adının, zaten eklenmiş olan '{1}' dosya adından tek farkı, büyük/küçük harf kullanımı.", + "File_name_0_has_a_1_extension_stripping_it_6132": "'{0}' dosya adında '{1}' uzantısı var; uzantı ayrılıyor.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Dosya belirtimi, özyinelemeli dizin joker karakterinden ('**') sonra görünen bir üst dizin ('..') içeremez: '{0}'.", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Dosya belirtimi, birden fazla özyinelemeli dizin joker karakter ('**') içeremez: '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Dosya belirtimi, özyinelemeli dizin joker karakter ('**') ile bitemez: '{0}'.", + "Found_package_json_at_0_6099": "'{0}' içinde 'package.json' bulundu.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez. Sınıf tanımları otomatik olarak katı moddadır.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez. Modüller otomatik olarak katı moddadır.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Dönüş türü ek açıklaması bulunmayan işlev ifadesi, örtük olarak '{0}' dönüş türüne sahip.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "İşlev uygulaması yok veya bildirimden hemen sonra gelmiyor.", + "Function_implementation_name_must_be_0_2389": "İşlev uygulamasının adı '{0}' olmalıdır.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dönüş türü ek açıklamasına sahip olmadığından ve doğrudan veya dolaylı olarak dönüş ifadelerinden birinde kendine başvurulduğundan işlev, örtük olarak 'any' türüne sahiptir.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "İşlevin sonunda return deyimi eksik ve dönüş türü 'undefined' içermiyor.", + "Function_overload_must_be_static_2387": "İşlev aşırı yüklemesi statik olmalıdır.", + "Function_overload_must_not_be_static_2388": "İşlev aşırı yüklemesi statik olmamalıdır.", + "Generates_corresponding_d_ts_file_6002": "İlgili '.d.ts' dosyasını oluşturur.", + "Generates_corresponding_map_file_6043": "İlgili '.map' dosyasını oluşturur.", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Oluşturucu herhangi bir değer içermediğinden örtük olarak '{0}' türüne sahip. Bir dönüş türü sağlamayı göz önünde bulundurun.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Çevresel bağlamda oluşturuculara izin verilmez.", + "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.", + "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.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Genel modül dışarı aktarmaları yalnızca modül dosyalarında görünebilir.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "'{0}' genel türü, bir sınıf veya arabirim türü olmalıdır.", + "Global_type_0_must_have_1_type_parameter_s_2317": "'{0}' genel türü, {1} türünde parametre içermelidir.", + "Hexadecimal_digit_expected_1125": "Onaltılık basamak bekleniyor.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür. Sınıf tanımları otomatik olarak katı moddadır.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür. Modüller otomatik olarak katı moddadır.", + "Identifier_expected_1003": "Tanımlayıcı bekleniyor.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Tanımlayıcı bekleniyor. '__esModule', ECMAScript modülleri dönüştürülürken, dışarı aktarılan bir işaretçi olarak ayrılmış.", + "Ignore_this_error_message_90019": "Bu hata iletisini yoksayın.", + "Implement_inherited_abstract_class_90007": "Devralınmış soyut sınıfı uygulayın.", + "Implement_interface_0_90006": "'{0}' arabirimini uygulayın.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "'{1}' özel adına sahip veya bu adı kullanan '{0}' dışarı aktarılan sınıfının yan tümcesini uygular.", + "Import_0_from_module_1_90013": "\"{1}\" modülünden '{0}' öğesini içeri aktarın.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript modülleri hedeflenirken içeri aktarma ataması kullanılamaz. Bunun yerine 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' veya başka bir modül biçimi kullanmayı deneyin.", + "Import_declaration_0_is_using_private_name_1_4000": "'{0}' içeri aktarma bildirimi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "İçeri aktarma bildirimi, yerel '{0}' bildirimiyle çakışıyor.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Ad alanındaki içeri aktarma bildirimleri bir modüle başvuramaz.", + "Import_emit_helpers_from_tslib_6139": "'Tslib'den yayma yardımcılarını içeri aktar.", + "Import_name_cannot_be_0_2438": "İçeri aktarma adı '{0}' olamaz.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Çevresel modül bildirimindeki içeri veya dışarı aktarma bildirimi, göreli modül adı aracılığıyla modüle başvuramaz.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Modül genişletmelerinde içeri aktarmalara izin verilmez. Bunları, kapsayan dış modüle taşımanız önerilir.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Çevresel numaralandırma bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Birden fazla bildirime sahip numaralandırmada yalnızca bir bildirim ilk numaralandırma öğesine ait başlatıcıyı atlayabilir.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' numaralandırma bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' türündeki dizin imzası yalnızca okumaya izin veriyor.", + "Index_signature_is_missing_in_type_0_2329": "'{0}' türündeki dizin imzası yok.", + "Index_signatures_are_incompatible_2330": "Dizin imzaları uyumsuz.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "'{0}' birleştirilmiş bildirimindeki bildirimlerin tümü dışarı aktarılmış veya yerel olmalıdır.", + "Infer_parameter_types_from_usage_95012": "Parametre türlerini kullanımdan çıkarsayın.", + "Infer_type_of_0_from_usage_95011": "'{0}' türünü kullanımdan çıkarsayın.", + "Initialize_property_0_in_the_constructor_90020": "Oluşturucu içinde '{0}' özelliğini başlatın.", + "Initialize_static_property_0_90021": "'{0}' statik özelliğini başlatın.", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "'{0}' örnek üyesi değişkeninin başlatıcısı, oluşturucuda bildirilen '{1}' tanımlayıcısına başvuramaz.", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "'{0}' parametresinin başlatıcısı, kendinden sonra bildirilen '{1}' tanımlayıcısına başvuramaz.", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Başlatıcı bu bağlama öğesi için bir değer sağlamıyor ve bağlama öğesi varsayılan değere sahip değil.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Çevresel bağlamlarda başlatıcılara izin verilmez.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Bir TypeScript projesi başlatır ve bir tsconfig.json dosyası oluşturur.", + "Insert_command_line_options_and_files_from_a_file_6030": "Dosyadaki komut satırı seçeneklerini ve dosyaları ekleyin.", + "Install_0_95014": "'{0}' yükle", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "'{0}' arabirimi, aynı anda '{1}' ve '{2}' türlerini genişletemez.", + "Interface_0_incorrectly_extends_interface_1_2430": "'{0}' arabirimi, '{1}' arabirimini yanlış genişletiyor.", + "Interface_declaration_cannot_have_implements_clause_1176": "Arabirim bildirimi, 'implements' yan tümcesine sahip olamaz.", + "Interface_name_cannot_be_0_2427": "Arabirim adı '{0}' olamaz.", + "Invalid_character_1127": "Geçersiz karakter.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Genişletmedeki modül adı geçersiz. '{0}' modülü, '{1}' konumundaki türü belirsiz ve genişletilemeyen bir modüle çözümleniyor.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Genişletmedeki modül adı geçersiz; '{0}' adlı modül bulunamıyor.", + "Invalid_reference_directive_syntax_1084": "Geçersiz 'reference' yönergesi söz dizimi.", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "Geçersiz '{0}' kullanımı. Sınıf tanımları otomatik olarak katı moddadır.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Geçersiz '{0}' kullanımı. Modüller otomatik olarak katı moddadır.", + "Invalid_use_of_0_in_strict_mode_1100": "Katı modda geçersiz '{0}' kullanımı.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' değeri geçersiz. '{0}' geçerli bir tanımlayıcı veya tam ad değil.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' için geçersiz değer. '{0}' geçerli bir tanımlayıcı değil.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}', 'extends {2}' yan tümcesiyle eşleşmiyor.", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' bir sınıfa eklenmemiş.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' yalnızca bir imzanın son parametresi içinde görünebilir.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' etiketinin adı '{0}' ancak bu ada sahip bir parametre yok.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' etiketi bir tür ek açıklamasına sahip olmalıdır veya sonrasında '@property' ya da '@member' etiketlerinden biri gelmelidir.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc türleri yalnızca belge açıklamalarının içinde kullanılabilir.", + "JSX_attribute_expected_17003": "JSX özniteliği bekleniyor.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX özniteliklerine yalnızca boş olmayan 'expression' ifadesi atanabilir.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "'{0}' adlı JSX öğesine karşılık gelen bir kapatma etiketi yok.", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX öğesinin öznitelik türü '{0}', birleşim türü olamaz.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX öğe sınıfı, '{0}' özelliğine sahip olmadığı için öznitelikleri desteklemiyor.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Herhangi bir arabirim 'JSX.{0}' öğesi olmadığı için JSX öğesi örtük olarak 'any' türüne sahip.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Genel türdeki 'JSX.Element' öğesi olmadığı için JSX öğesi örtük olarak 'any' türüne sahip.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX öğesi türü '{0}', oluşturma veya çağrı imzasına sahip değil.", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX öğesi türü '{0}', JSX öğelerine ait bir oluşturucu işlevi değil.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX öğeleri aynı ada sahip birden fazla özniteliğe sahip olamaz.", + "JSX_expressions_must_have_one_parent_element_2657": "JSX ifadelerinin bir üst öğesi olmalıdır.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX parçasına karşılık gelen bir kapatma etiketi yok.", + "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "JSX parçası --jsxFactory kullanılırken desteklenmiyor", + "JSX_spread_child_must_be_an_array_type_2609": "JSX yayılma alt öğesi, bir dizi türü olmalıdır.", + "Jump_target_cannot_cross_function_boundary_1107": "Atlama hedefi işlev sınırını geçemez.", + "KIND_6034": "TÜR", + "LOCATION_6037": "KONUM", + "Language_service_is_disabled_9004": "Dil hizmeti devre dışı.", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Virgül işlecinin sol tarafı kullanılmıyor ve herhangi bir yan etkisi yok.", + "Line_break_not_permitted_here_1142": "Burada satır sonuna izin verilmez.", + "Line_terminator_not_permitted_before_arrow_1200": "Oktan önce satır sonlandırıcısına izin verilmez.", + "List_of_folders_to_include_type_definitions_from_6161": "Eklenecek tür tanımlarının alınacağı klasörlerin listesi.", + "List_of_language_service_plugins_6181": "Dil hizmeti eklentilerinin listesi.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Birleştirilmiş içerikleri, çalışma zamanında proje yapısını temsil eden kök klasörlerin listesi.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "'{1}' kök dizininden '{0}' yükleniyor; aday konumu: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' klasöründen '{0}' modülü yükleniyor, hedef dosya türü '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "Modül, dosya/klasör olarak yükleniyor; aday modül konumu '{0}'; hedef dosya türü '{1}'.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Yerel ayar, veya - biçiminde olmalıdır. Örneğin, '{0}' veya '{1}'.", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}' için eşleşen en uzun ön ek: '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' klasöründe aranıyor; ilk konum: '{0}'.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Oluşturucudaki ilk deyime 'super()' tarafından çağrı yapılmasını sağla.", + "Member_0_implicitly_has_an_1_type_7008": "'{0}' üyesi örtük olarak '{1}' türüne sahip.", + "Merge_conflict_marker_encountered_1185": "Birleştirme çakışması işaretçisiyle karşılaşıldı.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "'{0}' birleştirilen bildirimi, varsayılan bir dışarı aktarma bildirimini içeremez. Bunun yerine ayrı bir 'export default {0}' bildirimi eklemeyi göz önünde bulundurun.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "'{0}' meta-özelliğine yalnızca bir işlev bildiriminin, işlev ifadesinin veya oluşturucunun gövdesinde izin verilir.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "'{0}' metodu abstract olarak işaretlendiğinden bir uygulamaya sahip olamaz.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Dışarı aktarılan arabirimin '{0}' metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Dışarı aktarılan arabirimin '{0}' metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Modifiers_cannot_appear_here_1184": "Değiştiriciler burada görüntülenemez.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} modülü, '{1}' adlı bir üyeyi zaten dışarı aktardı. Belirsizliği çözmek için açık olarak yeniden dışarı aktarmayı göz önünde bulundurun.", + "Module_0_has_no_default_export_1192": "'{0}' modülü için varsayılan dışarı aktarma yok.", + "Module_0_has_no_exported_member_1_2305": "'{0}' modülü, dışarı aktarılan '{1}' üyesine sahip değil.", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' modülü, aynı ada sahip bir yerel bildirim tarafından gizleniyor.", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "'{0}' modülü, modül olmayan bir varlığa çözümleniyor ve bu oluşturma ile içeri aktarılamaz.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "'{0}' modülü 'export =' kullanıyor ve 'export *' ile birlikte kullanılamaz.", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "'{1}' dosyası değiştirilmediğinden '{0}' modülü, bu dosyada bildirilen çevresel modül olarak çözümlendi.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "'{0}' modülü, '{1}' dosyasında yerel olarak bildirilmiş çevresel modül olarak çözümlendi.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "'{0}' modülü '{1}' olarak çözüldü ancak '--jsx' ayarlanmadı.", + "Module_Resolution_Options_6174": "Modül Çözünürlüğü Seçenekleri", + "Module_name_0_matched_pattern_1_6092": "Modül adı: '{0}', eşleşen desen: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== '{0}' modül adı çözümlenemedi. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== '{0}' modül adı '{1}' öğesine başarıyla çözümlendi. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Modül çözümleme türü belirtilmedi, '{0}' kullanılıyor.", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' kullanarak modül çözümleme başarısız oldu.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Birden çok oluşturucu uygulamasına izin verilmez.", + "NEWLINE_6061": "YENİ SATIR", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' ve '{2}' türündeki '{0}' adlı özellikler aynı değil.", + "Namespace_0_has_no_exported_member_1_2694": "'{0}' ad alanında dışarı aktarılan '{1}' üyesi yok.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Hiçbir temel oluşturucu, belirtilen tür bağımsız değişkeni sayısına sahip değil.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "'{0}' yapılandırma dosyasında giriş bulunamadı. Belirtilen 'include' yolları: '{1}', 'exclude' yolları: '{2}'.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Soyut olmayan '{0}' sınıfı, '{2}' sınıfından devralınan '{1}' soyut üyesini uygulamıyor.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Soyut olmayan sınıf ifadesi, '{1}' sınıfından devralınan '{0}' soyut üyesini uygulamıyor.", + "Not_all_code_paths_return_a_value_7030": "Tüm kod yolları bir değer döndürmez.", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "'{0}' sayısal dizin türü, '{1}' dize dizini türüne atanamaz.", + "Object_is_possibly_null_2531": "Nesne büyük olasılıkla 'null'.", + "Object_is_possibly_null_or_undefined_2533": "Nesne büyük olasılıkla 'null' veya 'undefined'.", + "Object_is_possibly_undefined_2532": "Nesne büyük olasılıkla 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Nesne sabit değeri yalnızca bilinen özellikleri belirtebilir ve '{0}', '{1}' türünde değil.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Nesne sabit değerinde yalnızca bilinen özellikler belirtilebilir, ancak '{0}', '{1}' türünde yok. '{2}' yazmak mı istediniz?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "'{0}' nesne sabit değeri özelliği, örtük olarak '{1}' türüne sahip.", + "Octal_digit_expected_1178": "Sekizli basamak bekleniyor.", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Sekizlik sabit değerli türlerde ES2015 söz dizimi kullanılmalıdır. '{0}' söz dizimini kullanın.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Sabit listesi üyelerinin başlatıcısında sekizlik sabit değerlere izin verilmez. '{0}' söz dizimini kullanın.", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "Katı modda sekizlik sabit değerlere izin verilmez.", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 ve üzeri hedeflenirken sekizlik sabit değerler kullanılamaz. '{0}' söz dizimini kullanın.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' deyiminde yalnızca tek bir değişken bildirimine izin verilir.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' deyiminde yalnızca tek bir değişken bildirimine izin verilir.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' anahtar sözcüğüyle yalnızca void işlevi çağrılabilir.", + "Only_ambient_modules_can_use_quoted_names_1035": "Yalnızca çevresel modüller tırnak içinde ad kullanabilir.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} ile birlikte yalnızca 'amd' ve 'system' modülleri desteklenir.", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Sınıf 'extends' yan tümceleri içinde, şu an için yalnızca isteğe bağlı tür bağımsız değişkenlerine sahip tanımlayıcılar/tam adlar destekleniyor.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' anahtar sözcüğüyle yalnızca temel sınıfa ait ortak ve korunan metotlara erişilebilir.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' işleci, '{1}' ve '{2}' türüne uygulanamaz.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "'{0}' seçeneği yalnızca 'tsconfig.json' dosyasında belirtilebilir.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "'{0} seçeneği yalnızca '--inlineSourceMap' veya '--sourceMap' seçeneği sağlandığında kullanılabilir.", + "Option_0_cannot_be_specified_with_option_1_5053": "'{0}' seçeneği, '{1}' seçeneği ile belirtilemez.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "'{0}' seçeneği, '{1}' seçeneği belirtilmeden belirtilemez.", + "Option_0_should_have_array_of_strings_as_a_value_6103": "'{0}' seçeneği değer olarak, dizelerden oluşan bir dizi içermelidir.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' seçeneği, yalnızca '--module' sağlandığında veya 'target' seçeneği 'ES2015' veya daha yüksek bir sürüm değerine sahip olduğunda kullanılabilir.", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'Paths' seçeneği, '--baseUrl' seçeneği belirtilmeden kullanılamaz.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "'project' seçeneği, komut satırındaki kaynak dosyalarıyla karıştırılamaz.", + "Options_Colon_6027": "Seçenekler:", + "Output_directory_for_generated_declaration_files_6166": "Oluşturulan bildirim dosyaları için çıkış dizini.", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "Aşırı yükleme imzası işlev uygulamasıyla uyumlu değil.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Aşırı yükleme imzalarının hepsi soyut veya soyut olmayan olmalıdır.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Aşırı yükleme imzalarının tümü çevresel veya çevresel olmayan türde olmalıdır.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Aşırı yükleme imzalarının hepsi dışarı aktarılmış veya dışarı aktarılmamış olmalıdır.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Aşırı yükleme imzalarının tümü isteğe bağlı veya gerekli olmalıdır.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Aşırı yükleme imzalarının tümü ortak, özel veya korumalı olmalıdır.", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "'{0}' parametresine başlatıcısında başvurulamaz.", + "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' parametresi örtük olarak '{1}' türüne sahip.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' parametresi, '{1}' parametresi ile aynı konumda değil.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Dışarı aktarılan işlevin '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Dışarı aktarılan işlevin '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Dışarı aktarılan işlevin '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Dışarı aktarılan arabirimin dizin imzasındaki '{0}' parametresi, '{2}' adlı özel modüldeki '{1}' adına sahip ya da bu adı kullanıyor.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Dışarı aktarılan arabirimin dizin imzasındaki '{0}' parametresi, '{1}' adına sahip ya da bu adı kullanıyor.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Dışarı aktarılan arabirimdeki metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Dışarı aktarılan arabirimdeki metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Dışarı aktarılan sınıftaki statik metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Dışarı aktarılan sınıftaki statik metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametre soru işareti ve başlatıcı içeremez.", + "Parameter_declaration_expected_1138": "Parametre bildirimi bekleniyor.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Katı modda ayrıştırın ve her kaynak dosya için \"use strict\" kullanın.", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' deseni en fazla bir adet '*' karakteri içerebilir.", + "Prefix_0_with_an_underscore_90025": "'{0}' için ön ek olarak alt çizgi kullanın.", + "Print_names_of_files_part_of_the_compilation_6155": "Derlemenin parçası olan dosyaların adlarını yazdırın.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Oluşturulan dosyalardan, derlemenin parçası olanların adlarını yazdırın.", + "Print_the_compiler_s_version_6019": "Derleyici sürümünü yazdır.", + "Print_this_message_6017": "Bu iletiyi yazdır.", + "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' numaralandırması üzerinde değil.", + "Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' özelliği '{1}' türünde yok. Bunu mu demek istediniz: '{2}'?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' özelliği, çakışan bildirimler içeriyor ve '{1}' türü içinde erişilebilir değil.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "'{0}' özelliği başlatıcı içermiyor ve oluşturucuda kesin olarak atanmamış.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' özelliği, get erişimcisinin dönüş türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' özelliği, set erişimcisinin parametre türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' türündeki '{0}' özelliği, '{2}' türüne atanamaz.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "'{0}' özelliği bildirildi ancak değeri hiç okunmadı.", + "Property_0_is_incompatible_with_index_signature_2530": "'{0}' özelliği, dizin imzasıyla uyumsuz.", + "Property_0_is_missing_in_type_1_2324": "'{0}' özelliği '{1}' türünde değil.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "'{0}' özelliği, '{1}' türünde isteğe bağlıdır, ancak '{2}' türünde gereklidir.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' özelliği özeldir ve yalnızca '{1}' sınıfı içinden erişilebilir.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "'{0}' özelliği, '{1}' türünde özel, '{2}' türünde özel değildir.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "'{0}' özelliği korumalıdır ve yalnızca '{1}' sınıfının örneği aracılığıyla erişilebilir.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' özelliği korumalıdır ve yalnızca '{1}' sınıfı içinden ve alt sınıflarından erişilebilir.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' özelliği korumalıdır; ancak '{1}' türü, '{2}' öğesinden türetilmiş bir sınıf değildir.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "'{0}' özelliği '{1}' türünde korumalı, '{2}' türünde ise ortaktır.", + "Property_0_is_used_before_being_assigned_2565": "'{0}' özelliği atanmadan önce kullanıldı.", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX yayılma özniteliğine ait '{0}' özelliği, hedef özelliğe atanamaz.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "Dışarı aktarılan sınıf ifadesinin '{0}' özelliği, özel veya korumalı olmayabilir.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Dışarı aktarılan arabirimin '{0}' özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Dışarı aktarılan arabirimin '{0}' özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "'{1}' türünün '{0}' özelliği, '{2}' sayısal dizin türüne atanamaz.", + "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "'{1}' türünün '{0}' özelliği, '{2}' dize dizini türüne atanamaz.", + "Property_assignment_expected_1136": "Özellik ataması bekleniyor.", + "Property_destructuring_pattern_expected_1180": "Özellik yok etme deseni bekleniyor.", + "Property_or_signature_expected_1131": "Özellik veya imza bekleniyor.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Özellik değeri yalnızca, dize sabit değeri, sayısal sabit değer, 'true', 'false', 'null', nesne sabit değeri veya dizi sabit değeri olabilir.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'ES5' veya 'ES3' hedefleniyorsa, 'for-of' içindeki yinelenebilir öğeler için yayılma ve yok etmeye yönelik tam destek sağlayın.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Dışarı aktarılan sınıfın '{0}' genel metodu, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Dışarı aktarılan sınıfın '{0}' genel metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Dışarı aktarılan sınıfın '{0}' genel metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Belirtilen 'any' türüne sahip ifade ve bildirimlerde hata oluştur.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Örtük olarak 'any' türü içeren 'this' ifadelerinde hata tetikle.", + "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", + "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldırın.", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.", + "Report_errors_in_js_files_8019": ".js dosyalarındaki hataları bildirin.", + "Report_errors_on_unused_locals_6134": "Kullanılmayan yerel öğelerdeki hataları bildirin.", + "Report_errors_on_unused_parameters_6135": "Kullanılmayan parametrelerdeki hataları bildirin.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Gerekli tür parametreleri, isteğe bağlı tür parametrelerini takip edemez.", + "Resolution_for_module_0_was_found_in_cache_6147": "'{0}' modülüne yönelik çözüm önbellekte bulundu.", + "Resolving_from_node_modules_folder_6118": "Node_modules klasöründen çözümleniyor...", + "Resolving_module_0_from_1_6086": "======== '{0}' modülü '{1}' öğesinden çözümleniyor. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "'{0}' modül adı, '{1}' - '{2}' temel url'sine göre çözümleniyor.", + "Resolving_real_path_for_0_result_1_6130": "'{0}' için gerçek yol çözümleniyor, sonuç: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== '{0}' tür başvurusu yönergesi çözümleniyor, kapsayan dosya: '{1}', kök dizini: '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== '{0}' tür başvuru yönergesi çözümleniyor, içeren dosya '{1}', kök dizin ayarlanmadı. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== '{0}' tür başvurusu yönergesi çözümleniyor, kapsayan dosya ayarlanmadı, kök dizin: '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== '{0}' tür başvurusu yönergesi çözümleniyor, kapsayan dosya ayarlanmadı, kök dizin ayarlanmadı. ========", + "Resolving_using_primary_search_paths_6117": "Birincil arama yolları kullanılarak çözümleniyor...", + "Resolving_with_primary_search_path_0_6121": "Birincil arama yolu '{0}' kullanılarak çözümleniyor.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "'{0}' rest parametresi, örtük olarak 'any[]' türüne sahip.", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest türleri yalnızca nesne türlerinden oluşturulabilir.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Dışarı aktarılan arabirimdeki çağrı imzasının dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Dışarı aktarılan arabirimdeki çağrı imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Dışarı aktarılan arabirimdeki oluşturucu imzasının dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Dışarı aktarılan arabirimdeki oluşturucu imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Oluşturucu imzasının dönüş türü, sınıfın örnek türüne atanabilir olmalıdır.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Dışarı aktarılan işlevin dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Dışarı aktarılan işlevin dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Dışarı aktarılan işlevin dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Dışarı aktarılan arabirimdeki dizin imzasının dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Dışarı aktarılan arabirimdeki dizin imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Dışarı aktarılan arabirimdeki metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Dışarı aktarılan arabirimdeki metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adını taşıyor veya kullanıyor ancak adlandırılamıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adını taşıyor veya kullanıyor ancak adlandırılamıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Eski programdaki çözmeler değişmediğinden '{0}' kaynaklı modül çözmeleri yeniden kullanılıyor.", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Eski programın '{1}' dosyasında '{0}' modülü çözmesi yeniden kullanılıyor.", + "Rewrite_as_the_indexed_access_type_0_90026": "Dizine eklenmiş erişim türü '{0}' olarak yeniden yazın.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Kök dizin belirlenemiyor, birincil arama yolları atlanıyor.", + "STRATEGY_6039": "STRATEJİ", + "Scoped_package_detected_looking_in_0_6182": "Kapsamlı paket algılandı, '{0}' içinde aranıyor", + "Setters_cannot_return_a_value_2408": "Ayarlayıcılar bir değer döndüremez.", + "Show_all_compiler_options_6169": "Tüm derleyici seçeneklerini gösterin.", + "Show_diagnostic_information_6149": "Tanılama bilgilerini gösterin.", + "Show_verbose_diagnostic_information_6150": "Ayrıntılı tanılama bilgilerini gösterin.", + "Signature_0_must_be_a_type_predicate_1224": "'{0}' imzası bir tür koşulu olmalıdır.", + "Skip_type_checking_of_declaration_files_6012": "Bildirim dosyalarının tür denetimini atla.", + "Source_Map_Options_6175": "Kaynak Eşleme Seçenekleri", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Özelleşmiş aşırı yükleme imzası özelleşmemiş imzalara atanamaz.", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Dinamik içeri aktarmanın tanımlayıcısı, yayılma öğesi olamaz.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript hedef sürümünü belirleyin: 'ES3' (varsayılan), 'ES5', 'ES2015', 'ES2016', 'ES2017' ya da 'ESNEXT'.", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX kod oluşturma seçeneğini belirtin: 'preserve', 'react-native' veya 'react'.", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Derlemeye dahil edilecek kitaplık dosyalarını belirtin: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Modül kodu oluşturmayı belirtin: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' veya 'ESNext'.", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Modül çözümleme stratejisini belirtin: 'Node' (Node.js) veya 'classic' (TypeScript pre-1.6).", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'React.createElement' veya 'h' gibi 'react' JSX emit hedeflerken kullanılacak JSX fabrika işlevini belirtin.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Dosyalar gösterilirken kullanılacak satır sonu dizisini belirtin: 'CRLF' (dos) veya 'LF' (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Hata ayıklayıcının TypeScript dosyalarını kaynak konumlar yerine nerede bulması gerektiğini belirtin.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Hata ayıklayıcının, eşlem dosyalarını üretilen konumlar yerine nerede bulması gerektiğini belirtin.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Giriş dosyalarının kök dizinini belirtin. Çıkış dizininin yapısını --outDir ile denetlemek için kullanın.", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' ifadelerindeki yayılma işleci yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", + "Spread_types_may_only_be_created_from_object_types_2698": "Spread türleri yalnızca nesne türlerinden oluşturulabilir.", + "Statement_expected_1129": "Deyim bekleniyor.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Çevresel bağlamlarda deyimlere izin verilmez.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statik üyeler sınıf türündeki parametrelere başvuramaz.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "'{0}' statik özelliği, '{1}' oluşturucu işlevinin yerleşik özelliği olan 'Function.{0}' ile çakışıyor.", + "Strict_Type_Checking_Options_6173": "Katı Tür Denetimi Seçenekleri", + "String_literal_expected_1141": "Dize sabit değeri bekleniyor.", + "String_literal_with_double_quotes_expected_1327": "Çift tırnak içine alınmış bir dize sabit değeri bekleniyor.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Renk ve bağlam kullanarak hataların ve iletilerin stilini belirleyin (deneysel).", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Ardışık değişken bildirimleri aynı türe sahip olmalıdır. '{0}' değişkeni '{1}' türünde olmalıdır, ancak burada '{2}' türüne sahip.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' deseni için '{0}' alternatifinin türü hatalı; beklenen: 'string' alınan: '{2}'.", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "'{1}' desenindeki '{0}' değişimi, en fazla bir adet '*' karakteri içerebilir.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "'{0}' deseni için değişimler bir dizi olmalıdır.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "'{0}' deseni için değiştirme değeri boş bir dizi olamaz.", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json dosyası başarıyla oluşturuldu.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Super çağrılarına oluşturucu dışında veya oluşturucu içindeki iç içe işlevlerde izin verilmez.", + "Suppress_excess_property_checks_for_object_literals_6072": "Nesne sabit değerlerine ait fazla özellik denetimlerini gösterme.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Dizin imzaları olmayan nesneler için dizin oluştururken noImplicitAny hatalarını gösterme.", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'Symbol' başvurusu, genel Simge oluşturucu nesnesine başvurmaz.", + "Syntax_Colon_0_6023": "Söz dizimi: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' işleci, 'symbol' türüne uygulanamaz.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' işlecine boole türü için izin verilmez. Bunun yerine '{1}' kullanmayı göz önünde bulundurun.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' türü başka çok az sayıda türe atanabilir. Bunun yerine 'any' türünü mü kullanmak istemiştiniz?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "ES3 ve ES5'te bulunan bir ok işlevinde 'arguments' nesnesine başvuru yapılamaz. Standart bir işlev ifadesi kullanmayı göz önünde bulundurun.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "ES3 ve ES5'te 'arguments' nesnesine zaman uyumsuz bir işlev veya metot içinde başvurulamaz. Standart bir işlev veya metot kullanmayı düşünün.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' deyiminin gövdesi boş deyim olamaz.", + "The_character_set_of_the_input_files_6163": "Girdi dosyalarının karakter kümesi.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "İçeren işlev veya modül gövdesi, denetim akışı analizi için çok büyük.", + "The_current_host_does_not_support_the_0_option_5001": "Mevcut ana bilgisayar '{0}' seçeneğini desteklemiyor.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Bir dışarı aktarma ataması ifadesi, çevresel bağlamda bir tanımlayıcı veya tam ad olmalıdır.", + "The_files_list_in_config_file_0_is_empty_18002": "'{0}' yapılandırma dosyasındaki 'dosyalar' listesi boş.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise'in 'then' metodunun ilk parametresi, bir geri arama parametresi olmalıdır.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "'JSX.{0}' genel türü birden fazla özelliğe sahip olamaz.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Çıkarsanan '{0}' türü, erişilemeyen bir '{1}' türüne başvuruyor. Tür ek açıklaması gereklidir.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' deyiminin sol tarafı yok etme deseni olamaz.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' deyiminin sol tarafında tür ek açıklaması kullanılamaz.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' deyiminin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' deyiminin sol tarafı 'string' veya 'any' türünde olmalıdır.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' deyiminin sol tarafında tür ek açıklaması kullanılamaz.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' deyiminin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Aritmetik işlemin sol tarafı, 'any', 'number' veya bir numaralandırma türünde olmalıdır.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Atama ifadesinin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' ifadesinin sol tarafı, 'any', 'string', 'number' veya 'symbol' türünde olmalıdır.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' ifadesinin sol tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Kullanıcıya ileti görüntülenirken kullanılacak yerel ayar (örn. 'tr-tr')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules altında arama yapmak ve JavaScript dosyalarını yüklemek için en yüksek bağımlılık derinliği.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Delete işlecinin işleneni, salt okunur bir özellik olamaz.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Delete işlecinin işleneni, bir özellik başvurusu olmalıdır.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Artırma veya eksiltme operatörünün işleneni, bir değişken veya özellik erişimi olmalıdır.", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX öğe oluşturucusuna ait dönüş türü bir nesne türünü döndürmelidir.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Parametre dekoratör işlevine ait dönüş türü 'void' veya 'any' olmalıdır.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Özellik dekoratör işlevine ait dönüş türü 'void' veya 'any' olmalıdır.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Zaman uyumsuz bir işlevin dönüş türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Zaman uyumsuz bir işlevin ya da metodun döndürme türü, genel Promise türü olmalıdır.", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "'for...in' deyiminin sağ tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Aritmetik işlemin sağ tarafı, 'any', 'number' veya bir numaralandırma türünde olmalıdır.", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' ifadesinin sağ tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", + "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "'instanceof' ifadesinin sağ tarafı 'any' türünde veya 'Function' arabirim türüne atanabilir bir türde olmalıdır.", + "The_specified_path_does_not_exist_Colon_0_5058": "Belirtilen yol yok: '{0}'.", + "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Atama hedefi, bir değişken veya özellik erişimi olmalıdır.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Nesne geri kalan özellik atamasının hedefi, bir değişken veya özellik erişimi olmalıdır.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "'{0}' türünün 'this' bağlamı, metodun '{1}' türündeki 'this' değerine atanamaz.", + "The_this_types_of_each_signature_are_incompatible_2685": "İmzaların 'this' türleri uyumsuz.", + "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "'{0}' tür parametresinin tür bağımsız değişkeni kullanımdan belirlenemez. Tür bağımsız değişkenlerini açık olarak belirtmeyi göz önünde bulundurun.", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "Zaman uyumsuz yineleyicinin 'next()' metodu tarafından döndürülen tür, 'value' özelliğine sahip bir tür için promise olmalıdır.", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "Bir yineleyicinin 'next()' metodu tarafından döndürülen tür, 'value' özelliğine sahip olmalıdır.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' deyiminin değişken bildirimi bir başlatıcıya sahip olamaz.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' deyiminin değişken bildirimi bir başlatıcıya sahip olamaz.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ifadesi desteklenmiyor. 'with' bloklarındaki tüm simgeler 'any' türüne sahip olacaktır.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Bu söz dizimi, içeri aktarılan bir yardımcı gerektiriyor ancak '{0}' modülü bulunamıyor.", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Bu söz dizimi, '{1}' adlı içeri aktarılan yardımcıyı gerektiriyor ancak '{0}' modülünde dışarı aktarılan '{1}' üyesi yok.", + "Trailing_comma_not_allowed_1009": "Sona eklenen virgüle izin verilmez.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Her dosyayı ayrı bir modül olarak derleyin ('ts.transpileModule' gibi).", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Varsa `npm install @types/{0}` deneyin veya `declare module '{0}';` öğesini içeren yeni bir bildirim (.d.ts) dosyası ekleyin", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs' içindeki diğer girişler deneniyor.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "'{0}' alternatifi deneniyor, aday modül konumu: '{1}'.", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "'{1}' uzunluğuna sahip '{0}' demeti, '{2}' uzunluğuna sahip demete atanamaz.", + "Type_0_cannot_be_converted_to_type_1_2352": "'{0}' türü '{1}' türüne dönüştürülemez.", + "Type_0_cannot_be_used_as_an_index_type_2538": "'{0}' türü, dizin türü olarak kullanılamaz.", + "Type_0_cannot_be_used_to_index_type_1_2536": "'{0}' türü, '{1}' türünü dizinlemek için kullanılamaz.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "'{0}' türü, '{1}' kısıtlamasını karşılamıyor.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "'{0}' türü, '{1}' türüyle eşleşen dizin imzasına sahip değil.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "'{0}' türünün '{1}' türüyle ortak özelliği yok.", + "Type_0_has_no_property_1_2460": "'{0}' türü, '{1}' özelliğine sahip değil.", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "'{0}' türü, '{1}' özelliğine ve dize dizin imzasına sahip değil.", + "Type_0_is_not_a_constructor_function_type_2507": "'{0}' türü bir oluşturucu işlevi türü değil.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "ES5/ES3 içindeki '{0}' türü, Promise ile uyumlu bir oluşturucu değerine başvurmadığından geçerli bir zaman uyumsuz işlev dönüş türü değil.", + "Type_0_is_not_an_array_type_2461": "'{0}' türü bir dizi türü değil.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' türü, bir dizi türü veya dize türü değil.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' türü, bir dizi türü veya dize türü değil ya da bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip değil.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' türü, bir dizi türü değil ya da bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip değil.", + "Type_0_is_not_assignable_to_type_1_2322": "'{0}' türü, '{1}' türüne atanamaz.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "'{0}' türü '{1}' türüne atanamaz. Bu ada sahip iki farklı tür mevcut, ancak bu türler birbiriyle ilişkisiz.", + "Type_0_is_not_comparable_to_type_1_2678": "'{0}' türü '{1}' türüyle karşılaştırılamaz.", + "Type_0_is_not_generic_2315": "'{0}' türü genel değil.", + "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' türü, '{1}' imzası için eşleşme sağlamıyor.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "'{0}' türü, öz yinelemeli şekilde kendine temel tür olarak başvuruyor.", + "Type_alias_0_circularly_references_itself_2456": "'{0}' tür diğer adı, döngüsel olarak kendine başvuruyor.", + "Type_alias_name_cannot_be_0_2457": "Tür diğer adı '{0}' olamaz.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Tür ek açıklaması, oluşturucu bildiriminde görüntülenemez.", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "'{1}' tür bağımsız değişken adayı, '{0}' adayının üst türü olmadığından geçerli bir tür bağımsız değişkeni değil.", + "Type_argument_expected_1140": "Tür bağımsız değişkeni bekleniyor.", + "Type_argument_list_cannot_be_empty_1099": "Tür bağımsız değişkeni listesi boş olamaz.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Derlemeye eklenecek tür bildirim dosyaları.", + "Type_expected_1110": "Tür bekleniyor.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Türe, kendi 'then' metodunun tamamlama geri aramasında doğrudan veya dolaylı olarak başvuruluyor.", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Türün, zaman uyumsuz bir yineleyici döndüren bir '[Symbol.asyncIterator]()' metoduna sahip olması gerekir.", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Tür, bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip olmalıdır.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Bir 'yield*' işleneninin yinelenen öğelerinin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Zaman uyumsuz bir oluşturucudaki 'yield' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", + "Type_parameter_0_has_a_circular_constraint_2313": "'{0}' tür parametresi döngüsel bir kısıtlamaya sahip.", + "Type_parameter_0_has_a_circular_default_2716": "'{0}' tür parametresi döngüsel bir varsayılana sahip.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Dışarı aktarılan sınıfın '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Dışarı aktarılan işlevin '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Dışarı aktarılan arabirimin '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Dışarı aktarılan tür diğer adına ait '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Dışarı aktarılan arabirimdeki metodun '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Dışarı aktarılan sınıftaki ortak metodun '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Dışarı aktarılan sınıftaki ortak statik metodun '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Type_parameter_declaration_expected_1139": "Tür parametresi bildirimi bekleniyor.", + "Type_parameter_list_cannot_be_empty_1098": "Tür parametresi listesi boş olamaz.", + "Type_parameter_name_cannot_be_0_2368": "Tür parametresi adı '{0}' olamaz.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Tür parametreleri, oluşturucu bildiriminde görüntülenemez.", + "Type_predicate_0_is_not_assignable_to_1_1226": "'{0}' tür koşulu, '{1}' öğesine atanamaz.", + "Type_reference_directive_0_was_not_resolved_6120": "======== '{0}' tür başvuru yönergesi çözümlenmedi. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== '{0}' tür başvuru yönergesi '{1}' olarak başarıyla çözümlendi, birincil: {2}. ========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Türler, '{0}' özel özelliğinin ayrı bildirimlerine sahip.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' ve '{1}' parametre türleri uyumsuz.", + "Types_of_property_0_are_incompatible_2326": "'{0}' özellik türleri uyumsuz.", + "Unable_to_open_file_0_6050": "'{0}' dosyası açılamıyor.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Bir ifade olarak çağrıldığında sınıf dekoratörünün imzası çözümlenemez.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Bir ifade olarak çağrıldığında metot dekoratörünün imzası çözümlenemez.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Bir ifade olarak çağrıldığında parametre dekoratörünün imzası çözümlenemez.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Bir ifade olarak çağrıldığında özellik dekoratörünün imzası çözümlenemez.", + "Unexpected_end_of_text_1126": "Beklenmeyen metin sonu.", + "Unexpected_token_1012": "Beklenmeyen belirteç.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Beklenmeyen belirteç. Bir oluşturucu, metot, erişimci veya özellik bekleniyordu.", + "Unexpected_token_expected_1179": "Beklenmeyen belirteç. '{' bekleniyordu.", + "Unknown_compiler_option_0_5023": "Bilinmeyen '{0}' derleyici seçeneği.", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "'Excludes' seçeneği bilinmiyor. 'Exclude' seçeneğini mi belirtmek istediniz?", + "Unknown_type_acquisition_option_0_17010": "Bilinmeyen '{0}' tür alımı seçeneği.", + "Unreachable_code_detected_7027": "Erişilemeyen kod algılandı.", + "Unsupported_locale_0_6049": "Desteklenmeyen '{0}' yerel ayarı.", + "Unterminated_Unicode_escape_sequence_1199": "Sonlandırılmamış Unicode kaçış dizisi.", + "Unterminated_quoted_string_in_response_file_0_6045": "'{0}' yanıt dosyasında sonlandırılmamış alıntılanmış dize.", + "Unterminated_regular_expression_literal_1161": "Sonlandırılmamış normal ifade sabit değeri.", + "Unterminated_string_literal_1002": "Sonlandırılmamış dize sabit değeri.", + "Unterminated_template_literal_1160": "Sonlandırılmamış şablon sabit değeri.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Türü belirtilmemiş işlev çağrıları tür bağımsız değişkenlerini kabul etmeyebilir.", + "Unused_label_7028": "Kullanılmayan etiket.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' deyiminde dize kullanma yalnızca ECMAScript 5 veya üzerinde desteklenir.", + "VERSION_6036": "SÜRÜM", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' türünün değeri ile '{1}' türü arasında hiç ortak özellik yok. Bunun yerine çağrı yapmak mı istediniz?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "'{0}' türündeki değeri çağrılabilir değil. 'new' öğesini mi eklemek istemiştiniz?", + "Variable_0_implicitly_has_an_1_type_7005": "'{0}' değişkeni örtük olarak '{1}' türüne sahip.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "'{0}' değişkeni, türünün belirlenemeyeceği bazı konumlarda örtülü olarak '{1}' türünü içeriyor.", + "Variable_0_is_used_before_being_assigned_2454": "'{0}' değişkeni atanmadan önce kullanılır.", + "Variable_declaration_expected_1134": "Değişken bildirimi bekleniyor.", + "Variable_declaration_list_cannot_be_empty_1123": "Değişken bildirim listesi boş olamaz.", + "Version_0_6029": "Sürüm {0}", + "Watch_input_files_6005": "Giriş dosyalarını izleyin.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Standart TypeScript kitaplığında tanımlanmış öğeleri yeniden adlandıramazsınız.", + "You_cannot_rename_this_element_8000": "Bu öğeyi yeniden adlandıramazsınız.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' burada dekoratör olarak kullanılmak için çok az bağımsız değişken kabul ediyor. Önce çağırıp '@{0}()' yazmak mı istediniz?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' iki kez belirtildi. '{0}' özniteliğinin üzerine yazılacak.", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' yalnızca bir .ts dosyasında kullanılabilir.", + "_0_expected_1005": "'{0}' bekleniyor.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "Dönüş türü ek açıklamasına sahip olmadığından ve doğrudan veya dolaylı olarak dönüş ifadelerinden birinde kendine başvurulduğundan, '{0}' öğesi örtük olarak 'any' türüne sahip.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Bir tür ek açıklamasına sahip olmadığından ve kendi başlatıcısında doğrudan veya dolaylı olarak başvurulduğundan, '{0}' öğesi örtük olarak 'any' türüne sahip.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' temel elemandır ancak '{1}' sarmalayıcı nesnedir. Mümkün olduğunda '{0}' kullanmayı tercih edin.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' bildirildi ancak değeri hiç okunmadı.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}', '{1}' anahtar sözcüğü için geçerli bir meta özellik değil. Bunu mu demek istediniz: '{2}'?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' öğesine kendi temel ifadesinde doğrudan veya dolaylı olarak başvuruluyor.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' öğesine kendi tür ek açıklamasında doğrudan veya dolaylı olarak başvuruluyor.", + "_0_list_cannot_be_empty_1097": "'{0}' listesi boş olamaz.", + "_0_modifier_already_seen_1030": "'{0}' değiştiricisi zaten görüldü.", + "_0_modifier_cannot_appear_on_a_class_element_1031": "'{0}' değiştiricisi bir sınıf öğesinde görüntülenemez.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "'{0}' değiştiricisi bir oluşturucu bildiriminde görüntülenemez.", + "_0_modifier_cannot_appear_on_a_data_property_1043": "'{0}' değiştiricisi bir veri özelliğinde görüntülenemez.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "'{0}' değiştiricisi, bir modülde veya ad alanı öğesinde görünemez.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "'{0}' değiştiricisi bir parametrede görüntülenemez.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "'{0}' değiştiricisi, bir tür üyesinde görünemez.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "'{0}' değiştiricisi, bir dizin imzasında görünemez.", + "_0_modifier_cannot_be_used_here_1042": "'{0}' değiştiricisi burada kullanılamaz.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "'{0}' değiştiricisi bir çevresel bağlamda kullanılamaz.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' değiştiricisi, '{1}' değiştiricisi ile birlikte kullanılamaz.", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' değiştiricisi bir sınıf bildirimiyle birlikte kullanılamaz.", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' değiştiricisi, '{1}' değiştiricisinden önce gelmelidir.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' yalnızca bir türe başvuruyor, ancak burada bir ad alanı olarak kullanılıyor.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' yalnızca bir türe başvuruyor, ancak burada bir değer olarak kullanılıyor.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' bir UMD genel öğesine başvuruyor, ancak geçerli dosya bir modül. Bunun yerine bir içeri aktarma eklemeyi deneyin.", + "_0_tag_already_specified_1223": "'{0}' etiketi zaten belirtildi.", + "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' etiketi tek başına üst düzey bir JSDoc etiketi olarak kullanılamaz.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "Dönüş türü ek açıklaması olmayan '{0}', örtük olarak '{1}' dönüş türüne sahip.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' değiştiricisi yalnızca sınıf, metot veya özellik bildiriminde görünebilir.", + "await_expression_is_only_allowed_within_an_async_function_1308": "'await' ifadesine yalnızca bir zaman uyumsuz işlevde izin verilir.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' ifadeleri bir parametre başlatıcısında kullanılamaz.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' seçeneği '{0}' olarak ayarlandı; göreli olmayan '{1}' modül adını çözümlemek için bu değer kullanılıyor.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=', yalnızca yok etme ataması içindeki bir nesne sabit değeri özelliğinde kullanılabilir.", + "case_or_default_expected_1130": "'case' veya 'default' ifadeleri bekleniyor.", + "class_expressions_are_not_currently_supported_9003": "'class' ifadeleri şu anda desteklenmiyor.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' bildirimleri yalnızca bir bloğun içinde bildirilebilir.", + "const_declarations_must_be_initialized_1155": "'const' bildirimlerinin başlatılması gerekiyor.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' numaralandırma üyesi başlatıcısı, sonlu olmayan bir değer olarak hesaplandı.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' numaralandırma üyesi başlatıcısı, izin verilmeyen 'NaN' değeri olarak hesaplandı.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' numaralandırmaları yalnızca bir özellikte, dizin erişim ifadelerinde, içeri aktarma bildiriminin sağ tarafında veya dışarı aktarma atamasında kullanılabilir.", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete', katı moddaki bir tanımlayıcıda çağrılamaz.", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' yalnızca bir .ts dosyasında kullanılabilir.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' değiştiricisi, her zaman görünür olduğu için çevresel modüllere ve modül genişletmelerine uygulanamaz.", + "extends_clause_already_seen_1172": "'extends' yan tümcesi zaten görüldü.", + "extends_clause_must_precede_implements_clause_1173": "'extends' yan tümcesi, 'implements' yan tümcesinden önce gelmelidir.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Dışarı aktarılan '{0}' sınıfının 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Dışarı aktarılan '{0}' arabirimin 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "file_6025": "dosya", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' ve 'set' erişimcisi aynı 'this' türüne sahip olmalıdır.", + "get_and_set_accessor_must_have_the_same_type_2380": "'get' ve 'set' erişimcisi aynı türde olmalıdır.", + "implements_clause_already_seen_1175": "'implements' yan tümcesi zaten görüldü.", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' yalnızca bir .ts dosyasında kullanılabilir.", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' yalnızca bir .ts dosyasında kullanılabilir.", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "let_declarations_can_only_be_declared_inside_a_block_1157": "'let' bildirimleri yalnızca bu bloğun içinde bildirilebilir.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' ifadesi, 'let' veya 'const' bildirimlerinde ad olarak kullanılamaz.", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "'new T[]', dizi oluşturmak için kullanılamaz. Bunun yerine 'new Array()' kullanın.", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Yapı imzası bulunmayan 'new' ifadesi örtük olarak 'any' türüne sahip.", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' yalnızca .ts dosyasında kullanılabilir.", + "options_6024": "seçenekler", + "or_expected_1144": "'{' veya ';' bekleniyor.", + "package_json_does_not_have_a_0_field_6100": "'package.json' geçerli bir '{0}' alanına sahip değil.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json', '{2}' öğesine başvuruda bulunan '{1}' adlı '{0}' alanını içeriyor.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' yalnızca bir .ts dosyasında kullanılabilir.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' seçeneği belirtildi, '{0}' modül adıyla eşleşen bir desen aranıyor.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' değiştiricisi yalnızca özellik bildiriminde ya da dizin imzasında görünebilir.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' seçeneği ayarlandı, '{0}' göreli modül adını çözümlemek için bu değer kullanılıyor.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' öğesine yalnızca bir türetilmiş sınıfta başvurulabilir.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' değerine yalnızca türetilen sınıfların üyelerinde ya da nesne değişmez ifadelerinde başvurulabilir.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' öğesine hesaplanan bir özellik adında başvurulamaz.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' öğesine oluşturucu bağımsız değişkenlerinde başvurulamaz.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Nesne değişmez ifadelerinde 'super' değerine yalnızca 'target' seçeneği 'ES2015' veya üzeri olarak ayarlandığında izin verilir.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Türetilmiş bir sınıfın oluşturucusunda 'super' özelliğine erişmeden önce 'super' çağrılmalıdır.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Türetilen bir sınıfın oluşturucusundaki 'this' değerine erişilmeden önce 'super' çağrılmalıdır.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' öğesinden sonra bir bağımsız değişken listesi veya üye erişimi gelmelidir.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' özellik erişimine yalnızca bir oluşturucuda, üye işlevinde veya bir türetilmiş sınıfa ait üye erişimcisinde izin verilir.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' öğesine hesaplanan bir özellik adında başvurulamaz.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' öğesine bir modülde veya ad alanı gövdesinde başvurulamaz.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' öğesine statik özellik başlatıcısında başvurulamaz.", + "this_cannot_be_referenced_in_constructor_arguments_2333": "'super' öğesine oluşturucu bağımsız değişkenlerinde başvurulamaz.", + "this_cannot_be_referenced_in_current_location_2332": "'this' öğesine geçerli konumda başvurulamaz.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this', tür ek açıklamasına sahip olmadığından örtük olarak 'any' türü içeriyor", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' yalnızca bir .ts dosyasında kullanılabilir.", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' yalnızca bir .ts dosyasında kullanılabilir.", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' yalnızca bir .ts dosyasında kullanılabilir.", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' yalnızca bir .ts dosyasında kullanılabilir.", + "types_can_only_be_used_in_a_ts_file_8010": "'types' yalnızca bir .ts dosyasında kullanılabilir.", + "unique_symbol_types_are_not_allowed_here_1335": "Burada 'unique symbol' türlerine izin verilmez.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' türlerine yalnızca bir değişken deyimindeki değişkenlerde izin verilir.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' türleri, bağlama adına sahip bir değişken bildiriminde kullanılamaz.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' deyimlerine zaman uyumsuz bir işlev bloğunda izin verilmez.", + "with_statements_are_not_allowed_in_strict_mode_1101": "'with' deyimlerine katı modda izin verilmez.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' ifadeleri bir parametre başlatıcısında kullanılamaz." +} \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index a6650351530f0..6efd1a954836b 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -24,443 +24,12 @@ var __assign = (this && this.__assign) || Object.assign || function(t) { }; var ts; (function (ts) { - var SyntaxKind; - (function (SyntaxKind) { - SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; - SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; - SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; - SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; - SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; - SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; - SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; - SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; - SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 126] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 127] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 128] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 129] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 130] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 131] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 132] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 133] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 134] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 135] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 136] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; - SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; - SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; - SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; - SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; - SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; - SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; - SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; - SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; - SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; - SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; - SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 270] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; - SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; - SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; - SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; - SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; - })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); - var NodeFlags; - (function (NodeFlags) { - NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Let"] = 1] = "Let"; - NodeFlags[NodeFlags["Const"] = 2] = "Const"; - NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; - NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; - NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; - NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; - NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; - NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; - NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; - NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; - NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; - })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); - var ModifierFlags; - (function (ModifierFlags) { - ModifierFlags[ModifierFlags["None"] = 0] = "None"; - ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; - ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; - ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; - ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; - ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; - ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; - ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; - ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; - ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; - ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; - ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; - ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; - ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; - ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); - var JsxFlags; - (function (JsxFlags) { - JsxFlags[JsxFlags["None"] = 0] = "None"; - JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; - JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; - })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); - var RelationComparisonResult; - (function (RelationComparisonResult) { - RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; - RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; - RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; - })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); - var NumericLiteralFlags; - (function (NumericLiteralFlags) { - NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; - NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; - NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; - NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; - NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; - })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); - var FlowFlags; - (function (FlowFlags) { - FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; - FlowFlags[FlowFlags["Start"] = 2] = "Start"; - FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; - FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; - FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; - FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; - FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; - FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; - FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; - FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; - FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; - FlowFlags[FlowFlags["Label"] = 12] = "Label"; - FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; - })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; - var StructureIsReused; - (function (StructureIsReused) { - StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; - StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; - StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; - })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -485,47 +54,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); - var TypeFormatFlags; - (function (TypeFormatFlags) { - TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; - })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); - var SymbolFormatFlags; - (function (SymbolFormatFlags) { - SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; - SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; - SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; - })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); - var SymbolAccessibility; - (function (SymbolAccessibility) { - SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; - SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; - SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; - })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); - var SyntheticSymbolKind; - (function (SyntheticSymbolKind) { - SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; - SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; - })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); - var TypePredicateKind; - (function (TypePredicateKind) { - TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; - TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; - })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -540,231 +68,6 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var SymbolFlags; - (function (SymbolFlags) { - SymbolFlags[SymbolFlags["None"] = 0] = "None"; - SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; - SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; - SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; - SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; - SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; - SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; - SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; - SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; - SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; - SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; - SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; - SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; - SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; - SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; - SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; - SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; - SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; - SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; - SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; - SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; - SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; - SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; - SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; - SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; - SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; - SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; - SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; - SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; - SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; - SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; - SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; - SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; - SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; - SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; - SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; - SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; - SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; - SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; - SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; - SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; - })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); - var EnumKind; - (function (EnumKind) { - EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; - EnumKind[EnumKind["Literal"] = 1] = "Literal"; - })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); - var CheckFlags; - (function (CheckFlags) { - CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; - CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; - CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; - CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; - CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; - CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; - })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); - var InternalSymbolName; - (function (InternalSymbolName) { - InternalSymbolName["Call"] = "__call"; - InternalSymbolName["Constructor"] = "__constructor"; - InternalSymbolName["New"] = "__new"; - InternalSymbolName["Index"] = "__index"; - InternalSymbolName["ExportStar"] = "__export"; - InternalSymbolName["Global"] = "__global"; - InternalSymbolName["Missing"] = "__missing"; - InternalSymbolName["Type"] = "__type"; - InternalSymbolName["Object"] = "__object"; - InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; - InternalSymbolName["Class"] = "__class"; - InternalSymbolName["Function"] = "__function"; - InternalSymbolName["Computed"] = "__computed"; - InternalSymbolName["Resolving"] = "__resolving__"; - InternalSymbolName["ExportEquals"] = "export="; - InternalSymbolName["Default"] = "default"; - })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); - var NodeCheckFlags; - (function (NodeCheckFlags) { - NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; - NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; - NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; - NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; - NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; - NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; - NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; - NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; - NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; - NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; - })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); - var TypeFlags; - (function (TypeFlags) { - TypeFlags[TypeFlags["Any"] = 1] = "Any"; - TypeFlags[TypeFlags["String"] = 2] = "String"; - TypeFlags[TypeFlags["Number"] = 4] = "Number"; - TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 32768] = "Object"; - TypeFlags[TypeFlags["Union"] = 65536] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 262144] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; - TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; - TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; - TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; - })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); - var ObjectFlags; - (function (ObjectFlags) { - ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; - ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; - ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; - ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; - ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; - ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; - ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; - ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; - ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; - ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; - })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); - var SignatureKind; - (function (SignatureKind) { - SignatureKind[SignatureKind["Call"] = 0] = "Call"; - SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; - })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); - var IndexKind; - (function (IndexKind) { - IndexKind[IndexKind["String"] = 0] = "String"; - IndexKind[IndexKind["Number"] = 1] = "Number"; - })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); - var InferencePriority; - (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; - })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); - var InferenceFlags; - (function (InferenceFlags) { - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; - })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); - var Ternary; - (function (Ternary) { - Ternary[Ternary["False"] = 0] = "False"; - Ternary[Ternary["Maybe"] = 1] = "Maybe"; - Ternary[Ternary["True"] = -1] = "True"; - })(Ternary = ts.Ternary || (ts.Ternary = {})); - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -786,312 +89,6 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); - var JsxEmit; - (function (JsxEmit) { - JsxEmit[JsxEmit["None"] = 0] = "None"; - JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; - JsxEmit[JsxEmit["React"] = 2] = "React"; - JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; - })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); - var NewLineKind; - (function (NewLineKind) { - NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; - NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; - })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); - var ScriptKind; - (function (ScriptKind) { - ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; - ScriptKind[ScriptKind["JS"] = 1] = "JS"; - ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; - ScriptKind[ScriptKind["TS"] = 3] = "TS"; - ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; - ScriptKind[ScriptKind["External"] = 5] = "External"; - ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; - })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); - var ScriptTarget; - (function (ScriptTarget) { - ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; - ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; - ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; - ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; - ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; - })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); - var LanguageVariant; - (function (LanguageVariant) { - LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; - LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; - })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); - var DiagnosticStyle; - (function (DiagnosticStyle) { - DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; - DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; - })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); - var WatchDirectoryFlags; - (function (WatchDirectoryFlags) { - WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; - WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; - })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); - var CharacterCodes; - (function (CharacterCodes) { - CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; - CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; - CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; - CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; - CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; - CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; - CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; - CharacterCodes[CharacterCodes["space"] = 32] = "space"; - CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; - CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; - CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; - CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; - CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; - CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; - CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; - CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; - CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; - CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; - CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; - CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; - CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; - CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; - CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; - CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; - CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; - CharacterCodes[CharacterCodes["_"] = 95] = "_"; - CharacterCodes[CharacterCodes["$"] = 36] = "$"; - CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; - CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; - CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; - CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; - CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; - CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; - CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; - CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; - CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; - CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; - CharacterCodes[CharacterCodes["a"] = 97] = "a"; - CharacterCodes[CharacterCodes["b"] = 98] = "b"; - CharacterCodes[CharacterCodes["c"] = 99] = "c"; - CharacterCodes[CharacterCodes["d"] = 100] = "d"; - CharacterCodes[CharacterCodes["e"] = 101] = "e"; - CharacterCodes[CharacterCodes["f"] = 102] = "f"; - CharacterCodes[CharacterCodes["g"] = 103] = "g"; - CharacterCodes[CharacterCodes["h"] = 104] = "h"; - CharacterCodes[CharacterCodes["i"] = 105] = "i"; - CharacterCodes[CharacterCodes["j"] = 106] = "j"; - CharacterCodes[CharacterCodes["k"] = 107] = "k"; - CharacterCodes[CharacterCodes["l"] = 108] = "l"; - CharacterCodes[CharacterCodes["m"] = 109] = "m"; - CharacterCodes[CharacterCodes["n"] = 110] = "n"; - CharacterCodes[CharacterCodes["o"] = 111] = "o"; - CharacterCodes[CharacterCodes["p"] = 112] = "p"; - CharacterCodes[CharacterCodes["q"] = 113] = "q"; - CharacterCodes[CharacterCodes["r"] = 114] = "r"; - CharacterCodes[CharacterCodes["s"] = 115] = "s"; - CharacterCodes[CharacterCodes["t"] = 116] = "t"; - CharacterCodes[CharacterCodes["u"] = 117] = "u"; - CharacterCodes[CharacterCodes["v"] = 118] = "v"; - CharacterCodes[CharacterCodes["w"] = 119] = "w"; - CharacterCodes[CharacterCodes["x"] = 120] = "x"; - CharacterCodes[CharacterCodes["y"] = 121] = "y"; - CharacterCodes[CharacterCodes["z"] = 122] = "z"; - CharacterCodes[CharacterCodes["A"] = 65] = "A"; - CharacterCodes[CharacterCodes["B"] = 66] = "B"; - CharacterCodes[CharacterCodes["C"] = 67] = "C"; - CharacterCodes[CharacterCodes["D"] = 68] = "D"; - CharacterCodes[CharacterCodes["E"] = 69] = "E"; - CharacterCodes[CharacterCodes["F"] = 70] = "F"; - CharacterCodes[CharacterCodes["G"] = 71] = "G"; - CharacterCodes[CharacterCodes["H"] = 72] = "H"; - CharacterCodes[CharacterCodes["I"] = 73] = "I"; - CharacterCodes[CharacterCodes["J"] = 74] = "J"; - CharacterCodes[CharacterCodes["K"] = 75] = "K"; - CharacterCodes[CharacterCodes["L"] = 76] = "L"; - CharacterCodes[CharacterCodes["M"] = 77] = "M"; - CharacterCodes[CharacterCodes["N"] = 78] = "N"; - CharacterCodes[CharacterCodes["O"] = 79] = "O"; - CharacterCodes[CharacterCodes["P"] = 80] = "P"; - CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; - CharacterCodes[CharacterCodes["R"] = 82] = "R"; - CharacterCodes[CharacterCodes["S"] = 83] = "S"; - CharacterCodes[CharacterCodes["T"] = 84] = "T"; - CharacterCodes[CharacterCodes["U"] = 85] = "U"; - CharacterCodes[CharacterCodes["V"] = 86] = "V"; - CharacterCodes[CharacterCodes["W"] = 87] = "W"; - CharacterCodes[CharacterCodes["X"] = 88] = "X"; - CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; - CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; - CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; - CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; - CharacterCodes[CharacterCodes["at"] = 64] = "at"; - CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; - CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; - CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; - CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; - CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; - CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; - CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; - CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; - CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; - CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; - CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; - CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; - CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; - CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; - CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; - CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; - CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; - CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; - CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; - CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; - CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; - CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; - CharacterCodes[CharacterCodes["question"] = 63] = "question"; - CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; - CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; - CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; - CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; - CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; - CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; - CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; - CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; - CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; - })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); - var Extension; - (function (Extension) { - Extension["Ts"] = ".ts"; - Extension["Tsx"] = ".tsx"; - Extension["Dts"] = ".d.ts"; - Extension["Js"] = ".js"; - Extension["Jsx"] = ".jsx"; - })(Extension = ts.Extension || (ts.Extension = {})); - var TransformFlags; - (function (TransformFlags) { - TransformFlags[TransformFlags["None"] = 0] = "None"; - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; - TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; - })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); - var EmitFlags; - (function (EmitFlags) { - EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; - EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; - EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; - EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; - EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; - EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; - EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; - EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; - EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; - EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; - EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; - EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; - EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; - EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; - EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; - EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; - EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; - EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; - EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; - EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; - EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; - })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); - var ExternalEmitHelpers; - (function (ExternalEmitHelpers) { - ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; - ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; - ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; - ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; - ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; - ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; - ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; - ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; - ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; - ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; - ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; - ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; - ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; - })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); - var EmitHint; - (function (EmitHint) { - EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; - EmitHint[EmitHint["Expression"] = 1] = "Expression"; - EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; - EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; - })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -1100,9 +97,7 @@ var ts; (function (ts) { var performance; (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (_markName) { }; + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; var enabled = false; var profilerStart = 0; var counts; @@ -1154,7 +149,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.6"; + ts.versionMajorMinor = "2.7"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { @@ -1164,12 +159,10 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { - ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; - ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } function createMap() { @@ -1274,12 +267,6 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -1296,6 +283,16 @@ var ts; return undefined; } ts.forEach = forEach; + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1311,10 +308,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1347,6 +346,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -1366,11 +375,12 @@ var ts; Debug.fail(); } ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (equalityComparer(v, value)) { return true; } } @@ -1433,22 +443,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1475,6 +469,14 @@ var ts; return result; } ts.map = map; + function mapIterator(iter, mapFn) { + return { next: next }; + function next() { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + } + ts.mapIterator = mapIterator; function sameMap(array, f) { var result; if (array) { @@ -1499,8 +501,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1540,8 +542,14 @@ var ts; if (done) break; var res = mapfn(value); - if (res) - result.push.apply(result, res); + if (res) { + if (isArray(res)) { + result.push.apply(result, res); + } + else { + result.push(res); + } + } } return result; } @@ -1582,6 +590,20 @@ var ts; return result; } ts.mapDefined = mapDefined; + function mapDefinedIter(iter, mapFn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapFn(value); + if (res !== undefined) { + result.push(res); + } + } + return result; + } + ts.mapDefinedIter = mapDefinedIter; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1644,8 +666,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1666,25 +688,64 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - function deduplicate(array, areEqual) { - var result; - if (array) { - result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } - } - result.push(item); - } + function deduplicateRelational(array, equalityComparer, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); } return result; } + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } ts.deduplicate = deduplicate; - function arrayIsEqualTo(array1, array2, equaler) { + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + case true: + case 0: + continue; + case -1: + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (!array1 || !array2) { return array1 === array2; } @@ -1692,8 +753,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { + if (!equalityComparer(array1[i], array2[i])) { return false; } } @@ -1737,30 +797,36 @@ var ts; return result || array; } ts.compact = compact; - function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { - if (comparer === void 0) { comparer = compareValues; } - if (offsetA === void 0) { offsetA = 0; } - if (offsetB === void 0) { offsetB = 0; } + function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; var result = []; - outer: for (; offsetB < arrayB.length; offsetB++) { - inner: for (; offsetA < arrayA.length; offsetA++) { + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0); + } switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1: break inner; - case 0: continue outer; - case 1: continue inner; + case -1: + result.push(arrayB[offsetB]); + continue loopB; + case 0: + continue loopB; + case 1: + continue loopA; } } - result.push(arrayB[offsetB]); } return result; } ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result += v[prop]; } return result; @@ -1779,23 +845,22 @@ var ts; return offset < 0 ? array.length + offset : offset; } function addRange(to, from, start, end) { - if (from === undefined) + if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); end = end === undefined ? from.length : toOffset(from, end); for (var i = start; i < end && i < from.length; i++) { - var v = from[i]; - if (v !== undefined) { + if (from[i] !== undefined) { to.push(from[i]); } } return to; } ts.addRange = addRange; - function pushIfUnique(array, toAdd) { - if (contains(array, toAdd)) { + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { return false; } else { @@ -1804,9 +869,9 @@ var ts; } } ts.pushIfUnique = pushIfUnique; - function appendIfUnique(array, toAdd) { + function appendIfUnique(array, toAdd, equalityComparer) { if (array) { - pushIfUnique(array, toAdd); + pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -1814,12 +879,47 @@ var ts; } } ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function best(iter, isBetter) { + var x = iter.next(); + if (x.done) { + return undefined; + } + var best = x.value; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return best; + } + if (isBetter(value, best)) { + best = value; + } + } + } + ts.best = best; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; function stableSort(array, comparer) { - if (comparer === void 0) { comparer = compareValues; } - return array - .map(function (_, i) { return i; }) - .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) - .map(function (i) { return array[i]; }); + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); } ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { @@ -1846,10 +946,20 @@ var ts; return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; function lastOrUndefined(array) { return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -1868,26 +978,25 @@ var ts; return result; } ts.replaceElement = replaceElement; - function binarySearch(array, value, comparer, offset) { + function binarySearch(array, value, keySelector, keyComparer, offset) { if (!array || array.length === 0) { return -1; } var low = offset || 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; + var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); - var midValue = array[middle]; - if (comparer(midValue, value) === 0) { - return middle; - } - else if (comparer(midValue, value) > 0) { - high = middle - 1; - } - else { - low = middle + 1; + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1: + low = middle + 1; + break; + case 0: + return middle; + case 1: + high = middle - 1; + break; } } return ~low; @@ -1917,30 +1026,6 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial, start, count) { - if (array) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start > size - 1 ? size - 1 : start; - var end = count === undefined || pos - count < 0 ? 0 : pos - count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos--; - } - else { - result = initial; - } - while (pos >= end) { - result = f(result, array[pos], pos); - pos--; - } - return result; - } - } - return initial; - } - ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; function hasProperty(map, key) { return hasOwnProperty.call(map, key); @@ -2027,6 +1112,7 @@ var ts; } ts.assign = assign; function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (left === right) return true; if (!left || !right) @@ -2035,7 +1121,7 @@ var ts; if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + if (!equalityComparer(left[key], right[key])) return false; } } @@ -2050,13 +1136,22 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2122,6 +1217,14 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -2132,8 +1235,12 @@ var ts; Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } ts.cast = cast; - function noop() { } + function noop(_) { } ts.noop = noop; + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + function returnTrue() { return true; } + ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; function notImplemented() { @@ -2288,47 +1395,137 @@ var ts; return headChain; } ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + a < b ? -1 : + 1; + } function compareValues(a, b) { - if (a === b) - return 0; - if (a === undefined) - return -1; - if (b === undefined) - return 1; - return a < b ? -1 : 1; + return compareComparableValues(a, b); } ts.compareValues = compareValues; - function compareStrings(a, b, ignoreCase) { + function compareStringsCaseInsensitive(a, b) { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; - if (ignoreCase) { - if (ts.collator) { - var result = ts.localeCompareIsCorrect ? - ts.collator.compare(a, b) : - a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); - return result < 0 ? -1 : result > 0 ? 1 : 0; - } - a = a.toUpperCase(); - b = b.toUpperCase(); + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 : a > b ? 1 : 0; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { if (a === b) return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var value = comparer(a, b); + return value < 0 ? -1 : value > 0 ? 1 : 0; } - return a < b ? -1 : 1; - } - ts.compareStrings = compareStrings; - function compareStringsCaseInsensitive(a, b) { - return compareStrings(a, b, true); - } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function createIntlCollatorStringComparer(locale) { + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 : a > b ? 1 : 0; + } + } + function getStringComparerFactory() { + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + return createFallbackStringComparer; + } + function createStringComparer(locale) { + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } function compareDiagnostics(d1, d2) { - return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2338,14 +1535,14 @@ var ts; ts.compareDiagnostics = compareDiagnostics; function compareMessageText(text1, text2) { while (text1 && text2) { - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + var string1 = isString(text1) ? text1 : text1.messageText; + var string2 = isString(text2) ? text2 : text2.messageText; + var res = compareStringsCaseSensitive(string1, string2); if (res) { return res; } - text1 = typeof text1 === "string" ? undefined : text1.next; - text2 = typeof text2 === "string" ? undefined : text2.next; + text1 = isString(text1) ? undefined : text1.next; + text2 = isString(text2) ? undefined : text2.next; } if (!text1 && !text2) { return 0; @@ -2353,26 +1550,9 @@ var ts; return text1 ? 1 : -1; } function sortAndDeduplicateDiagnostics(diagnostics) { - return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + return sortAndDeduplicate(diagnostics, compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function deduplicateSortedDiagnostics(diagnostics) { - if (diagnostics.length < 2) { - return diagnostics; - } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; - if (!isDupe) { - newDiagnostics.push(currentDiagnostic); - previousDiagnostic = currentDiagnostic; - } - } - return newDiagnostics; - } - ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; function normalizeSlashes(path) { return path.replace(/\\/g, "/"); } @@ -2392,7 +1572,6 @@ var ts; if (path.charCodeAt(1) === 58) { if (path.charCodeAt(2) === 47) return 3; - return 2; } if (path.lastIndexOf("file:///", 0) === 0) { return "file:///".length; @@ -2451,7 +1630,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -2480,6 +1659,17 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2635,8 +1825,9 @@ var ts; var aComponents = getNormalizedPathComponents(a, currentDirectory); var bComponents = getNormalizedPathComponents(b, currentDirectory); var sharedLength = Math.min(aComponents.length, bComponents.length); + var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; for (var i = 0; i < sharedLength; i++) { - var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + var result = comparer(aComponents[i], bComponents[i]); if (result !== 0) { return result; } @@ -2658,9 +1849,9 @@ var ts; if (childComponents.length < parentComponents.length) { return false; } + var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { - var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); - if (result !== 0) { + if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } } @@ -2680,8 +1871,16 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -2823,13 +2022,13 @@ var ts; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); + var comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive; var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var regexFlag = useCaseSensitiveFileNames ? "" : "i"; var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -2837,7 +2036,6 @@ var ts; return flatten(results); function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - files = files.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -2855,8 +2053,8 @@ var ts; } } }; - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; + for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + var current = _b[_i]; _loop_1(current); } if (depth !== undefined) { @@ -2865,9 +2063,8 @@ var ts; return; } } - directories = directories.slice().sort(comparer); - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var current = directories_1[_b]; + for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && @@ -2887,7 +2084,7 @@ var ts; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); @@ -2940,7 +2137,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -2964,13 +2161,6 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; - var ExtensionPriority; - (function (ExtensionPriority) { - ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; - ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; - ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; - ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; - })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -3025,6 +2215,11 @@ var ts; return (removeFileExtension(path) + newExtension); } ts.changeExtension = changeExtension; + function removeMinAndVersionNumbers(fileName) { + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; function Symbol(flags, name) { this.flags = flags; this.escapedName = name; @@ -3036,8 +2231,7 @@ var ts; this.checker = checker; } } - function Signature() { - } + function Signature() { } function Node(kind, pos, end) { this.id = 0; this.kind = kind; @@ -3064,13 +2258,6 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - var AssertionLevel; - (function (AssertionLevel) { - AssertionLevel[AssertionLevel["None"] = 0] = "None"; - AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; - AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; - AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; - })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -3259,6 +2446,14 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3269,6 +2464,168 @@ var ts; ts.and = and; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; + function createCachedDirectoryStructureHost(host) { + var cachedReadDirectoryResult = createMap(); + var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); + var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, + newLine: host.newLine, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + write: function (s) { return host.write(s); }, + writeFile: writeFile, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: createDirectory, + getCurrentDirectory: getCurrentDirectory, + getDirectories: getDirectories, + readDirectory: readDirectory, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache, + exit: function (code) { return host.exit(code); } + }; + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + } + else { + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (parentResult) { + var baseName = getBaseNameOfFileName(fileOrDirectory); + if (parentResult) { + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + } + } + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; })(ts || (ts = {})); var ts; (function (ts) { @@ -3300,12 +2657,13 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { + var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); var fileWatcherCallbacks = ts.createMultiMap(); @@ -3327,7 +2685,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3348,7 +2706,7 @@ var ts; fileWatcherCallbacks.remove(filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = typeof relativeFileName !== "string" + var fileName = !ts.isString(relativeFileName) ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); if ((eventName === "change" || eventName === "rename")) { @@ -3379,6 +2737,65 @@ var ts; } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { + return; + } + callback(fileName, eventKind); + } + } + function fsWatchDirectory(directoryName, callback, recursive) { + var options; + var watcher = !directoryExists(directoryName) ? + watchMissingDirectory() : + watchPresentDirectory(); + return { + close: function () { + watcher.close(); + } + }; + function watchPresentDirectory() { + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + var dirWatcher = _fs.watch(directoryName, options, callback); + dirWatcher.on("error", function () { + if (!directoryExists(directoryName)) { + watcher = watchMissingDirectory(); + callback("rename", ""); + } + }); + return dirWatcher; + } + function watchMissingDirectory() { + return fsWatchFile(directoryName, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { + watcher.close(); + watcher = watchPresentDirectory(); + callback("rename", ""); + } + }); + } + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -3404,7 +2821,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } var fd; try { @@ -3451,11 +2868,6 @@ var ts; function readDirectory(path, extensions, excludes, includes, depth) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); } - var FileSystemEntryKind; - (function (FileSystemEntryKind) { - FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; - FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; - })(FileSystemEntryKind || (FileSystemEntryKind = {})); function fileSystemEntryExists(path, entryKind) { try { var stat = _fs.statSync(path); @@ -3477,7 +2889,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -3495,43 +2906,15 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); - return { - close: function () { return _fs.unwatchFile(fileName, fileChanged); } - }; - } - function fileChanged(curr, prev) { - var isCurrZero = +curr.mtime === 0; - var isPrevZero = +prev.mtime === 0; - var created = !isCurrZero && isPrevZero; - var deleted = isCurrZero && !isPrevZero; - var eventKind = created - ? FileWatcherEventKind.Created - : deleted - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { - return; - } - callback(fileName, eventKind); + return fsWatchFile(fileName, callback, pollingInterval); } }, watchDirectory: function (directoryName, callback, recursive) { - var options; - if (!directoryExists(directoryName)) { - return noOpFileWatcher; - } - if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - return _fs.watch(directoryName, options, function (eventName, relativeFileName) { + return fsWatchDirectory(directoryName, function (eventName, relativeFileName) { if (eventName === "rename") { callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); } - }); + }, recursive); }, resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, @@ -3578,7 +2961,7 @@ var ts; return stat.size; } } - catch (e) { } + catch (_a) { } return 0; }, exit: function (exitCode) { @@ -3592,7 +2975,7 @@ var ts; try { require("source-map-support").install(); } - catch (e) { + catch (_a) { } }, setTimeout: setTimeout, @@ -3612,7 +2995,7 @@ var ts; }, writeFile: function (path, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } ChakraHost.writeFile(path, data); }, @@ -3634,7 +3017,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -3799,11 +3182,11 @@ var ts; An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), @@ -3884,6 +3267,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "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."), @@ -3903,6 +3287,13 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4104,7 +3495,7 @@ var ts; No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), - Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), @@ -4120,7 +3511,7 @@ var ts; await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), @@ -4149,14 +3540,16 @@ var ts; Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), - Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4230,6 +3623,11 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "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."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4253,16 +3651,16 @@ var ts; Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), @@ -4305,6 +3703,14 @@ var ts; Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4333,6 +3739,7 @@ var ts; File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -4346,7 +3753,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -4448,7 +3855,6 @@ var ts; Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), - The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), @@ -4504,6 +3910,8 @@ var ts; Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), 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."), @@ -4553,6 +3961,13 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4570,37 +3985,50 @@ var ts; super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), - Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), - Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), - Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), - Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), - Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), - Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), - Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), - Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), - Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), - Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), - Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), - Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), - Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), - Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), - Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), + Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), }; })(ts || (ts = {})); var ts; @@ -4609,6 +4037,10 @@ var ts; return token >= 71; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 29 || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; var textToToken = ts.createMapFromTemplate({ "abstract": 117, "any": 119, @@ -4633,7 +4065,7 @@ var ts; "false": 86, "finally": 87, "for": 88, - "from": 140, + "from": 141, "function": 89, "get": 125, "if": 90, @@ -4658,7 +4090,7 @@ var ts; "public": 114, "readonly": 131, "require": 132, - "global": 141, + "global": 142, "return": 96, "set": 135, "static": 115, @@ -4673,6 +4105,7 @@ var ts; "type": 138, "typeof": 103, "undefined": 139, + "unique": 140, "var": 104, "void": 105, "while": 106, @@ -4680,7 +4113,7 @@ var ts; "yield": 116, "async": 120, "await": 121, - "of": 142, + "of": 143, "{": 17, "}": 18, "(": 19, @@ -4838,7 +4271,7 @@ var ts; } ts.getLineStarts = getLineStarts; function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position); + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); if (lineNumber < 0) { lineNumber = ~lineNumber - 1; ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); @@ -5193,10 +4626,7 @@ var ts; var tokenPos; var token; var tokenValue; - var precedingLineBreak; - var hasExtendedUnicodeEscape; - var tokenIsUnterminated; - var numericLiteralFlags; + var tokenFlags; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -5205,12 +4635,12 @@ var ts; getTokenPos: function () { return tokenPos; }, getTokenText: function () { return text.substring(tokenPos, pos); }, getTokenValue: function () { return tokenValue; }, - hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, - hasPrecedingLineBreak: function () { return precedingLineBreak; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1) !== 0; }, isIdentifier: function () { return token === 71 || token > 107; }, isReservedWord: function () { return token >= 72 && token <= 107; }, - isUnterminated: function () { return tokenIsUnterminated; }, - getNumericLiteralFlags: function () { return numericLiteralFlags; }, + isUnterminated: function () { return (tokenFlags & 4) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, @@ -5247,7 +4677,7 @@ var ts; var end = pos; if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { pos++; - numericLiteralFlags = 2; + tokenFlags |= 16; if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; if (isDigit(text.charCodeAt(pos))) { @@ -5300,8 +4730,8 @@ var ts; } return value; } - function scanString(allowEscapes) { - if (allowEscapes === void 0) { allowEscapes = true; } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -5309,7 +4739,7 @@ var ts; while (true) { if (pos >= end) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -5319,15 +4749,15 @@ var ts; pos++; break; } - if (ch === 92 && allowEscapes) { + if (ch === 92 && !jsxAttributeString) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; continue; } - if (isLineBreak(ch)) { + if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -5344,7 +4774,7 @@ var ts; while (true) { if (pos >= end) { contents += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_template_literal); resultingToken = startedWithBacktick ? 13 : 16; break; @@ -5413,7 +4843,7 @@ var ts; return "\""; case 117: if (pos < end && text.charCodeAt(pos) === 123) { - hasExtendedUnicodeEscape = true; + tokenFlags |= 8; pos++; return scanExtendedUnicodeEscape(); } @@ -5547,10 +4977,7 @@ var ts; } function scan() { startPos = pos; - hasExtendedUnicodeEscape = false; - precedingLineBreak = false; - tokenIsUnterminated = false; - numericLiteralFlags = 0; + tokenFlags = 0; while (true) { tokenPos = pos; if (pos >= end) { @@ -5569,7 +4996,7 @@ var ts; switch (ch) { case 10: case 13: - precedingLineBreak = true; + tokenFlags |= 1; if (skipTrivia) { pos++; continue; @@ -5694,6 +5121,9 @@ var ts; } if (text.charCodeAt(pos + 1) === 42) { pos += 2; + if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) !== 47) { + tokenFlags |= 2; + } var commentClosed = false; while (pos < end) { var ch_1 = text.charCodeAt(pos); @@ -5703,7 +5133,7 @@ var ts; break; } if (isLineBreak(ch_1)) { - precedingLineBreak = true; + tokenFlags |= 1; } pos++; } @@ -5714,7 +5144,9 @@ var ts; continue; } else { - tokenIsUnterminated = !commentClosed; + if (!commentClosed) { + tokenFlags |= 4; + } return token = 3; } } @@ -5732,7 +5164,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 8; + tokenFlags |= 64; return token = 8; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) { @@ -5743,7 +5175,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 16; + tokenFlags |= 128; return token = 8; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) { @@ -5754,12 +5186,12 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 32; + tokenFlags |= 256; return token = 8; } if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); - numericLiteralFlags = 4; + tokenFlags |= 32; return token = 8; } case 49: @@ -5909,7 +5341,7 @@ var ts; continue; } else if (isLineBreak(ch)) { - precedingLineBreak = true; + tokenFlags |= 1; pos++; continue; } @@ -5948,13 +5380,13 @@ var ts; var inCharacterClass = false; while (true) { if (p >= end) { - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } var ch = text.charCodeAt(p); if (isLineBreak(ch)) { - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } @@ -6056,7 +5488,7 @@ var ts; switch (text.charCodeAt(pos)) { case 34: case 39: - tokenValue = scanString(false); + tokenValue = scanString(true); return token = 9; default: return scan(); @@ -6100,6 +5532,12 @@ var ts; case 93: pos++; return token = 22; + case 60: + pos++; + return token = 27; + case 62: + pos++; + return token = 29; case 61: pos++; return token = 58; @@ -6108,13 +5546,24 @@ var ts; return token = 26; case 46: pos++; + if (text.substr(tokenPos, pos + 2) === "...") { + pos += 2; + return token = 24; + } return token = 23; + case 33: + pos++; + return token = 51; + case 63: + pos++; + return token = 55; } - if (isIdentifierStart(ch, 5)) { + if (isIdentifierStart(ch, 6)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } + tokenValue = text.substring(tokenPos, pos); return token = 71; } else { @@ -6127,7 +5576,7 @@ var ts; var saveTokenPos = tokenPos; var saveToken = token; var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; + var saveTokenFlags = tokenFlags; var result = callback(); if (!result || isLookahead) { pos = savePos; @@ -6135,7 +5584,7 @@ var ts; tokenPos = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; - precedingLineBreak = savePrecedingLineBreak; + tokenFlags = saveTokenFlags; } return result; } @@ -6145,10 +5594,8 @@ var ts; var saveStartPos = startPos; var saveTokenPos = tokenPos; var saveToken = token; - var savePrecedingLineBreak = precedingLineBreak; var saveTokenValue = tokenValue; - var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - var saveTokenIsUnterminated = tokenIsUnterminated; + var saveTokenFlags = tokenFlags; setText(text, start, length); var result = callback(); end = saveEnd; @@ -6156,10 +5603,8 @@ var ts; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; - precedingLineBreak = savePrecedingLineBreak; tokenValue = saveTokenValue; - hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; - tokenIsUnterminated = saveTokenIsUnterminated; + tokenFlags = saveTokenFlags; return result; } function lookAhead(callback) { @@ -6191,10 +5636,8 @@ var ts; startPos = textPos; tokenPos = textPos; token = 0; - precedingLineBreak = false; tokenValue = undefined; - hasExtendedUnicodeEscape = false; - tokenIsUnterminated = false; + tokenFlags = 0; } } ts.createScanner = createScanner; @@ -6237,6 +5680,7 @@ var ts; clear: function () { return str = ""; }, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; } @@ -6319,7 +5763,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 265) { + while (node && node.kind !== 269) { node = node.parent; } return node; @@ -6327,11 +5771,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 207: - case 235: - case 214: + case 208: + case 236: case 215: case 216: + case 217: return true; } return false; @@ -6407,7 +5851,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { + if (node.kind === 290 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -6441,15 +5885,13 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } function indexOfNode(nodeArray, node) { - return ts.binarySearch(nodeArray, node, compareNodePos); + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } ts.indexOfNode = indexOfNode; - function compareNodePos(_a, _b) { - var aPos = _a.pos; - var bPos = _b.pos; - return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; - } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -6484,7 +5926,7 @@ var ts; } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { - return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; function escapeLeadingUnderscores(identifier) { @@ -6506,14 +5948,18 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 226 && node.parent.kind === 260; + return node.kind === 227 && node.parent.kind === 264; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 233 && + return node && node.kind === 234 && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 9; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } @@ -6523,11 +5969,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node && node.kind === 233 && (!node.body); + return node && node.kind === 234 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 || - node.kind === 233 || + return node.kind === 269 || + node.kind === 234 || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -6540,36 +5986,36 @@ var ts; return false; } switch (node.parent.kind) { - case 265: + case 269: return ts.isExternalModule(node.parent); - case 234: + case 235: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 265: - case 235: - case 260: - case 233: - case 214: + case 269: + case 236: + case 264: + case 234: case 215: case 216: - case 152: - case 151: + case 217: case 153: + case 152: case 154: - case 228: - case 186: + case 155: + case 229: case 187: + case 188: return true; - case 207: + case 208: return parentNode && !ts.isFunctionLike(parentNode); } return false; @@ -6577,25 +6023,25 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 155: case 156: - case 150: case 157: - case 160: + case 151: + case 158: case 161: - case 273: - case 229: - case 199: + case 162: + case 277: case 230: + case 200: case 231: - case 282: - case 228: - case 151: + case 232: + case 287: + case 229: case 152: case 153: case 154: - case 186: + case 155: case 187: + case 188: return true; default: ts.assertTypeIsNever(node); @@ -6603,6 +6049,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 239: + case 238: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -6628,7 +6084,7 @@ var ts; case 9: case 8: return escapeLeadingUnderscores(name.text); - case 144: + case 145: if (isStringOrNumericLiteral(name.expression)) { return escapeLeadingUnderscores(name.expression.text); } @@ -6639,22 +6095,22 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71: - return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); - case 143: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 144: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179: + case 180: return entityNameToString(name.expression) + "." + entityNameToString(name.name); } } ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { @@ -6679,7 +6135,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207) { + if (node.body && node.body.kind === 208) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -6691,29 +6147,29 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 265: + case 269: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 226: - case 176: - case 229: - case 199: + case 227: + case 177: case 230: + case 200: + case 231: + case 234: case 233: - case 232: - case 264: - case 228: - case 186: - case 151: - case 153: + case 268: + case 229: + case 187: + case 152: case 154: - case 231: + case 155: + case 232: errorNode = node.name; break; - case 187: + case 188: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -6730,7 +6186,7 @@ var ts; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isConstEnumDeclaration(node) { - return node.kind === 232 && isConst(node); + return node.kind === 233 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -6743,15 +6199,15 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 181 && n.expression.kind === 97; + return n.kind === 182 && n.expression.kind === 97; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 181 && n.expression.kind === 91; + return n.kind === 182 && n.expression.kind === 91; } ts.isImportCall = isImportCall; function isPrologueDirective(node) { - return node.kind === 210 + return node.kind === 211 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; @@ -6760,11 +6216,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 || - node.kind === 145 || - node.kind === 186 || + var commentRanges = (node.kind === 147 || + node.kind === 146 || node.kind === 187 || - node.kind === 185) ? + node.kind === 188 || + node.kind === 186) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { @@ -6779,7 +6235,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (158 <= node.kind && node.kind <= 173) { + if (159 <= node.kind && node.kind <= 174) { return true; } switch (node.kind) { @@ -6792,56 +6248,56 @@ var ts; case 130: return true; case 105: - return node.parent.kind !== 190; - case 201: + return node.parent.kind !== 191; + case 202: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 71: - if (node.parent.kind === 143 && node.parent.right === node) { + if (node.parent.kind === 144 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 179 && node.parent.name === node) { + else if (node.parent.kind === 180 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 143: - case 179: + ts.Debug.assert(node.kind === 71 || node.kind === 144 || node.kind === 180, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 144: + case 180: case 99: var parent = node.parent; - if (parent.kind === 162) { + if (parent.kind === 163) { return false; } - if (158 <= parent.kind && parent.kind <= 173) { + if (159 <= parent.kind && parent.kind <= 174) { return true; } switch (parent.kind) { - case 201: + case 202: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 145: + case 146: return node === parent.constraint; + case 150: case 149: - case 148: - case 146: - case 226: + case 147: + case 227: return node === parent.type; - case 228: - case 186: + case 229: case 187: + case 188: + case 153: case 152: case 151: - case 150: - case 153: case 154: - return node === parent.type; case 155: + return node === parent.type; case 156: case 157: + case 158: return node === parent.type; - case 184: + case 185: return node === parent.type; - case 181: case 182: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; case 183: + return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + case 184: return false; } } @@ -6862,23 +6318,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219: + case 220: return visitor(node); - case 235: - case 207: - case 211: + case 236: + case 208: case 212: case 213: case 214: case 215: case 216: - case 220: + case 217: case 221: - case 257: - case 258: case 222: - case 224: - case 260: + case 261: + case 262: + case 223: + case 225: + case 264: return ts.forEachChild(node, traverse); } } @@ -6888,24 +6344,24 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 197: + case 198: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 232: - case 230: case 233: case 231: - case 229: - case 199: + case 234: + case 232: + case 230: + case 200: return; default: if (ts.isFunctionLike(node)) { var name = node.name; - if (name && name.kind === 144) { + if (name && name.kind === 145) { traverse(name.expression); return; } @@ -6918,10 +6374,10 @@ var ts; } ts.forEachYieldExpression = forEachYieldExpression; function getRestParameterElementType(node) { - if (node && node.kind === 164) { + if (node && node.kind === 165) { return node.elementType; } - else if (node && node.kind === 159) { + else if (node && node.kind === 160) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -6929,32 +6385,55 @@ var ts; } } ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 231: + case 230: + case 200: + case 164: + return node.members; + case 179: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; function isVariableLike(node) { if (node) { switch (node.kind) { - case 176: - case 264: - case 146: - case 261: + case 177: + case 268: + case 147: + case 265: + case 150: case 149: - case 148: - case 262: - case 226: + case 266: + case 227: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 228 + && node.parent.parent.kind === 209; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 228: - case 186: + case 155: + case 229: + case 187: return true; } return false; @@ -6965,7 +6444,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 222) { + if (node.statement.kind !== 223) { return node.statement; } node = node.statement; @@ -6973,17 +6452,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 && ts.isFunctionLike(node.parent); + return node && node.kind === 208 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 151 && node.parent.kind === 178; + return node && node.kind === 152 && node.parent.kind === 179; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 && - (node.parent.kind === 178 || - node.parent.kind === 199); + return node.kind === 152 && + (node.parent.kind === 179 || + node.parent.kind === 200); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -6996,7 +6475,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 261) { + if (property.kind === 265) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); } @@ -7018,39 +6497,39 @@ var ts; return undefined; } switch (node.kind) { - case 144: + case 145: if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148: + if (node.parent.kind === 147 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { node = node.parent; } break; - case 187: + case 188: if (!includeArrowFunctions) { continue; } - case 228: - case 186: - case 233: - case 149: - case 148: - case 151: + case 229: + case 187: + case 234: case 150: + case 149: case 152: + case 151: case 153: case 154: case 155: case 156: case 157: - case 232: - case 265: + case 158: + case 233: + case 269: return node; } } @@ -7060,9 +6539,9 @@ var ts; var container = getThisContainer(node, false); if (container) { switch (container.kind) { - case 152: - case 228: - case 186: + case 153: + case 229: + case 187: return container; } } @@ -7076,25 +6555,25 @@ var ts; return node; } switch (node.kind) { - case 144: + case 145: node = node.parent; break; - case 228: - case 186: + case 229: case 187: + case 188: if (!stopOnFunctions) { continue; } - case 149: - case 148: - case 151: case 150: + case 149: case 152: + case 151: case 153: case 154: + case 155: return node; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148: + if (node.parent.kind === 147 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { @@ -7106,14 +6585,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 || func.kind === 187) { + if (func.kind === 187 || func.kind === 188) { var prev = func; var parent = func.parent; - while (parent.kind === 185) { + while (parent.kind === 186) { prev = parent; parent = parent.parent; } - if (parent.kind === 181 && parent.expression === prev) { + if (parent.kind === 182 && parent.expression === prev) { return parent; } } @@ -7121,27 +6600,33 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 179 || kind === 180) + return (kind === 180 || kind === 181) && node.expression.kind === 97; } ts.isSuperProperty = isSuperProperty; + function isThisProperty(node) { + var kind = node.kind; + return (kind === 180 || kind === 181) + && node.expression.kind === 99; + } + ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 159: + case 160: return node.typeName; - case 201: + case 202: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71: - case 143: + case 144: return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 183) { + if (node.kind === 184) { return node.tag; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -7150,101 +6635,102 @@ var ts; return node.expression; } ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { + function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 229: + case 230: return true; - case 149: - return node.parent.kind === 229; - case 153: + case 150: + return parent.kind === 230; case 154: - case 151: + case 155: + case 152: return node.body !== undefined - && node.parent.kind === 229; - case 146: - return node.parent.body !== undefined - && (node.parent.kind === 152 - || node.parent.kind === 151 - || node.parent.kind === 154) - && node.parent.parent.kind === 229; + && parent.kind === 230; + case 147: + return parent.body !== undefined + && (parent.kind === 153 + || parent.kind === 152 + || parent.kind === 155) + && grandparent.kind === 230; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { + function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node); + && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { + function childIsDecorated(node, parent) { switch (node.kind) { - case 229: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151: - case 154: - return ts.forEach(node.parameters, nodeIsDecorated); + case 230: + return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 152: + case 155: + return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 251 || - parent.kind === 250 || - parent.kind === 252) { + if (parent.kind === 252 || + parent.kind === 251 || + parent.kind === 253) { return parent.tagName === node; } return false; } ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { + function isExpressionNode(node) { switch (node.kind) { case 97: case 95: case 101: case 86: case 12: - case 177: case 178: case 179: case 180: case 181: case 182: case 183: - case 202: case 184: case 203: case 185: + case 204: case 186: - case 199: case 187: - case 190: + case 200: case 188: + case 191: case 189: - case 192: + case 190: case 193: case 194: case 195: - case 198: case 196: + case 199: + case 197: case 13: - case 200: - case 249: + case 201: case 250: - case 197: - case 191: - case 204: + case 251: + case 254: + case 198: + case 192: + case 205: return true; - case 143: - while (node.parent.kind === 143) { + case 144: + while (node.parent.kind === 144) { node = node.parent; } - return node.parent.kind === 162 || isJSXTagName(node); + return node.parent.kind === 163 || isJSXTagName(node); case 71: - if (node.parent.kind === 162 || isJSXTagName(node)) { + if (node.parent.kind === 163 || isJSXTagName(node)) { return true; } case 8: @@ -7255,59 +6741,59 @@ var ts; return false; } } - ts.isPartOfExpression = isPartOfExpression; + ts.isExpressionNode = isExpressionNode; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 226: - case 146: + case 227: + case 147: + case 150: case 149: - case 148: - case 264: - case 261: - case 176: + case 268: + case 265: + case 177: return parent.initializer === node; - case 210: case 211: case 212: case 213: - case 219: + case 214: case 220: case 221: - case 257: - case 223: + case 222: + case 261: + case 224: return parent.expression === node; - case 214: + case 215: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 228) || forStatement.condition === node || forStatement.incrementor === node; - case 215: case 216: + case 217: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 228) || forInStatement.expression === node; - case 184: - case 202: + case 185: + case 203: return node === parent.expression; - case 205: + case 206: return node === parent.expression; - case 144: + case 145: return node === parent.expression; - case 147: - case 256: - case 255: - case 263: + case 148: + case 260: + case 259: + case 267: return true; - case 201: + case 202: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: - return isPartOfExpression(parent); + return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind === 248; + return node.kind === 238 && node.moduleReference.kind === 249; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -7316,7 +6802,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind !== 248; + return node.kind === 238 && node.moduleReference.kind !== 249; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -7331,8 +6817,16 @@ var ts; return node && !!(node.flags & 1048576); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 || node.typeArguments[0].kind === 133); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181) { + if (callExpression.kind !== 182) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -7350,10 +6844,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226) { + if (s.valueDeclaration && s.valueDeclaration.kind === 227) { var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); + return declaration.initializer && (declaration.initializer.kind === 187 || declaration.initializer.kind === 200); } return false; } @@ -7373,12 +6871,11 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { + function getSpecialPropertyAssignmentKind(expr) { + if (!isInJavaScriptFile(expr)) { return 0; } - var expr = expression; - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { + if (expr.operatorToken.kind !== 58 || expr.left.kind !== 180) { return 0; } var lhs = expr.left; @@ -7397,7 +6894,7 @@ var ts; else if (lhs.expression.kind === 99) { return 4; } - else if (lhs.expression.kind === 179) { + else if (lhs.expression.kind === 180) { var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; @@ -7412,36 +6909,42 @@ var ts; return 0; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isSpecialPropertyDeclaration(expr) { + return isInJavaScriptFile(expr) && + expr.parent && expr.parent.kind === 211 && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function getExternalModuleName(node) { - if (node.kind === 238) { + if (node.kind === 239) { return node.moduleSpecifier; } - if (node.kind === 237) { + if (node.kind === 238) { var reference = node.moduleReference; - if (reference.kind === 248) { + if (reference.kind === 249) { return reference.expression; } } - if (node.kind === 244) { + if (node.kind === 245) { return node.moduleSpecifier; } - if (node.kind === 233 && node.name.kind === 9) { + if (isModuleWithStringLiteralName(node)) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 237) { + if (node.kind === 238) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 241) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 238 + return node.kind === 239 && node.importClause && !!node.importClause.name; } @@ -7449,13 +6952,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 146: + case 147: + case 152: case 151: + case 266: + case 265: case 150: - case 262: - case 261: case 149: - case 148: return node.questionToken !== undefined; } } @@ -7463,7 +6966,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 273 && + return node.kind === 277 && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; @@ -7476,37 +6979,55 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 58 && + node.expression.right; + } + ts.getSourceOfAssignment = getSourceOfAssignment; + function getSingleInitializerOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0].initializer === child) && + node.declarationList.declarations[0].initializer; + } + ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; + function getSingleVariableOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0] === child) && + node.declarationList.declarations[0]; + } + ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; + function getNestedModuleDeclaration(node) { + return node.kind === 234 && + node.body && + node.body.kind === 234 && + node.body; + } + ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocCommentsAndTagsWorker(variableStatementNode); - } - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 && - parent.operatorToken.kind === 58 && - parent.parent.kind === 210; - if (isSourceOfAssignmentExpressionStatement) { + if (parent && (parent.kind === 265 || getNestedModuleDeclaration(parent))) { + getJSDocCommentsAndTagsWorker(parent); + } + if (parent && parent.parent && + (getSingleVariableOfVariableStatement(parent.parent, node) || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - var isModuleDeclaration = node.kind === 233 && - parent && parent.kind === 233; - var isPropertyAssignmentExpression = parent && parent.kind === 261; - if (isModuleDeclaration || isPropertyAssignmentExpression) { + if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatement(parent.parent.parent, node)) { + getJSDocCommentsAndTagsWorker(parent.parent.parent); + } + if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || + node.kind === 180 && node.parent && node.parent.kind === 211) { getJSDocCommentsAndTagsWorker(parent); } - if (node.kind === 146) { + if (node.kind === 147) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { @@ -7526,17 +7047,29 @@ var ts; return undefined; } var name = node.name.escapedText; - ts.Debug.assert(node.parent.kind === 275); - var func = node.parent.parent; - if (!ts.isFunctionLike(func)) { + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { return undefined; } - var parameter = ts.find(func.parameters, function (p) { - return p.name.kind === 71 && p.name.escapedText === name; - }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + var host = getJSDocHost(node); + var decl = getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatement(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getJSDocHost(node) { + ts.Debug.assert(node.parent.kind === 279); + return node.parent.parent; + } + ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { var name = node.name.escapedText; var typeParameters = node.parent.parent.parent.typeParameters; @@ -7544,61 +7077,42 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; - var AssignmentKind; - (function (AssignmentKind) { - AssignmentKind[AssignmentKind["None"] = 0] = "None"; - AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; - AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; - })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { switch (parent.kind) { - case 194: + case 195: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 ? 1 : 2 : 0; - case 192: case 193: + case 194: var unaryOperator = parent.operator; return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; - case 215: case 216: + case 217: return parent.initializer === node ? 1 : 0; - case 185: - case 177: - case 198: + case 186: + case 178: + case 199: node = parent; break; - case 262: + case 266: if (parent.name !== node) { return 0; } node = parent.parent; break; - case 261: + case 265: if (parent.name === node) { return 0; } @@ -7615,15 +7129,26 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 169); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 186); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function isDeleteTarget(node) { - if (node.kind !== 179 && node.kind !== 180) { + if (node.kind !== 180 && node.kind !== 181) { return false; } - node = node.parent; - while (node && node.kind === 185) { - node = node.parent; - } - return node && node.kind === 188; + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 189; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -7635,16 +7160,6 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { switch (name.kind) { case 71: @@ -7673,49 +7188,49 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 144 && + node.parent.kind === 145 && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { + case 150: case 149: - case 148: + case 152: case 151: - case 150: - case 153: case 154: - case 264: - case 261: - case 179: + case 155: + case 268: + case 265: + case 180: return parent.name === node; - case 143: + case 144: if (parent.right === node) { - while (parent.kind === 143) { + while (parent.kind === 144) { parent = parent.parent; } - return parent.kind === 162; + return parent.kind === 163; } return false; - case 176: - case 242: + case 177: + case 243: return parent.propertyName === node; - case 246: - case 253: + case 247: + case 257: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 237 || - node.kind === 236 || - node.kind === 239 && !!node.name || - node.kind === 240 || - node.kind === 242 || - node.kind === 246 || - node.kind === 243 && exportAssignmentIsAlias(node); + return node.kind === 238 || + node.kind === 237 || + node.kind === 240 && !!node.name || + node.kind === 241 || + node.kind === 243 || + node.kind === 247 || + node.kind === 244 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7799,34 +7314,39 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 72 <= token && token <= 142; + return 72 <= token && token <= 143; } ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 117 <= token && token <= 143; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; function isTrivia(token) { return 2 <= token && token <= 7; } ts.isTrivia = isTrivia; - var FunctionFlags; - (function (FunctionFlags) { - FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; - FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; - FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; - })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { if (!node) { return 4; } var flags = 0; switch (node.kind) { - case 228: - case 186: - case 151: + case 229: + case 187: + case 152: if (node.asteriskToken) { flags |= 1; } - case 187: + case 188: if (hasModifier(node, 256)) { flags |= 2; } @@ -7840,10 +7360,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 228: - case 186: + case 229: case 187: - case 151: + case 188: + case 152: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256); @@ -7863,7 +7383,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 144 && + return name.kind === 145 && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -7879,11 +7399,10 @@ var ts; if (name.kind === 9 || name.kind === 8) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 144) { + if (name.kind === 145) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.escapedText; - return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } else if (nameExpression.kind === 9 || nameExpression.kind === 8) { return escapeLeadingUnderscores(nameExpression.text); @@ -7895,7 +7414,7 @@ var ts; function getTextOfIdentifierOrLiteral(node) { if (node) { if (node.kind === 71) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } if (node.kind === 9 || node.kind === 8) { @@ -7932,11 +7451,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 146; + return root.kind === 147; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 176) { + while (node.kind === 177) { node = node.parent.parent; } return node; @@ -7944,15 +7463,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 152 - || kind === 186 - || kind === 228 + return kind === 153 || kind === 187 - || kind === 151 - || kind === 153 + || kind === 229 + || kind === 188 + || kind === 152 || kind === 154 - || kind === 233 - || kind === 265; + || kind === 155 + || kind === 234 + || kind === 269; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -7964,30 +7483,25 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - var Associativity; - (function (Associativity) { - Associativity[Associativity["Left"] = 0] = "Left"; - Associativity[Associativity["Right"] = 1] = "Right"; - })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 182: + case 183: return hasArguments ? 0 : 1; - case 192: - case 189: + case 193: case 190: - case 188: case 191: - case 195: - case 197: + case 189: + case 192: + case 196: + case 198: return 1; - case 194: + case 195: switch (operator) { case 40: case 58: @@ -8011,15 +7525,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 194) { + if (expression.kind === 195) { return expression.operatorToken.kind; } - else if (expression.kind === 192 || expression.kind === 193) { + else if (expression.kind === 193 || expression.kind === 194) { return expression.operator; } else { @@ -8037,36 +7551,37 @@ var ts; case 86: case 8: case 9: - case 177: case 178: - case 186: + case 179: case 187: - case 199: - case 249: + case 188: + case 200: case 250: + case 251: + case 254: case 12: case 13: - case 196: - case 185: - case 200: + case 197: + case 186: + case 201: return 19; - case 183: - case 179: + case 184: case 180: + case 181: return 18; - case 182: + case 183: return hasArguments ? 18 : 17; - case 181: + case 182: return 17; - case 193: + case 194: return 16; - case 192: - case 189: + case 193: case 190: - case 188: case 191: + case 189: + case 192: return 15; - case 194: + case 195: switch (operatorKind) { case 51: case 52: @@ -8124,13 +7639,13 @@ var ts; default: return -1; } - case 195: + case 196: return 4; - case 197: - return 2; case 198: + return 2; + case 199: return 1; - case 289: + case 293: return 0; default: return -1; @@ -8140,6 +7655,7 @@ var ts; function createDiagnosticCollection() { var nonFileDiagnostics = []; var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; var diagnosticsModified = false; var modificationCount = 0; return { @@ -8165,6 +7681,10 @@ var ts; } } else { + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); @@ -8173,6 +7693,7 @@ var ts; } function getGlobalDiagnostics() { sortAndDeduplicate(); + hasReadNonFileDiagnostics = true; return nonFileDiagnostics; } function getDiagnostics(fileName) { @@ -8236,8 +7757,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; + var ch = name.charCodeAt(0); + return (ch >= 97 && ch <= 122) || name.indexOf("-") > -1; } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -8420,7 +7941,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 152 && nodeIsPresent(member.body)) { + if (member.kind === 153 && nodeIsPresent(member.body)) { return member; } }); @@ -8465,10 +7986,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 153) { + if (accessor.kind === 154) { getAccessor = accessor; } - else if (accessor.kind === 154) { + else if (accessor.kind === 155) { setAccessor = accessor; } else { @@ -8477,7 +7998,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 153 || member.kind === 154) + if ((member.kind === 154 || member.kind === 155) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -8488,10 +8009,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 153 && !getAccessor) { + if (member.kind === 154 && !getAccessor) { getAccessor = member; } - if (member.kind === 154 && !setAccessor) { + if (member.kind === 155 && !setAccessor) { setAccessor = member; } } @@ -8506,37 +8027,37 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node) { + function getEffectiveTypeAnnotationNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node) { + function getEffectiveReturnTypeNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node) { + function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node) { + function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter); + return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -8695,6 +8216,14 @@ var ts; return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64); + } + ts.hasReadonlyModifier = hasReadonlyModifier; function getSelectedModifierFlags(node, flags) { return getModifierFlags(node) & flags; } @@ -8750,7 +8279,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 && + if (node.kind === 202 && node.parent.token === 85 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -8768,8 +8297,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, true)) { var kind = node.left.kind; - return kind === 178 - || kind === 177; + return kind === 179 + || kind === 178; } return false; } @@ -8779,7 +8308,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 + return node.kind === 202 && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 @@ -8789,21 +8318,21 @@ var ts; ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 || - node.kind === 179 && isEntityNameExpression(node.expression); + node.kind === 180 && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 && node.parent.right === node) || - (node.parent.kind === 179 && node.parent.name === node); + return (node.parent.kind === 144 && node.parent.right === node) || + (node.parent.kind === 180 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 178 && + return expression.kind === 179 && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 177 && + return expression.kind === 178 && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -8873,17 +8402,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options) { + function getNewLineCharacter(options, system) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; + return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -9019,8 +8545,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 232: case 233: + case 234: return parseNode === parseNode.parent.name; } } @@ -9061,25 +8587,6 @@ var ts; return 0; } ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; - function levenshtein(s1, s2) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - for (var i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (var i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (var j = 1; j < s2.length + 1; j++) { - current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - var tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; function skipAlias(symbol, checker) { return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; } @@ -9096,38 +8603,113 @@ var ts; return accessKind(node) !== 0; } ts.isWriteAccess = isWriteAccess; - var AccessKind; - (function (AccessKind) { - AccessKind[AccessKind["Read"] = 0] = "Read"; - AccessKind[AccessKind["Write"] = 1] = "Write"; - AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; - })(AccessKind || (AccessKind = {})); function accessKind(node) { var parent = node.parent; if (!parent) return 0; switch (parent.kind) { + case 194: case 193: - case 192: var operator = parent.operator; return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; - case 194: + case 195: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; - case 179: + case 180: return parent.name !== node ? 0 : accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 210 ? 1 : 2; + return parent.parent && parent.parent.kind === 211 ? 1 : 2; + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function clearMap(map, onDeleteValue) { + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + 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); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128); } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 65536 ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 5: + case 6: return "lib.esnext.full.d.ts"; case 4: return "lib.es2017.full.d.ts"; @@ -9256,9 +8838,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 145) { + if (d && d.kind === 146) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 231) { return current; } } @@ -9266,7 +8848,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 153 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -9284,7 +8866,7 @@ var ts; } ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 || ts.isBindingPattern(node))) { + while (node && (node.kind === 177 || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -9292,14 +8874,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 226) { + if (node.kind === 227) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209) { flags |= ts.getModifierFlags(node); } return flags; @@ -9308,14 +8890,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 226) { + if (node.kind === 227) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209) { flags |= node.flags; } return flags; @@ -9334,6 +8916,7 @@ var ts; if (!trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, undefined, errors); } + ts.setUILocale(locale); function trySetLanguageAndTerritory(language, territory, errors) { var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); @@ -9397,6 +8980,14 @@ var ts; return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; } ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; function unescapeIdentifier(id) { return id; } @@ -9410,18 +9001,18 @@ var ts; return getDeclarationIdentifier(hostNode); } switch (hostNode.kind) { - case 208: + case 209: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 210: + case 211: var expr = hostNode.expression; switch (expr.kind) { - case 179: - return expr.name; case 180: + return expr.name; + case 181: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -9430,10 +9021,10 @@ var ts; return undefined; case 1: return undefined; - case 185: { + case 186: { return getDeclarationIdentifier(hostNode.expression); } - case 222: { + case 223: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -9455,27 +9046,37 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 71: + return declaration; + case 289: + case 284: { + var name = declaration.name; + if (name.kind === 144) { + return name.right; + } + break; + } + case 195: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + case 288: + return getNameOfJSDocTypedef(declaration); + case 244: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; function getJSDocParameterTags(param) { @@ -9487,27 +9088,27 @@ var ts; } ts.getJSDocParameterTags = getJSDocParameterTags; function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); + return !!getFirstJSDocTag(node, 284); } ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); + return getFirstJSDocTag(node, 282); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); + return getFirstJSDocTag(node, 283); } ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); + return getFirstJSDocTag(node, 285); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); + return getFirstJSDocTag(node, 287); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 281); + var tag = getFirstJSDocTag(node, 286); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -9515,8 +9116,8 @@ var ts; } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { + var tag = getFirstJSDocTag(node, 286); + if (!tag && node.kind === 147) { var paramTags = getJSDocParameterTags(node); if (paramTags) { tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); @@ -9542,6 +9143,11 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -9581,584 +9187,600 @@ var ts; } ts.isIdentifier = isIdentifier; function isQualifiedName(node) { - return node.kind === 143; + return node.kind === 144; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 144; + return node.kind === 145; } ts.isComputedPropertyName = isComputedPropertyName; function isTypeParameterDeclaration(node) { - return node.kind === 145; + return node.kind === 146; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 146; + return node.kind === 147; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 147; + return node.kind === 148; } ts.isDecorator = isDecorator; function isPropertySignature(node) { - return node.kind === 148; + return node.kind === 149; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 149; + return node.kind === 150; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 150; + return node.kind === 151; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 151; + return node.kind === 152; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 152; + return node.kind === 153; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 153; + return node.kind === 154; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 154; + return node.kind === 155; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 155; + return node.kind === 156; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 156; + return node.kind === 157; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 157; + return node.kind === 158; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isTypePredicateNode(node) { - return node.kind === 158; + return node.kind === 159; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 159; + return node.kind === 160; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 160; + return node.kind === 161; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 161; + return node.kind === 162; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 162; + return node.kind === 163; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 163; + return node.kind === 164; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 164; + return node.kind === 165; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 165; + return node.kind === 166; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 166; + return node.kind === 167; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 167; + return node.kind === 168; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 168; + return node.kind === 169; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 169; + return node.kind === 170; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 170; + return node.kind === 171; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 171; + return node.kind === 172; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 172; + return node.kind === 173; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 173; + return node.kind === 174; } ts.isLiteralTypeNode = isLiteralTypeNode; function isObjectBindingPattern(node) { - return node.kind === 174; + return node.kind === 175; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 175; + return node.kind === 176; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 176; + return node.kind === 177; } ts.isBindingElement = isBindingElement; function isArrayLiteralExpression(node) { - return node.kind === 177; + return node.kind === 178; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 178; + return node.kind === 179; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 179; + return node.kind === 180; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 180; + return node.kind === 181; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 181; + return node.kind === 182; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 182; + return node.kind === 183; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 183; + return node.kind === 184; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 184; + return node.kind === 185; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 185; + return node.kind === 186; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 292) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 186; + return node.kind === 187; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 187; + return node.kind === 188; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 188; + return node.kind === 189; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 191; + return node.kind === 192; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 190; + return node.kind === 191; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 191; + return node.kind === 192; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 192; + return node.kind === 193; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 193; + return node.kind === 194; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 194; + return node.kind === 195; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 195; + return node.kind === 196; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 196; + return node.kind === 197; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 197; + return node.kind === 198; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 198; + return node.kind === 199; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 199; + return node.kind === 200; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 200; + return node.kind === 201; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 201; + return node.kind === 202; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 202; + return node.kind === 203; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 203; + return node.kind === 204; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 204; + return node.kind === 205; } ts.isMetaProperty = isMetaProperty; function isTemplateSpan(node) { - return node.kind === 205; + return node.kind === 206; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 206; + return node.kind === 207; } ts.isSemicolonClassElement = isSemicolonClassElement; function isBlock(node) { - return node.kind === 207; + return node.kind === 208; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 208; + return node.kind === 209; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 209; + return node.kind === 210; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 210; + return node.kind === 211; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 211; + return node.kind === 212; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 212; + return node.kind === 213; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 213; + return node.kind === 214; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 214; + return node.kind === 215; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 215; + return node.kind === 216; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 216; + return node.kind === 217; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 217; + return node.kind === 218; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 218; + return node.kind === 219; } ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 219 || node.kind === 218; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 219; + return node.kind === 220; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 220; + return node.kind === 221; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 221; + return node.kind === 222; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 222; + return node.kind === 223; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 223; + return node.kind === 224; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 224; + return node.kind === 225; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 225; + return node.kind === 226; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 226; + return node.kind === 227; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 227; + return node.kind === 228; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 228; + return node.kind === 229; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 229; + return node.kind === 230; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 230; + return node.kind === 231; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 231; + return node.kind === 232; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 232; + return node.kind === 233; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 233; + return node.kind === 234; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 234; + return node.kind === 235; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 235; + return node.kind === 236; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 236; + return node.kind === 237; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 237; + return node.kind === 238; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 238; + return node.kind === 239; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 239; + return node.kind === 240; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 240; + return node.kind === 241; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 241; + return node.kind === 242; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 242; + return node.kind === 243; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 243; + return node.kind === 244; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 244; + return node.kind === 245; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 245; + return node.kind === 246; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 246; + return node.kind === 247; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 247; + return node.kind === 248; } ts.isMissingDeclaration = isMissingDeclaration; function isExternalModuleReference(node) { - return node.kind === 248; + return node.kind === 249; } ts.isExternalModuleReference = isExternalModuleReference; function isJsxElement(node) { - return node.kind === 249; + return node.kind === 250; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 250; + return node.kind === 251; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 251; + return node.kind === 252; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 252; + return node.kind === 253; } ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 254; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 255; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 256; + } + ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 253; + return node.kind === 257; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 254; + return node.kind === 258; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 255; + return node.kind === 259; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 256; + return node.kind === 260; } ts.isJsxExpression = isJsxExpression; function isCaseClause(node) { - return node.kind === 257; + return node.kind === 261; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 258; + return node.kind === 262; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 259; + return node.kind === 263; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 260; + return node.kind === 264; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 261; + return node.kind === 265; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 262; + return node.kind === 266; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 263; + return node.kind === 267; } ts.isSpreadAssignment = isSpreadAssignment; function isEnumMember(node) { - return node.kind === 264; + return node.kind === 268; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 265; + return node.kind === 269; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 266; + return node.kind === 270; } ts.isBundle = isBundle; function isJSDocTypeExpression(node) { - return node.kind === 267; + return node.kind === 271; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 268; + return node.kind === 272; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 269; + return node.kind === 273; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 270; + return node.kind === 274; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 271; + return node.kind === 275; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 272; + return node.kind === 276; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 273; + return node.kind === 277; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 274; + return node.kind === 278; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 275; + return node.kind === 279; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 277; + return node.kind === 282; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocParameterTag(node) { - return node.kind === 279; + return node.kind === 284; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 280; + return node.kind === 285; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 281; + return node.kind === 286; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 282; + return node.kind === 287; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 283; + return node.kind === 288; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 284; + return node.kind === 289; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 284 || node.kind === 279; + return node.kind === 289 || node.kind === 284; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 285; + return node.kind === 280; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 286; + return n.kind === 290; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -10166,11 +9788,11 @@ var ts; } ts.isNode = isNode; function isNodeKind(kind) { - return kind >= 143; + return kind >= 144; } ts.isNodeKind = isNodeKind; function isToken(n) { - return n.kind >= 0 && n.kind <= 142; + return n.kind >= 0 && n.kind <= 143; } ts.isToken = isToken; function isNodeArray(array) { @@ -10196,16 +9818,7 @@ var ts; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isStringTextContainingNode(node) { - switch (node.kind) { - case 9: - case 14: - case 15: - case 16: - case 13: - return true; - default: - return false; - } + return node.kind === 9 || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { @@ -10236,7 +9849,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 143 + return kind === 144 || kind === 71; } ts.isEntityName = isEntityName; @@ -10245,14 +9858,14 @@ var ts; return kind === 71 || kind === 9 || kind === 8 - || kind === 144; + || kind === 145; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 - || kind === 174 - || kind === 175; + || kind === 175 + || kind === 176; } ts.isBindingName = isBindingName; function isFunctionLike(node) { @@ -10265,13 +9878,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 228: - case 151: + case 229: case 152: case 153: case 154: - case 186: + case 155: case 187: + case 188: return true; default: return false; @@ -10279,13 +9892,13 @@ var ts; } function isFunctionLikeKind(kind) { switch (kind) { - case 150: - case 155: + case 151: case 156: case 157: - case 160: - case 273: + case 158: case 161: + case 277: + case 162: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -10298,47 +9911,47 @@ var ts; ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 + return kind === 153 + || kind === 150 + || kind === 152 || kind === 154 - || kind === 157 - || kind === 206 - || kind === 247; + || kind === 155 + || kind === 158 + || kind === 207 + || kind === 248; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); + return node && (node.kind === 230 || node.kind === 200); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); + return node && (node.kind === 154 || node.kind === 155); } ts.isAccessor = isAccessor; function isTypeElement(node) { var kind = node.kind; - return kind === 156 - || kind === 155 - || kind === 148 - || kind === 150 - || kind === 157 - || kind === 247; + return kind === 157 + || kind === 156 + || kind === 149 + || kind === 151 + || kind === 158 + || kind === 248; } ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 261 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 + return kind === 265 + || kind === 266 + || kind === 267 + || kind === 152 || kind === 154 - || kind === 247; + || kind === 155 + || kind === 248; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) + return (kind >= 159 && kind <= 174) || kind === 119 || kind === 133 || kind === 134 @@ -10350,7 +9963,14 @@ var ts; || kind === 139 || kind === 95 || kind === 130 - || kind === 201; + || kind === 202 + || kind === 272 + || kind === 273 + || kind === 274 + || kind === 275 + || kind === 276 + || kind === 277 + || kind === 278; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -10358,8 +9978,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 160: case 161: + case 162: return true; } return false; @@ -10368,29 +9988,29 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 175 - || kind === 174; + return kind === 176 + || kind === 175; } return false; } ts.isBindingPattern = isBindingPattern; function isAssignmentPattern(node) { var kind = node.kind; - return kind === 177 - || kind === 178; + return kind === 178 + || kind === 179; } ts.isAssignmentPattern = isAssignmentPattern; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 176 - || kind === 200; + return kind === 177 + || kind === 201; } ts.isArrayBindingElement = isArrayBindingElement; function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 226: - case 146: - case 176: + case 227: + case 147: + case 177: return true; } return false; @@ -10403,8 +10023,8 @@ var ts; ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 174: - case 178: + case 175: + case 179: return true; } return false; @@ -10412,8 +10032,8 @@ var ts; ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: + case 176: + case 178: return true; } return false; @@ -10421,18 +10041,18 @@ var ts; ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 179 - || kind === 143; + return kind === 180 + || kind === 144; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { + case 252: case 251: - case 250: - case 181: case 182: case 183: - case 147: + case 184: + case 148: return true; default: return false; @@ -10440,12 +10060,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 181 || node.kind === 182; + return node.kind === 182 || node.kind === 183; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 196 + return kind === 197 || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; @@ -10455,31 +10075,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 179: case 180: - case 182: case 181: - case 249: - case 250: case 183: - case 177: - case 185: + case 182: + case 250: + case 251: + case 254: + case 184: case 178: - case 199: case 186: + case 179: + case 200: + case 187: case 71: case 12: case 8: case 9: case 13: - case 196: + case 197: case 86: case 95: case 99: case 101: case 97: - case 203: case 204: + case 205: case 91: return true; default: @@ -10492,13 +10113,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 192: case 193: - case 188: + case 194: case 189: case 190: case 191: - case 184: + case 192: + case 185: return true; default: return isLeftHandSideExpressionKind(kind); @@ -10506,9 +10127,9 @@ var ts; } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 193: + case 194: return true; - case 192: + case 193: return expr.operator === 43 || expr.operator === 44; default: @@ -10522,15 +10143,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 195: - case 197: - case 187: - case 194: + case 196: case 198: - case 202: - case 200: - case 289: - case 288: + case 188: + case 195: + case 199: + case 203: + case 201: + case 293: + case 292: return true; default: return isUnaryExpressionKind(kind); @@ -10538,16 +10159,16 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 184 - || kind === 202; + return kind === 185 + || kind === 203; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 292; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 291; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -10557,20 +10178,20 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 214: case 215: case 216: - case 212: + case 217: case 213: + case 214: return true; - case 222: + case 223: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isForInOrOfStatement(node) { - return node.kind === 215 || node.kind === 216; + return node.kind === 216 || node.kind === 217; } ts.isForInOrOfStatement = isForInOrOfStatement; function isConciseBody(node) { @@ -10589,106 +10210,106 @@ var ts; ts.isForInitializer = isForInitializer; function isModuleBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233 + return kind === 235 + || kind === 234 || kind === 71; } ts.isModuleBody = isModuleBody; function isNamespaceBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233; + return kind === 235 + || kind === 234; } ts.isNamespaceBody = isNamespaceBody; function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 - || kind === 233; + || kind === 234; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 241 - || kind === 240; + return kind === 242 + || kind === 241; } ts.isNamedImportBindings = isNamedImportBindings; function isModuleOrEnumDeclaration(node) { - return node.kind === 233 || node.kind === 232; + return node.kind === 234 || node.kind === 233; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 + return kind === 188 + || kind === 177 + || kind === 230 + || kind === 200 + || kind === 153 + || kind === 233 + || kind === 268 + || kind === 247 || kind === 229 - || kind === 199 + || kind === 187 + || kind === 154 + || kind === 240 + || kind === 238 + || kind === 243 + || kind === 231 + || kind === 257 || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 || kind === 151 + || kind === 234 + || kind === 237 + || kind === 241 + || kind === 147 + || kind === 265 || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 283; + || kind === 155 + || kind === 266 + || kind === 232 + || kind === 146 + || kind === 227 + || kind === 288; } function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 + return kind === 229 + || kind === 248 || kind === 230 || kind === 231 || kind === 232 || kind === 233 + || kind === 234 + || kind === 239 || kind === 238 - || kind === 237 + || kind === 245 || kind === 244 - || kind === 243 - || kind === 236; + || kind === 237; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 + return kind === 219 + || kind === 218 + || kind === 226 + || kind === 213 + || kind === 211 + || kind === 210 + || kind === 216 || kind === 217 - || kind === 225 + || kind === 215 || kind === 212 - || kind === 210 + || kind === 223 + || kind === 220 + || kind === 222 + || kind === 224 + || kind === 225 || kind === 209 - || kind === 215 - || kind === 216 || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 287 || kind === 291 - || kind === 290; + || kind === 295 + || kind === 294; } function isDeclaration(node) { - if (node.kind === 145) { - return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + if (node.kind === 146) { + return node.parent.kind !== 287 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -10709,10 +10330,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 207) + if (node.kind !== 208) return false; if (node.parent !== undefined) { - if (node.parent.kind === 224 || node.parent.kind === 260) { + if (node.parent.kind === 225 || node.parent.kind === 264) { return false; } } @@ -10720,8 +10341,8 @@ var ts; } function isModuleReference(node) { var kind = node.kind; - return kind === 248 - || kind === 143 + return kind === 249 + || kind === 144 || kind === 71; } ts.isModuleReference = isModuleReference; @@ -10729,53 +10350,62 @@ var ts; var kind = node.kind; return kind === 99 || kind === 71 - || kind === 179; + || kind === 180; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; + return kind === 250 + || kind === 260 + || kind === 251 + || kind === 10 + || kind === 254; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 253 - || kind === 255; + return kind === 257 + || kind === 259; } ts.isJsxAttributeLike = isJsxAttributeLike; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 - || kind === 256; + || kind === 260; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 251 - || kind === 250; + return kind === 252 + || kind === 251; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 257 - || kind === 258; + return kind === 261 + || kind === 262; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 285; + return node.kind >= 271 && node.kind <= 289; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 275 || isJSDocTag(node); + return node.kind === 279 || isJSDocTag(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 276 && node.kind <= 285; + return node.kind >= 281 && node.kind <= 289; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 155; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 154; + } + ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } @@ -10783,22 +10413,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var SignatureFlags; - (function (SignatureFlags) { - SignatureFlags[SignatureFlags["None"] = 0] = "None"; - SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; - SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; - SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; - SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; - SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; - SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; - })(SignatureFlags || (SignatureFlags = {})); var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 265) { + if (kind === 269) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71) { @@ -10830,59 +10450,60 @@ var ts; } } function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 142) { + if (!node || node.kind <= 143) { return; } switch (node.kind) { - case 143: + case 144: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 145: + case 146: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 262: + case 266: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 263: + case 267: return visitNode(cbNode, node.expression); - case 146: + case 147: + case 150: case 149: - case 148: - case 261: - case 226: - case 176: + case 265: + case 227: + case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 160: case 161: - case 155: + case 162: case 156: case 157: + case 158: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: + case 229: + case 188: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -10893,287 +10514,291 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 159: + case 160: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 158: + case 159: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 162: - return visitNode(cbNode, node.exprName); case 163: - return visitNodes(cbNode, cbNodes, node.members); + return visitNode(cbNode, node.exprName); case 164: - return visitNode(cbNode, node.elementType); + return visitNodes(cbNode, cbNodes, node.members); case 165: - return visitNodes(cbNode, cbNodes, node.elementTypes); + return visitNode(cbNode, node.elementType); case 166: + return visitNodes(cbNode, cbNodes, node.elementTypes); case 167: - return visitNodes(cbNode, cbNodes, node.types); case 168: - case 170: - return visitNode(cbNode, node.type); + return visitNodes(cbNode, cbNodes, node.types); + case 169: case 171: + return visitNode(cbNode, node.type); + case 172: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 172: + case 173: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 173: - return visitNode(cbNode, node.literal); case 174: + return visitNode(cbNode, node.literal); case 175: - return visitNodes(cbNode, cbNodes, node.elements); - case 177: + case 176: return visitNodes(cbNode, cbNodes, node.elements); case 178: - return visitNodes(cbNode, cbNodes, node.properties); + return visitNodes(cbNode, cbNodes, node.elements); case 179: + return visitNodes(cbNode, cbNodes, node.properties); + case 180: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 180: + case 181: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 181: case 182: + case 183: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 183: + case 184: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 184: + case 185: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.expression); - case 188: + case 186: return visitNode(cbNode, node.expression); case 189: return visitNode(cbNode, node.expression); case 190: return visitNode(cbNode, node.expression); - case 192: - return visitNode(cbNode, node.operand); - case 197: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 191: return visitNode(cbNode, node.expression); case 193: return visitNode(cbNode, node.operand); + case 198: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.expression); case 194: + return visitNode(cbNode, node.operand); + case 195: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 202: + case 203: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 203: - return visitNode(cbNode, node.expression); case 204: + return visitNode(cbNode, node.expression); + case 205: return visitNode(cbNode, node.name); - case 195: + case 196: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 198: + case 199: return visitNode(cbNode, node.expression); - case 207: - case 234: + case 208: + case 235: return visitNodes(cbNode, cbNodes, node.statements); - case 265: + case 269: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 208: + case 209: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 227: + case 228: return visitNodes(cbNode, cbNodes, node.declarations); - case 210: - return visitNode(cbNode, node.expression); case 211: + return visitNode(cbNode, node.expression); + case 212: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 212: + case 213: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 213: + case 214: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 214: + case 215: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 215: + case 216: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 216: + case 217: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 217: case 218: - return visitNode(cbNode, node.label); case 219: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.label); case 220: + return visitNode(cbNode, node.expression); + case 221: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221: + case 222: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 235: + case 236: return visitNodes(cbNode, cbNodes, node.clauses); - case 257: + case 261: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 258: + case 262: return visitNodes(cbNode, cbNodes, node.statements); - case 222: + case 223: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 223: - return visitNode(cbNode, node.expression); case 224: + return visitNode(cbNode, node.expression); + case 225: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 260: + case 264: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 147: + case 148: return visitNode(cbNode, node.expression); - case 229: - case 199: + case 230: + case 200: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 230: + case 231: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 231: + case 232: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 232: + case 233: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 264: + case 268: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 233: + case 234: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 237: + case 238: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 238: + case 239: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 239: + case 240: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 236: - return visitNode(cbNode, node.name); - case 240: + case 237: return visitNode(cbNode, node.name); case 241: - case 245: + return visitNode(cbNode, node.name); + case 242: + case 246: return visitNodes(cbNode, cbNodes, node.elements); - case 244: + case 245: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: + case 243: + case 247: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 243: + case 244: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 196: + case 197: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 205: + case 206: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: + case 145: return visitNode(cbNode, node.expression); - case 259: + case 263: return visitNodes(cbNode, cbNodes, node.types); - case 201: + case 202: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 248: + case 249: return visitNode(cbNode, node.expression); - case 247: + case 248: return visitNodes(cbNode, cbNodes, node.decorators); - case 289: + case 293: return visitNodes(cbNode, cbNodes, node.elements); - case 249: + case 250: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 250: + case 254: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); case 251: + case 252: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.attributes); - case 254: + case 258: return visitNodes(cbNode, cbNodes, node.properties); - case 253: + case 257: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 255: + case 259: return visitNode(cbNode, node.expression); - case 256: + case 260: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 252: + case 253: return visitNode(cbNode, node.tagName); - case 267: - return visitNode(cbNode, node.type); case 271: return visitNode(cbNode, node.type); - case 270: + case 275: return visitNode(cbNode, node.type); - case 272: + case 274: return visitNode(cbNode, node.type); - case 273: + case 276: + return visitNode(cbNode, node.type); + case 277: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 274: + case 278: return visitNode(cbNode, node.type); - case 275: - return visitNodes(cbNode, cbNodes, node.tags); case 279: + return visitNodes(cbNode, cbNodes, node.tags); case 284: + case 289: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -11182,17 +10807,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 280: + case 285: return visitNode(cbNode, node.typeExpression); - case 281: - return visitNode(cbNode, node.typeExpression); - case 277: + case 286: return visitNode(cbNode, node.typeExpression); case 282: + return visitNode(cbNode, node.class); + case 287: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 283: + case 288: if (node.typeExpression && - node.typeExpression.kind === 267) { + node.typeExpression.kind === 271) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -11200,7 +10825,7 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 285: + case 280: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -11208,7 +10833,7 @@ var ts; } } return; - case 288: + case 292: return visitNode(cbNode, node.expression); } } @@ -11254,7 +10879,7 @@ var ts; ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; var Parser; (function (Parser) { - var scanner = ts.createScanner(5, true); + var scanner = ts.createScanner(6, true); var disallowInAndDecoratorContext = 2048 | 8192; var NodeConstructor; var TokenConstructor; @@ -11290,7 +10915,7 @@ var ts; Parser.parseIsolatedEntityName = parseIsolatedEntityName; function parseJsonText(fileName, sourceText) { initializeState(sourceText, 2, undefined, 6); - sourceFile = createSourceFile(fileName, 2, 6); + sourceFile = createSourceFile(fileName, 2, 6, false); var result = sourceFile; nextToken(); if (token() === 1) { @@ -11324,7 +10949,16 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + switch (scriptKind) { + case 1: + case 2: + case 6: + contextFlags = 65536; + break; + default: + contextFlags = 0; + break; + } parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -11341,7 +10975,11 @@ var ts; sourceText = undefined; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 2097152; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; nextToken(); processReferenceComments(sourceFile); @@ -11364,13 +11002,14 @@ var ts; for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; + if (jsDoc) { + if (!node.jsDoc) { + node.jsDoc = [jsDoc]; + } + else { + node.jsDoc.push(jsDoc); + } } - node.jsDoc.push(jsDoc); } } return node; @@ -11398,15 +11037,15 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + var sourceFile = new SourceFileConstructor(269, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.isDeclarationFile = isDeclarationFile; sourceFile.scriptKind = scriptKind; return sourceFile; } @@ -11620,12 +11259,17 @@ var ts; } function createNode(kind, pos) { nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 ? new NodeConstructor(kind, p, p) : + kind === 71 ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind) { + var node = createNode(kind); + if (scanner.getTokenFlags() & 2) { + addJSDocComment(node); } - return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return node; } function createNodeArray(elements, pos, end) { var length = elements.length; @@ -11652,7 +11296,7 @@ var ts; else { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); + var result = createNode(kind); if (kind === 71) { result.escapedText = ""; } @@ -11685,8 +11329,8 @@ var ts; function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || @@ -11708,7 +11352,7 @@ var ts; return parsePropertyNameWorker(true); } function parseComputedPropertyName() { - var node = createNode(144); + var node = createNode(145); parseExpected(21); node.expression = allowInAnd(parseExpression); parseExpected(22); @@ -11836,6 +11480,10 @@ var ts; nextToken(); return ts.tokenIsIdentifierOrKeyword(token()); } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } function isHeritageClauseExtendsOrImplementsKeyword() { if (token() === 108 || token() === 85) { @@ -11952,7 +11600,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 96256; + var nodeContextFlags = node.flags & 6387712; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -12001,14 +11649,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 152: - case 157: case 153: + case 158: case 154: - case 149: - case 206: + case 155: + case 150: + case 207: return true; - case 151: + case 152: var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 71 && methodDeclaration.name.originalKeywordKind === 123; @@ -12020,8 +11668,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 257: - case 258: + case 261: + case 262: return true; } } @@ -12030,65 +11678,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 228: + case 229: + case 209: case 208: - case 207: + case 212: case 211: - case 210: - case 223: + case 224: + case 220: + case 222: case 219: - case 221: case 218: + case 216: case 217: case 215: - case 216: case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: + case 221: + case 210: case 225: + case 223: + case 213: + case 226: + case 239: case 238: - case 237: + case 245: case 244: - case 243: - case 233: - case 229: + case 234: case 230: - case 232: case 231: + case 233: + case 232: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 264; + return node.kind === 268; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 156: - case 150: case 157: - case 148: - case 155: + case 151: + case 158: + case 149: + case 156: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { + if (node.kind !== 227) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 146) { + if (node.kind !== 147) { return false; } var parameter = node; @@ -12182,7 +11830,7 @@ var ts; return createMissingList(); } function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); while (parseOptional(23)) { if (token() === 27) { @@ -12195,7 +11843,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(143, entity.pos); + var node = createNode(144, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -12210,7 +11858,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(196); + var template = createNode(197); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); var list = []; @@ -12222,7 +11870,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(205); + var span = createNode(206); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18) { @@ -12259,15 +11907,15 @@ var ts; node.isUnterminated = true; } if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + node.numericLiteralFlags = scanner.getTokenFlags() & 496; } nextToken(); finishNode(node); return node; } function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + var node = createNode(160); + node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27) { node.typeArguments = parseBracketedList(19, parseType, 27, 29); } @@ -12275,18 +11923,18 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(158, lhs.pos); + var node = createNode(159, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(169); + var node = createNode(170); nextToken(); return finishNode(node); } function parseJSDocAllType() { - var result = createNode(268); + var result = createNode(272); nextToken(); return finishNode(result); } @@ -12299,28 +11947,28 @@ var ts; token() === 29 || token() === 58 || token() === 49) { - var result = createNode(269, pos); + var result = createNode(273, pos); return finishNode(result); } else { - var result = createNode(270, pos); + var result = createNode(274, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNode(273); + var result = createNodeWithJSDoc(277); nextToken(); fillSignature(56, 4 | 32, result); - return addJSDocComment(finishNode(result)); + return finishNode(result); } - var node = createNode(159); + var node = createNode(160); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(146); + var parameter = createNode(147); if (token() === 99 || token() === 94) { parameter.name = parseIdentifierName(); parseExpected(56); @@ -12331,17 +11979,17 @@ var ts; function parseJSDocNodeWithType(kind) { var result = createNode(kind); nextToken(); - result.type = parseType(); + result.type = parseNonArrayType(); return finishNode(result); } function parseTypeQuery() { - var node = createNode(162); + var node = createNode(163); parseExpected(103); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(145); + var node = createNode(146); node.name = parseIdentifier(); if (parseOptional(85)) { if (isStartOfType() || !isStartOfExpression()) { @@ -12374,8 +12022,8 @@ var ts; token() === 57 || isStartOfType(true); } - function parseParameter(requireEqualsToken) { - var node = createNode(146); + function parseParameter() { + var node = createNodeWithJSDoc(147); if (token() === 99) { node.name = createIdentifier(true); node.type = parseParameterType(); @@ -12390,8 +12038,8 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseInitializer(true, requireEqualsToken); - return addJSDocComment(finishNode(node)); + node.initializer = parseInitializer(); + return finishNode(node); } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { @@ -12424,7 +12072,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -12441,19 +12089,16 @@ var ts; parseSemicolon(); } function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { + var node = createNodeWithJSDoc(kind); + if (kind === 157) { parseExpected(94); } fillSignature(56, 4, node); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); + return token() === 21 && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); @@ -12481,39 +12126,29 @@ var ts; nextToken(); return token() === 56 || token() === 26 || token() === 22; } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseIndexSignatureDeclaration(node) { + node.kind = 158; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, 4, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); - } - else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + node.kind = 151; + fillSignature(56, 4, node); + } + else { + node.kind = 149; + node.type = parseTypeAnnotation(); if (token() === 58) { - property.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); } + parseTypeMemberSemicolon(); + return finishNode(node); } function isTypeMemberStart() { if (token() === 19 || token() === 27) { @@ -12543,24 +12178,24 @@ var ts; } function parseTypeMember() { if (token() === 19 || token() === 27) { - return parseSignatureMember(155); + return parseSignatureMember(156); } if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(156); + return parseSignatureMember(157); } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0); + node.modifiers = parseModifiers(); if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + return parseIndexSignatureDeclaration(node); } - return parsePropertyOrMethodSignature(fullStart, modifiers); + return parsePropertyOrMethodSignature(node); } function nextTokenIsOpenParenOrLessThan() { nextToken(); return token() === 19 || token() === 27; } function parseTypeLiteral() { - var node = createNode(163); + var node = createNode(164); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -12583,14 +12218,14 @@ var ts; return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; } function parseMappedTypeParameter() { - var node = createNode(145); + var node = createNode(146); node.name = parseIdentifier(); parseExpected(92); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(172); + var node = createNode(173); parseExpected(17); node.readonlyToken = parseOptionalToken(131); parseExpected(21); @@ -12603,34 +12238,34 @@ var ts; return finishNode(node); } function parseTupleType() { - var node = createNode(165); + var node = createNode(166); node.elementTypes = parseBracketedList(20, parseType, 21, 22); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(168); + var node = createNode(169); parseExpected(19); node.type = parseType(); parseExpected(20); return finishNode(node); } function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { + var node = createNodeWithJSDoc(kind); + if (kind === 162) { parseExpected(94); } fillSignature(36, 4, node); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); return token() === 23 ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(173); + var node = createNode(174); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(192); + unaryMinusExpression = createNode(193); unaryMinusExpression.operator = 38; nextToken(); } @@ -12653,8 +12288,8 @@ var ts; case 119: case 136: case 133: - case 122: case 137: + case 122: case 139: case 130: case 134: @@ -12665,10 +12300,8 @@ var ts; return parseJSDocUnknownOrNullableType(); case 89: return parseJSDocFunctionType(); - case 24: - return parseJSDocNodeWithType(274); case 51: - return parseJSDocNodeWithType(271); + return parseJSDocNodeWithType(275); case 13: case 9: case 8: @@ -12708,6 +12341,7 @@ var ts; case 133: case 122: case 137: + case 140: case 105: case 139: case 95: @@ -12742,58 +12376,71 @@ var ts; nextToken(); return token() === 20 || isStartOfParameter() || isStartOfType(); } - function parseJSDocPostfixTypeOrHigher() { + function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); - var kind = getKind(token()); - if (!kind) - return type; - nextToken(); - var postfix = createNode(kind, type.pos); - postfix.type = type; - return finishNode(postfix); - function getKind(tokenKind) { - switch (tokenKind) { + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { case 58: - return contextFlags & 1048576 ? 272 : undefined; + if (!(contextFlags & 1048576)) { + return type; + } + type = createJSDocPostfixType(276, type); + break; case 51: - return 271; + type = createJSDocPostfixType(275, type); + break; case 55: - return 270; - } - } - } - function parseArrayTypeOrHigher() { - var type = parseJSDocPostfixTypeOrHigher(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); + type = createJSDocPostfixType(274, type); + break; + case 21: + parseExpected(21); + if (isStartOfType()) { + var node = createNode(172, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(165, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + break; + default: + return type; } } return type; } + function createJSDocPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } function parseTypeOperator(operator) { - var node = createNode(170); + var node = createNode(171); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseTypeOperatorOrHigher() { - switch (token()) { + var operator = token(); + switch (operator) { case 127: - return parseTypeOperator(127); + case 140: + return parseTypeOperator(operator); + case 24: { + var result = createNode(278); + nextToken(); + result.type = parsePostfixTypeOrHigher(); + return finishNode(result); + } } - return parseArrayTypeOrHigher(); + return parsePostfixTypeOrHigher(); } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { parseOptional(operator); @@ -12810,10 +12457,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + return parseUnionOrIntersectionType(168, parseTypeOperatorOrHigher, 48); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + return parseUnionOrIntersectionType(167, parseIntersectionTypeOrHigher, 49); } function isStartOfFunctionType() { if (token() === 27) { @@ -12859,7 +12506,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); + var node = createNode(159, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -12880,10 +12527,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); + return parseFunctionOrConstructorType(161); } if (token() === 94) { - return parseFunctionOrConstructorType(161); + return parseFunctionOrConstructorType(162); } return parseUnionTypeOrHigher(); } @@ -12964,19 +12611,8 @@ var ts; } return expr; } - function parseInitializer(inParameter, requireEqualsToken) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - if (inParameter && requireEqualsToken) { - var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); - result.escapedText = "= not found"; - return result; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); + function parseInitializer() { + return parseOptional(58) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { if (isYieldExpression()) { @@ -13009,7 +12645,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(197); + var node = createNode(198); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 39 || isStartOfExpression())) { @@ -13025,13 +12661,13 @@ var ts; ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(187, asyncModifier.pos); + node = createNode(188, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(187, identifier.pos); + node = createNode(188, identifier.pos); } - var parameter = createNode(146, identifier.pos); + var parameter = createNode(147, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -13056,7 +12692,7 @@ var ts; arrowFunction.body = (lastToken === 36 || lastToken === 17) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); + return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { if (token() === 19 || token() === 27 || token() === 120) { @@ -13097,13 +12733,27 @@ var ts; if (second === 24) { return 1; } + if (ts.isModifierKind(second) && second !== 120 && lookAhead(nextTokenIsIdentifier)) { + return 1; + } if (!isIdentifier()) { return 0; } - if (nextToken() === 56) { - return 1; + switch (nextToken()) { + case 56: + return 1; + case 55: + nextToken(); + if (token() === 56 || token() === 26 || token() === 58 || token() === 20) { + return 1; + } + return 0; + case 26: + case 58: + case 20: + return 2; } - return 2; + return 0; } else { ts.Debug.assert(first === 27); @@ -13163,15 +12813,14 @@ var ts; return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); + var node = createNodeWithJSDoc(188); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || - ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { + if (!allowAmbiguity && token() !== 36 && token() !== 17) { return undefined; } return node; @@ -13196,7 +12845,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(195, leftOperand.pos); + var node = createNode(196, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -13209,7 +12858,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 || t === 142; + return t === 92 || t === 143; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -13287,39 +12936,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); + var node = createNode(195, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(202, left.pos); + var node = createNode(203, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(192); + var node = createNode(193); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(188); + var node = createNode(189); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(189); + var node = createNode(190); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(190); + var node = createNode(191); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -13334,7 +12983,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(191); + var node = createNode(192); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -13350,7 +12999,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { + if (simpleUnaryExpression.kind === 185) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -13403,19 +13052,19 @@ var ts; } function parseUpdateExpression() { if (token() === 43 || token() === 44) { - var node = createNode(192); + var node = createNode(193); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + return parseJsxElementOrSelfClosingElementOrFragment(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); + var node = createNode(194, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -13443,7 +13092,7 @@ var ts; if (token() === 19 || token() === 23 || token() === 21) { return expression; } - var node = createNode(179, expression.pos); + var node = createNode(180, expression.pos); node.expression = expression; parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); @@ -13462,28 +13111,35 @@ var ts; return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); + if (opening.kind === 252) { + var node = createNode(250, opening.pos); node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); + node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } + else if (opening.kind === 255) { + var node = createNode(254, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } else { - ts.Debug.assert(opening.kind === 250); + ts.Debug.assert(opening.kind === 251); result = opening; } if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); + var badNode = createNode(195, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -13495,7 +13151,7 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); + var node = createNode(10); node.containsOnlyWhiteSpaces = currentToken === 11; currentToken = scanner.scanJsxToken(); return finishNode(node); @@ -13508,11 +13164,11 @@ var ts; case 17: return parseJsxExpression(false); case 27: - return parseJsxElementOrSelfClosingElement(false); + return parseJsxElementOrSelfClosingElementOrFragment(false); } ts.Debug.fail("Unknown JSX child kind " + token()); } - function parseJsxChildren(openingTagName) { + function parseJsxChildren(openingTag) { var list = []; var listPos = getNodePos(); var saveParsingContext = parsingContext; @@ -13523,7 +13179,13 @@ var ts; break; } else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + var openingTagName = openingTag.tagName; + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + } break; } else if (token() === 7) { @@ -13538,18 +13200,23 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(254); + var jsxAttributes = createNode(258); jsxAttributes.properties = parseList(13, parseJsxAttribute); return finishNode(jsxAttributes); } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); parseExpected(27); + if (token() === 29) { + parseExpected(29); + var node_1 = createNode(255, fullStart); + return finishNode(node_1); + } var tagName = parseJsxElementName(); var attributes = parseJsxAttributes(); var node; if (token() === 29) { - node = createNode(251, fullStart); + node = createNode(252, fullStart); scanJsxText(); } else { @@ -13561,7 +13228,7 @@ var ts; parseExpected(29, undefined, false); scanJsxText(); } - node = createNode(250, fullStart); + node = createNode(251, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -13572,7 +13239,7 @@ var ts; var expression = token() === 99 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -13580,7 +13247,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(256); + var node = createNode(260); parseExpected(17); if (token() !== 18) { node.dotDotDotToken = parseOptionalToken(24); @@ -13600,7 +13267,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(253); + var node = createNode(257); node.name = parseIdentifierName(); if (token() === 58) { switch (scanJsxAttributeValue()) { @@ -13615,7 +13282,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(255); + var node = createNode(259); parseExpected(17); parseExpected(24); node.expression = parseExpression(); @@ -13623,7 +13290,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); + var node = createNode(253); parseExpected(28); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -13635,8 +13302,24 @@ var ts; } return finishNode(node); } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(256); + parseExpected(28); + if (ts.tokenIsIdentifierOrKeyword(token())) { + var unexpectedTagName = parseJsxElementName(); + parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } function parseTypeAssertion() { - var node = createNode(184); + var node = createNode(185); parseExpected(27); node.type = parseType(); parseExpected(29); @@ -13647,7 +13330,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23); if (dotToken) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -13655,13 +13338,13 @@ var ts; } if (token() === 51 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(203, expression.pos); + var nonNullExpression = createNode(204, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); + var indexedAccess = createNode(181, expression.pos); indexedAccess.expression = expression; if (token() !== 22) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -13675,7 +13358,7 @@ var ts; continue; } if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); + var tagExpression = createNode(184, expression.pos); tagExpression.tag = expression; tagExpression.template = token() === 13 ? parseLiteralNode() @@ -13694,7 +13377,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -13702,7 +13385,7 @@ var ts; continue; } else if (token() === 19) { - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -13797,28 +13480,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(185); + var node = createNodeWithJSDoc(186); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseSpreadElement() { - var node = createNode(198); + var node = createNode(199); parseExpected(24); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : + token() === 26 ? createNode(201) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(177); + var node = createNode(178); parseExpected(21); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -13827,60 +13510,46 @@ var ts; parseExpected(22); return finishNode(node); } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0); + if (parseOptionalToken(24)) { + node.kind = 267; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(node, 154); } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + if (parseContextualModifier(135)) { + return parseAccessorDeclaration(node, 155); } var asteriskToken = parseOptionalToken(39); var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + return parseMethodDeclaration(node, asteriskToken); } var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; + node.kind = 266; var equalsToken = parseOptionalToken(58); if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; + node.kind = 265; parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } + return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(178); + var node = createNode(179); parseExpected(17); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -13894,7 +13563,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(186); + var node = createNodeWithJSDoc(187); node.modifiers = parseModifiers(); parseExpected(89); node.asteriskToken = parseOptionalToken(39); @@ -13910,7 +13579,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(true); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; @@ -13919,12 +13588,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(94); if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); + var node_2 = createNode(205, fullStart); + node_2.keywordToken = 94; + node_2.name = parseIdentifierName(); + return finishNode(node_2); } - var node = createNode(182, fullStart); + var node = createNode(183, fullStart); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); if (node.typeArguments || token() === 19) { @@ -13933,7 +13602,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); + var node = createNode(208); if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -13964,12 +13633,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(209); + var node = createNode(210); parseExpected(25); return finishNode(node); } function parseIfStatement() { - var node = createNode(211); + var node = createNode(212); parseExpected(90); parseExpected(19); node.expression = allowInAnd(parseExpression); @@ -13979,7 +13648,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(212); + var node = createNode(213); parseExpected(81); node.statement = parseStatement(); parseExpected(106); @@ -13990,7 +13659,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(213); + var node = createNode(214); parseExpected(106); parseExpected(19); node.expression = allowInAnd(parseExpression); @@ -14013,8 +13682,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); + if (awaitToken ? parseExpected(143) : parseOptional(143)) { + var forOfStatement = createNode(217, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -14022,14 +13691,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); + var forInStatement = createNode(216, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(214, pos); + var forStatement = createNode(215, pos); forStatement.initializer = initializer; parseExpected(25); if (token() !== 25 && token() !== 20) { @@ -14047,7 +13716,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); + parseExpected(kind === 219 ? 72 : 77); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -14055,7 +13724,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(219); + var node = createNode(220); parseExpected(96); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -14064,16 +13733,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(220); + var node = createNode(221); parseExpected(107); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - node.statement = parseStatement(); + node.statement = doInsideOfContext(4194304, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(257); + var node = createNode(261); parseExpected(73); node.expression = allowInAnd(parseExpression); parseExpected(56); @@ -14081,7 +13750,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(258); + var node = createNode(262); parseExpected(79); parseExpected(56); node.statements = parseList(3, parseStatement); @@ -14091,12 +13760,12 @@ var ts; return token() === 73 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(221); + var node = createNode(222); parseExpected(98); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); + var caseBlock = createNode(236); parseExpected(17); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(18); @@ -14104,14 +13773,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(223); + var node = createNode(224); parseExpected(100); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(224); + var node = createNode(225); parseExpected(102); node.tryBlock = parseBlock(false); node.catchClause = token() === 74 ? parseCatchClause() : undefined; @@ -14122,7 +13791,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(260); + var result = createNode(264); parseExpected(74); if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); @@ -14135,26 +13804,25 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(225); + var node = createNode(226); parseExpected(78); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); + var node = createNodeWithJSDoc(0); var expression = allowInAnd(parseExpression); if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); + node.kind = 223; + node.label = expression; + node.statement = parseStatement(); } else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; + node.kind = 211; + node.expression = expression; parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); } + return finishNode(node); } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); @@ -14200,7 +13868,7 @@ var ts; return false; } continue; - case 141: + case 142: nextToken(); return token() === 17 || token() === 71 || token() === 84; case 91: @@ -14262,7 +13930,7 @@ var ts; case 128: case 129: case 138: - case 141: + case 142: return true; case 114: case 112: @@ -14288,16 +13956,16 @@ var ts; case 17: return parseBlock(false); case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227)); case 110: if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227)); } break; case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + return parseFunctionDeclaration(createNodeWithJSDoc(229)); case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + return parseClassDeclaration(createNodeWithJSDoc(230)); case 90: return parseIfStatement(); case 81: @@ -14307,9 +13975,9 @@ var ts; case 88: return parseForOrForInOrForOfStatement(); case 77: - return parseBreakOrContinueStatement(217); - case 72: return parseBreakOrContinueStatement(218); + case 72: + return parseBreakOrContinueStatement(219); case 96: return parseReturnStatement(); case 107: @@ -14342,7 +14010,7 @@ var ts; case 117: case 115: case 131: - case 141: + case 142: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -14350,49 +14018,64 @@ var ts; } return parseExpressionOrLabeledStatement(); } + function isDeclareModifier(modifier) { + return modifier.kind === 124; + } function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 2097152; + } + return doInsideOfContext(2097152, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { switch (token()) { case 104: case 110: case 76: - return parseVariableStatement(fullStart, decorators, modifiers); + return parseVariableStatement(node); case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); + return parseFunctionDeclaration(node); case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); + return parseClassDeclaration(node); case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); + return parseInterfaceDeclaration(node); case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + return parseTypeAliasDeclaration(node); case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: + return parseEnumDeclaration(node); + case 142: case 128: case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); + return parseModuleDeclaration(node); case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + return parseImportDeclarationOrImportEqualsDeclaration(node); case 84: nextToken(); switch (token()) { case 79: case 58: - return parseExportAssignment(fullStart, decorators, modifiers); + return parseExportAssignment(node); case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + return parseNamespaceExportDeclaration(node); default: - return parseExportDeclaration(fullStart, decorators, modifiers); + return parseExportDeclaration(node); } default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); + if (node.decorators || node.modifiers) { + var missing = createMissingNode(248, true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); } } } @@ -14409,16 +14092,16 @@ var ts; } function parseArrayBindingElement() { if (token() === 26) { - return createNode(200); + return createNode(201); } - var node = createNode(176); + var node = createNode(177); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(176); + var node = createNode(177); node.dotDotDotToken = parseOptionalToken(24); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -14430,18 +14113,18 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(174); + var node = createNode(175); parseExpected(17); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(18); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(175); + var node = createNode(176); parseExpected(21); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(22); @@ -14459,17 +14142,24 @@ var ts; } return parseIdentifier(); } - function parseVariableDeclaration() { - var node = createNode(226); + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(227); node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 71 && + token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); + var node = createNode(228); switch (token()) { case 104: break; @@ -14483,13 +14173,13 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 143 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); + node.declarations = parseDelimitedList(8, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -14497,18 +14187,14 @@ var ts; function canFollowContextualOfKeyword() { return nextTokenIsIdentifier() && nextToken() === 20; } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseVariableStatement(node) { + node.kind = 209; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseFunctionDeclaration(node) { + node.kind = 229; parseExpected(89); node.asteriskToken = parseOptionalToken(39); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); @@ -14516,65 +14202,51 @@ var ts; var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; + function parseConstructorDeclaration(node) { + node.kind = 153; parseExpected(123); fillSignature(56, 0, node); node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 152; + node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 : 0; - var isAsync = ts.hasModifier(method, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 150; + if (!node.questionToken && token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + node.initializer = ts.hasModifier(node, 32) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 | 2048, parseInitializer); parseSemicolon(); - return addJSDocComment(finishNode(property)); + return finishNode(node); } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + function parsePropertyOrMethodDeclaration(node) { var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } + return parsePropertyDeclaration(node); } - function parseNonParameterInitializer() { - return parseInitializer(false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseAccessorDeclaration(node, kind) { + node.kind = kind; node.name = parsePropertyName(); fillSignature(56, 0, node); node.body = parseFunctionBlockOrSemicolon(0); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -14635,7 +14307,7 @@ var ts; if (!parseOptional(57)) { break; } - var decorator = createNode(147, decoratorStart); + var decorator = createNode(148, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -14676,46 +14348,46 @@ var ts; } function parseClassElement() { if (token() === 25) { - var result = createNode(206); + var result = createNode(207); nextToken(); return finishNode(result); } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(true); + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(node, 154); + } + if (parseContextualModifier(135)) { + return parseAccessorDeclaration(node, 155); } if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); + return parseConstructorDeclaration(node); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + return parseIndexSignatureDeclaration(node); } if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 || token() === 8 || token() === 39 || token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + return parsePropertyOrMethodDeclaration(node); } - if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + if (node.decorators || node.modifiers) { + node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 200); } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 230); } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; parseExpected(75); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -14727,7 +14399,7 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseNameOfClassDeclarationOrExpression() { return isIdentifier() && !isImplementsClause() @@ -14746,7 +14418,7 @@ var ts; function parseHeritageClause() { var tok = token(); if (tok === 85 || tok === 108) { - var node = createNode(259); + var node = createNode(263); node.token = tok; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -14755,52 +14427,49 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(201); + var node = createNode(202); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } + node.typeArguments = tryParseTypeArguments(); return finishNode(node); } + function tryParseTypeArguments() { + return token() === 27 + ? parseBracketedList(19, parseType, 27, 29) + : undefined; + } function isHeritageClause() { return token() === 85 || token() === 108; } function parseClassMembers() { return parseList(5, parseClassElement); } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseInterfaceDeclaration(node) { + node.kind = 231; parseExpected(109); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseTypeAliasDeclaration(node) { + node.kind = 232; parseExpected(138); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(58); node.type = parseType(); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); + var node = createNodeWithJSDoc(268); node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseEnumDeclaration(node) { + node.kind = 233; parseExpected(83); node.name = parseIdentifier(); if (parseExpected(17)) { @@ -14810,10 +14479,10 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); + var node = createNode(235); if (parseExpected(17)) { node.statements = parseList(1, parseStatement); parseExpected(18); @@ -14823,23 +14492,19 @@ var ts; } return finishNode(node); } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 234; var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(createNode(0), 4 | namespaceFlag) : parseModuleBlock(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 234; + if (token() === 142) { node.name = parseIdentifier(); node.flags |= 512; } @@ -14855,10 +14520,10 @@ var ts; } return finishNode(node); } - function parseModuleDeclaration(fullStart, decorators, modifiers) { + function parseModuleDeclaration(node) { var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + if (token() === 142) { + return parseAmbientExternalModuleDeclaration(node); } else if (parseOptional(129)) { flags |= 16; @@ -14866,10 +14531,10 @@ var ts; else { parseExpected(128); if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { return token() === 132 && @@ -14881,57 +14546,51 @@ var ts; function nextTokenIsSlash() { return nextToken() === 41; } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; + function parseNamespaceExportDeclaration(node) { + node.kind = 237; parseExpected(118); parseExpected(129); - exportDeclaration.name = parseIdentifier(); + node.name = parseIdentifier(); parseSemicolon(); - return finishNode(exportDeclaration); + return finishNode(node); } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + function parseImportDeclarationOrImportEqualsDeclaration(node) { parseExpected(91); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + if (token() !== 26 && token() !== 141) { + return parseImportEqualsDeclaration(node, identifier); } } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; + node.kind = 239; if (identifier || token() === 39 || token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(141); } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); + node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); - return finishNode(importDeclaration); + return finishNode(node); } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 238; + node.name = identifier; parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); + node.moduleReference = parseModuleReference(); parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); + return finishNode(node); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); + var importClause = createNode(240, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(242); } return finishNode(importClause); } @@ -14941,7 +14600,7 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(248); + var node = createNode(249); parseExpected(132); parseExpected(19); node.expression = parseModuleSpecifier(); @@ -14959,7 +14618,7 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(240); + var namespaceImport = createNode(241); parseExpected(39); parseExpected(118); namespaceImport.name = parseIdentifier(); @@ -14967,14 +14626,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + node.elements = parseBracketedList(22, kind === 242 ? parseImportSpecifier : parseExportSpecifier, 17, 18); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); + return parseImportOrExportSpecifier(247); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); + return parseImportOrExportSpecifier(243); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -14993,33 +14652,29 @@ var ts; else { node.name = identifierName; } - if (kind === 242 && checkIdentifierIsKeyword) { + if (kind === 243 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportDeclaration(node) { + node.kind = 245; if (parseOptional(39)) { - parseExpected(140); + parseExpected(141); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); + node.exportClause = parseNamedImportsOrExports(246); + if (token() === 141 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(141); node.moduleSpecifier = parseModuleSpecifier(); } } parseSemicolon(); return finishNode(node); } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportAssignment(node) { + node.kind = 244; if (parseOptional(58)) { node.isExportEquals = true; } @@ -15095,7 +14750,7 @@ var ts; var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment); if (checkJsDirectiveMatchResult) { checkJsDirective = { - enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", true) === 0, + enabled: ts.equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"), end: range.end, pos: range.pos }; @@ -15111,52 +14766,19 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1) - || node.kind === 237 && node.moduleReference.kind === 248 - || node.kind === 238 - || node.kind === 243 + || node.kind === 238 && node.moduleReference.kind === 249 + || node.kind === 239 || node.kind === 244 + || node.kind === 245 ? node : undefined; }); } - var ParsingContext; - (function (ParsingContext) { - ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; - ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; - ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; - ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; - ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; - ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; - ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; - ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; - ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; - ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; - ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; - ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; - ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; - ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; - ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; - ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; - ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; - })(ParsingContext || (ParsingContext = {})); - var Tristate; - (function (Tristate) { - Tristate[Tristate["False"] = 0] = "False"; - Tristate[Tristate["True"] = 1] = "True"; - Tristate[Tristate["Unknown"] = 2] = "Unknown"; - })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = createSourceFile("file.js", 5, 1); + initializeState(content, 6, undefined, 1); + sourceFile = createSourceFile("file.js", 6, 1, false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -15165,19 +14787,19 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression(requireBraces) { - var result = createNode(267, scanner.getTokenPos()); - if (!parseExpected(17) && requireBraces) { - return undefined; - } + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(271, scanner.getTokenPos()); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(1048576, parseType); - parseExpected(18); + if (!mayOmitBraces || hasBrace) { + parseExpected(18); + } fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); + initializeState(content, 6, undefined, 1); sourceFile = { languageVariant: 0, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -15193,7 +14815,7 @@ var ts; if (comment) { comment.parent = parent; } - if (ts.isInJavaScriptFile(parent)) { + if (contextFlags & 65536) { if (!sourceFile.jsDocDiagnostics) { sourceFile.jsDocDiagnostics = []; } @@ -15206,17 +14828,6 @@ var ts; var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; - var JSDocState; - (function (JSDocState) { - JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; - JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; - JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; - })(JSDocState || (JSDocState = {})); - var PropertyLikeParse; - (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; - })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -15335,7 +14946,7 @@ var ts; content.charCodeAt(start + 3) !== 42; } function createJSDocComment() { - var result = createNode(275, start); + var result = createNode(279, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -15359,6 +14970,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -15451,7 +15063,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(276, atToken.pos); + var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -15487,7 +15099,7 @@ var ts; switch (node.kind) { case 134: return true; - case 164: + case 165: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; @@ -15503,8 +15115,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(279, atToken.pos) : - createNode(284, atToken.pos); + createNode(284, atToken.pos) : + createNode(289, atToken.pos); var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -15520,7 +15132,7 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var typeLiteralExpression = createNode(271, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); @@ -15532,9 +15144,9 @@ var ts; children.push(child); } if (children) { - jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral = createNode(280, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 164) { + if (typeExpression.type.kind === 165) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -15543,35 +15155,55 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + if (ts.forEach(tags, function (t) { return t.kind === 285; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(280, atToken.pos); + var result = createNode(285, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + if (ts.forEach(tags, function (t) { return t.kind === 286; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(281, atToken.pos); + var result = createNode(286, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = parseJSDocTypeExpression(true); - var result = createNode(277, atToken.pos); + var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = typeExpression; + result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(17); + var node = createNode(202); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(18); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(true); + while (parseOptional(23)) { + var prop = createNode(180, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } function parseClassTag(atToken, tagName) { - var tag = createNode(278, atToken.pos); + var tag = createNode(283, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); @@ -15579,7 +15211,7 @@ var ts; function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(283, atToken.pos); + var typedefTag = createNode(288, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); @@ -15602,9 +15234,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(285, start_3); + jsdocTypeLiteral = createNode(280, start_3); } - if (child.kind === 281) { + if (child.kind === 286) { if (childTypeTag) { break; } @@ -15620,10 +15252,10 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 164) { + if (typeExpression && typeExpression.type.kind === 165) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -15633,7 +15265,7 @@ var ts; var pos = scanner.getTokenPos(); var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); + var jsDocNamespaceNode = createNode(234, pos); jsDocNamespaceNode.flags |= flags; jsDocNamespaceNode.name = typeNameOrNamespaceName; jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); @@ -15666,7 +15298,7 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 279 && + if (child && child.kind === 284 && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -15694,7 +15326,7 @@ var ts; } function tryParseChildTag(target) { ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); + var atToken = createNode(57); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15716,7 +15348,7 @@ var ts; return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + if (ts.forEach(tags, function (t) { return t.kind === 287; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; @@ -15728,7 +15360,7 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145, name.pos); + var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -15740,7 +15372,7 @@ var ts; break; } } - var result = createNode(282, atToken.pos); + var result = createNode(287, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -16070,70 +15702,61 @@ var ts; } } } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts"); + } })(ts || (ts = {})); var ts; (function (ts) { - var ModuleInstanceState; - (function (ModuleInstanceState) { - ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; - ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; - ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; - })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { - if (node.kind === 230 || node.kind === 231) { - return 0; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { - return 0; - } - else if (node.kind === 234) { - var state_1 = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state_1 = 2; - return false; - case 1: - state_1 = 1; - return true; + return node.body ? getModuleInstanceStateWorker(node.body) : 1; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + switch (node.kind) { + case 231: + case 232: + return 0; + case 233: + if (ts.isConst(node)) { + return 2; + } + break; + case 239: + case 238: + if (!(ts.hasModifier(node, 1))) { + return 0; + } + break; + case 235: { + var state_1 = 0; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0: + return; + case 2: + state_1 = 2; + return; + case 1: + state_1 = 1; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 234: + return getModuleInstanceState(node); + case 71: + if (node.isInJSDocNamespace) { + return 0; } - }); - return state_1; - } - else if (node.kind === 233) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1; - } - else if (node.kind === 71 && node.isInJSDocNamespace) { - return 0; - } - else { - return 1; } + return 1; } - ts.getModuleInstanceState = getModuleInstanceState; - var ContainerFlags; - (function (ContainerFlags) { - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; - ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; - ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; - ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; - ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; - ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; - })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -16169,6 +15792,9 @@ var ts; var reportedUnreachableFlow = { flags: 1 }; var subtreeTransformFlags = 0; var skipTransformFlagAggregation; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -16204,7 +15830,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { return true; } else { @@ -16233,60 +15859,61 @@ var ts; if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 234)) { symbol.valueDeclaration = node; } } } function getDeclarationName(node) { + if (node.kind === 244) { + return node.isExportEquals ? "export=" : "default"; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 144) { + if (name.kind === 145) { var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } return ts.getEscapedTextOfIdentifierOrLiteral(name); } switch (node.kind) { - case 152: + case 153: return "__constructor"; - case 160: - case 155: - return "__call"; case 161: case 156: - return "__new"; + return "__call"; + case 162: case 157: + return "__new"; + case 158: return "__index"; - case 244: + case 245: return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; - case 194: + case 195: if (ts.getSpecialPropertyAssignmentKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 228: case 229: + case 230: return (ts.hasModifier(node, 512) ? "default" : undefined); - case 273: + case 277: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); - case 146: - ts.Debug.assert(node.parent.kind === 273); + case 147: + ts.Debug.assert(node.parent.kind === 277); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 283: + case 288: var name_2 = ts.getNameOfJSDocTypedef(node); return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } @@ -16304,7 +15931,7 @@ var ts; } else { symbol = symbolTable.get(name); - if (includes & 788448) { + if (includes & 2885600) { classifiableNames.set(name, true); } if (!symbol) { @@ -16332,15 +15959,15 @@ var ts; } else { if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { + (isDefaultExport || (node.kind === 244 && !node.isExportEquals))) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -16352,7 +15979,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 2097152) { - if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { + if (node.kind === 247 || (node.kind === 238 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -16360,9 +15987,9 @@ var ts; } } else { - if (node.kind === 283) + if (node.kind === 288) ts.Debug.assert(ts.isInJavaScriptFile(node)); - var isJSDocTypedefInJSDocNamespace = node.kind === 283 && + var isJSDocTypedefInJSDocNamespace = node.kind === 288 && node.name && node.name.kind === 71 && node.name.isInJSDocNamespace; @@ -16400,16 +16027,13 @@ var ts; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { + if (!isIIFE) { currentFlow = { flags: 2 }; if (containerFlags & (16 | 128)) { currentFlow.container = node; } - currentReturnTarget = undefined; } + currentReturnTarget = isIIFE || node.kind === 153 ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -16421,14 +16045,17 @@ var ts; if (hasExplicitReturn) node.flags |= 256; } - if (node.kind === 265) { + if (node.kind === 269) { node.flags |= emitFlags; } - if (isIIFE) { + if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 153) { + node.returnFlowNode = currentFlow; + } } - else { + if (!isIIFE) { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; @@ -16508,70 +16135,70 @@ var ts; return; } switch (node.kind) { - case 213: + case 214: bindWhileStatement(node); break; - case 212: + case 213: bindDoStatement(node); break; - case 214: + case 215: bindForStatement(node); break; - case 215: case 216: + case 217: bindForInOrForOfStatement(node); break; - case 211: + case 212: bindIfStatement(node); break; - case 219: - case 223: + case 220: + case 224: bindReturnOrThrow(node); break; + case 219: case 218: - case 217: bindBreakOrContinueStatement(node); break; - case 224: + case 225: bindTryStatement(node); break; - case 221: + case 222: bindSwitchStatement(node); break; - case 235: + case 236: bindCaseBlock(node); break; - case 257: + case 261: bindCaseClause(node); break; - case 222: + case 223: bindLabeledStatement(node); break; - case 192: + case 193: bindPrefixUnaryExpressionFlow(node); break; - case 193: + case 194: bindPostfixUnaryExpressionFlow(node); break; - case 194: + case 195: bindBinaryExpressionFlow(node); break; - case 188: + case 189: bindDeleteExpressionFlow(node); break; - case 195: + case 196: bindConditionalExpressionFlow(node); break; - case 226: + case 227: bindVariableDeclarationFlow(node); break; - case 181: + case 182: bindCallExpressionFlow(node); break; - case 275: + case 279: bindJSDocComment(node); break; - case 283: + case 288: bindJSDocTypedefTag(node); break; default: @@ -16583,15 +16210,15 @@ var ts; switch (expr.kind) { case 71: case 99: - case 179: + case 180: return isNarrowableReference(expr); - case 181: + case 182: return hasNarrowableArgument(expr); - case 185: + case 186: return isNarrowingExpression(expr.expression); - case 194: + case 195: return isNarrowingBinaryExpression(expr); - case 192: + case 193: return expr.operator === 51 && isNarrowingExpression(expr.operand); } return false; @@ -16600,7 +16227,7 @@ var ts; return expr.kind === 71 || expr.kind === 99 || expr.kind === 97 || - expr.kind === 179 && isNarrowableReference(expr.expression); + expr.kind === 180 && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -16611,14 +16238,14 @@ var ts; } } } - if (expr.expression.kind === 179 && + if (expr.expression.kind === 180 && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -16639,9 +16266,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 185: + case 186: return isNarrowableOperand(expr.expression); - case 194: + case 195: switch (expr.operatorToken.kind) { case 58: return isNarrowableOperand(expr.left); @@ -16718,33 +16345,33 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 211: - case 213: case 212: - return parent.expression === node; case 214: - case 195: + case 213: + return parent.expression === node; + case 215: + case 196: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 185) { + if (node.kind === 186) { node = node.expression; } - else if (node.kind === 192 && node.operator === 51) { + else if (node.kind === 193 && node.operator === 51) { node = node.operand; } else { - return node.kind === 194 && (node.operatorToken.kind === 53 || + return node.kind === 195 && (node.operatorToken.kind === 53 || node.operatorToken.kind === 54); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 || - node.parent.kind === 192 && + while (node.parent.kind === 186 || + node.parent.kind === 193 && node.parent.operator === 51) { node = node.parent; } @@ -16786,7 +16413,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 + var enclosingLabeledStatement = node.parent.kind === 223 ? ts.lastOrUndefined(activeLabels) : undefined; var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); @@ -16818,13 +16445,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 216) { + if (node.kind === 217) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 227) { + if (node.initializer.kind !== 228) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -16846,7 +16473,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 219) { + if (node.kind === 220) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -16866,7 +16493,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 ? breakTarget : continueTarget; + var flowLabel = node.kind === 219 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -16929,7 +16556,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 262; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -16992,15 +16619,15 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - if (!node.statement || node.statement.kind !== 212) { + if (!node.statement || node.statement.kind !== 213) { addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 194 && node.operatorToken.kind === 58) { + if (node.kind === 195 && node.operatorToken.kind === 58) { bindAssignmentTargetFlow(node.left); } else { @@ -17011,10 +16638,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 177) { + else if (node.kind === 178) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 198) { + if (e.kind === 199) { bindAssignmentTargetFlow(e.expression); } else { @@ -17022,16 +16649,16 @@ var ts; } } } - else if (node.kind === 178) { + else if (node.kind === 179) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 261) { + if (p.kind === 265) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 262) { + else if (p.kind === 266) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 263) { + else if (p.kind === 267) { bindAssignmentTargetFlow(p.expression); } } @@ -17087,7 +16714,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 180) { + if (operator === 58 && node.left.kind === 181) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -17098,7 +16725,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 179) { + if (node.expression.kind === 180) { bindAssignmentTargetFlow(node.expression); } } @@ -17137,7 +16764,7 @@ var ts; } function bindJSDocComment(node) { ts.forEachChild(node, function (n) { - if (n.kind !== 283) { + if (n.kind !== 288) { bind(n); } }); @@ -17152,10 +16779,10 @@ var ts; } function bindCallExpressionFlow(node) { var expr = node.expression; - while (expr.kind === 185) { + while (expr.kind === 186) { expr = expr.expression; } - if (expr.kind === 186 || expr.kind === 187) { + if (expr.kind === 187 || expr.kind === 188) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -17163,7 +16790,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 179) { + if (node.expression.kind === 180) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -17172,52 +16799,52 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 199: - case 229: - case 232: - case 178: - case 163: - case 285: - case 254: - return 1; + case 200: case 230: - return 1 | 64; case 233: + case 179: + case 164: + case 280: + case 258: + return 1; case 231: - case 172: + return 1 | 64; + case 234: + case 232: + case 173: return 1 | 32; - case 265: + case 269: return 1 | 4 | 32; - case 151: + case 152: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 | 4 | 32 | 8 | 128; } - case 152: - case 228: - case 150: case 153: + case 229: + case 151: case 154: case 155: - case 273: - case 160: case 156: - case 157: + case 277: case 161: + case 157: + case 158: + case 162: return 1 | 4 | 32 | 8; - case 186: case 187: + case 188: return 1 | 4 | 32 | 8 | 16; - case 234: + case 235: return 4; - case 149: + case 150: return node.initializer ? 4 : 0; - case 260: - case 214: + case 264: case 215: case 216: - case 235: + case 217: + case 236: return 2; - case 207: + case 208: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -17230,37 +16857,37 @@ var ts; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 233: + case 234: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265: + case 269: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199: - case 229: + case 200: + case 230: return declareClassMember(node, symbolFlags, symbolExcludes); - case 232: + case 233: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 285: - case 178: - case 230: - case 254: + case 164: + case 280: + case 179: + case 231: + case 258: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160: case 161: - case 155: + case 162: case 156: case 157: - case 151: - case 150: + case 158: case 152: + case 151: case 153: case 154: - case 228: - case 186: + case 155: + case 229: case 187: - case 273: - case 231: - case 172: + case 188: + case 277: + case 232: + case 173: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -17275,11 +16902,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 265 ? node : node.body; - if (body && (body.kind === 265 || body.kind === 234)) { + var body = node.kind === 269 ? node : node.body; + if (body && (body.kind === 269 || body.kind === 235)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 244 || stat.kind === 243) { + if (stat.kind === 245 || stat.kind === 244) { return true; } } @@ -17287,7 +16914,7 @@ var ts; return false; } function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + if (node.flags & 2097152 && !hasExportDeclarations(node)) { node.flags |= 32; } else { @@ -17323,18 +16950,10 @@ var ts; else { var state = declareModuleSymbol(node); if (state !== 0) { - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } + var symbol = node.symbol; + symbol.constEnumOnlyModule = (!(symbol.flags & (16 | 32 | 256))) + && state === 2 + && symbol.constEnumOnlyModule !== false; } } } @@ -17353,20 +16972,15 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); if (inStrictMode) { var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 || prop.name.kind !== 71) { + if (prop.kind === 267 || prop.name.kind !== 71) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 + var currentKind = prop.kind === 265 || prop.kind === 266 || prop.kind === 152 ? 1 : 2; var existingKind = seen.get(identifier.escapedText); @@ -17390,17 +17004,17 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & 8) { + if (symbolFlags & (8 | 106500)) { symbol.parent = container.symbol; } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 233: + case 234: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 265: + case 269: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -17421,9 +17035,9 @@ var ts; node.originalKeywordKind >= 108 && node.originalKeywordKind <= 116 && !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { + !(node.flags & 2097152)) { if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -17460,7 +17074,7 @@ var ts; var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -17489,8 +17103,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 265 && - blockScopeContainer.kind !== 233 && + if (blockScopeContainer.kind !== 269 && + blockScopeContainer.kind !== 234 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -17498,8 +17112,8 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + if (inStrictMode && node.numericLiteralFlags & 32) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -17532,7 +17146,7 @@ var ts; if (ts.isInJavaScriptFile(node)) bindJSDocTypedefTagIfAny(node); bindWorker(node); - if (node.kind > 142) { + if (node.kind > 143) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -17560,7 +17174,7 @@ var ts; } for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; - if (tag.kind === 283) { + if (tag.kind === 288) { var savedParent = parent; parent = jsDoc; bind(tag); @@ -17592,23 +17206,26 @@ var ts; case 71: if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 283) { + while (parentNode && parentNode.kind !== 288) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288, 793064); break; } case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 266)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 179: + case 180: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } break; - case 194: + case 195: var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { case 1: @@ -17632,122 +17249,122 @@ var ts; ts.Debug.fail("Unknown special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 260: + case 264: return checkStrictModeCatchClause(node); - case 188: + case 189: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 193: + case 194: return checkStrictModePostfixUnaryExpression(node); - case 192: + case 193: return checkStrictModePrefixUnaryExpression(node); - case 220: + case 221: return checkStrictModeWithStatement(node); - case 169: + case 170: seenThisKeyword = true; return; - case 158: + case 159: return checkTypePredicate(node); - case 145: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); case 146: + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + case 147: return bindParameter(node); - case 226: + case 227: return bindVariableDeclarationOrBindingElement(node); - case 176: + case 177: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); + case 150: case 149: - case 148: return bindPropertyWorker(node); - case 261: - case 262: + case 265: + case 266: return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 264: + case 268: return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 155: case 156: case 157: + case 158: return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 152: case 151: - case 150: return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 228: + case 229: return bindFunctionDeclaration(node); - case 152: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 153: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 154: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 155: return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 160: - case 273: case 161: + case 277: + case 162: return bindFunctionOrConstructorType(node); - case 163: - case 285: - case 172: + case 164: + case 280: + case 173: return bindAnonymousTypeWorker(node); - case 178: + case 179: return bindObjectLiteralExpression(node); - case 186: case 187: + case 188: return bindFunctionExpression(node); - case 181: + case 182: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 199: - case 229: + case 200: + case 230: inStrictMode = true; return bindClassLikeDeclaration(node); - case 230: - return bindBlockScopedDeclaration(node, 64, 792968); case 231: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 64, 792968); case 232: - return bindEnumDeclaration(node); + return bindBlockScopedDeclaration(node, 524288, 793064); case 233: + return bindEnumDeclaration(node); + case 234: return bindModuleDeclaration(node); - case 254: + case 258: return bindJsxAttributes(node); - case 253: + case 257: return bindJsxAttribute(node, 4, 0); - case 237: - case 240: - case 242: - case 246: + case 238: + case 241: + case 243: + case 247: return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); - case 236: + case 237: return bindNamespaceExportDeclaration(node); - case 239: + case 240: return bindImportClause(node); - case 244: + case 245: return bindExportDeclaration(node); - case 243: + case 244: return bindExportAssignment(node); - case 265: + case 269: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 207: + case 208: if (!ts.isFunctionLike(node.parent)) { return; } - case 234: + case 235: return updateStrictModeStatementList(node.statements); - case 279: - if (node.parent.kind !== 285) { + case 284: + if (node.parent.kind !== 280) { break; } - case 284: + case 289: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 276 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 283: { + case 288: { var fullName = node.fullName; if (!fullName || fullName.kind === 71) { return bindBlockScopedDeclaration(node, 524288, 793064); @@ -17767,7 +17384,7 @@ var ts; if (parameterName && parameterName.kind === 71) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 169) { + if (parameterName && parameterName.kind === 170) { seenThisKeyword = true; } bind(type); @@ -17786,28 +17403,28 @@ var ts; bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); } else { - var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 244 && ts.exportAssignmentIsAlias(node) ? 2097152 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 2097152 | 32 | 16); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + if (node.parent.kind !== 269) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -17842,15 +17459,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -17869,22 +17483,32 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var container = ts.getThisContainer(node, false); switch (container.kind) { - case 228: - case 186: + case 229: + case 187: container.symbol.members = container.symbol.members || ts.createSymbolTable(); declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); break; - case 152: - case 149: - case 151: case 153: + case 150: + case 152: case 154: + case 155: var containingClass = container.parent; var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); break; } } + function bindSpecialPropertyDeclaration(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (node.expression.kind === 99) { + bindThisPropertyAssignment(node); + } + else if ((node.expression.kind === 71 || node.expression.kind === 180) && + node.parent.parent.kind === 269) { + bindStaticPropertyAssignment(node); + } + } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; var classPrototype = leftSideOfAssignment.expression; @@ -17895,32 +17519,62 @@ var ts; bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); } function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.left; + var leftSideOfAssignment = node.kind === 180 ? node : node.left; var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + if (ts.isIdentifier(target)) { + target.parent = leftSideOfAssignment; + if (node.kind === 195) { + leftSideOfAssignment.parent = node; + } + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + } } } function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { + var symbol = lookupSymbolForName(functionName); + var targetSymbol = symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol) ? + symbol.valueDeclaration.initializer.symbol : + symbol; + ts.Debug.assert(propertyAccess.parent.kind === 195 || propertyAccess.parent.kind === 211); + var isLegalPosition; + if (propertyAccess.parent.kind === 195) { + var initializerKind = propertyAccess.parent.right.kind; + isLegalPosition = (initializerKind === 200 || initializerKind === 187) && + propertyAccess.parent.parent.parent.kind === 269; + } + else { + isLegalPosition = propertyAccess.parent.parent.kind === 269; + } + if (!isPrototypeProperty && (!targetSymbol || !(targetSymbol.flags & 1920)) && isLegalPosition) { + ts.Debug.assert(ts.isIdentifier(propertyAccess.expression)); + var identifier = propertyAccess.expression; + var flags = 1536 | 67108864; + var excludeFlags = 106639 & ~67108864; + if (targetSymbol) { + addDeclarationToSymbol(symbol, identifier, flags); + } + else { + targetSymbol = declareSymbol(container.locals, undefined, identifier, flags, excludeFlags); + } } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { + if (!targetSymbol || !(targetSymbol.flags & (16 | 32 | 1024))) { return; } var symbolTable = isPrototypeProperty ? (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); + declareSymbol(symbolTable, targetSymbol, propertyAccess, 4, 0); } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -17928,7 +17582,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 229) { + if (node.kind === 230) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -17945,7 +17599,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -17972,7 +17626,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { + if (inStrictMode && !(node.flags & 2097152)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -17987,7 +17641,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -18002,7 +17656,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -18015,7 +17669,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152) && ts.isAsyncFunction(node)) { emitFlags |= 1024; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { @@ -18034,15 +17688,15 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || - node.kind === 229 || - (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 210) || + node.kind === 230 || + (node.kind === 234 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 233 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 || + !(node.flags & 2097152) && + (node.kind !== 209 || ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -18056,56 +17710,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 181: - return computeCallExpression(node, subtreeFlags); case 182: + return computeCallExpression(node, subtreeFlags); + case 183: return computeNewExpression(node, subtreeFlags); - case 233: + case 234: return computeModuleDeclaration(node, subtreeFlags); - case 185: + case 186: return computeParenthesizedExpression(node, subtreeFlags); - case 194: + case 195: return computeBinaryExpression(node, subtreeFlags); - case 210: + case 211: return computeExpressionStatement(node, subtreeFlags); - case 146: + case 147: return computeParameter(node, subtreeFlags); - case 187: + case 188: return computeArrowFunction(node, subtreeFlags); - case 186: + case 187: return computeFunctionExpression(node, subtreeFlags); - case 228: + case 229: return computeFunctionDeclaration(node, subtreeFlags); - case 226: - return computeVariableDeclaration(node, subtreeFlags); case 227: + return computeVariableDeclaration(node, subtreeFlags); + case 228: return computeVariableDeclarationList(node, subtreeFlags); - case 208: + case 209: return computeVariableStatement(node, subtreeFlags); - case 222: + case 223: return computeLabeledStatement(node, subtreeFlags); - case 229: + case 230: return computeClassDeclaration(node, subtreeFlags); - case 199: + case 200: return computeClassExpression(node, subtreeFlags); - case 259: + case 263: return computeHeritageClause(node, subtreeFlags); - case 260: + case 264: return computeCatchClause(node, subtreeFlags); - case 201: + case 202: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152: + case 153: return computeConstructor(node, subtreeFlags); - case 149: + case 150: return computePropertyDeclaration(node, subtreeFlags); - case 151: + case 152: return computeMethod(node, subtreeFlags); - case 153: case 154: + case 155: return computeAccessor(node, subtreeFlags); - case 237: + case 238: return computeImportEquals(node, subtreeFlags); - case 179: + case 180: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -18125,6 +17779,9 @@ var ts; } if (expression.kind === 91) { transformFlags |= 67108864; + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } } node.transformFlags = transformFlags | 536870912; return transformFlags & ~537396545; @@ -18133,8 +17790,8 @@ var ts; switch (kind) { case 97: return true; - case 179: case 180: + case 181: var expression = node.expression; var expressionKind = expression.kind; return expressionKind === 97; @@ -18156,10 +17813,10 @@ var ts; var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 178) { + if (operatorTokenKind === 58 && leftKind === 179) { transformFlags |= 8 | 192 | 3072; } - else if (operatorTokenKind === 58 && leftKind === 177) { + else if (operatorTokenKind === 58 && leftKind === 178) { transformFlags |= 192 | 3072; } else if (operatorTokenKind === 40 @@ -18197,8 +17854,8 @@ var ts; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 202 - || expressionKind === 184) { + if (expressionKind === 203 + || expressionKind === 185) { transformFlags |= 3; } if (expressionTransformFlags & 1024) { @@ -18290,6 +17947,7 @@ var ts; || ts.hasModifier(node, 2270) || node.typeParameters || node.type + || (node.name && ts.isComputedPropertyName(node.name)) || !node.body) { transformFlags |= 3; } @@ -18310,6 +17968,7 @@ var ts; if (node.decorators || ts.hasModifier(node, 2270) || node.type + || (node.name && ts.isComputedPropertyName(node.name)) || !node.body) { transformFlags |= 3; } @@ -18485,7 +18144,7 @@ var ts; var excludeFlags = 536872257; switch (kind) { case 120: - case 191: + case 192: transformFlags |= 8 | 16; break; case 114: @@ -18494,34 +18153,37 @@ var ts; case 117: case 124: case 76: - case 232: - case 264: - case 184: - case 202: + case 233: + case 268: + case 185: case 203: + case 204: case 131: transformFlags |= 3; break; - case 249: case 250: case 251: - case 10: case 252: + case 10: case 253: case 254: case 255: case 256: + case 257: + case 258: + case 259: + case 260: transformFlags |= 4; break; case 13: case 14: case 15: case 16: - case 196: - case 183: - case 262: + case 197: + case 184: + case 266: case 115: - case 204: + case 205: transformFlags |= 192; break; case 9: @@ -18530,17 +18192,17 @@ var ts; } break; case 8: - if (node.numericLiteralFlags & 48) { + if (node.numericLiteralFlags & 384) { transformFlags |= 192; } break; - case 216: + case 217: if (node.awaitModifier) { transformFlags |= 8; } transformFlags |= 192; break; - case 197: + case 198: transformFlags |= 8 | 192 | 16777216; break; case 119: @@ -18551,10 +18213,9 @@ var ts; case 122: case 137: case 105: - case 145: - case 148: - case 150: - case 155: + case 146: + case 149: + case 151: case 156: case 157: case 158: @@ -18568,27 +18229,28 @@ var ts; case 166: case 167: case 168: - case 230: - case 231: case 169: + case 231: + case 232: case 170: case 171: case 172: case 173: - case 236: + case 174: + case 237: transformFlags = 3; excludeFlags = -3; break; - case 144: + case 145: transformFlags |= 2097152; if (subtreeFlags & 16384) { transformFlags |= 65536; } break; - case 198: + case 199: transformFlags |= 192 | 524288; break; - case 263: + case 267: transformFlags |= 8 | 1048576; break; case 97: @@ -18597,27 +18259,27 @@ var ts; case 99: transformFlags |= 16384; break; - case 174: + case 175: transformFlags |= 192 | 8388608; if (subtreeFlags & 524288) { transformFlags |= 8 | 1048576; } excludeFlags = 537396545; break; - case 175: + case 176: transformFlags |= 192 | 8388608; excludeFlags = 537396545; break; - case 176: + case 177: transformFlags |= 192; if (node.dotDotDotToken) { transformFlags |= 524288; } break; - case 147: + case 148: transformFlags |= 3 | 4096; break; - case 178: + case 179: excludeFlags = 540087617; if (subtreeFlags & 2097152) { transformFlags |= 192; @@ -18629,29 +18291,29 @@ var ts; transformFlags |= 8; } break; - case 177: - case 182: + case 178: + case 183: excludeFlags = 537396545; if (subtreeFlags & 524288) { transformFlags |= 192; } break; - case 212: case 213: case 214: case 215: + case 216: if (subtreeFlags & 4194304) { transformFlags |= 192; } break; - case 265: + case 269: if (subtreeFlags & 32768) { transformFlags |= 192; } break; - case 219: - case 217: + case 220: case 218: + case 219: transformFlags |= 33554432; break; } @@ -18659,33 +18321,33 @@ var ts; return transformFlags & ~excludeFlags; } function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 && kind <= 173) { + if (kind >= 159 && kind <= 174) { return -3; } switch (kind) { - case 181: case 182: - case 177: + case 183: + case 178: return 537396545; - case 233: + case 234: return 574674241; - case 146: + case 147: return 536872257; - case 187: + case 188: return 601249089; - case 186: - case 228: + case 187: + case 229: return 601281857; - case 227: + case 228: return 546309441; - case 229: - case 199: + case 230: + case 200: return 539358529; - case 152: - return 601015617; - case 151: case 153: + return 601015617; + case 152: case 154: + case 155: return 601015617; case 119: case 133: @@ -18695,21 +18357,21 @@ var ts; case 122: case 137: case 105: - case 145: - case 148: - case 150: - case 155: + case 146: + case 149: + case 151: case 156: case 157: - case 230: + case 158: case 231: + case 232: return -3; - case 178: + case 179: return 540087617; - case 260: + case 264: return 537920833; - case 174: case 175: + case 176: return 537396545; default: return 536872257; @@ -18762,7 +18424,7 @@ var ts; var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; - if (type.flags & 32768) { + if (type.flags & 65536) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4) { @@ -18778,16 +18440,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 16384) { + if (type.flags & 32768) { visitTypeParameter(type); } - if (type.flags & 196608) { + if (type.flags & 393216) { visitUnionOrIntersectionType(type); } - if (type.flags & 262144) { + if (type.flags & 524288) { visitIndexType(type); } - if (type.flags & 524288) { + if (type.flags & 1048576) { visitIndexedAccessType(type); } } @@ -18870,7 +18532,7 @@ var ts; symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { - if (d.type && d.type.kind === 162) { + if (d.type && d.type.kind === 163) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -18926,7 +18588,7 @@ var ts; return; } var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { + if (!ts.isString(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); } @@ -18969,7 +18631,7 @@ var ts; return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; } var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -19298,8 +18960,8 @@ var ts; matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -19500,14 +19162,14 @@ var ts; var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; - return { packageJsonContent: packageJsonContent, packageId: packageId }; + return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } failedLookupLocations.push(packageJsonPath); - return { packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined }; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { @@ -19551,10 +19213,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var packageJsonContent; + var packageId; + var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); + if (packageInfo.found) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); + } + else { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + } + } var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); @@ -19566,6 +19238,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); } @@ -19574,7 +19247,7 @@ var ts; } function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); if (resolutionFromCache) { @@ -19608,23 +19281,30 @@ var ts; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); } } - return moduleName; + return packageName; } function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -19654,7 +19334,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -19690,19 +19370,6 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } - 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 || (ts = {})); var ts; (function (ts) { @@ -19750,10 +19417,12 @@ var ts; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4, "undefined"); @@ -19898,15 +19567,34 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, - getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -19914,25 +19602,27 @@ var ts; var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4, "unknown"); var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1, "any"); var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); + var undefinedType = createIntrinsicType(4096, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 | 4194304, "undefined"); + var nullType = createIntrinsicType(8192, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 | 4194304, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var trueType = createIntrinsicType(128, "true"); var falseType = createIntrinsicType(128, "false"); var booleanType = createBooleanType([trueType, falseType]); var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); - var silentNeverType = createIntrinsicType(8192, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var voidType = createIntrinsicType(2048, "void"); + var neverType = createIntrinsicType(16384, "never"); + var silentNeverType = createIntrinsicType(16384, "never"); + var implicitNeverType = createIntrinsicType(16384, "never"); + var nonPrimitiveType = createIntrinsicType(33554432, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); @@ -19940,9 +19630,14 @@ var ts; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; + anyFunctionType.flags |= 16777216; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(32768); + var markerSubType = createType(32768); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(32768); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); @@ -19950,6 +19645,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); + var ambientModulesCache; var patternAmbientModules; var globalObjectType; var globalFunctionType; @@ -20005,90 +19701,30 @@ var ts; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var TypeFacts; - (function (TypeFacts) { - TypeFacts[TypeFacts["None"] = 0] = "None"; - TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString"; - TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber"; - TypeFacts[TypeFacts["TypeofEQBoolean"] = 4] = "TypeofEQBoolean"; - TypeFacts[TypeFacts["TypeofEQSymbol"] = 8] = "TypeofEQSymbol"; - TypeFacts[TypeFacts["TypeofEQObject"] = 16] = "TypeofEQObject"; - TypeFacts[TypeFacts["TypeofEQFunction"] = 32] = "TypeofEQFunction"; - TypeFacts[TypeFacts["TypeofEQHostObject"] = 64] = "TypeofEQHostObject"; - TypeFacts[TypeFacts["TypeofNEString"] = 128] = "TypeofNEString"; - TypeFacts[TypeFacts["TypeofNENumber"] = 256] = "TypeofNENumber"; - TypeFacts[TypeFacts["TypeofNEBoolean"] = 512] = "TypeofNEBoolean"; - TypeFacts[TypeFacts["TypeofNESymbol"] = 1024] = "TypeofNESymbol"; - TypeFacts[TypeFacts["TypeofNEObject"] = 2048] = "TypeofNEObject"; - TypeFacts[TypeFacts["TypeofNEFunction"] = 4096] = "TypeofNEFunction"; - TypeFacts[TypeFacts["TypeofNEHostObject"] = 8192] = "TypeofNEHostObject"; - TypeFacts[TypeFacts["EQUndefined"] = 16384] = "EQUndefined"; - TypeFacts[TypeFacts["EQNull"] = 32768] = "EQNull"; - TypeFacts[TypeFacts["EQUndefinedOrNull"] = 65536] = "EQUndefinedOrNull"; - TypeFacts[TypeFacts["NEUndefined"] = 131072] = "NEUndefined"; - TypeFacts[TypeFacts["NENull"] = 262144] = "NENull"; - TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; - TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; - TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; - TypeFacts[TypeFacts["All"] = 8388607] = "All"; - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; - TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; - TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; - TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; - TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; - TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; - TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; - TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; - TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; - })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ - "string": 1, - "number": 2, - "boolean": 4, - "symbol": 8, - "undefined": 16384, - "object": 16, - "function": 32 + string: 1, + number: 2, + boolean: 4, + symbol: 8, + undefined: 16384, + object: 16, + function: 32 }); var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128, - "number": 256, - "boolean": 512, - "symbol": 1024, - "undefined": 131072, - "object": 2048, - "function": 4096 + string: 128, + number: 256, + boolean: 512, + symbol: 1024, + undefined: 131072, + object: 2048, + function: 4096 }); var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType + string: stringType, + number: numberType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType }); var typeofType = createTypeofType(); var _jsxNamespace; @@ -20098,35 +19734,12 @@ var ts; var _jsxElementChildrenPropertyName; var _hasComputedJsxElementChildrenPropertyName = false; var jsxTypes = ts.createUnderscoreEscapedMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); var _displayBuilder; - var TypeSystemPropertyName; - (function (TypeSystemPropertyName) { - TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; - TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); - var CheckMode; - (function (CheckMode) { - CheckMode[CheckMode["Normal"] = 0] = "Normal"; - CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; - CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; - })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -20151,16 +19764,16 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } - function error(location, message, arg0, arg1, arg2) { + function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); } - function createSymbol(flags, name) { + function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432, name)); - symbol.checkFlags = 0; + symbol.checkFlags = checkFlags || 0; return symbol; } function isTransientSymbol(symbol) { @@ -20225,14 +19838,15 @@ var ts; return result; } function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + source.flags & 67108864 || target.flags & 67108864) { if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { + (target.valueDeclaration.kind === 234 && source.valueDeclaration.kind !== 234))) { target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -20262,6 +19876,16 @@ var ts; }); } } + function combineSymbolTables(first, second) { + if (!first || first.size === 0) + return second; + if (!second || second.size === 0) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); @@ -20287,7 +19911,7 @@ var ts; mergeSymbolTable(globals, moduleAugmentation.symbol.exports); } else { - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); @@ -20328,11 +19952,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } - function getObjectFlags(type) { - return type.flags & 32768 ? type.objectFlags : 0; - } function isGlobalSourceFile(node) { - return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 269 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -20355,7 +19976,7 @@ var ts; var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -20368,7 +19989,7 @@ var ts; if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - ts.isInAmbientContext(declaration)) { + declaration.flags & 2097152) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -20378,23 +19999,23 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - if (declaration.kind === 176) { - var errorBindingElement = ts.getAncestor(usage, 176); + if (declaration.kind === 177) { + var errorBindingElement = ts.getAncestor(usage, 177); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 227), usage); } - else if (declaration.kind === 226) { + else if (declaration.kind === 227) { return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return true; } - if (usage.parent.kind === 246 || (usage.parent.kind === 243 && usage.parent.isExportEquals)) { + if (usage.parent.kind === 247 || (usage.parent.kind === 244 && usage.parent.isExportEquals)) { return true; } - if (usage.kind === 243 && usage.isExportEquals) { + if (usage.kind === 244 && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -20402,9 +20023,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 208: - case 214: - case 216: + case 209: + case 215: + case 217: if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } @@ -20421,16 +20042,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 149 && + current.parent.kind === 150 && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32)) { - if (declaration.kind === 151) { + if (declaration.kind === 152) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !ts.hasModifier(declaration, 32); + var isDeclarationInstanceProperty = declaration.kind === 150 && !ts.hasModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -20446,6 +20067,7 @@ var ts; var originalLocation = location; var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -20455,18 +20077,18 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 275) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 279) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 146 || - lastLocation.kind === 145 + lastLocation.kind === 147 || + lastLocation.kind === 146 : false; } if (meaning & 107455 && result.flags & 1) { useResult = - lastLocation.kind === 146 || + lastLocation.kind === 147 || (lastLocation === location.type && - result.valueDeclaration.kind === 146); + result.valueDeclaration.kind === 147); } } if (useResult) { @@ -20478,13 +20100,13 @@ var ts; } } switch (location.kind) { - case 265: + case 269: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 233: + case 234: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 || ts.isAmbientModule(location)) { + if (location.kind === 269 || ts.isAmbientModule(location)) { if (result = moduleExports.get("default")) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { @@ -20495,7 +20117,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 && - ts.getDeclarationOfKind(moduleExport, 246)) { + ts.getDeclarationOfKind(moduleExport, 247)) { break; } } @@ -20503,13 +20125,13 @@ var ts; break loop; } break; - case 232: + case 233: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; + case 150: case 149: - case 148: if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -20519,10 +20141,10 @@ var ts; } } break; - case 229: - case 199: case 230: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { + case 200: + case 231: + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -20533,7 +20155,7 @@ var ts; } break loop; } - if (location.kind === 199 && meaning & 32) { + if (location.kind === 200 && meaning & 32) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -20541,7 +20163,7 @@ var ts; } } break; - case 201: + case 202: if (lastLocation === location.expression && location.parent.token === 85) { var container = location.parent.parent; if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064))) { @@ -20552,28 +20174,28 @@ var ts; } } break; - case 144: + case 145: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230) { + if (ts.isClassLike(grandparent) || grandparent.kind === 231) { if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 228: - case 187: + case 155: + case 229: + case 188: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 186: + case 187: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -20586,8 +20208,8 @@ var ts; } } break; - case 147: - if (location.parent && location.parent.kind === 146) { + case 148: + if (location.parent && location.parent.kind === 147) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -20595,15 +20217,18 @@ var ts; } break; } + if (location.kind !== 208) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 265); + ts.Debug.assert(lastLocation.kind === 269); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -20622,7 +20247,7 @@ var ts; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); } } if (!suggestion) { @@ -20649,7 +20274,7 @@ var ts; } if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236) { + if (decls && decls.length === 1 && decls[0].kind === 237) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -20657,12 +20282,12 @@ var ts; return result; } function diagnosticName(nameArg) { - return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 145 && decl.parent === container) { + if (decl.kind === 146 && decl.parent === container) { return true; } } @@ -20708,18 +20333,19 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71: - case 179: + case 180: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; + case 202: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } default: return undefined; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~1920, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -20760,7 +20386,7 @@ var ts; } } else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~793064, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -20770,9 +20396,9 @@ var ts; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 233) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + if (!(declaration.flags & 2097152) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } @@ -20789,13 +20415,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 237: + case 238: return node; - case 239: - return node.parent; case 240: + return node.parent; + case 241: return node.parent.parent; - case 242: + case 243: return node.parent.parent.parent; default: return undefined; @@ -20805,7 +20431,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248) { + if (node.moduleReference.kind === 249) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -20914,19 +20540,19 @@ var ts; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { - case 237: + case 238: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239: - return getTargetOfImportClause(node, dontRecursivelyResolve); case 240: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 241: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242: + case 243: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246: + case 247: return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); - case 243: + case 244: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236: + case 237: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); } } @@ -20975,10 +20601,10 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 243) { + if (node.kind === 244) { checkExpressionCached(node.expression); } - else if (node.kind === 246) { + else if (node.kind === 247) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -20990,11 +20616,11 @@ var ts; if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 71 || entityName.parent.kind === 143) { + if (entityName.kind === 71 || entityName.parent.kind === 144) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 237); + ts.Debug.assert(entityName.parent.kind === 238); return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } @@ -21013,19 +20639,19 @@ var ts; return undefined; } } - else if (name.kind === 143 || name.kind === 179) { + else if (name.kind === 144 || name.kind === 180) { var left = void 0; - if (name.kind === 143) { + if (name.kind === 144) { left = name.left; } - else if (name.kind === 179 && - (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { + else if (name.kind === 180 && + (name.expression.kind === 186 || ts.isEntityNameExpression(name.expression))) { left = name.expression; } else { return undefined; } - var right = name.kind === 143 ? name.right : name.name; + var right = name.kind === 144 ? name.right : name.name; var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -21033,6 +20659,9 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } + if (ts.isInJavaScriptFile(name) && ts.isDeclarationOfFunctionOrClassExpression(namespace)) { + namespace = getSymbolOfNode(namespace.valueDeclaration.initializer); + } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { @@ -21041,7 +20670,7 @@ var ts; return undefined; } } - else if (name.kind === 185) { + else if (name.kind === 186) { return ts.isEntityNameExpression(name.expression) ? resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : undefined; @@ -21156,23 +20785,29 @@ var ts; } function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); - if (!symbol) { - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); - } + if (symbol) { + return symbol; } - return symbol; + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 16382 ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + return symbol.flags & 32 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports") : + symbol.flags & 1536 ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; } function getExportsOfModule(moduleSymbol) { var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); } function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { if (id === "default") return; var targetSymbol = target.get(id); @@ -21234,10 +20869,10 @@ var ts; return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; } function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); } function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576) !== 0 @@ -21251,7 +20886,7 @@ var ts; var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 152 && ts.nodeIsPresent(member.body)) { + if (member.kind === 153 && ts.nodeIsPresent(member.body)) { return member; } } @@ -21274,7 +20909,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(32768); + var type = createType(65536); type.objectFlags = objectFlags; type.symbol = symbol; return type; @@ -21324,11 +20959,11 @@ var ts; } } switch (location.kind) { - case 265: + case 269: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 233: + case 234: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -21373,7 +21008,6 @@ var ts; return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246) && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -21398,7 +21032,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 247)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -21412,10 +21046,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 149: - case 151: - case 153: + case 150: + case 152: case 154: + case 155: continue; default: return false; @@ -21472,7 +21106,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 269 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -21499,11 +21133,13 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 163 || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 145) { meaning = 107455 | 1048576; } - else if (entityName.kind === 143 || entityName.kind === 179 || - entityName.parent.kind === 237) { + else if (entityName.kind === 144 || entityName.kind === 180 || + entityName.parent.kind === 238) { meaning = 1920; } else { @@ -21576,18 +21212,21 @@ var ts; function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; @@ -21621,10 +21260,10 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 256 && !(type.flags & 65536)) { + if (type.flags & 256 && !(type.flags & 131072)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 793064, false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 272) { @@ -21641,24 +21280,27 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024) { - return ts.createKeywordTypeNode(105); + return ts.createTypeOperatorNode(140, ts.createKeywordTypeNode(137)); } if (type.flags & 2048) { - return ts.createKeywordTypeNode(139); + return ts.createKeywordTypeNode(105); } if (type.flags & 4096) { - return ts.createKeywordTypeNode(95); + return ts.createKeywordTypeNode(139); } if (type.flags & 8192) { + return ts.createKeywordTypeNode(95); + } + if (type.flags & 16384) { return ts.createKeywordTypeNode(130); } if (type.flags & 512) { return ts.createKeywordTypeNode(137); } - if (type.flags & 16777216) { + if (type.flags & 33554432) { return ts.createKeywordTypeNode(134); } - if (type.flags & 16384 && type.isThisType) { + if (type.flags & 32768 && type.isThisType) { if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; @@ -21666,13 +21308,13 @@ var ts; } return ts.createThis(); } - var objectFlags = getObjectFlags(type); + var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 32768)); + ts.Debug.assert(!!(type.flags & 65536)); return typeReferenceToTypeNode(type); } - if (type.flags & 16384 || objectFlags & 3) { - var name = symbolToName(type.symbol, context, 793064, false); + if (type.flags & 32768 || objectFlags & 3) { + var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { @@ -21680,11 +21322,11 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - if (type.flags & (65536 | 131072)) { - var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + if (type.flags & (131072 | 262144)) { + var types = type.flags & 131072 ? formatUnionTypes(type.types) : type.types; var typeNodes = mapToTypeNodes(types, context); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 ? 167 : 168, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -21695,22 +21337,22 @@ var ts; } } if (objectFlags & (16 | 32)) { - ts.Debug.assert(!!(type.flags & 32768)); + ts.Debug.assert(!!(type.flags & 65536)); return createAnonymousTypeNode(type); } - if (type.flags & 262144) { + if (type.flags & 524288) { var indexedType = type.type; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 524288) { + if (type.flags & 1048576) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768)); + ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); @@ -21755,7 +21397,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; + return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return ts.contains(context.symbolStack, symbol); @@ -21773,12 +21415,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 162, context); return signatureNode; } } @@ -21888,11 +21530,11 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 157, context)); } if (resolvedType.stringIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); @@ -21916,7 +21558,7 @@ var ts; var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 151, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); @@ -21935,8 +21577,8 @@ var ts; function mapToTypeNodes(types, context) { if (ts.some(types)) { var result = []; - for (var i = 0; i < types.length; ++i) { - var type = types[i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -21991,23 +21633,23 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); - if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { - return ts.createParameter(undefined, undefined, parameterSymbol.isRestParameter ? ts.createToken(24) : undefined, "args", undefined, typeToTypeNodeHelper(anyArrayType, context), undefined); - } - var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; - var name = parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : - cloneBindingName(parameterDeclaration.name) : - ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); - var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 147); + ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); var parameterType = getTypeOfSymbol(parameterSymbol); - if (isRequiredInitializedParameter(parameterDeclaration)) { - parameterType = getNullableType(parameterType, 2048); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; function cloneBindingName(node) { @@ -22015,7 +21657,7 @@ var ts; function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 176) { + if (clone.kind === 177) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 | 16777216); @@ -22056,8 +21698,7 @@ var ts; } typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol, context); - var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -22096,10 +21737,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 6144)) { + if (!(t.flags & 12288)) { if (t.flags & (128 | 256)) { var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 65536) { + if (baseType.flags & 131072) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -22111,9 +21752,9 @@ var ts; result.push(t); } } - if (flags & 4096) + if (flags & 8192) result.push(nullType); - if (flags & 2048) + if (flags & 4096) result.push(undefinedType); return result || types; } @@ -22128,8 +21769,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); - if (node.kind === 231) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 169; }); + if (node.kind === 232) { return getSymbolOfNode(node); } } @@ -22137,30 +21778,30 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 234 && + node.parent.kind === 235 && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol, context) { + function getNameOfSymbolAsWritten(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 226) { + if (declaration.parent && declaration.parent.kind === 227) { return ts.declarationNameToString(declaration.parent.name); } if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { context.encounteredError = true; } switch (declaration.kind) { - case 199: + case 200: return "(Anonymous class)"; - case 186: case 187: + case 188: return "(Anonymous function)"; } } @@ -22170,25 +21811,29 @@ var ts; return "\"" + ts.escapeString(stringValue, 34) + "\""; } } - return ts.unescapeLeadingUnderscores(symbol.escapedName); + return ts.symbolName(symbol); } function getSymbolDisplayBuilder() { function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); + writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); } function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); + var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 21); + if (firstChar !== 91) { + writePunctuation(writer, 21); + } if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 22); + if (firstChar !== 91) { + writePunctuation(writer, 22); + } } else { writePunctuation(writer, 23); @@ -22252,21 +21897,21 @@ var ts; return writeType(type, globalFlags); function writeType(type, flags) { var nextFlags = flags & ~1024; - if (type.flags & 16793231) { + if (type.flags & 33585807) { writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 16384 && type.isThisType) { + else if (type.flags & 32768 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (getObjectFlags(type) & 4) { + else if (ts.getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 && !(type.flags & 65536)) { + else if (type.flags & 256 && !(type.flags & 131072)) { var parent = getParentOfSymbol(type.symbol); buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); if (getDeclaredTypeOfSymbol(parent) !== type) { @@ -22274,7 +21919,7 @@ var ts; appendSymbolNameOnly(type.symbol, writer); } } - else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { + else if (ts.getObjectFlags(type) & 3 || type.flags & (272 | 32768)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 1024) && type.aliasSymbol && @@ -22282,16 +21927,26 @@ var ts; var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } - else if (type.flags & 196608) { + else if (type.flags & 393216) { writeUnionOrIntersectionType(type, nextFlags); } - else if (getObjectFlags(type) & (16 | 32)) { + else if (ts.getObjectFlags(type) & (16 | 32)) { writeAnonymousType(type, nextFlags); } + else if (type.flags & 1024) { + if (flags & 131072) { + writeKeyword(writer, 140); + writeSpace(writer); + } + else { + writer.reportInaccessibleUniqueSymbolError(); + } + writeKeyword(writer, 137); + } else if (type.flags & 96) { writer.writeStringLiteral(literalTypeToString(type)); } - else if (type.flags & 262144) { + else if (type.flags & 524288) { if (flags & 128) { writePunctuation(writer, 19); } @@ -22302,7 +21957,7 @@ var ts; writePunctuation(writer, 20); } } - else if (type.flags & 524288) { + else if (type.flags & 1048576) { writeType(type.objectType, 128); writePunctuation(writer, 21); writeType(type.indexType, 0); @@ -22359,8 +22014,8 @@ var ts; } else if (flags & 16384 && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 199) { - writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + type.symbol.valueDeclaration.kind === 200) { + writeAnonymousType(type, flags); } else { var outerTypeParameters = type.target.outerTypeParameters; @@ -22387,7 +22042,7 @@ var ts; if (flags & 128) { writePunctuation(writer, 19); } - if (type.flags & 65536) { + if (type.flags & 131072) { writeTypeList(formatUnionTypes(type.types), 49); } else { @@ -22402,12 +22057,12 @@ var ts; if (symbol) { if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 199 && flags & 16384) || + !(symbol.valueDeclaration.kind === 200 && flags & 16384) || symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); @@ -22442,7 +22097,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; + return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 4) || @@ -22450,13 +22105,13 @@ var ts; } } } - function writeTypeOfSymbol(type, typeFormatFlags) { + function writeTypeOfSymbol(symbol, typeFormatFlags) { if (typeFormatFlags & 32768) { writePunctuation(writer, 19); } writeKeyword(writer, 103); writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); if (typeFormatFlags & 32768) { writePunctuation(writer, 20); } @@ -22466,6 +22121,13 @@ var ts; writeKeyword(writer, 131); writeSpace(writer); } + if (ts.getCheckFlags(prop) & 1024) { + var decl = ts.firstOrUndefined(prop.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + if (name) { + writer.trackSymbol(name, enclosingDeclaration, 107455); + } + } buildSymbolDisplay(prop, writer); if (prop.flags & 16777216) { writePunctuation(writer, 55); @@ -22550,7 +22212,7 @@ var ts; continue; } if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); } } var t = getTypeOfSymbol(p); @@ -22642,17 +22304,17 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048); + type = getOptionalType(type); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 174) { + if (bindingPattern.kind === 175) { writePunctuation(writer, 17); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); writePunctuation(writer, 18); } - else if (bindingPattern.kind === 175) { + else if (bindingPattern.kind === 176) { writePunctuation(writer, 21); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); @@ -22666,7 +22328,7 @@ var ts; if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 176); + ts.Debug.assert(bindingElement.kind === 177); if (bindingElement.propertyName) { writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 56); @@ -22824,87 +22486,92 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 176: + case 177: return isDeclarationVisible(node.parent.parent); - case 226: + case 227: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 233: - case 229: + case 234: case 230: case 231: - case 228: case 232: - case 237: + case 229: + case 233: + case 238: if (ts.isExternalModuleAugmentation(node)) { return true; } var parent = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { + !(node.kind !== 238 && parent.kind !== 269 && parent.flags & 2097152)) { return isGlobalSourceFile(parent); } return isDeclarationVisible(parent); + case 150: case 149: - case 148: - case 153: case 154: + case 155: + case 152: case 151: - case 150: if (ts.hasModifier(node, 8 | 16)) { return false; } - case 152: - case 156: - case 155: + case 153: case 157: - case 146: - case 234: - case 160: + case 156: + case 158: + case 147: + case 235: case 161: - case 163: - case 159: + case 162: case 164: + case 160: case 165: case 166: case 167: case 168: + case 169: return isDeclarationVisible(node.parent); - case 239: case 240: - case 242: + case 241: + case 243: return false; - case 145: - case 265: - case 236: + case 146: + case 269: + case 237: return true; - case 243: + case 244: return false; default: return false; } } } - function collectLinkedAliases(node) { + function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node, false); + if (node.parent && node.parent.kind === 244) { + exportSymbol = resolveName(node, node.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, node, false); } - else if (node.parent.kind === 246) { + else if (node.parent.kind === 247) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); } - var result = []; + var result; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } return result; function buildVisibleNodeList(declarations) { ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - ts.pushIfUnique(result, resultNode); + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); @@ -22964,12 +22631,12 @@ var ts; function getDeclarationContainer(node) { node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 226: case 227: + case 228: + case 243: case 242: case 241: case 240: - case 239: return false; default: return true; @@ -22993,14 +22660,14 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function isComputedNonLiteralName(name) { - return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 145 && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144); }); - if (source.flags & 8192) { + source = filterType(source, function (t) { return !(t.flags & 12288); }); + if (source.flags & 16384) { return emptyObjectType; } - if (source.flags & 65536) { + if (source.flags & 131072) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); @@ -23028,14 +22695,14 @@ var ts; if (parentType === unknownType) { return unknownType; } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; - if (pattern.kind === 174) { + if (pattern.kind === 175) { if (declaration.dotDotDotToken) { if (!isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -23055,10 +22722,10 @@ var ts; if (isComputedNonLiteralName(name)) { return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } var text = ts.getTextOfPropertyName(name); + if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || @@ -23090,7 +22757,7 @@ var ts; } } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096)) { type = getTypeWithFacts(type, 131072); } return declaration.initializer ? @@ -23110,17 +22777,18 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 177 && expr.elements.length === 0; + return expr.kind === 178 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048) : type; + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.parent.parent.kind === 215) { + if (declaration.parent.parent.kind === 216) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 | 262144) ? indexType : stringType; + return indexType.flags & (32768 | 524288) ? indexType : stringType; } - if (declaration.parent.parent.kind === 216) { + if (declaration.parent.parent.kind === 217) { var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } @@ -23130,11 +22798,11 @@ var ts; var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, declaration.questionToken && includeOptionality); + return addOptionality(declaredType, !!declaration.questionToken && includeOptionality); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + declaration.kind === 227 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 2097152)) { if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { return autoType; } @@ -23142,10 +22810,10 @@ var ts; return autoArrayType; } } - if (declaration.kind === 146) { + if (declaration.kind === 147) { var func = declaration.parent; - if (func.kind === 154 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); + if (func.kind === 155 && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 154); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -23164,17 +22832,17 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, declaration.questionToken && includeOptionality); + return addOptionality(type, !!declaration.questionToken && includeOptionality); } } if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, declaration.questionToken && includeOptionality); + return addOptionality(type, !!declaration.questionToken && includeOptionality); } if (ts.isJsxAttribute(declaration)) { return trueType; } - if (declaration.kind === 262) { + if (declaration.kind === 266) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -23189,14 +22857,14 @@ var ts; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = declaration.kind === 194 ? declaration : - declaration.kind === 179 ? ts.getAncestor(declaration, 194) : + var expression = declaration.kind === 195 ? declaration : + declaration.kind === 180 ? ts.getAncestor(declaration, 195) : undefined; if (!expression) { return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 152) { + if (ts.getThisContainer(expression, false).kind === 153) { definedInConstructor = true; } else { @@ -23209,9 +22877,10 @@ var ts; if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { - var name = ts.getNameOfDeclaration(declaration); - error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); + else if (jsDocType !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(jsDocType, declarationType) && + !(symbol.flags & 67108864)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } else if (!jsDocType) { @@ -23278,7 +22947,7 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 + return pattern.kind === 175 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -23288,7 +22957,10 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (declaration.kind === 261) { + if (type.flags & 1024 && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + if (declaration.kind === 265) { return type; } return getWidenedType(type); @@ -23303,7 +22975,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 ? root.parent : root; + var memberDeclaration = root.kind === 147 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -23316,7 +22988,7 @@ var ts; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } - if (declaration.kind === 243) { + if (declaration.kind === 244) { return links.type = checkExpression(declaration.expression); } if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { @@ -23326,8 +22998,8 @@ var ts; return unknownType; } var type = void 0; - if (declaration.kind === 194 || - declaration.kind === 179 && declaration.parent.kind === 194) { + if (declaration.kind === 195 || + declaration.kind === 180 && declaration.parent.kind === 195) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } else { @@ -23342,7 +23014,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 153) { + if (accessor.kind === 154) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -23363,8 +23035,8 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153); - var setter = ts.getDeclarationOfKind(symbol, 154); + var getter = ts.getDeclarationOfKind(symbol, 154); + var setter = ts.getDeclarationOfKind(symbol, 155); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { @@ -23405,7 +23077,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153); + var getter_1 = ts.getDeclarationOfKind(symbol, 154); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -23415,7 +23087,7 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; + return baseConstructorType.flags & 1081344 ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -23430,7 +23102,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 16777216 ? getNullableType(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 16777216 ? getOptionalType(type) : type; } } } @@ -23509,20 +23181,20 @@ var ts; function isReferenceToType(type, target) { return type !== undefined && target !== undefined - && (getObjectFlags(type) & 4) !== 0 + && (ts.getObjectFlags(type) & 4) !== 0 && type.target === target; } function getTargetType(type) { - return getObjectFlags(type) & 4 ? type.target : type; + return ts.getObjectFlags(type) & 4 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); function check(type) { - if (getObjectFlags(type) & (3 | 4)) { + if (ts.getObjectFlags(type) & (3 | 4)) { var target = getTargetType(type); return target === checkBase || ts.forEach(getBaseTypes(target), check); } - else if (type.flags & 131072) { + else if (type.flags & 262144) { return ts.forEach(type.types, check); } } @@ -23542,44 +23214,44 @@ var ts; return undefined; } switch (node.kind) { - case 229: - case 199: case 230: - case 155: + case 200: + case 231: case 156: - case 150: - case 160: - case 161: - case 273: - case 228: + case 157: case 151: - case 186: + case 161: + case 162: + case 277: + case 229: + case 152: case 187: - case 231: - case 282: - case 172: + case 188: + case 232: + case 287: + case 173: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 172) { + if (node.kind === 173) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); var thisType = includeThisTypes && - (node.kind === 229 || node.kind === 199 || node.kind === 230) && + (node.kind === 230 || node.kind === 200 || node.kind === 231) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 231); return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 230 || node.kind === 229 || - node.kind === 199 || node.kind === 231) { + if (node.kind === 231 || node.kind === 230 || + node.kind === 200 || node.kind === 232) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -23603,14 +23275,21 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { return true; } - if (type.flags & 540672) { + if (type.flags & 1081344) { var constraint = getBaseConstraintOfType(type); return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + var decl = type.symbol.valueDeclaration; + if (ts.isInJavaScriptFile(decl)) { + var tag = ts.getJSDocAugmentsTag(decl); + if (tag) { + return tag.class; + } + } + return ts.getClassExtendsHeritageClauseElement(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -23624,6 +23303,8 @@ var ts; } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getClassExtendsHeritageClauseElement(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -23632,7 +23313,11 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 | 131072)) { + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (65536 | 262144)) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -23669,7 +23354,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { + if (!(baseConstructorType.flags & (65536 | 262144 | 1))) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -23691,13 +23376,6 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag && augTag.typeExpression && augTag.typeExpression.type) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } if (baseType === unknownType) { return; } @@ -23706,7 +23384,7 @@ var ts; return; } if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } type.resolvedBaseTypes = [baseType]; @@ -23714,21 +23392,21 @@ var ts; function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; + var last_1 = outerTypeParameters.length - 1; var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; } return true; } function isValidBaseType(type) { - return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || - type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return type.flags & (65536 | 33554432 | 1) && !isGenericMappedType(type) || + type.flags & 262144 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 231 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -23754,10 +23432,10 @@ var ts; } } } - function isIndependentInterface(symbol) { + function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230) { + if (declaration.kind === 231) { if (declaration.flags & 64) { return false; } @@ -23784,7 +23462,7 @@ var ts; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + if (outerTypeParameters || localTypeParameters || kind === 1 || !isThislessInterface(symbol)) { type.objectFlags |= 4; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; @@ -23793,7 +23471,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384); + type.thisType = createType(32768); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -23808,9 +23486,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 283 || d.kind === 231; + return d.kind === 288 || d.kind === 232; }); - var typeNode = declaration.kind === 283 ? declaration.typeExpression : declaration.type; + var typeNode = declaration.kind === 288 ? declaration.typeExpression : declaration.type; var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -23831,13 +23509,13 @@ var ts; function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !ts.isInAmbientContext(member); + return !(member.flags & 2097152); } switch (expr.kind) { case 9: case 8: return true; - case 192: + case 193: return expr.operator === 38 && expr.operand.kind === 8; case 71: @@ -23854,7 +23532,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232) { + if (declaration.kind === 233) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9) { @@ -23869,7 +23547,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 : 1; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 256 && !(type.flags & 131072) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -23881,7 +23559,7 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232) { + if (declaration.kind === 233) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); @@ -23892,7 +23570,7 @@ var ts; } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); - if (enumType_1.flags & 65536) { + if (enumType_1.flags & 131072) { enumType_1.flags |= 256; enumType_1.symbol = symbol; } @@ -23916,7 +23594,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384); + var type = createType(32768); type.symbol = symbol; links.declaredType = type; } @@ -23930,6 +23608,9 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { if (symbol.flags & (32 | 64)) { return getDeclaredTypeOfClassOrInterface(symbol); } @@ -23948,20 +23629,9 @@ var ts; if (symbol.flags & 2097152) { return getDeclaredTypeOfAlias(symbol); } - return unknownType; - } - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; + return undefined; } - function isIndependentType(node) { + function isThislessType(node) { switch (node.kind) { case 119: case 136: @@ -23973,46 +23643,40 @@ var ts; case 139: case 95: case 130: - case 173: + case 174: return true; - case 164: - return isIndependentType(node.elementType); - case 159: - return isIndependentTypeReference(node); + case 165: + return isThislessType(node.elementType); + case 160: + return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; } - function isIndependentVariableLikeDeclaration(node) { + function isThislessTypeParameter(node) { + return !node.constraint || isThislessType(node.constraint); + } + function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isIndependentType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !node.initializer; } - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152) { - var typeNode = ts.getEffectiveReturnTypeNode(node); - if (!typeNode || !isIndependentType(typeNode)) { - return false; - } - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + return (node.kind === 153 || (returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); } - function isIndependentMember(symbol) { + function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 149: - case 148: - return isIndependentVariableLikeDeclaration(declaration); - case 151: case 150: + case 149: + return isThislessVariableLikeDeclaration(declaration); case 152: - return isIndependentFunctionLikeDeclaration(declaration); + case 151: + case 153: + return isThislessFunctionLikeDeclaration(declaration); } } } @@ -24022,7 +23686,7 @@ var ts; var result = ts.createSymbolTable(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; - result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; } @@ -24037,23 +23701,139 @@ var ts; function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call")); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new")); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); } return type; } + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 1120); + } + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return name && isLateBindableName(name); + } + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + function getLateBoundNameFromType(type) { + if (type.flags & 1024) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & 96) { + return ts.escapeLeadingUnderscores("" + type.value); + } + } + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0, memberName, 1024)); + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0, memberName, 1024); + } + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + lateSymbol.parent = parent; + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports"; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 ? getExportsOfModuleWorker(symbol) : + symbol.exports; + links[resolutionKind] = earlySymbols || emptySymbols; + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { + var member = members_3[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers") + : symbol.members || emptySymbols; + } + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 && symbol.escapedName === "__computed") { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4) { + if (ts.getObjectFlags(type) & 4) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); } } - else if (type.flags & 131072) { + else if (type.flags & 262144) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); } return type; @@ -24067,7 +23847,7 @@ var ts; var numberIndexInfo; if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = identityMapper; - members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); callSignatures = source.declaredCallSignatures; constructSignatures = source.declaredConstructSignatures; stringIndexInfo = source.declaredStringIndexInfo; @@ -24083,7 +23863,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -24144,7 +23924,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -24212,8 +23992,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type = types_1[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -24291,7 +24071,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { - var members = symbol.members; + var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call")); var constructSignatures = getSignaturesOfSymbol(members.get("__new")); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); @@ -24307,7 +24087,7 @@ var ts; if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 | 131072 | 540672)) { + if (baseConstructorType.flags & (65536 | 262144 | 1081344)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -24340,18 +24120,20 @@ var ts; var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 171 && + constraintDeclaration.operator === 127) { for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var propertySymbol = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); } - if (getIndexInfoOfType(modifiersType, 0)) { + if (modifiersType.flags & 1 || getIndexInfoOfType(modifiersType, 0)) { addMemberForKeyType(stringType); } } else { - var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + var keyType = constraintType.flags & 1081344 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 524288 ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -24367,8 +24149,8 @@ var ts; var propName = ts.escapeLeadingUnderscores(t.value); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216); - var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + var checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName, checkFlags); prop.type = propType; if (propertySymbol) { prop.syntheticOrigin = propertySymbol; @@ -24377,7 +24159,7 @@ var ts; prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } - else if (t.flags & 2) { + else if (t.flags & (1 | 2)) { stringIndexInfo = createIndexInfo(propType, templateReadonly); } } @@ -24399,27 +24181,37 @@ var ts; function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170) { + if (constraintDeclaration.kind === 171 && + constraintDeclaration.operator === 127) { type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); } else { var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 32768 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } + function getMappedTypeModifiers(type) { + return (type.declaration.readonlyToken ? 1 : 0) | + (type.declaration.questionToken ? 2 : 0); + } + function getCombinedMappedTypeModifiers(type) { + var modifiersType = getModifiersTypeFromMappedType(type); + return getMappedTypeModifiers(type) | + (isGenericMappedType(modifiersType) ? getMappedTypeModifiers(modifiersType) : 0); + } function isPartialMappedType(type) { - return getObjectFlags(type) & 32 && !!type.declaration.questionToken; + return ts.getObjectFlags(type) & 32 && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return ts.getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 32768) { + if (type.flags & 65536) { if (type.objectFlags & 4) { resolveTypeReferenceMembers(type); } @@ -24433,23 +24225,23 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 65536) { + else if (type.flags & 131072) { resolveUnionTypeMembers(type); } - else if (type.flags & 131072) { + else if (type.flags & 262144) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -24471,7 +24263,7 @@ var ts; } } } - if (type.flags & 65536) { + if (type.flags & 131072) { break; } } @@ -24481,19 +24273,19 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 196608 ? + return type.flags & 393216 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 65536)) { - return getPropertiesOfType(unionType); + if (!(unionType.flags & 131072)) { + return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var memberType = types_2[_i]; - for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); @@ -24503,8 +24295,8 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 16384 ? getConstraintOfTypeParameter(type) : - type.flags & 524288 ? getConstraintOfIndexedAccess(type) : + return type.flags & 32768 ? getConstraintOfTypeParameter(type) : + type.flags & 1048576 ? getConstraintOfIndexedAccess(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { @@ -24520,13 +24312,13 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (540672 | 196608)) { + if (type.flags & (1081344 | 393216)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 262144) { + else if (type.flags & 524288) { return stringType; } return undefined; @@ -24554,29 +24346,29 @@ var ts; return result; } function computeBaseConstraint(t) { - if (t.flags & 16384) { + if (t.flags & 32768) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType ? constraint : constraint ? getBaseConstraint(constraint) : undefined; } - if (t.flags & 196608) { + if (t.flags & 393216) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_2 = types_4[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 131072 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 262144 && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 262144) { + if (t.flags & 524288) { return stringType; } - if (t.flags & 524288) { + if (t.flags & 1048576) { var transformed = getTransformedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); @@ -24595,39 +24387,56 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } function getApparentType(type) { - var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 ? globalStringType : + var t = type.flags & 1081344 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 262144 ? getApparentTypeOfIntersectionType(t) : + t.flags & 524322 ? globalStringType : t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : - t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : + t.flags & 1536 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 33554432 ? emptyObjectType : t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var types = containingType.types; - var isUnion = containingType.flags & 65536; + var isUnion = containingType.flags & 131072; var excludeModifiers = isUnion ? 24 : 0; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var current = types_5[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -24672,8 +24481,7 @@ var ts; } propTypes.push(type); } - var result = createSymbol(4 | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; + var result = createSymbol(4 | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; result.declarations = declarations; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -24696,7 +24504,7 @@ var ts; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -24710,13 +24518,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 196608) { + if (type.flags & 393216) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376) { + if (type.flags & 458752) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -24726,7 +24534,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376) { + if (type.flags & 458752) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -24742,7 +24550,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -24775,7 +24583,7 @@ var ts; } function isJSDocOptionalParameter(node) { if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 272) { + if (node.type && node.type.kind === 276) { return true; } var paramTags = ts.getJSDocParameterTags(node); @@ -24786,7 +24594,7 @@ var ts; return true; } if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 272; + return paramTag.typeExpression.type.kind === 276; } } } @@ -24839,29 +24647,33 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } } return minTypeArgumentCount; } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { if (!typeArguments) { typeArguments = []; } for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); } for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + defaultType = anyType; + } + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); } + typeArguments.length = typeParameters.length; } } return typeArguments; @@ -24891,7 +24703,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 173) { + if (param.type && param.type.kind === 174) { hasLiteralTypes = true; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || @@ -24902,35 +24714,46 @@ var ts; minArgumentCount = parameters.length; } } - if ((declaration.kind === 153 || declaration.kind === 154) && - !ts.hasDynamicName(declaration) && + if ((declaration.kind === 154 || declaration.kind === 155) && + !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 ? 154 : 153; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + var otherKind = declaration.kind === 154 ? 155 : 154; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 152 ? + var classType = declaration.kind === 153 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 ? + var typePredicate = declaration.type && declaration.type.kind === 159 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - var hasRestLikeParameter = ts.hasRestParameter(declaration); - if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { - hasRestLikeParameter = true; - var syntheticArgsSymbol = createSymbol(3, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - parameters.push(syntheticArgsSymbol); - } + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { + return false; + } + var syntheticArgsSymbol = createSymbol(3, "args"); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + if (lastParamVariadicType) { + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); @@ -24942,8 +24765,8 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154); + if (declaration.kind === 154 && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 155); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -24966,12 +24789,12 @@ var ts; return false; switch (node.kind) { case 71: - return node.escapedText === "arguments" && ts.isPartOfExpression(node); - case 149: - case 151: - case 153: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 150: + case 152: case 154: - return node.name.kind === 144 + case 155: + return node.name.kind === 145 && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); @@ -24985,20 +24808,20 @@ var ts; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 160: case 161: - case 228: - case 151: - case 150: + case 162: + case 229: case 152: - case 155: + case 151: + case 153: case 156: case 157: - case 153: + case 158: case 154: - case 186: + case 155: case 187: - case 273: + case 188: + case 277: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -25063,7 +24886,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 && type.target === globalArrayType) { + if (ts.getObjectFlags(type) & 4 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -25098,9 +24921,18 @@ var ts; function createCanonicalSignature(signature) { return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), true); + } + return signature; + } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; + var isConstructor = signature.declaration.kind === 153 || signature.declaration.kind === 157; var type = createObjectType(16); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -25141,7 +24973,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145).constraint; + return type.symbol && ts.getDeclarationOfKind(type.symbol, 146).constraint; } function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { @@ -25157,7 +24989,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 146).parent); } function getTypeListId(types) { var result = ""; @@ -25184,13 +25016,13 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } } - return result & 14680064; + return result & 29360128; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -25221,14 +25053,24 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJavascript = ts.isInJavaScriptFile(node); - if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); - return unknownType; + var isJs = ts.isInJavaScriptFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && node.parent.kind !== 282; + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, undefined, 1); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + return unknownType; + } } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25268,18 +25110,11 @@ var ts; } return type; } - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } function getTypeReferenceName(node) { switch (node.kind) { - case 159: + case 160: return node.typeName; - case 201: + case 202: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -25302,18 +25137,26 @@ var ts; if (type) { return type; } - if (symbol.flags & 107455 && isJSDocTypeReference(node)) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res !== undefined) { + if (typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return res; + } + if (!(symbol.flags & 107455 && isJSDocTypeReference(node))) { + return unknownType; + } + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; } - resolveTypeReferenceName(getTypeReferenceName(node), 793064); - return valueType; } - return getTypeFromNonGenericTypeReference(node, symbol); + resolveTypeReferenceName(getTypeReferenceName(node), 793064); + return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 | 64)) { @@ -25329,18 +25172,16 @@ var ts; } } function isJSDocTypeReference(node) { - return node.flags & 1048576 && node.kind === 159; + return node.flags & 1048576 && node.kind === 160; } function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -25371,7 +25212,7 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; + return strictNullChecks ? getNullableType(type, 8192) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); @@ -25408,9 +25249,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 229: case 230: - case 232: + case 231: + case 233: return declaration; } } @@ -25419,12 +25260,12 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + if (!(type.flags & 65536)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } return type; @@ -25523,12 +25364,15 @@ var ts; var typeParameters = []; var properties = []; for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); + var typeParameter = createType(32768); typeParameters.push(typeParameter); var property = createSymbol(4, "" + i); property.type = typeParameter; properties.push(property); } + var lengthSymbol = createSymbol(4, "length"); + lengthSymbol.type = getLiteralType(arity); + properties.push(lengthSymbol); var type = createObjectType(8 | 4); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; @@ -25537,7 +25381,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384); + type.thisType = createType(32768); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -25560,37 +25404,21 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; + function getTypeId(type) { + return type.id; } function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } function isEmptyIntersectionType(type) { var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6368 && combined & 6368) { + if (t.flags & 13536 && combined & 13536) { return true; } combined |= t.flags; - if (combined & 6144 && combined & (32768 | 16777216)) { + if (combined & 12288 && combined & (65536 | 33554432)) { return true; } } @@ -25598,31 +25426,33 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 65536) { + if (flags & 131072) { addTypesToUnion(typeSet, type.types); } else if (flags & 1) { typeSet.containsAny = true; } - else if (!strictNullChecks && flags & 6144) { - if (flags & 2048) - typeSet.containsUndefined = true; + else if (!strictNullChecks && flags & 12288) { if (flags & 4096) + typeSet.containsUndefined = true; + if (flags & 8192) typeSet.containsNull = true; - if (!(flags & 2097152)) + if (!(flags & 4194304)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 || flags & 131072 && isEmptyIntersectionType(type))) { + else if (!(flags & 16384 || flags & 262144 && isEmptyIntersectionType(type))) { if (flags & 2) typeSet.containsString = true; if (flags & 4) typeSet.containsNumber = true; - if (flags & 96) - typeSet.containsStringOrNumberLiteral = true; + if (flags & 512) + typeSet.containsESSymbol = true; + if (flags & 1120) + typeSet.containsLiteralOrUniqueESSymbol = true; var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 32768 && type.objectFlags & 16 && + if (!(flags & 65536 && type.objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } @@ -25630,24 +25460,26 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; if (isTypeIdenticalTo(t, type)) { return true; } } return false; } - function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - if (candidate !== type && isTypeSubtypeOf(candidate, type)) { + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || + !(ts.getObjectFlags(getTargetType(target)) & 1) || + isTypeDerivedFrom(source, target))) { return true; } } @@ -25686,7 +25518,8 @@ var ts; var t = types[i]; var remove = t.flags & 32 && types.containsString || t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); + t.flags & 1024 && types.containsESSymbol || + t.flags & 96 && t.flags & 2097152 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -25707,7 +25540,7 @@ var ts; if (subtypeReduction) { removeSubtypes(typeSet); } - else if (typeSet.containsStringOrNumberLiteral) { + else if (typeSet.containsLiteralOrUniqueESSymbol) { removeRedundantLiteralTypes(typeSet); } if (typeSet.length === 0) { @@ -25727,8 +25560,8 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = createType(65536 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, 12288); + type = createType(131072 | propagatedFlags); unionTypes.set(id, type); type.types = types; type.aliasSymbol = aliasSymbol; @@ -25744,26 +25577,26 @@ var ts; return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072) { + if (type.flags & 262144) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1) { typeSet.containsAny = true; } - else if (type.flags & 8192) { + else if (type.flags & 16384) { typeSet.containsNever = true; } - else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { + else if (ts.getObjectFlags(type) & 16 && isEmptyObjectType(type)) { typeSet.containsEmptyObject = true; } - else if ((strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768) { + else if ((strictNullChecks || !(type.flags & 12288)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536) { typeSet.containsObjectType = true; } - if (type.flags & 65536 && typeSet.unionIndex === undefined) { + if (type.flags & 131072 && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - if (!(type.flags & 32768 && type.objectFlags & 16 && + if (!(type.flags & 65536 && type.objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.push(type); } @@ -25772,7 +25605,7 @@ var ts; function addTypesToIntersection(typeSet, types) { for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { var type = types_9[_i]; - addTypeToIntersection(typeSet, type); + addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -25801,8 +25634,8 @@ var ts; var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = createType(131072 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 12288); + type = createType(262144 | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; @@ -25819,7 +25652,7 @@ var ts; } function getIndexTypeForGenericType(type) { if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144); + type.resolvedIndexType = createType(524288); type.resolvedIndexType.type = type; } return type.resolvedIndexType; @@ -25827,40 +25660,48 @@ var ts; function getLiteralTypeFromPropertyName(prop) { return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? neverType : - getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + getLiteralType(ts.symbolName(prop)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + return maybeTypeOfKind(type, 1081344) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; + return indexType.flags & 16384 ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + switch (node.operator) { + case 127: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 140: + links.resolvedType = node.type.kind === 137 + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : unknownType; + break; + } } return links.resolvedType; } function createIndexedAccessType(objectType, indexType) { - var type = createType(524288); + var type = createType(1048576); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & 96 ? - ts.escapeLeadingUnderscores("" + indexType.value) : + var accessExpression = accessNode && accessNode.kind === 181 ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); @@ -25877,7 +25718,7 @@ var ts; return getTypeOfSymbol(prop); } } - if (!(indexType.flags & 6144) && isTypeAssignableToKind(indexType, 262178 | 84 | 512)) { + if (!(indexType.flags & 12288) && isTypeAssignableToKind(indexType, 524322 | 84 | 1536)) { if (isTypeAny(objectType)) { return anyType; } @@ -25903,7 +25744,7 @@ var ts; } } if (accessNode) { - var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = accessNode.kind === 181 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } @@ -25918,18 +25759,18 @@ var ts; return anyType; } function isGenericObjectType(type) { - return type.flags & 540672 ? true : - getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : - type.flags & 196608 ? ts.forEach(type.types, isGenericObjectType) : + return type.flags & 1081344 ? true : + ts.getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 393216 ? ts.forEach(type.types, isGenericObjectType) : false; } function isGenericIndexType(type) { - return type.flags & (540672 | 262144) ? true : - type.flags & 196608 ? ts.forEach(type.types, isGenericIndexType) : + return type.flags & (1081344 | 524288) ? true : + type.flags & 393216 ? ts.forEach(type.types, isGenericIndexType) : false; } function isStringIndexOnlyType(type) { - if (type.flags & 32768 && !isGenericMappedType(type)) { + if (type.flags & 65536 && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && @@ -25939,7 +25780,7 @@ var ts; } function getTransformedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 131072 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + if (objectType.flags & 262144 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { @@ -25965,7 +25806,7 @@ var ts; return undefined; } function getIndexedAccessType(objectType, indexType, accessNode) { - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; } @@ -25977,7 +25818,7 @@ var ts; return type; } var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8)) { + if (indexType.flags & 131072 && !(indexType.flags & 8)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -26014,7 +25855,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { links.resolvedType = emptyTypeLiteralType; } else { @@ -26030,32 +25871,32 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; + return node.parent.kind === 232 ? getSymbolOfNode(node.parent) : undefined; } function getAliasTypeArgumentsForTypeNode(node) { var symbol = getAliasSymbolForTypeNode(node); return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 || right.flags & 1) { return anyType; } - if (left.flags & 8192) { + if (left.flags & 16384) { return right; } - if (right.flags & 8192) { + if (right.flags & 16384) { return left; } - if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + if (left.flags & 131072) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } - if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + if (right.flags & 131072) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 16777216) { + if (right.flags & 33554432) { return nonPrimitiveType; } - if (right.flags & (136 | 84 | 262178 | 272)) { + if (right.flags & (136 | 84 | 524322 | 272)) { return left; } var members = ts.createSymbolTable(); @@ -26105,7 +25946,11 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= propagatedFlags; + spread.flags |= 2097152 | 8388608; + spread.objectFlags |= (128 | 1024); + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -26118,6 +25963,12 @@ var ts; result.syntheticOrigin = prop; return result; } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, false, index.declaration); + } + return index; + } function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } @@ -26128,9 +25979,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 && !(type.flags & 1048576)) { + if (type.flags & 96 && !(type.flags & 2097152)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 2097152, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -26139,7 +25990,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; + return type.flags & 96 && type.flags & 2097152 ? type.regularType : type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : "@"; @@ -26158,20 +26009,25 @@ var ts; } return links.resolvedType; } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; + function createUniqueESSymbolType(symbol) { + var type = createType(1024); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.type || (links.type = createUniqueESSymbolType(symbol)); } - return links.resolvedType; + return esSymbolType; } function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 231)) { if (!ts.hasModifier(container, 32) && - (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 153 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -26188,8 +26044,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119: - case 268: - case 269: + case 272: + case 273: return anyType; case 136: return stringType; @@ -26209,52 +26065,52 @@ var ts; return neverType; case 134: return node.flags & 65536 ? anyType : nonPrimitiveType; - case 169: + case 170: case 99: return getTypeFromThisTypeNode(node); - case 173: + case 174: return getTypeFromLiteralTypeNode(node); - case 159: + case 160: return getTypeFromTypeReference(node); - case 158: + case 159: return booleanType; - case 201: + case 202: return getTypeFromTypeReference(node); - case 162: + case 163: return getTypeFromTypeQueryNode(node); - case 164: - return getTypeFromArrayTypeNode(node); case 165: - return getTypeFromTupleTypeNode(node); + return getTypeFromArrayTypeNode(node); case 166: - return getTypeFromUnionTypeNode(node); + return getTypeFromTupleTypeNode(node); case 167: + return getTypeFromUnionTypeNode(node); + case 168: return getTypeFromIntersectionTypeNode(node); - case 270: + case 274: return getTypeFromJSDocNullableTypeNode(node); - case 168: + case 169: + case 275: + case 276: case 271: - case 272: - case 267: return getTypeFromTypeNode(node.type); - case 160: + case 278: + return getTypeFromJSDocVariadicType(node); case 161: - case 163: - case 285: - case 273: + case 162: + case 164: + case 280: + case 277: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170: - return getTypeFromTypeOperatorNode(node); case 171: - return getTypeFromIndexedAccessTypeNode(node); + return getTypeFromTypeOperatorNode(node); case 172: + return getTypeFromIndexedAccessTypeNode(node); + case 173: return getTypeFromMappedTypeNode(node); case 71: - case 143: + case 144: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 274: - return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -26319,7 +26175,7 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { - var result = createType(16384); + var result = createType(32768); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -26365,8 +26221,7 @@ var ts; symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(symbol.flags, symbol.escapedName); - result.checkFlags = 1; + var result = createSymbol(symbol.flags, symbol.escapedName, 1); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -26388,7 +26243,7 @@ var ts; var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -26410,20 +26265,31 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 208 ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 170: + return tp.isThisType; + case 71: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 163: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144) { + if (constraintType.flags & 524288) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384) { + if (typeVariable_1.flags & 32768) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -26438,7 +26304,7 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (16384 | 32768 | 131072 | 524288); + return type.flags & (1 | 32768 | 65536 | 262144 | 1048576); } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64, type.symbol); @@ -26453,10 +26319,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { + if (type.flags & 32768) { return mapper(type); } - if (type.flags & 32768) { + if (type.flags & 65536) { if (type.objectFlags & 16) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? getAnonymousTypeInstantiation(type, mapper) : type; @@ -26468,16 +26334,16 @@ var ts; return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } - if (type.flags & 65536 && !(type.flags & 8190)) { + if (type.flags & 131072 && !(type.flags & 16382)) { return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 131072) { + if (type.flags & 262144) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 262144) { + if (type.flags & 524288) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 524288) { + if (type.flags & 1048576) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } @@ -26487,31 +26353,31 @@ var ts; return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 186: case 187: - case 151: + case 188: + case 152: return isContextSensitiveFunctionLikeDeclaration(node); - case 178: + case 179: return ts.forEach(node.properties, isContextSensitive); - case 177: + case 178: return ts.forEach(node.elements, isContextSensitive); - case 195: + case 196: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 194: + case 195: return node.operatorToken.kind === 54 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261: + case 265: return isContextSensitive(node.initializer); - case 185: + case 186: return isContextSensitive(node.expression); - case 254: + case 258: return ts.forEach(node.properties, isContextSensitive); - case 253: + case 257: return node.initializer && isContextSensitive(node.initializer); - case 256: + case 260: return node.expression && isContextSensitive(node.expression); } return false; @@ -26523,19 +26389,19 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 187) { + if (node.kind !== 188) { var parameter = ts.firstOrUndefined(node.parameters); if (!(parameter && ts.parameterIsThisKeyword(parameter))) { return true; } } - return node.body.kind === 207 ? false : isContextSensitive(node.body); + return node.body.kind === 208 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(16, type.symbol); @@ -26546,7 +26412,7 @@ var ts; return result; } } - else if (type.flags & 131072) { + else if (type.flags & 262144) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -26566,8 +26432,12 @@ var ts; function isTypeAssignableTo(source, target) { return isTypeRelatedTo(source, target, assignableRelation); } - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + function isTypeDerivedFrom(source, target) { + return source.flags & 131072 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 131072 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 1081344 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + hasBaseType(source, getTargetType(target)); } function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); @@ -26582,9 +26452,9 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { if (source === target) { return -1; } @@ -26595,12 +26465,15 @@ var ts; target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } + var kind = target.declaration ? target.declaration.kind : 0; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 152 && + kind !== 151 && kind !== 153; var result = -1; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { var targetThisType = getThisTypeOfSignature(target); if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType, false) + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, false) || compareTypes(targetThisType, sourceThisType, reportErrors); if (!related) { if (reportErrors) { @@ -26619,16 +26492,16 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); + (getFalsyFlags(sourceType) & 12288) === (getFalsyFlags(targetType) & 12288); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); } return 0; } @@ -26652,7 +26525,7 @@ var ts; } } else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + result &= callbackCheck === 1 && compareTypes(targetReturnType, sourceReturnType, false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -26726,10 +26599,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 ? true : - type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 65536 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 33554432 ? true : + type.flags & 131072 ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 262144 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -26752,7 +26625,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); } enumRelation.set(id, false); return false; @@ -26765,11 +26638,11 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 8192) - return false; - if (t & 1 || s & 8192) + if (t & 1 || s & 16384) return true; - if (s & 262178 && t & 2) + if (t & 16384) + return false; + if (s & 524322 && t & 2) return true; if (s & 32 && s & 256 && t & 32 && !(t & 256) && @@ -26783,22 +26656,26 @@ var ts; return true; if (s & 136 && t & 8) return true; + if (s & 1536 && t & 512) + return true; if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 256 && t & 256) { - if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 131072 && t & 131072 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 224 && t & 224 && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) + if (s & 4096 && (!strictNullChecks || t & (4096 | 2048))) return true; - if (s & 4096 && (!strictNullChecks || t & 4096)) + if (s & 8192 && (!strictNullChecks || t & 8192)) return true; - if (s & 32768 && t & 16777216) + if (s & 65536 && t & 33554432) return true; + if (s & 1024 || t & 1024) + return false; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1) return true; @@ -26808,22 +26685,24 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 1048576) { + if (source.flags & 96 && source.flags & 2097152) { source = source.regularType; } - if (target.flags & 96 && target.flags & 1048576) { + if (target.flags & 96 && target.flags & 2097152) { target = target.regularType; } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + if (source === target || + relation === comparableRelation && !(target.flags & 16384) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 32768 && target.flags & 32768) { + if (source.flags & 65536 && target.flags & 65536) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1; } } - if (source.flags & 1032192 || target.flags & 1032192) { + if (source.flags & 2064384 || target.flags & 2064384) { return checkTypeRelatedTo(source, target, relation, undefined); } return false; @@ -26835,13 +26714,6 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var ExpandingFlags; - (function (ExpandingFlags) { - ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; - ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; - ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; - ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; - })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0; var overflow = false; var isIntersectionConstituent = false; @@ -26892,13 +26764,13 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608)) { + if (!(type.flags & 393216)) { return false; } var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6144) { + if (t.flags & 12288) { continue; } if (seenNonNullable) { @@ -26909,10 +26781,10 @@ var ts; return false; } function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 && source.flags & 1048576) { + if (source.flags & 96 && source.flags & 2097152) { source = source.regularType; } - if (target.flags & 96 && target.flags & 1048576) { + if (target.flags & 96 && target.flags & 2097152) { target = target.regularType; } if (source === target) @@ -26920,9 +26792,10 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + if (relation === comparableRelation && !(target.flags & 16384) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - if (getObjectFlags(source) & 128 && source.flags & 1048576) { + if (isObjectLiteralType(source) && source.flags & 2097152) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -26934,13 +26807,11 @@ var ts; } } if (relation !== comparableRelation && - !(source.flags & 196608) && - !(target.flags & 65536) && + !(source.flags & 393216) && + !(target.flags & 131072) && !isIntersectionConstituent && source !== globalObjectType && - (getPropertiesOfType(source).length > 0 || - getSignaturesOfType(source, 0).length > 0 || - getSignaturesOfType(source, 1).length > 0) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { @@ -26960,23 +26831,23 @@ var ts; var saveErrorInfo = errorInfo; var saveIsIntersectionConstituent = isIntersectionConstituent; isIntersectionConstituent = false; - if (source.flags & 65536) { + if (source.flags & 131072) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382)); } else { - if (target.flags & 65536) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190)); + if (target.flags & 131072) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382) && !(target.flags & 16382)); } - else if (target.flags & 131072) { + else if (target.flags & 262144) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 131072) { + else if (source.flags & 262144) { result = someTypeRelatedToType(source, target, false); } - if (!result && (source.flags & 1032192 || target.flags & 1032192)) { + if (!result && (source.flags & 2064384 || target.flags & 2064384)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } @@ -26984,10 +26855,10 @@ var ts; } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 32768 && target.flags & 8190) { + if (source.flags & 65536 && target.flags & 16382) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 32768 && globalObjectType === source) { + else if (source.symbol && source.flags & 65536 && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -26996,11 +26867,11 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 32768 && target.flags & 32768) { + if (source.flags & 65536 && target.flags & 65536) { return recursiveTypeRelatedTo(source, target, false); } - if (source.flags & 65536 && target.flags & 65536 || - source.flags & 131072 && target.flags & 131072) { + if (source.flags & 131072 && target.flags & 131072 || + source.flags & 262144 && target.flags & 262144) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; @@ -27010,12 +26881,18 @@ var ts; return 0; } function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { - var isComparingJsxAttributes = !!(source.flags & 33554432); + if (maybeTypeOfKind(target, 65536) && !(ts.getObjectFlags(target) & 512)) { + var isComparingJsxAttributes = !!(source.flags & 67108864); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 131072) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -27035,7 +26912,7 @@ var ts; } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); } else { reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); @@ -27069,7 +26946,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 65536 && containsType(targetTypes, source)) { + if (target.flags & 131072 && containsType(targetTypes, source)) { return -1; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -27086,22 +26963,30 @@ var ts; return 0; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { + var sourceProperty = sourcePropertiesFiltered_1[_i]; var sourceType = getTypeOfSymbol(sourceProperty); for (var _a = 0, _b = target.types; _a < _b.length; _a++) { var type = _b[_a]; var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); if (targetType && isRelatedTo(sourceType, targetType)) { - return type; + if (type === match) + continue; + if (match) { + return undefined; + } + match = type; } } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; @@ -27118,7 +27003,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 65536 && containsType(sourceTypes, target)) { + if (source.flags & 131072 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; @@ -27143,7 +27028,7 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, reportErrors) { + function typeArgumentsRelatedTo(source, target, variances, reportErrors) { var sources = source.typeArguments || ts.emptyArray; var targets = target.typeArguments || ts.emptyArray; if (sources.length !== targets.length && relation === identityRelation) { @@ -27152,11 +27037,34 @@ var ts; var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1; for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0; + var variance = i < variances.length ? variances[i] : 1; + if (variance !== 4) { + var s = sources[i]; + var t = targets[i]; + var related = -1; + if (variance === 1) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3) { + related = isRelatedTo(t, s, false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0; + } + result &= related; } - result &= related; } return result; } @@ -27220,9 +27128,10 @@ var ts; } function structuredTypeRelatedTo(source, target, reportErrors) { var result; + var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 16384) { - if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (target.flags & 32768) { + if (ts.getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -27232,8 +27141,8 @@ var ts; } } } - else if (target.flags & 262144) { - if (source.flags & 262144) { + else if (target.flags & 524288) { + if (source.flags & 524288) { if (result = isRelatedTo(target.type, source.type, false)) { return result; } @@ -27245,7 +27154,7 @@ var ts; } } } - else if (target.flags & 524288) { + else if (target.flags & 1048576) { var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -27254,31 +27163,28 @@ var ts; } } } - if (source.flags & 16384) { - if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + else if (isGenericMappedType(target) && !isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + if (source.flags & 32768) { + var constraint = getConstraintOfTypeParameter(source); + if (constraint || !(target.flags & 33554432)) { + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; } } - else { - var constraint = getConstraintOfTypeParameter(source); - if (constraint || !(target.flags & 16777216)) { - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; - } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } } - else if (source.flags & 524288) { + else if (source.flags & 1048576) { var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -27286,23 +27192,33 @@ var ts; return result; } } - else if (target.flags & 524288 && source.indexType === target.indexType) { + else if (target.flags & 1048576 && source.indexType === target.indexType) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } else { - if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && + !(source.flags & 134217728 || target.flags & 134217728)) { + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { return result; } + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + if (!(reportErrors && ts.some(variances, function (v) { return v === 0; }))) { + return 0; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } } - var sourceIsPrimitive = !!(source.flags & 8190); + var sourceIsPrimitive = !!(source.flags & 16382); if (relation !== identityRelation) { source = getApparentType(source); } - if (source.flags & (32768 | 131072) && target.flags & 32768) { + if (source.flags & (65536 | 262144) && target.flags & 65536) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { result = -1; @@ -27326,26 +27242,25 @@ var ts; } } if (result) { - errorInfo = saveErrorInfo; - return result; + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; } } } return 0; } function mappedTypeRelatedTo(source, target, reportErrors) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + !(getCombinedMappedTypeModifiers(source) & 2) || + getCombinedMappedTypeModifiers(target) & 2); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_1; + if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -27354,7 +27269,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -27362,10 +27277,24 @@ var ts; } return 0; } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0; + } + } + } + } var result = -1; var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { + var targetProp = properties_3[_b]; if (!(targetProp.flags & 4194304)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -27424,20 +27353,20 @@ var ts; return result; } function isWeakType(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); } - if (type.flags & 131072) { + if (type.flags & 262144) { return ts.every(type.types, isWeakType); } return false; } function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(source.flags & 33554432); + var isComparingJsxAttributes = !!(source.flags & 67108864); for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { @@ -27447,7 +27376,7 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 && target.flags & 32768)) { + if (!(source.flags & 65536 && target.flags & 65536)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -27456,8 +27385,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0; @@ -27480,7 +27409,7 @@ var ts; var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); if (kind === 1 && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { if (reportErrors) { reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); } @@ -27492,7 +27421,7 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + if (ts.getObjectFlags(source) & 64 && ts.getObjectFlags(target) & 64 && source.symbol === target.symbol) { for (var i = 0; i < targetSignatures.length; i++) { var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], true, reportErrors); if (!related) { @@ -27528,7 +27457,7 @@ var ts; return result; } function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -27586,7 +27515,7 @@ var ts; if (isGenericMappedType(source)) { return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1; if (kind === 0) { var sourceNumberInfo = getIndexInfoOfType(source, 1); @@ -27636,11 +27565,53 @@ var ts; return false; } } + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.flags |= 134217728; + return result; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + var typeParameters = type.typeParameters || ts.emptyArray; + var variances = type.variances; + if (!variances) { + if (type === globalArrayType || type === globalReadonlyArrayType) { + variances = [1]; + } + else { + type.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); + var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 : 0); + if (variance === 3 && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { + variance = 4; + } + variances.push(variance); + } + } + type.variances = variances; + } + return variances; + } + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 && type.typeArguments[i].flags & 2048) { + return true; + } + } + return false; + } function isUnconstrainedTypeParameter(type) { - return type.flags & 16384 && !getConstraintFromTypeParameter(type); + return type.flags & 32768 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return ts.getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } function getTypeReferenceId(type, typeParameters, depth) { if (depth === void 0) { depth = 0; } @@ -27707,26 +27678,14 @@ var ts; return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.hasModifier(declaration, 128)) { - return true; - } - } - } - return false; - } function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 32768) { + if (depth >= 5 && type.flags & 65536) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 32768 && t.symbol === symbol) { + if (t.flags & 65536 && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -27844,27 +27803,34 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288) : getUnionType(types, true); } + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } function isArrayType(type) { - return getObjectFlags(type) & 4 && type.target === globalArrayType; + return ts.getObjectFlags(type) & 4 && type.target === globalArrayType; } function isArrayLikeType(type) { - return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 12288) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return !!(type.flags & 6368); + return !!(type.flags & 13536); } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 131072 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -27872,19 +27838,30 @@ var ts; type.flags & 32 ? stringType : type.flags & 64 ? numberType : type.flags & 128 ? booleanType : - type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 32 && type.flags & 2097152 ? stringType : + type.flags & 64 && type.flags & 2097152 ? numberType : type.flags & 128 ? booleanType : - type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 1024 ? esSymbolType : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } function isTupleType(type) { - return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); + return !!(ts.getObjectFlags(type) & 4 && type.target.objectFlags & 8); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -27895,15 +27872,15 @@ var ts; return result; } function getFalsyFlags(type) { - return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 131072 ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 ? type.value === "" ? 32 : 0 : type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; + type.flags & 14574; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : + return getFalsyFlags(type) & 14560 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 14560); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -27913,25 +27890,28 @@ var ts; return type.flags & 2 ? emptyStringType : type.flags & 4 ? zeroType : type.flags & 8 || type === falseType ? falseType : - type.flags & (1024 | 2048 | 4096) || + type.flags & (2048 | 4096 | 8192) || type.flags & 32 && type.value === "" || type.flags & 64 && type.value === 0 ? type : neverType; } function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (2048 | 4096); + var missing = (flags & ~type.flags) & (4096 | 8192); return missing === 0 ? type : - missing === 2048 ? getUnionType([type, undefinedType]) : - missing === 4096 ? getUnionType([type, nullType]) : + missing === 4096 ? getUnionType([type, undefinedType]) : + missing === 8192 ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 4096 ? type : getUnionType([type, undefinedType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && - getSignaturesOfType(type, 0).length === 0 && - getSignaturesOfType(type, 1).length === 0; + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && + !typeHasCallOrConstructSignatures(type); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName); @@ -27955,7 +27935,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { + if (!(isObjectLiteralType(type) && type.flags & 2097152)) { return type; } var regularType = type.regularType; @@ -27965,39 +27945,97 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; + regularNew.flags = resolved.flags & ~2097152; regularNew.objectFlags |= 128; type.regularType = regularNew; return regularNew; } - function getWidenedProperty(prop) { + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertyNamesOfContext(context) { + if (!context.resolvedPropertyNames) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, true); + } + } + } + context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + } + return context.resolvedPropertyNames; + } + function getWidenedProperty(prop, context) { var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); + var propContext = context && createWideningContext(context, prop.escapedName, undefined); + var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getWidenedTypeOfObjectLiteral(type) { + function getUndefinedProperty(name) { + var cached = undefinedProperties.get(name); + if (cached) { + return cached; + } + var result = createSymbol(4 | 16777216, name); + result.type = undefinedType; + undefinedProperties.set(name, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; - members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop) : prop); + members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop, context) : prop); + } + if (context) { + for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { + var name = _c[_b]; + if (!members.has(name)) { + members.set(name, getUndefinedProperty(name)); + } + } } var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } - function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); - } function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 6144) { + return getWidenedTypeWithContext(type, undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 12582912) { + if (type.flags & 12288) { return anyType; } - if (getObjectFlags(type) & 128) { - return getWidenedTypeOfObjectLiteral(type); + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 65536) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + if (type.flags & 131072) { + var unionContext_1 = context || createWideningContext(undefined, undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 ? t : getWidenedTypeWithContext(t, unionContext_1); }); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -28007,31 +28045,38 @@ var ts; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 65536) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { + if (type.flags & 4194304) { + if (type.flags & 131072) { + if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } } } - } - if (getObjectFlags(type) & 128) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 4194304) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.symbolName(p), typeToString(getWidenedType(t))); + } + errorReported = true; } - errorReported = true; } } } @@ -28041,25 +28086,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 150: case 149: - case 148: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 146: + case 147: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 176: + case 177: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 228: + case 229: + case 152: case 151: - case 150: - case 153: case 154: - case 186: + case 155: case 187: + case 188: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -28072,7 +28117,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { + if (produceDiagnostics && noImplicitAny && type.flags & 4194304) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -28137,12 +28182,12 @@ var ts; }; } function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & (540672 | 262144) || + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & (1081344 | 524288) || objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || objectFlags & 32 || - type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 393216 && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -28151,9 +28196,27 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 393216 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypeForHomomorphicMappedType(source, target) { + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 32)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4, name); + literalProp.type = emptyObjectType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 2 ? createIndexInfo(emptyObjectType, false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { var properties = getPropertiesOfType(source); var indexInfo = getIndexInfoOfType(source, 0); if (properties.length === 0 && !indexInfo) { @@ -28168,32 +28231,28 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); - if (!inferredPropType) { + var propType = getTypeOfSymbol(prop); + if (propType.flags & 16777216) { return undefined; } - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; + inferredProp.type = inferTargetType(propType); members.set(prop.escapedName, inferredProp); } if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); } return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); function inferTargetType(sourceType) { inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType); - return inference.candidates && getUnionType(inference.candidates, true); + inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); + return inference.candidates ? getUnionType(inference.candidates, true) : emptyObjectType; } } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = getPropertiesOfObjectType(target); + var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; if (requireOptionalProperties || !(targetProp.flags & 16777216)) { @@ -28205,7 +28264,7 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; @@ -28222,8 +28281,8 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || - source.flags & 131072 && target.flags & 131072) { + if (source.flags & 131072 && target.flags & 131072 && !(source.flags & 256 && target.flags & 256) || + source.flags & 262144 && target.flags & 262144) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -28250,43 +28309,58 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 540672) { - if (source.flags & 8388608 || source === silentNeverType) { + if (target.flags & 1081344) { + if (source.flags & 16777216 || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - if (!inference.candidates || priority < inference.priority) { + var p = priority | (source === implicitNeverType ? 16 : 0); + if (!inference.candidates || p < inference.priority) { inference.candidates = [source]; - inference.priority = priority; + inference.priority = p; } - else if (priority === inference.priority) { + else if (p === inference.priority) { inference.candidates.push(source); } - if (!(priority & 4) && target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(p & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + else if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); + if (i < variances.length && variances[i] === 2) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } } } - else if (source.flags & 262144 && target.flags & 262144) { + else if (source.flags & 524288 && target.flags & 524288) { + priority ^= 1; inferFromTypes(source.type, target.type); + priority ^= 1; } - else if (source.flags & 524288 && target.flags & 524288) { + else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + priority ^= 1; + inferFromTypes(empty, target.type); + priority ^= 1; + } + else if (source.flags & 1048576 && target.flags & 1048576) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (target.flags & 196608) { + else if (target.flags & 393216) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -28302,12 +28376,12 @@ var ts; } if (typeVariableCount === 1) { var savePriority = priority; - priority |= 1; + priority |= 2; inferFromTypes(source, typeVariable); priority = savePriority; } } - else if (source.flags & 65536) { + else if (source.flags & 131072) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -28316,14 +28390,14 @@ var ts; } else { source = getApparentType(source); - if (source.flags & (32768 | 131072)) { + if (source.flags & (65536 | 262144)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; } (visited || (visited = ts.createMap())).set(key, true); - var isNonConstructorObject = target.flags & 32768 && - !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var isNonConstructorObject = target.flags & 65536 && + !(ts.getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (ts.contains(symbolStack, symbol)) { @@ -28339,8 +28413,18 @@ var ts; } } } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes) { + priority ^= 1; + inferFromTypes(source, target); + priority ^= 1; + } + else { + inferFromTypes(source, target); + } + } function getInferenceInfoForType(type) { - if (type.flags & 540672) { + if (type.flags & 1081344) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -28355,22 +28439,28 @@ var ts; inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); } - if (getObjectFlags(target) & 32) { + if (ts.getObjectFlags(target) & 32) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144) { + if (constraintType.flags & 524288) { var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); + var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); + if (ts.contains(mappedTypeStack, key)) { + return; + } + (mappedTypeStack || (mappedTypeStack = [])).push(key); + var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); + mappedTypeStack.pop(); if (inferredType) { var savePriority = priority; - priority |= 2; + priority |= 4; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } } return; } - if (constraintType.flags & 16384) { + if (constraintType.flags & 32768) { inferFromTypes(getIndexType(source), constraintType); inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; @@ -28400,11 +28490,11 @@ var ts; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); } } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromContravariantTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -28449,25 +28539,40 @@ var ts; reducedTypes.push(t); } } - return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 131072 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 | 262144); + return constraint && maybeTypeOfKind(constraint, 16382 | 524288); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, true)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; } function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; if (!inferredType) { if (inference.candidates) { + var candidates = widenObjectLiteralCandidates(inference.candidates); var signature = context.signature; var widenLiteralTypes = inference.topLevel && !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; - var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? - getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unionOrSuperType); + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var unwidenedType = inference.priority & 1 ? getCommonSubtype(baseCandidates) : + context.flags & 1 || inference.priority & 8 ? getUnionType(baseCandidates, true) : + getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unwidenedType); } else if (context.flags & 2) { inferredType = silentNeverType; @@ -28481,12 +28586,13 @@ var ts; inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); } } + inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); } } } @@ -28511,7 +28617,7 @@ var ts; return links.resolvedSymbol; } function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 163 ? true : n.kind === 71 || n.kind === 144 ? false : "quit"; }); } function getFlowCacheKey(node) { if (node.kind === 71) { @@ -28521,13 +28627,13 @@ var ts; if (node.kind === 99) { return "0"; } - if (node.kind === 179) { + if (node.kind === 180) { var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + return key && key + "." + ts.idText(node.name); } - if (node.kind === 176) { + if (node.kind === 177) { var container = node.parent.parent; - var key = container.kind === 176 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 177 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -28535,12 +28641,12 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 174) { + if (element.parent.kind === 175) { var name = element.propertyName || element.name; switch (name.kind) { case 71: - return ts.unescapeLeadingUnderscores(name.escapedText); - case 144: + return ts.idText(name); + case 145: return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9: case 8: @@ -28557,26 +28663,26 @@ var ts; switch (source.kind) { case 71: return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 || target.kind === 176) && + (target.kind === 227 || target.kind === 177) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99: return target.kind === 99; case 97: return target.kind === 97; - case 179: - return target.kind === 179 && + case 180: + return target.kind === 180 && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 176: - if (target.kind !== 179) + case 177: + if (target.kind !== 180) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 176 && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 177 && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 226) { + if (source.parent.parent.kind === 227) { var maybeId = source.parent.parent.initializer; return maybeId && isMatchingReference(maybeId, t.expression); } @@ -28584,7 +28690,7 @@ var ts; return false; } function containsMatchingReference(source, target) { - while (source.kind === 179) { + while (source.kind === 180) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -28593,7 +28699,7 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 && + return target.kind === 180 && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -28601,14 +28707,14 @@ var ts; if (expr.kind === 71) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 179) { + if (expr.kind === 180) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536) { + if (type && type.flags & 131072) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { @@ -28619,6 +28725,20 @@ var ts; } return false; } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -28631,7 +28751,7 @@ var ts; } } } - if (callExpression.expression.kind === 179 && + if (callExpression.expression.kind === 180 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -28645,7 +28765,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536)) { + if (!(source.flags & 131072)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -28658,11 +28778,11 @@ var ts; } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 8192) { + if (assignedType.flags & 16384) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192)) { + if (!(reducedType.flags & 16384)) { return reducedType; } } @@ -28709,32 +28829,40 @@ var ts; type === falseType ? 3030404 : 1981828 : type === falseType ? 3145092 : 4193668; } - if (flags & 32768) { + if (flags & 65536) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 : 8376288 : strictNullChecks ? 6166480 : 8378320; } - if (flags & (1024 | 2048)) { + if (flags & (2048 | 4096)) { return 2457472; } - if (flags & 4096) { + if (flags & 8192) { return 2340752; } - if (flags & 512) { + if (flags & 1536) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 16777216) { + if (flags & 33554432) { return strictNullChecks ? 6166480 : 8378320; } - if (flags & 540672) { + if (flags & 1081344) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 196608) { + if (flags & 393216) { return getTypeFactsOfTypes(type.types); } return 8388607; } function getTypeWithFacts(type, include) { + if (type.flags & 1048576) { + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -28760,15 +28888,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 178 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 265 && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 && parent.parent.left === parent || - parent.parent.kind === 216 && parent.parent.initializer === parent; + return parent.parent.kind === 195 && parent.parent.left === parent || + parent.parent.kind === 217 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); @@ -28785,21 +28913,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 215: - return stringType; case 216: + return stringType; + case 217: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194: + case 195: return getAssignedTypeOfBinaryExpression(parent); - case 188: + case 189: return undefinedType; - case 177: + case 178: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198: + case 199: return getAssignedTypeOfSpreadExpression(parent); - case 261: + case 265: return getAssignedTypeOfPropertyAssignment(parent); - case 262: + case 266: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -28807,7 +28935,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 ? + var type = pattern.kind === 175 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : @@ -28822,35 +28950,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 215) { + if (node.parent.parent.kind === 216) { return stringType; } - if (node.parent.parent.kind === 216) { + if (node.parent.parent.kind === 217) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 226 ? + return node.kind === 227 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 226 || node.kind === 176 ? + return node.kind === 227 || node.kind === 177 ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 226 && node.initializer && + return node.kind === 227 && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 && node.parent.kind === 194 && + node.kind !== 177 && node.parent.kind === 195 && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 185: + case 186: return getReferenceCandidate(node.expression); - case 194: + case 195: switch (node.operatorToken.kind) { case 58: return getReferenceCandidate(node.left); @@ -28862,13 +28990,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 185 || - parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? + return parent.kind === 186 || + parent.kind === 195 && parent.operatorToken.kind === 58 && parent.left === node || + parent.kind === 195 && parent.operatorToken.kind === 26 && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 257) { + if (clause.kind === 261) { var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } @@ -28890,13 +29018,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 131072 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 131072 && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536) { + if (source.flags & 131072) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -28911,10 +29039,10 @@ var ts; return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + return type.flags & 131072 ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 65536) { + if (type.flags & 131072) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); @@ -28922,7 +29050,7 @@ var ts; return f(type) ? type : neverType; } function mapType(type, mapper) { - if (!(type.flags & 65536)) { + if (!(type.flags & 131072)) { return mapper(type); } var types = type.types; @@ -28981,9 +29109,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 8192 ? + return elementType.flags & 16384 ? autoArrayType : - createArrayType(elementType.flags & 65536 ? + createArrayType(elementType.flags & 131072 ? getUnionType(elementType.types, true) : elementType); } @@ -28991,17 +29119,17 @@ var ts; return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); } function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + return ts.getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; } function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? type.elementType : neverType; + return ts.getObjectFlags(type) & 256 ? type.elementType : neverType; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var t = types_15[_i]; - if (!(t.flags & 8192)) { - if (!(getObjectFlags(t) & 256)) { + if (!(t.flags & 16384)) { + if (!(ts.getObjectFlags(t) & 256)) { return false; } hasEvolvingArrayType = true; @@ -29017,11 +29145,11 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.escapedText === "length" || - parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 && + var isLengthPushOrUnshift = parent.kind === 180 && (parent.name.escapedText === "length" || + parent.parent.kind === 182 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 181 && parent.expression === root && - parent.parent.kind === 194 && + parent.parent.kind === 195 && parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -29061,14 +29189,14 @@ var ts; if (flowAnalysisDisabled) { return unknownType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 35620607)) { return declaredType; } var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); sharedFlowCount = sharedFlowStart; - var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { + var resultType = ts.getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 204 && getTypeWithFacts(resultType, 524288).flags & 16384) { return declaredType; } return resultType; @@ -29130,7 +29258,7 @@ var ts; } else if (flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { + if (container && container !== flowContainer && reference.kind !== 180 && reference.kind !== 99) { flow = container.flowNode; continue; } @@ -29162,7 +29290,7 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 65536) { + if (declaredType.flags & 131072) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; @@ -29175,15 +29303,15 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 181 ? + var expr = node.kind === 182 ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { + if (ts.getObjectFlags(type) & 256) { var evolvedType_1 = type; - if (node.kind === 181) { + if (node.kind === 182) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -29205,7 +29333,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 8192) { + if (type.flags & 16384) { return flowType; } var assumeTrue = (flow.flags & 32) !== 0; @@ -29215,7 +29343,7 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 16384 ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -29307,8 +29435,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 179 && - computedType.flags & 65536 && + return expr.kind === 180 && + computedType.flags & 131072 && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -29341,10 +29469,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 && right_1.kind === 9) { + if (left_1.kind === 190 && right_1.kind === 9) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 189 && left_1.kind === 9) { + if (right_1.kind === 190 && left_1.kind === 9) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -29378,7 +29506,7 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144) { + if (valueType.flags & 12288) { if (!strictNullChecks) { return type; } @@ -29390,12 +29518,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 16810497) { + if (type.flags & 33620481) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 16384 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29414,13 +29542,13 @@ var ts; if (operator === 33 || operator === 35) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 65536)) { + if (assumeTrue && !(type.flags & 131072)) { var targetType = typeofTypesByName.get(literal.text); if (targetType) { if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 540672) { + if (type.flags & 1081344) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -29441,13 +29569,13 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : + var caseType = discriminantType.flags & 16384 ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 16384 ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); @@ -29474,10 +29602,10 @@ var ts; } if (!targetType) { var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2) { + if (ts.getObjectFlags(rightType) & 2) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (getObjectFlags(rightType) & 16) { + else if (ts.getObjectFlags(rightType) & 16) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -29485,7 +29613,7 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } return type; } @@ -29493,9 +29621,9 @@ var ts; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 65536) { + if (type.flags & 131072) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192)) { + if (!(assignableType.flags & 16384)) { return assignableType; } } @@ -29529,7 +29657,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { + if (invokedExpression.kind === 181 || invokedExpression.kind === 180) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -29547,15 +29675,15 @@ var ts; case 71: case 99: case 97: - case 179: + case 180: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181: + case 182: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185: + case 186: return narrowType(type, expr.expression, assumeTrue); - case 194: + case 195: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192: + case 193: if (expr.operator === 51) { return narrowType(type, expr.operand, !assumeTrue); } @@ -29570,7 +29698,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -29582,9 +29710,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 || - node.kind === 265 || - node.kind === 149; + node.kind === 235 || + node.kind === 269 || + node.kind === 150; }); } function isParameterAssigned(symbol) { @@ -29605,7 +29733,7 @@ var ts; if (node.kind === 71) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 147) { symbol.isAssigned = true; } } @@ -29619,20 +29747,20 @@ var ts; } function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 && + declaration.kind === 147 && declaration.initializer && - getFalsyFlags(declaredType) & 2048 && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); + getFalsyFlags(declaredType) & 4096 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } function isApparentTypePosition(node) { var parent = node.parent; - return parent.kind === 179 || - parent.kind === 181 && parent.expression === node || - parent.kind === 180 && parent.expression === node; + return parent.kind === 180 || + parent.kind === 182 && parent.expression === node || + parent.kind === 181 && parent.expression === node; } function typeHasNullableConstraint(type) { - return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + return type.flags & 1081344 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } function getDeclaredOrApparentType(symbol, node) { var type = getTypeOfSymbol(symbol); @@ -29649,7 +29777,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 187) { + if (container.kind === 188) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256)) { @@ -29665,7 +29793,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32) { - if (declaration.kind === 229 + if (declaration.kind === 230 && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -29677,11 +29805,11 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 199) { + else if (declaration.kind === 200) { var container = ts.getThisContainer(node, false); while (container !== undefined) { if (container.parent === declaration) { - if (container.kind === 149 && ts.hasModifier(container, 32)) { + if (container.kind === 150 && ts.hasModifier(container, 32)) { getNodeLinks(declaration).flags |= 8388608; getNodeLinks(node).flags |= 16777216; } @@ -29722,22 +29850,24 @@ var ts; if (!declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 146; + var isParameter = ts.getRootDeclaration(declaration).kind === 147; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || - flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 187 || + flowContainer.kind === 188 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } var assumeInitialized = isParameter || isAlias || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || - node.parent.kind === 203 || - ts.isInAmbientContext(declaration); + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || + isInTypeQuery(node) || node.parent.kind === 247) || + node.parent.kind === 204 || + declaration.kind === 227 && declaration.exclamationToken || + declaration.flags & 2097152; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048); + getOptionalType(type); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { @@ -29748,7 +29878,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 4096) && getFalsyFlags(flowType) & 4096) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -29760,7 +29890,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 260) { + symbol.valueDeclaration.parent.kind === 264) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -29778,8 +29908,8 @@ var ts; if (usedInFunction) { getNodeLinks(current).flags |= 65536; } - if (container.kind === 214 && - ts.getAncestor(symbol.valueDeclaration, 227).parent === container && + if (container.kind === 215 && + ts.getAncestor(symbol.valueDeclaration, 228).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152; } @@ -29791,14 +29921,14 @@ var ts; } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 185) { + while (current.parent.kind === 186) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 192 || current.parent.kind === 193)) { + else if ((current.parent.kind === 193 || current.parent.kind === 194)) { var expr = current.parent; isAssigned = expr.operator === 43 || expr.operator === 44; } @@ -29809,7 +29939,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 149 || container.kind === 152) { + if (container.kind === 150 || container.kind === 153) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -29853,32 +29983,32 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 152) { + if (container.kind === 153) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 187) { + if (container.kind === 188) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 233: + case 234: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 232: + case 233: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 152: + case 153: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; + case 150: case 149: - case 148: if (ts.hasModifier(container, 32)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 144: + case 145: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -29887,8 +30017,8 @@ var ts; } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 186 && - container.parent.kind === 194 && + if (container.kind === 187 && + container.parent.kind === 195 && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { var className = container.parent .left @@ -29922,7 +30052,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 273) { + if (jsdocType && jsdocType.kind === 277) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -29932,14 +30062,14 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 147; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 182 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 187) { + while (container && container.kind === 188) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -29947,14 +30077,14 @@ var ts; var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); - if (current && current.kind === 144) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 145; }); + if (current && current.kind === 145) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 179)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -29962,7 +30092,7 @@ var ts; } return unknownType; } - if (!isCallExpression && container.kind === 152) { + if (!isCallExpression && container.kind === 153) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32) || isCallExpression) { @@ -29972,7 +30102,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.hasModifier(container, 256)) { + if (container.kind === 152 && ts.hasModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -29983,7 +30113,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 178) { + if (container.parent.kind === 179) { if (languageVersion < 2) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -29993,15 +30123,16 @@ var ts; } } var classLikeDeclaration = container.parent; + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return unknownType; + } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } return unknownType; } - if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 153 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -30013,24 +30144,24 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 152; + return container.kind === 153; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 178) { + if (ts.isClassLike(container.parent) || container.parent.kind === 179) { if (ts.hasModifier(container, 32)) { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154; + return container.kind === 152 || + container.kind === 151 || + container.kind === 154 || + container.kind === 155; } else { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || + return container.kind === 152 || + container.kind === 151 || container.kind === 154 || + container.kind === 155 || + container.kind === 150 || container.kind === 149 || - container.kind === 148 || - container.kind === 152; + container.kind === 153; } } } @@ -30038,22 +30169,22 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 151 || - func.kind === 153 || - func.kind === 154) && func.parent.kind === 178 ? func.parent : - func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : + return (func.kind === 152 || + func.kind === 154 || + func.kind === 155) && func.parent.kind === 179 ? func.parent : + func.kind === 187 && func.parent.kind === 265 ? func.parent.parent : undefined; } function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + return ts.getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 262144 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 187) { + if (func.kind === 188) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -30077,7 +30208,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 261) { + if (literal.parent.kind !== 265) { break; } literal = literal.parent.parent; @@ -30086,9 +30217,9 @@ var ts; return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } var parent = func.parent; - if (parent.kind === 194 && parent.operatorToken.kind === 58) { + if (parent.kind === 195 && parent.operatorToken.kind === 58) { var target = parent.left; - if (target.kind === 179 || target.kind === 180) { + if (target.kind === 180 || target.kind === 181) { var expression = target.expression; if (inJs && ts.isIdentifier(expression)) { var sourceFile = ts.getSourceFileOfNode(parent); @@ -30129,6 +30260,10 @@ var ts; var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); + indexOfParameter -= 1; + } if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -30143,12 +30278,12 @@ var ts; } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer) { + if (node === declaration.initializer || node.kind === 58) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 146) { + if (declaration.kind === 147) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -30160,7 +30295,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176) { + if (parentDeclaration.kind !== 177) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -30201,16 +30336,20 @@ var ts; return undefined; } function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 && node.parent.initializer === node) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { return true; } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } node = node.parent; } return false; } function getContextualReturnType(functionDecl) { - if (functionDecl.kind === 152 || + if (functionDecl.kind === 153 || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); @@ -30231,39 +30370,51 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183) { + if (template.parent.kind === 184) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (ts.isAssignmentOperator(operator)) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 58: + return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + case 54: + var type = getContextualType(binaryExpression); + return !type && node === right ? getTypeOfExpression(left, true) : type; + case 53: + case 26: + return node === right ? getContextualType(binaryExpression) : undefined; + case 34: + case 32: + case 35: + case 33: + return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; + default: return undefined; - } - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } - } - else if (operator === 54) { - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left, true); - } - return type; } - else if (operator === 53 || operator === 26) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } + } + function isContextSensitiveAssignment(binaryExpression) { + var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + switch (kind) { + case 0: + return true; + case 5: + return !binaryExpression.left.symbol; + case 1: + case 2: + case 3: + case 4: + return false; + default: + ts.Debug.assertNever(kind); } - return undefined; } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 458752 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -30271,11 +30422,11 @@ var ts; return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 131072 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return undefined; } return getContextualTypeForObjectLiteralElement(node); @@ -30284,9 +30435,9 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { - if (!ts.hasDynamicName(element)) { - var symbolName = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (!hasNonBindableDynamicName(element)) { + var symbolName_1 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); if (propertyType) { return propertyType; } @@ -30308,7 +30459,12 @@ var ts; function getContextualTypeForJsxExpression(node) { var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? node.parent.parent : - node.parent.openingElement.attributes; + ts.isJsxElement(node.parent) ? + node.parent.openingElement.attributes : + undefined; + if (!jsxAttributes) { + return undefined; + } var attributesType = getContextualType(jsxAttributes); if (!attributesType || isTypeAny(attributesType)) { return undefined; @@ -30316,7 +30472,7 @@ var ts; if (ts.isJsxAttribute(node.parent)) { return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } - else if (node.parent.kind === 249) { + else if (node.parent.kind === 250) { var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } @@ -30337,11 +30493,39 @@ var ts; } } function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (!(contextualType && contextualType.flags & 131072 && ts.isObjectLiteralExpression(node))) { + return contextualType; + } + var match; + propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (!prop.symbol) + continue; + if (prop.kind !== 265) + continue; + if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = getTypeOfNode(prop.initializer); + for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); + if (targetType && checkTypeAssignableTo(discriminatingType, targetType, undefined)) { + if (match) { + if (type === match) + continue; + match = undefined; + break propLoop; + } + match = type; + } + } + } + } + return match || contextualType; } function getContextualType(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return undefined; } if (node.contextualType) { @@ -30349,52 +30533,61 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 226: - case 146: + case 227: + case 147: + case 150: case 149: - case 148: - case 176: + case 177: return getContextualTypeForInitializerExpression(node); - case 187: - case 219: + case 188: + case 220: return getContextualTypeForReturnExpression(node); - case 197: + case 198: return getContextualTypeForYieldOperand(parent); - case 181: + case 183: + if (node.kind === 94) { + return getContextualType(parent); + } case 182: return getContextualTypeForArgument(parent, node); - case 184: - case 202: + case 185: + case 203: return getTypeFromTypeNode(parent.type); - case 194: + case 195: return getContextualTypeForBinaryOperand(node); - case 261: - case 262: + case 265: + case 266: return getContextualTypeForObjectLiteralElement(parent); - case 263: + case 267: return getApparentTypeOfContextualType(parent.parent); - case 177: { + case 178: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 195: + case 196: return getContextualTypeForConditionalOperand(node); - case 205: - ts.Debug.assert(parent.parent.kind === 196); + case 206: + ts.Debug.assert(parent.parent.kind === 197); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: { + case 186: { var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 256: + case 260: return getContextualTypeForJsxExpression(parent); - case 253: - case 255: + case 257: + case 259: return getContextualTypeForJsxAttribute(parent); + case 252: case 251: - case 250: return getAttributesTypeFromJsxOpeningLikeElement(parent); + case 261: { + if (node.kind === 73) { + var switchStatement = parent.parent.parent; + return getTypeOfExpression(switchStatement.expression); + } + } } return undefined; } @@ -30426,7 +30619,7 @@ var ts; return sourceLength < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 || node.kind === 187; + return node.kind === 187 || node.kind === 188; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -30439,12 +30632,12 @@ var ts; getApparentTypeOfContextualType(node); } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 65536)) { + if (!(type.flags & 131072)) { return getContextualCallSignature(type, node); } var signatureList; @@ -30480,8 +30673,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); } function hasDefaultValue(node) { - return (node.kind === 176 && !!node.initializer) || - (node.kind === 194 && node.operatorToken.kind === 58); + return (node.kind === 177 && !!node.initializer) || + (node.kind === 195 && node.operatorToken.kind === 58); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; @@ -30491,7 +30684,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elements.length; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 198) { + if (inDestructuringPattern && e.kind === 199) { var restArrayType = checkExpression(e.expression, checkMode); var restElementType = getIndexTypeOfType(restArrayType, 1) || getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); @@ -30504,7 +30697,7 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 198; + hasSpreadElement = hasSpreadElement || e.kind === 199; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -30512,18 +30705,17 @@ var ts; type.pattern = node; return type; } - var contextualType_1 = getApparentTypeOfContextualType(node); - if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { - var pattern = contextualType_1.pattern; - if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + if (pattern && (pattern.kind === 176 || pattern.kind === 178)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType_1.typeArguments[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 200) { + if (patternElement.kind !== 201) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -30537,11 +30729,11 @@ var ts; } return createArrayType(elementTypes.length ? getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); + strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 144: + case 145: return isNumericComputedName(name); case 71: return isNumericLiteralName(name.escapedText); @@ -30565,8 +30757,8 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (links.resolvedType.flags & 6144 || - !isTypeAssignableToKind(links.resolvedType, 262178 | 84 | 512) && + if (links.resolvedType.flags & 12288 || + !isTypeAssignableToKind(links.resolvedType, 524322 | 84 | 1536) && !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -30595,7 +30787,7 @@ var ts; var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); + (contextualType.pattern.kind === 175 || contextualType.pattern.kind === 179); var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); var typeFlags = 0; var patternWithComputedProperties = false; @@ -30605,18 +30797,18 @@ var ts; var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; - var member = memberDecl.symbol; + var member = getSymbolOfNode(memberDecl); var literalName = void 0; - if (memberDecl.kind === 261 || - memberDecl.kind === 262 || + if (memberDecl.kind === 265 || + memberDecl.kind === 266 || ts.isObjectLiteralMethod(memberDecl)) { var jsdocType = void 0; if (isInJSFile) { jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); } var type = void 0; - if (memberDecl.kind === 261) { - if (memberDecl.name.kind === 144) { + if (memberDecl.kind === 265) { + if (memberDecl.name.kind === 145) { var t = checkComputedPropertyName(memberDecl.name); if (t.flags & 224) { literalName = ts.escapeLeadingUnderscores("" + t.value); @@ -30624,11 +30816,11 @@ var ts; } type = checkPropertyAssignment(memberDecl, checkMode); } - else if (memberDecl.kind === 151) { + else if (memberDecl.kind === 152) { type = checkObjectLiteralMethod(memberDecl, checkMode); } else { - ts.Debug.assert(memberDecl.kind === 262); + ts.Debug.assert(memberDecl.kind === 266); type = checkExpressionForMutableLocation(memberDecl.name, checkMode); } if (jsdocType) { @@ -30636,10 +30828,13 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, literalName || member.escapedName); + var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; + var prop = nameType && isTypeUsableAsLateBoundName(nameType) + ? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) + : createSymbol(4 | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 265 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 266 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } @@ -30647,7 +30842,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.escapedName); if (impliedProp) { prop.flags |= impliedProp.flags & 16777216; @@ -30665,12 +30860,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 263) { + else if (memberDecl.kind === 267) { if (languageVersion < 2) { checkExternalEmitHelpers(memberDecl, 2); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -30682,15 +30877,15 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } else { - ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); + ts.Debug.assert(memberDecl.kind === 154 || memberDecl.kind === 155); checkNodeDeferred(memberDecl); } - if (!literalName && ts.hasDynamicName(memberDecl)) { + if (!literalName && hasNonBindableDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -30706,7 +30901,7 @@ var ts; if (contextualTypeHasPattern) { for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; - if (!propertiesTable.get(prop.escapedName)) { + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { if (!(prop.flags & 16777216)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -30717,13 +30912,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -30732,8 +30921,8 @@ var ts; var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 2097152; + result.flags |= 8388608 | freshObjectLiteralFlag | (typeFlags & 29360128); result.objectFlags |= 128; if (patternWithComputedProperties) { result.objectFlags |= 512; @@ -30741,24 +30930,24 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 6144)) { - propagatedFlags |= (result.flags & 14680064); + if (!(result.flags & 12288)) { + propagatedFlags |= (result.flags & 29360128); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 | 16777216) || - getFalsyFlags(type) & 7392 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 32768 && !isGenericMappedType(type) || - type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (1 | 33554432) || + getFalsyFlags(type) & 14560 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 65536 && !isGenericMappedType(type) || + type.flags & 393216 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); + checkJsxOpeningLikeElementOrOpeningFragment(node); return getJsxGlobalElementType() || anyType; } function checkJsxElement(node) { - checkJsxOpeningLikeElement(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); } @@ -30767,12 +30956,19 @@ var ts; } return getJsxGlobalElementType() || anyType; } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) { + error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + } + return getJsxGlobalElementType() || anyType; + } function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } function isJsxIntrinsicIdentifier(tagName) { switch (tagName.kind) { - case 179: + case 180: case 99: return false; case 71: @@ -30812,9 +31008,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 255); + ts.Debug.assert(attributeDecl.kind === 259); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -30823,7 +31019,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -30833,7 +31029,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); } attributesArray = getPropertiesOfType(spread); } @@ -30845,20 +31041,9 @@ var ts; } } } - var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 250 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { - var childrenTypes = []; - for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - if (child.kind === 10) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } + var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); @@ -30878,11 +31063,26 @@ var ts; typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 33554432 | 4194304; + result.flags |= 67108864 | 8388608; result.objectFlags |= 128; return result; } } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === 10) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + return childrenTypes; + } function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); } @@ -30910,7 +31110,7 @@ var ts; links.jsxFlags |= 2; return links.resolvedSymbol = intrinsicElementsType.symbol; } - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { @@ -30923,7 +31123,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536)); + ts.Debug.assert(!(valueType.flags & 131072)); if (isTypeAny(valueType)) { return anyType; } @@ -30985,7 +31185,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 131072) { + if (propsType.flags & 262144) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -30996,7 +31196,7 @@ var ts; return getApparentType(propsType); } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); + ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { @@ -31018,7 +31218,7 @@ var ts; return undefined; } function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); + ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { @@ -31062,7 +31262,7 @@ var ts; } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } - if (elementType.flags & 65536) { + if (elementType.flags & 131072) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); @@ -31074,8 +31274,8 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + var stringLiteralTypeName = elementType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); } @@ -31083,7 +31283,7 @@ var ts; if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); } return anyType; } @@ -31219,22 +31419,31 @@ var ts; } } } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace, true); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 107455, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = true; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { markAliasSymbolAsReferenced(reactSym); } } - checkJsxAttributesAssignableToTagNameAttributes(node); + if (isNodeOpeningLikeElement) { + checkJsxAttributesAssignableToTagNameAttributes(node); + } + else { + checkJsxChildren(node.parent); + } } function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 32768) { + if (targetType.flags & 65536) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -31243,7 +31452,7 @@ var ts; return true; } } - else if (targetType.flags & 196608) { + else if (targetType.flags & 393216) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -31269,7 +31478,7 @@ var ts; for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); break; } } @@ -31280,7 +31489,7 @@ var ts; if (node.expression) { var type = checkExpression(node.expression, checkMode); if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); } return type; } @@ -31289,7 +31498,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149; + return s.valueDeclaration ? s.valueDeclaration.kind : 150; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; @@ -31299,7 +31508,7 @@ var ts; } function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 || node.kind === 226 ? + var errorNode = node.kind === 180 || node.kind === 227 ? node.name : node.right; if (ts.getCheckFlags(prop) & 256) { @@ -31308,11 +31517,7 @@ var ts; } if (left.kind === 97) { if (languageVersion < 2) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 && propKind !== 150; - }); - if (hasNonMethodDeclaration) { + if (symbolHasNonMethodDeclaration(prop)) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -31322,11 +31527,18 @@ var ts; return false; } } + if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + return false; + } + } if (!(flags & 24)) { return true; } if (flags & 8) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; @@ -31347,27 +31559,33 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 16384 && type.isThisType) { - type = getConstraintOfTypeParameter(type); + if (type.flags & 32768) { + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } - if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { + if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; } + function symbolHasNonMethodDeclaration(symbol) { + return forEachProperty(symbol, function (prop) { + var propKind = getDeclarationKindFromSymbol(prop); + return propKind !== 152 && propKind !== 151; + }); + } function checkNonNullExpression(node) { return checkNonNullType(checkExpression(node), node); } function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288; if (kind) { - error(errorNode, kind & 2048 ? kind & 4096 ? + error(errorNode, kind & 4096 ? kind & 8192 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); var t = getNonNullableType(type); - return t.flags & (6144 | 8192) ? unknownType : t; + return t.flags & (12288 | 16384) ? unknownType : t; } return type; } @@ -31378,46 +31596,67 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + var propType; + var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; + var leftType = checkNonNullExpression(left); + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { return apparentType; } + var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0); - if (indexInfo && indexInfo.type) { - if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { - error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + if (!(indexInfo && indexInfo.type)) { + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 32768 && leftType.isThisType ? apparentType : leftType); } - return indexInfo.type; + return unknownType; } - if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); } - return unknownType; + propType = indexInfo.type; } - checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); - return unknownType; + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 99); + leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && + !(isNonLocalAlias(leftSymbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { + getSymbolLinks(leftSymbol).referenced = undefined; } + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + return unknownType; + } + } + propType = getDeclaredOrApparentType(prop, node); } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { + if (node.kind !== 180 || + assignmentKind === 1 || + prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 131072)) { + return propType; + } + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 99) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 153 && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 4096) && getFalsyFlags(flowType) & 4096) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); return propType; } - var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { @@ -31428,24 +31667,24 @@ var ts; if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); } - else if (valueDeclaration.kind === 229 && - node.parent.kind !== 159 && - !ts.isInAmbientContext(valueDeclaration) && + else if (valueDeclaration.kind === 230 && + node.parent.kind !== 160 && + !(valueDeclaration.flags & 2097152) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 149: + case 150: return true; - case 261: + case 265: return false; default: - return ts.isPartOfExpression(node) ? false : "quit"; + return ts.isExpressionNode(node) ? false : "quit"; } }); } @@ -31472,7 +31711,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + if (containingType.flags & 131072 && !(containingType.flags & 16382)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -31483,7 +31722,7 @@ var ts; } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -31491,76 +31730,104 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455); - return suggestion && suggestion.escapedName; + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455); + return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, undefined, name, false, function (symbols, name, meaning) { + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); - if (symbol) { - return symbol; - } - return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - if (result) { - return result.escapedName; - } + return result && ts.symbolName(result); } function getSpellingSuggestionForName(name, symbols, meaning) { - var worstDistance = name.length * 0.4; - var maximumLengthDifference = Math.min(3, name.length * 0.34); - var bestDistance = Number.MAX_VALUE; - var bestCandidate = undefined; + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; + var bestCandidate; var justCheckExactMatches = false; - if (name.length > 30) { - return undefined; - } - name = name.toLowerCase(); + var nameLowerCase = name.toLowerCase(); for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; - var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); - if (candidate.flags & meaning && - candidateName && - Math.abs(candidateName.length - name.length) < maximumLengthDifference) { - candidateName = candidateName.toLowerCase(); - if (candidateName === name) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3 || - name.length < 3 || - candidateName === "eval" || - candidateName === "intl" || - candidateName === "undefined" || - candidateName === "map" || - candidateName === "nan" || - candidateName === "set") { - continue; - } - var distance = ts.levenshtein(name, candidateName); - if (distance > worstDistance) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else if (distance < bestDistance) { - bestDistance = distance; - bestCandidate = candidate; - } + var candidateName = ts.symbolName(candidate); + if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + continue; + } + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + continue; + } + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + ts.Debug.assert(distance < bestDistance); + bestDistance = distance; + bestCandidate = candidate; } } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -31570,7 +31837,7 @@ var ts; } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 179 + var left = node.kind === 180 ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); @@ -31581,7 +31848,7 @@ var ts; if (prop) { return checkPropertyAccessibility(node, left, type, prop); } - if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + if (ts.isInJavaScriptFile(left) && (type.flags & 131072)) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var elementType = _a[_i]; if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { @@ -31595,7 +31862,7 @@ var ts; } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 227) { + if (initializer.kind === 228) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -31617,7 +31884,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 215 && + if (node.kind === 216 && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -31635,7 +31902,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 && node.parent.expression === node) { + if (node.parent.kind === 183 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -31664,7 +31931,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 512) === 0) { + if ((expressionType.flags & 1536) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -31694,10 +31961,10 @@ var ts; if (callLikeExpressionMayHaveTypeArguments(node)) { ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 183) { + if (node.kind === 184) { checkExpression(node.template); } - else if (node.kind !== 147) { + else if (node.kind !== 148) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -31748,7 +32015,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 198) { + if (arg && arg.kind === 199) { return i; } } @@ -31763,11 +32030,11 @@ var ts; if (ts.isJsxOpeningLikeElement(node)) { return true; } - if (node.kind === 183) { + if (node.kind === 184) { var tagExpression = node; argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 196) { + if (tagExpression.template.kind === 197) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -31779,14 +32046,14 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 147) { + else if (node.kind === 148) { typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); } else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 182); + ts.Debug.assert(callExpression.kind === 183); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -31802,7 +32069,8 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + return isRestParameterIndex(signature, spreadArgIndex) || + signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -31811,7 +32079,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -31826,7 +32094,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -31837,7 +32105,7 @@ var ts; inference.inferredType = undefined; } } - if (node.kind !== 147) { + if (node.kind !== 148) { var contextualType = getContextualType(node); if (contextualType) { var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); @@ -31846,7 +32114,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); } } var thisType = getThisTypeOfSignature(signature); @@ -31858,7 +32126,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { + if (arg === undefined || arg.kind !== 201) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { @@ -31879,29 +32147,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (!constraint) + continue; + var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return false; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { var callIsIncomplete = node.attributes.end === node.end; @@ -31925,7 +32191,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182) { + if (thisType && thisType !== voidType && node.kind !== 183) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -31938,7 +32204,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { + if (arg === undefined || arg.kind !== 201) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i) || checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); @@ -31952,28 +32218,28 @@ var ts; return true; } function getThisArgumentOfCall(node) { - if (node.kind === 181) { + if (node.kind === 182) { var callee = node.expression; - if (callee.kind === 179) { + if (callee.kind === 180) { return callee.expression; } - else if (callee.kind === 180) { + else if (callee.kind === 181) { return callee.expression; } } } function getEffectiveCallArguments(node) { - if (node.kind === 183) { + if (node.kind === 184) { var template = node.template; var args_4 = [undefined]; - if (template.kind === 196) { + if (template.kind === 197) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 147) { + else if (node.kind === 148) { return undefined; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -31984,21 +32250,21 @@ var ts; } } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147) { + if (node.kind === 148) { switch (node.parent.kind) { - case 229: - case 199: + case 230: + case 200: return 1; - case 149: + case 150: return 2; - case 151: - case 153: + case 152: case 154: + case 155: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 146: + case 147: return 3; } } @@ -32007,51 +32273,51 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 229) { + if (node.kind === 230) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 146) { + if (node.kind === 147) { node = node.parent; - if (node.kind === 152) { + if (node.kind === 153) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 150 || + node.kind === 152 || + node.kind === 154 || + node.kind === 155) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 229) { + if (node.kind === 230) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 146) { + if (node.kind === 147) { node = node.parent; - if (node.kind === 152) { + if (node.kind === 153) { return anyType; } } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 150 || + node.kind === 152 || + node.kind === 154 || + node.kind === 155) { var element = node; switch (element.name.kind) { case 71: - return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + return getLiteralType(ts.idText(element.name)); case 8: case 9: return getLiteralType(element.name.text); - case 144: + case 145: var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 512)) { + if (isTypeAssignableToKind(nameType, 1536)) { return nameType; } else { @@ -32066,20 +32332,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 229) { + if (node.kind === 230) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 146) { + if (node.kind === 147) { return numberType; } - if (node.kind === 149) { + if (node.kind === 150) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 152 || + node.kind === 154 || + node.kind === 155) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -32100,26 +32366,26 @@ var ts; return unknownType; } function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 147) { + if (node.kind === 148) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 183) { + else if (argIndex === 0 && node.kind === 184) { return getGlobalTemplateStringsArrayType(); } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 147 || - (argIndex === 0 && node.kind === 183)) { + if (node.kind === 148 || + (argIndex === 0 && node.kind === 184)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147) { + if (node.kind === 148) { return node.expression; } - else if (argIndex === 0 && node.kind === 183) { + else if (argIndex === 0 && node.kind === 184) { return node.template; } else { @@ -32127,8 +32393,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183; - var isDecorator = node.kind === 147; + var isTaggedTemplate = node.kind === 184; + var isDecorator = node.kind === 148; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { @@ -32161,7 +32427,7 @@ var ts; var candidateForArgumentError; var candidateForTypeArgumentError; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 182 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -32178,8 +32444,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -32205,10 +32470,13 @@ var ts; var paramCount = hasRestParameter_1 ? min : min < max ? min + "-" + max : min; - var argCount = args.length - (hasSpreadArgument ? 1 : 0); - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + var argCount = args.length; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1; diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); } @@ -32221,14 +32489,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -32263,10 +32531,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -32274,6 +32544,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { @@ -32351,19 +32622,8 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray); } function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 65536) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 | 16384)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { @@ -32391,9 +32651,9 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.hasModifier(valueDecl, 128)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } return resolveCall(node, constructSignatures, candidatesOutArray); @@ -32421,7 +32681,7 @@ var ts; if (!modifiers) { return true; } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); @@ -32466,16 +32726,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 229: - case 199: + case 230: + case 200: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146: + case 147: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149: + case 150: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151: - case 153: + case 152: case 154: + case 155: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -32490,6 +32750,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -32500,13 +32765,19 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + }); + } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; + ts.Debug.assert(!(elementType.flags & 131072)); + return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); } function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 65536) { + if (elementType.flags & 131072) { var types = elementType.types; var result = void 0; for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { @@ -32523,17 +32794,17 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 181: - return resolveCallExpression(node, candidatesOutArray); case 182: - return resolveNewExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray); case 183: + return resolveNewExpression(node, candidatesOutArray); + case 184: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147: + case 148: return resolveDecorator(node, candidatesOutArray); + case 252: case 251: - case 250: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -32576,31 +32847,33 @@ var ts; function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); } return links.inferredClassType; } function isInferredClassType(type) { return type.symbol - && getObjectFlags(type) & 16 + && ts.getObjectFlags(type) & 16 && getSymbolLinks(type.symbol).inferredClassType === type; } function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97) { return voidType; } - if (node.kind === 182) { + if (node.kind === 183) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 152 && - declaration.kind !== 156 && - declaration.kind !== 161 && + declaration.kind !== 153 && + declaration.kind !== 157 && + declaration.kind !== 162 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 71 ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 71) { + funcSymbol = getResolvedSymbol(node.expression); + } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { return type; @@ -32614,10 +32887,31 @@ var ts; if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } - return getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1536 && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + return returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 107455, undefined, undefined, false); } function checkImportCallExpression(node) { - checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -32626,7 +32920,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 2048 || specifierType.flags & 4096 || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 4096 || specifierType.flags & 8192 || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } var moduleSymbol = resolveExternalModuleName(node, specifier); @@ -32674,17 +32968,20 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 - ? 228 + ? 229 : resolvedRequire.flags & 3 - ? 226 + ? 227 : 0; if (targetDeclarationKind !== 0) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return ts.isInAmbientContext(decl); + return !!decl && !!(decl.flags & 2097152); } return false; } function checkTaggedTemplateExpression(node) { + if (languageVersion < 2) { + checkExternalEmitHelpers(node, 65536); + } return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { @@ -32712,7 +33009,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return unknownType; } - else if (container.kind === 152) { + else if (container.kind === 153) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -32726,7 +33023,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return getNullableType(type, 2048); + return getOptionalType(type); } } return type; @@ -32834,7 +33131,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 207) { + if (func.body.kind !== 208) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2) { type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -32868,24 +33165,40 @@ var ts; } } type = getUnionType(types, true); - if (functionFlags & 1) { - type = functionFlags & 2 - ? createAsyncIterableIteratorType(type) - : createIterableIteratorType(type); - } } if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3) { + case 3: + contextualType = getIteratedTypeOfGenerator(contextualType, true); + break; + case 1: + contextualType = getIteratedTypeOfGenerator(contextualType, false); + break; + case 2: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); } var widenedType = getWidenedType(type); - return (functionFlags & 3) === 2 - ? createPromiseReturnType(func, widenedType) - : widenedType; + switch (functionFlags & 3) { + case 3: + return createAsyncIterableIteratorType(widenedType); + case 1: + return createIterableIteratorType(widenedType); + case 2: + return createPromiseType(widenedType); + default: + return widenedType; + } } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; @@ -32925,8 +33238,7 @@ var ts; if (!(func.flags & 128)) { return false; } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 222 && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -32943,7 +33255,7 @@ var ts; if (functionFlags & 2) { type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 8192) { + if (type.flags & 16384) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -32953,7 +33265,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 || func.kind === 187)) { + func.kind === 187 || func.kind === 188)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -32965,14 +33277,14 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 2048)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 208 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 8192) { + if (returnType && returnType.flags & 16384) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -32995,13 +33307,13 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); if (checkMode === 1 && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { + if (!hasGrammarError && node.kind === 187) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -33032,7 +33344,7 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 151) { + if (produceDiagnostics && node.kind !== 152) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -33040,7 +33352,7 @@ var ts; return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnOrPromisedType = returnTypeNode && @@ -33054,7 +33366,7 @@ var ts; if (!returnTypeNode) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 207) { + if (node.body.kind === 208) { checkSourceElement(node.body); } else { @@ -33089,10 +33401,10 @@ var ts; function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { if (symbol.flags & 4 && - (expr.kind === 179 || expr.kind === 180) && + (expr.kind === 180 || expr.kind === 181) && expr.expression.kind === 99) { var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152)) { + if (!(func && func.kind === 153)) { return true; } return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); @@ -33102,13 +33414,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 || expr.kind === 180) { + if (expr.kind === 180 || expr.kind === 181) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240; + return declaration && declaration.kind === 241; } } } @@ -33116,7 +33428,7 @@ var ts; } function checkReferenceExpression(expr, invalidReferenceMessage) { var node = ts.skipOuterExpressions(expr, 2 | 1); - if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { + if (node.kind !== 71 && node.kind !== 180 && node.kind !== 181) { error(expr, invalidReferenceMessage); return false; } @@ -33125,7 +33437,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 && expr.kind !== 180) { + if (expr.kind !== 180 && expr.kind !== 181) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -33174,7 +33486,7 @@ var ts; case 38: case 52: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512)) { + if (maybeTypeOfKind(operandType, 1536)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -33208,7 +33520,7 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 196608) { + if (type.flags & 393216) { var types = type.types; for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { var t = types_18[_i]; @@ -33223,21 +33535,26 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 | 1024 | 2048 | 4096)) { + if (strict && source.flags & (1 | 2048 | 4096 | 8192)) { return false; } return (kind & 84 && isTypeAssignableTo(source, numberType)) || - (kind & 262178 && isTypeAssignableTo(source, stringType)) || + (kind & 524322 && isTypeAssignableTo(source, stringType)) || (kind & 136 && isTypeAssignableTo(source, booleanType)) || - (kind & 1024 && isTypeAssignableTo(source, voidType)) || - (kind & 8192 && isTypeAssignableTo(source, neverType)) || - (kind & 4096 && isTypeAssignableTo(source, nullType)) || - (kind & 2048 && isTypeAssignableTo(source, undefinedType)) || + (kind & 2048 && isTypeAssignableTo(source, voidType)) || + (kind & 16384 && isTypeAssignableTo(source, neverType)) || + (kind & 8192 && isTypeAssignableTo(source, nullType)) || + (kind & 4096 && isTypeAssignableTo(source, undefinedType)) || (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || - (kind & 16777216 && isTypeAssignableTo(source, nonPrimitiveType)); + (kind & 33554432 && isTypeAssignableTo(source, nonPrimitiveType)); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 131072 ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + return ts.getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -33246,13 +33563,11 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190)) { + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 16382)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0).length || - getSignaturesOfType(rightType, 1).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); } return booleanType; @@ -33263,10 +33578,10 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 1536))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { + if (!isTypeAssignableToKind(rightType, 33554432 | 1081344)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -33280,9 +33595,9 @@ var ts; return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 || property.kind === 262) { + if (property.kind === 265 || property.kind === 266) { var name = property.name; - if (name.kind === 144) { + if (name.kind === 145) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -33295,7 +33610,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || getIndexTypeOfType(objectLiteralType, 0); if (type) { - if (property.kind === 262) { + if (property.kind === 266) { return checkDestructuringAssignment(property, type); } else { @@ -33306,8 +33621,8 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 263) { - if (languageVersion < 5) { + else if (property.kind === 267) { + if (languageVersion < 6) { checkExternalEmitHelpers(property, 4); } var nonRestNames = []; @@ -33337,8 +33652,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 200) { - if (element.kind !== 198) { + if (element.kind !== 201) { + if (element.kind !== 199) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -33364,7 +33679,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { + if (restExpression.kind === 195 && restExpression.operatorToken.kind === 58) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -33377,11 +33692,11 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 262) { + if (exprOrAssignment.kind === 266) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -33391,21 +33706,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 194 && target.operatorToken.kind === 58) { + if (target.kind === 195 && target.operatorToken.kind === 58) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 178) { + if (target.kind === 179) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 177) { + if (target.kind === 178) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 ? + var error = target.parent.kind === 267 ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -33419,35 +33734,35 @@ var ts; case 71: case 9: case 12: - case 183: - case 196: + case 184: + case 197: case 13: case 8: case 101: case 86: case 95: case 139: - case 186: - case 199: case 187: - case 177: + case 200: + case 188: case 178: - case 189: - case 203: + case 179: + case 190: + case 204: + case 251: case 250: - case 249: return true; - case 195: + case 196: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 194: + case 195: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 192: case 193: + case 194: switch (node.operator) { case 51: case 37: @@ -33456,29 +33771,22 @@ var ts; return true; } return false; - case 190: - case 184: - case 202: + case 191: + case 185: + case 203: default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); + return (target.flags & 12288) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 178 || left.kind === 177)) { + if (operator === 58 && (left.kind === 179 || left.kind === 178)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); @@ -33530,7 +33838,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 262178) && !isTypeAssignableToKind(rightType, 262178)) { + if (!isTypeAssignableToKind(leftType, 524322) && !isTypeAssignableToKind(rightType, 524322)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } @@ -33538,7 +33846,7 @@ var ts; if (isTypeAssignableToKind(leftType, 84, true) && isTypeAssignableToKind(rightType, 84, true)) { resultType = numberType; } - else if (isTypeAssignableToKind(leftType, 262178, true) || isTypeAssignableToKind(rightType, 262178, true)) { + else if (isTypeAssignableToKind(leftType, 524322, true) || isTypeAssignableToKind(rightType, 524322, true)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -33591,7 +33899,7 @@ var ts; leftType; case 54: return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], true) : leftType; case 58: checkAssignmentOperator(rightType); @@ -33606,8 +33914,8 @@ var ts; return node.kind === 71 && node.escapedText === "eval"; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536) ? left : + maybeTypeOfKind(rightType, 1536) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -33670,7 +33978,7 @@ var ts; var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { if ((functionFlags & 3) === 3 && - languageVersion < 5) { + languageVersion < 6) { checkExternalEmitHelpers(node, 26624); } if ((functionFlags & 3) === 1 && @@ -33707,7 +34015,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2], true); } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -33739,24 +34047,35 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 184 || node.kind === 202; + return node.kind === 185 || node.kind === 203; } function checkDeclarationInitializer(declaration) { var type = getTypeOfExpression(declaration.initializer, true); return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || + (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } - function isLiteralContextualType(contextualType) { + function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 540672) { + if (contextualType.flags & 131072 && !(contextualType.flags & 8)) { + var types_19 = contextualType.types; + return ts.some(types_19, function (t) { + return !(t.flags & 128 && containsType(types_19, trueType) && containsType(types_19, falseType)) && + isLiteralOfContextualType(candidateType, t); + }); + } + if (contextualType.flags & 1081344) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - if (constraint.flags & (2 | 4 | 8 | 16)) { - return true; - } - contextualType = constraint; + return constraint.flags & 2 && maybeTypeOfKind(candidateType, 32) || + constraint.flags & 4 && maybeTypeOfKind(candidateType, 64) || + constraint.flags & 8 && maybeTypeOfKind(candidateType, 128) || + constraint.flags & 512 && maybeTypeOfKind(candidateType, 1024) || + isLiteralOfContextualType(candidateType, constraint); } - return maybeTypeOfKind(contextualType, (224 | 262144)); + return contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || + contextualType.flags & 64 && maybeTypeOfKind(candidateType, 64) || + contextualType.flags & 128 && maybeTypeOfKind(candidateType, 128) || + contextualType.flags & 1024 && maybeTypeOfKind(candidateType, 1024); } return false; } @@ -33765,18 +34084,18 @@ var ts; contextualType = getContextualType(node); } var type = checkExpression(node, checkMode); - var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); - return shouldWiden ? type : getWidenedLiteralType(type); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); } function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node, checkMode) { checkGrammarMethod(node); - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -33798,7 +34117,7 @@ var ts; return type; } function getTypeOfExpression(node, cache) { - if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { + if (node.kind === 182 && node.expression.kind !== 97 && !ts.isRequireCall(node, true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -33816,7 +34135,7 @@ var ts; } function checkExpression(node, checkMode) { var type; - if (node.kind === 143) { + if (node.kind === 144) { type = checkQualifiedName(node); } else { @@ -33824,9 +34143,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 179 && node.parent.expression === node) || - (node.parent.kind === 180 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 180 && node.parent.expression === node) || + (node.parent.kind === 181 && node.parent.expression === node) || + ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -33860,71 +34179,73 @@ var ts; return trueType; case 86: return falseType; - case 196: + case 197: return checkTemplateExpression(node); case 12: return globalRegExpType; - case 177: - return checkArrayLiteral(node, checkMode); case 178: - return checkObjectLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode); case 179: - return checkPropertyAccessExpression(node); + return checkObjectLiteral(node, checkMode); case 180: - return checkIndexedAccess(node); + return checkPropertyAccessExpression(node); case 181: + return checkIndexedAccess(node); + case 182: if (node.expression.kind === 91) { return checkImportCallExpression(node); } - case 182: - return checkCallExpression(node); case 183: + return checkCallExpression(node); + case 184: return checkTaggedTemplateExpression(node); - case 185: + case 186: return checkParenthesizedExpression(node, checkMode); - case 199: + case 200: return checkClassExpression(node); - case 186: case 187: + case 188: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189: + case 190: return checkTypeOfExpression(node); - case 184: - case 202: - return checkAssertion(node); + case 185: case 203: - return checkNonNullAssertion(node); + return checkAssertion(node); case 204: + return checkNonNullAssertion(node); + case 205: return checkMetaProperty(node); - case 188: + case 189: return checkDeleteExpression(node); - case 190: - return checkVoidExpression(node); case 191: - return checkAwaitExpression(node); + return checkVoidExpression(node); case 192: - return checkPrefixUnaryExpression(node); + return checkAwaitExpression(node); case 193: - return checkPostfixUnaryExpression(node); + return checkPrefixUnaryExpression(node); case 194: - return checkBinaryExpression(node, checkMode); + return checkPostfixUnaryExpression(node); case 195: + return checkBinaryExpression(node, checkMode); + case 196: return checkConditionalExpression(node, checkMode); - case 198: + case 199: return checkSpreadExpression(node, checkMode); - case 200: + case 201: return undefinedWideningType; - case 197: + case 198: return checkYieldExpression(node); - case 256: + case 260: return checkJsxExpression(node, checkMode); - case 249: - return checkJsxElement(node); case 250: + return checkJsxElement(node); + case 251: return checkJsxSelfClosingElement(node); case 254: + return checkJsxFragment(node); + case 258: return checkJsxAttributes(node, checkMode); - case 251: + case 252: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -33939,6 +34260,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -33949,12 +34273,11 @@ var ts; } } function checkParameter(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92)) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 153 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -33965,7 +34288,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 152 || func.kind === 156 || func.kind === 161) { + if (func.kind === 153 || func.kind === 157 || func.kind === 162) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -34027,13 +34350,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { + case 188: + case 156: + case 229: case 187: - case 155: - case 228: - case 186: - case 160: + case 161: + case 152: case 151: - case 150: var parent = node.parent; if (node === parent.type) { return parent; @@ -34051,7 +34374,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 175 || name.kind === 174) { + else if (name.kind === 176 || name.kind === 175) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -34059,17 +34382,17 @@ var ts; } } function checkSignatureDeclaration(node) { - if (node.kind === 157) { + if (node.kind === 158) { checkGrammarIndexSignature(node); } - else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || - node.kind === 155 || node.kind === 152 || - node.kind === 156) { + else if (node.kind === 161 || node.kind === 229 || node.kind === 162 || + node.kind === 156 || node.kind === 153 || + node.kind === 157) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); if (!(functionFlags & 4)) { - if ((functionFlags & 3) === 3 && languageVersion < 5) { + if ((functionFlags & 3) === 3 && languageVersion < 6) { checkExternalEmitHelpers(node, 6144); } if ((functionFlags & 3) === 2 && languageVersion < 4) { @@ -34089,10 +34412,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 156: + case 157: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 155: + case 156: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -34122,18 +34445,11 @@ var ts; } } function checkClassForDuplicateDeclarations(node) { - var Declaration; - (function (Declaration) { - Declaration[Declaration["Getter"] = 1] = "Getter"; - Declaration[Declaration["Setter"] = 2] = "Setter"; - Declaration[Declaration["Method"] = 4] = "Method"; - Declaration[Declaration["Property"] = 3] = "Property"; - })(Declaration || (Declaration = {})); var instanceNames = ts.createUnderscoreEscapedMap(); var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152) { + if (member.kind === 153) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -34147,16 +34463,16 @@ var ts; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 153: + case 154: addName(names, member.name, memberName, 1); break; - case 154: + case 155: addName(names, member.name, memberName, 2); break; - case 149: + case 150: addName(names, member.name, memberName, 3); break; - case 151: + case 152: addName(names, member.name, memberName, 4); break; } @@ -34197,7 +34513,7 @@ var ts; case "arguments": case "prototype": var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); error(memberNameNode, message, memberName, className); break; } @@ -34208,7 +34524,7 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 149) { var memberName = void 0; switch (member.name.kind) { case 9: @@ -34216,7 +34532,7 @@ var ts; memberName = member.name.text; break; case 71: - memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + memberName = ts.idText(member.name); break; default: continue; @@ -34232,7 +34548,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230) { + if (node.kind === 231) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -34269,11 +34585,13 @@ var ts; } } function checkPropertyDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); } function checkMethodDeclaration(node) { - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); if (ts.hasModifier(node, 128) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); @@ -34281,7 +34599,8 @@ var ts; } function checkConstructorDeclaration(node) { checkSignatureDeclaration(node); - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); @@ -34312,7 +34631,7 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function isInstancePropertyWithInitializer(n) { - return n.kind === 149 && + return n.kind === 150 && !ts.hasModifier(n, 32) && !!n.initializer; } @@ -34332,7 +34651,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -34352,22 +34671,23 @@ var ts; } function checkAccessorDeclaration(node) { if (produceDiagnostics) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 153) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (node.kind === 154) { + if (!(node.flags & 2097152) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 153 ? 154 : 153; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (!hasNonBindableDynamicName(node)) { + var otherKind = node.kind === 154 ? 155 : 154; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); var otherFlags = ts.getModifierFlags(otherAccessor); @@ -34382,7 +34702,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153) { + if (node.kind === 154) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -34412,14 +34732,14 @@ var ts; mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, instantiateType(constraint, mapper), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 160 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -34429,11 +34749,13 @@ var ts; if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; if (!symbol) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; - if (!typeParameters && getObjectFlags(type) & 4) { + if (!typeParameters && ts.getObjectFlags(type) & 4) { typeParameters = type.target.localTypeParameters; } checkTypeArgumentConstraints(typeParameters, node.typeArguments); @@ -34470,14 +34792,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288)) { + if (!(type.flags & 1048576)) { return type; } var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { + if (accessNode.kind === 181 && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; @@ -34500,15 +34822,19 @@ var ts; var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8) && !!(node.flags & 2097152); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 230 && - n.parent.kind !== 229 && - n.parent.kind !== 199 && - ts.isInAmbientContext(n)) { + if (n.parent.kind !== 231 && + n.parent.kind !== 230 && + n.parent.kind !== 200 && + n.flags & 2097152) { if (!(flags & 2)) { flags |= 1; } @@ -34587,7 +34913,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 151 || node.kind === 150) && + var reportError = (node.kind === 152 || node.kind === 151) && ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); if (reportError) { var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -34619,12 +34945,12 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; + var inAmbientContext = node.flags & 2097152; + var inAmbientContextOrInterface = node.parent.kind === 231 || node.parent.kind === 164 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { + if (node.kind === 229 || node.kind === 152 || node.kind === 151 || node.kind === 153) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -34734,37 +35060,30 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(d) { switch (d.kind) { - case 230: case 231: - case 283: + case 232: + case 288: return 2; - case 233: + case 234: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4 | 1 : 4; - case 229: - case 232: + case 230: + case 233: return 2 | 1; - case 237: + case 238: + case 241: case 240: - case 239: - var result_3 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 226: - case 176: - case 228: - case 242: + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; + case 227: + case 177: + case 229: + case 243: return 1; default: ts.Debug.fail(ts.SyntaxKind[d.kind]); @@ -34821,7 +35140,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 65536) { + if (type.flags & 131072) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -34830,7 +35149,7 @@ var ts; if (!types) { return undefined; } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { @@ -34903,7 +35222,7 @@ var ts; var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; } } @@ -34919,22 +35238,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 229: + case 230: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 146: + case 147: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 149: + case 150: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 151: - case 153: + case 152: case 154: + case 155: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -34967,11 +35286,20 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { + case 168: case 167: - case 166: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169) { + typeNode = typeNode.type; + } + if (typeNode.kind === 130) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 139)) { + continue; + } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) { return undefined; @@ -34988,9 +35316,9 @@ var ts; } } return commonEntityName; - case 168: + case 169: return getEntityNameForDecoratorMetadata(node.type); - case 159: + case 160: return node.typeName; } } @@ -35003,7 +35331,7 @@ var ts; if (!node.decorators) { return; } - if (!ts.nodeCanBeDecorated(node)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { @@ -35011,13 +35339,13 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 146) { + if (node.kind === 147) { checkExternalEmitHelpers(firstDecorator, 32); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 229: + case 230: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -35026,20 +35354,25 @@ var ts; } } break; - case 151: - case 153: + case 152: case 154: + case 155: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 149: + case 150: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 146: + case 147: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } break; } } @@ -35061,14 +35394,50 @@ var ts; error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 144 ? node.name.right : node.name)); + } + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 282); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 71: + return node; + case 180: + return node.name; + default: + return undefined; + } + } function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 144) { + if (node.name && node.name.kind === 145) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); @@ -35109,68 +35478,67 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 265: - case 233: + case 269: + case 234: checkUnusedModuleMembers(node); break; - case 229: - case 199: + case 230: + case 200: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 230: + case 231: checkUnusedTypeParameters(node); break; - case 207: - case 235: - case 214: + case 208: + case 236: case 215: case 216: + case 217: checkUnusedLocalsAndParameters(node); break; - case 152: - case 186: - case 228: - case 187: - case 151: case 153: + case 187: + case 229: + case 188: + case 152: case 154: + case 155: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 150: - case 155: + case 151: case 156: case 157: - case 160: case 161: + case 162: + case 232: checkUnusedTypeParameters(node); break; - case 231: - checkUnusedTypeParameters(node); - break; + default: + ts.Debug.fail("Node should not have been registered for unused identifiers check"); } } } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + if (noUnusedIdentifiers && !(node.flags & 2097152)) { node.locals.forEach(function (local) { if (!local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 147) { var parameter = ts.getRootDeclaration(local.valueDeclaration); var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); } } }); @@ -35187,8 +35555,8 @@ var ts; var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 226 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 145) { + if ((declaration_2.kind === 227 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 146) { return; } } @@ -35200,23 +35568,23 @@ var ts; return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95; + return node.kind === 71 && ts.idText(node).charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 || member.kind === 149) { + if (member.kind === 152 || member.kind === 150) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); } } - else if (member.kind === 152) { + else if (member.kind === 153) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } } @@ -35225,7 +35593,7 @@ var ts; } } function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { if (node.typeParameters) { var symbol = getSymbolOfNode(node); var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); @@ -35235,20 +35603,20 @@ var ts; for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); } } } } } function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { node.locals.forEach(function (local) { if (!local.isReferenced && !local.exportSymbol) { for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.symbolName(local)); } } } @@ -35256,7 +35624,7 @@ var ts; } } function checkBlock(node) { - if (node.kind === 207) { + if (node.kind === 208) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -35272,7 +35640,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || node.flags & 2097152 || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -35285,19 +35653,19 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 149 || - node.kind === 148 || + if (node.kind === 150 || + node.kind === 149 || + node.kind === 152 || node.kind === 151 || - node.kind === 150 || - node.kind === 153 || - node.kind === 154) { + node.kind === 154 || + node.kind === 155) { return false; } - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 147 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -35345,7 +35713,7 @@ var ts; return; } var enclosingClass = ts.getContainingClass(node); - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + if (!enclosingClass || enclosingClass.flags & 2097152) { return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { @@ -35365,11 +35733,11 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 269 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -35377,11 +35745,11 @@ var ts; if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + if (parent.kind === 269 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -35389,7 +35757,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 226 && !node.initializer) { + if (node.kind === 227 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -35401,15 +35769,15 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); - var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 228); + var container = varDeclList.parent.kind === 209 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 207 && ts.isFunctionLike(container.parent) || + (container.kind === 208 && ts.isFunctionLike(container.parent) || + container.kind === 235 || container.kind === 234 || - container.kind === 233 || - container.kind === 265); + container.kind === 269); if (!namesShareScope) { var name = symbolToString(localDeclarationSymbol); error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); @@ -35419,7 +35787,7 @@ var ts; } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146) { + if (ts.getRootDeclaration(node).kind !== 147) { return; } var func = ts.getContainingFunction(node); @@ -35428,7 +35796,7 @@ var ts; if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { return; } - if (n.kind === 179) { + if (n.kind === 180) { return visit(n.expression); } else if (n.kind === 71) { @@ -35442,8 +35810,8 @@ var ts; } var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 || - symbol.valueDeclaration.kind === 176) { + if (symbol.valueDeclaration.kind === 147 || + symbol.valueDeclaration.kind === 177) { if (symbol.valueDeclaration.pos < node.pos) { return; } @@ -35452,7 +35820,7 @@ var ts; return "quit"; } return ts.isFunctionLike(current.parent) || - (current.parent.kind === 149 && + (current.parent.kind === 150 && !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)); })) { @@ -35476,40 +35844,40 @@ var ts; if (!node.name) { return; } - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 176) { - if (node.parent.kind === 174 && languageVersion < 5) { + if (node.kind === 177) { + if (node.parent.kind === 175 && languageVersion < 6) { checkExternalEmitHelpers(node, 4); } - if (node.propertyName && node.propertyName.kind === 144) { + if (node.propertyName && node.propertyName.kind === 145) { checkComputedPropertyName(node.propertyName); } var parent = node.parent.parent; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, undefined); + markPropertyAsReferenced(property, undefined, false); if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { + if (node.name.kind === 176 && languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512); } ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 147 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 215) { + if (node.initializer && node.parent.parent.kind !== 216) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } @@ -35518,15 +35886,17 @@ var ts; var symbol = getSymbolOfNode(node); var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 215) { + if (node.initializer && node.parent.parent.kind !== 216) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } } else { var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); + if (type !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); @@ -35536,9 +35906,9 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 149 && node.kind !== 148) { + if (node.kind !== 150 && node.kind !== 149) { checkExportsOnMergedDeclarations(node); - if (node.kind === 226 || node.kind === 176) { + if (node.kind === 227 || node.kind === 177) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -35548,9 +35918,16 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 150 || nextDeclaration.kind === 149 + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 && right.kind === 226) || - (left.kind === 226 && right.kind === 146)) { + if ((left.kind === 147 && right.kind === 227) || + (left.kind === 227 && right.kind === 147)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -35573,11 +35950,12 @@ var ts; return checkVariableLikeDeclaration(node); } function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 178) { + if (node.modifiers && node.parent.kind === 179) { if (ts.getFunctionFlags(node) & 2) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -35596,7 +35974,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209) { + if (node.thenStatement.kind === 210) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -35613,12 +35991,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227) { + if (node.initializer && node.initializer.kind === 228) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -35636,10 +36014,10 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 216) { + if (node.kind === 217) { if (node.awaitModifier) { var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 6) { checkExternalEmitHelpers(node, 16384); } } @@ -35647,13 +36025,13 @@ var ts; checkExternalEmitHelpers(node, 256); } } - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 177 || varExpr.kind === 178) { + if (varExpr.kind === 178 || varExpr.kind === 179) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { @@ -35672,7 +36050,7 @@ var ts; function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -35682,7 +36060,7 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 || varExpr.kind === 178) { + if (varExpr.kind === 178 || varExpr.kind === 179) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -35692,7 +36070,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { + if (!isTypeAssignableToKind(rightType, 33554432 | 1081344)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -35730,14 +36108,14 @@ var ts; var reportedError = false; var hasStringConstituent = false; if (allowStringInput) { - if (arrayType.flags & 65536) { + if (arrayType.flags & 131072) { var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, true); } } - else if (arrayType.flags & 262178) { + else if (arrayType.flags & 524322) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -35748,7 +36126,7 @@ var ts; reportedError = true; } } - if (arrayType.flags & 8192) { + if (arrayType.flags & 16384) { return stringType; } } @@ -35768,7 +36146,7 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1); if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 262178) { + if (arrayElementType.flags & 524322) { return stringType; } return getUnionType([arrayElementType, stringType], true); @@ -35885,17 +36263,18 @@ var ts; || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); } function checkBreakOrContinueStatement(node) { - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 153 - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154)) !== undefined; + return node.kind === 154 + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 155)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 ? getPromisedTypeOfPromise(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -35908,18 +36287,18 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return; + } + if (strictNullChecks || node.expression || returnType.flags & 16384) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return; - } - if (func.kind === 154) { + if (func.kind === 155) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 152) { + else if (func.kind === 153) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -35937,7 +36316,7 @@ var ts; } } } - else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 153 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } @@ -35963,7 +36342,7 @@ var ts; var expressionType = checkExpression(node.expression); var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 258 && !hasDuplicateDefaultClause) { + if (clause.kind === 262 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -35975,7 +36354,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 257) { + if (produceDiagnostics && clause.kind === 261) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); var caseIsLiteral = isLiteralType(caseType); @@ -36000,7 +36379,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 222 && current.label.escapedText === node.label.escapedText) { + if (current.kind === 223 && current.label.escapedText === node.label.escapedText) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); return true; @@ -36060,14 +36439,15 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (ts.getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!ts.hasModifier(member, 32) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + if (!ts.hasModifier(member, 32) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); } } } @@ -36075,7 +36455,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (getObjectFlags(type) & 2)) { + if (!errorNode && (ts.getObjectFlags(type) & 2)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -36093,15 +36473,15 @@ var ts; } var errorNode; if (propDeclaration && - (propDeclaration.kind === 194 || - ts.getNameOfDeclaration(propDeclaration).kind === 144 || + (propDeclaration.kind === 195 || + ts.getNameOfDeclaration(propDeclaration).kind === 145 || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (getObjectFlags(containingType) & 2) { + else if (ts.getObjectFlags(containingType) & 2) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -36233,7 +36613,7 @@ var ts; var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); - if (!ts.isInAmbientContext(node)) { + if (!(node.flags & 2097152)) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); @@ -36259,10 +36639,10 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 1081344 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 1081344)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); @@ -36295,6 +36675,7 @@ var ts; if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); } } function checkBaseTypeAccessibility(type, node) { @@ -36302,7 +36683,7 @@ var ts; if (signatures.length) { var declaration = signatures[0].declaration; if (declaration && ts.hasModifier(declaration, 8)) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } @@ -36312,12 +36693,9 @@ var ts; function getTargetSymbol(s) { return ts.getCheckFlags(s) & 1 ? s.target : s; } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); - } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 || d.kind === 230; + return d.kind === 230 || d.kind === 231; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -36333,9 +36711,9 @@ var ts; ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { - if (derivedClassDecl.kind === 199) { + if (derivedClassDecl.kind === 200) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -36403,15 +36781,48 @@ var ts; } return ok; } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 1 || getFalsyFlags(type) & 4096)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 150 && + !ts.hasModifier(node, 32 | 128) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 4096); + } function checkInterfaceDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 231); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -36438,7 +36849,7 @@ var ts; } } function checkTypeAliasDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); checkTypeParameters(node.typeParameters); checkSourceElement(node.type); @@ -36470,7 +36881,7 @@ var ts; if (member.initializer) { return computeConstantValue(member); } - if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + if (member.parent.flags & 2097152 && !ts.isConst(member.parent)) { return undefined; } if (autoValue !== undefined) { @@ -36498,7 +36909,7 @@ var ts; else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (ts.isInAmbientContext(member.parent)) { + else if (member.parent.flags & 2097152) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { @@ -36507,7 +36918,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 192: + case 193: var value_1 = evaluate(expr.operand); if (typeof value_1 === "number") { switch (expr.operator) { @@ -36517,7 +36928,7 @@ var ts; } } break; - case 194: + case 195: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -36541,18 +36952,18 @@ var ts; case 8: checkGrammarNumericLiteral(expr); return +expr.text; - case 185: + case 186: return evaluate(expr.expression); case 71: return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + case 181: case 180: - case 179: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384) { var name = void 0; - if (ex.kind === 179) { + if (ex.kind === 180) { name = ex.name.escapedText; } else { @@ -36573,7 +36984,7 @@ var ts; var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { - return getNodeLinks(declaration).enumMemberValue; + return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; @@ -36584,15 +36995,15 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 || - node.kind === 179 && isConstantMemberAccess(node.expression) || - node.kind === 180 && isConstantMemberAccess(node.expression) && + node.kind === 180 && isConstantMemberAccess(node.expression) || + node.kind === 181 && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -36601,7 +37012,7 @@ var ts; checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } var enumSymbol = getSymbolOfNode(node); @@ -36616,7 +37027,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 232) { + if (declaration.kind !== 233) { return false; } var enumDeclaration = declaration; @@ -36639,9 +37050,9 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { var declaration = declarations_7[_i]; - if ((declaration.kind === 229 || - (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 230 || + (declaration.kind === 229 && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 2097152)) { return declaration; } } @@ -36663,7 +37074,7 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContext = node.flags & 2097152; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -36674,7 +37085,7 @@ var ts; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node)) { if (!inAmbientContext && node.name.kind === 9) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -36699,7 +37110,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 229); + var mergedClass = ts.getDeclarationOfKind(symbol, 230); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -36742,22 +37153,22 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 208: + case 209: for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 243: case 244: + case 245: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 237: case 238: + case 239: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 176: - case 226: + case 177: + case 227: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -36766,12 +37177,12 @@ var ts; } break; } - case 229: - case 232: - case 228: case 230: case 233: + case 229: case 231: + case 234: + case 232: if (isGlobalAugmentation) { return; } @@ -36789,12 +37200,12 @@ var ts; switch (node.kind) { case 71: return node; - case 143: + case 144: do { node = node.left; } while (node.kind !== 71); return node; - case 179: + case 180: do { node = node.expression; } while (node.kind !== 71); @@ -36807,9 +37218,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 ? + var inAmbientExternalModule = node.parent.kind === 235 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 269 && !inAmbientExternalModule) { + error(moduleName, node.kind === 245 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -36830,15 +37241,15 @@ var ts; (symbol.flags & 793064 ? 793064 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 246 ? + var message = node.kind === 247 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } if (compilerOptions.isolatedModules - && node.kind === 246 + && node.kind === 247 && !(target.flags & 107455) - && !ts.isInAmbientContext(node)) { + && !(node.flags & 2097152)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } @@ -36853,7 +37264,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -36863,7 +37274,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { + if (importClause.namedBindings.kind === 241) { checkImportBinding(importClause.namedBindings); } else { @@ -36877,13 +37288,13 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); if (ts.hasModifier(node, 1)) { markExportAsReferenced(node); } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.moduleReference.kind !== 249) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 107455) { @@ -36898,7 +37309,7 @@ var ts; } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152)) { grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } @@ -36908,16 +37319,16 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 235 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 235 && + !node.moduleSpecifier && node.flags & 2097152; + if (node.parent.kind !== 269 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -36933,7 +37344,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; + var isInAppropriateContext = node.parent.kind === 269 || node.parent.kind === 235 || node.parent.kind === 234; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -36941,11 +37352,14 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.propertyName || node.name, true); + } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { markExportAsReferenced(node); @@ -36956,8 +37370,8 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 ? node.parent : node.parent.parent; + if (container.kind === 234 && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -36966,20 +37380,23 @@ var ts; } return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71) { markExportAsReferenced(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.expression, true); + } } else { checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 2097152) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (node.isExportEquals && !(node.flags & 2097152)) { if (modulekind >= ts.ModuleKind.ES2015) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -37003,27 +37420,29 @@ var ts; } } var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - if (flags & (1920 | 64 | 384)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); - if (flags & 524288 && exportedDeclarationsCount <= 2) { - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (exports) { + exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + if (flags & (1920 | 64 | 384)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } - } - }); + }); + } links.exportsChecked = true; } } @@ -37031,7 +37450,7 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || + return (declaration.kind !== 229 && declaration.kind !== 152) || !!declaration.body; } function checkSourceElement(node) { @@ -37047,143 +37466,189 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 233: - case 229: + case 234: case 230: - case 228: + case 231: + case 229: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 145: - return checkTypeParameter(node); case 146: + return checkTypeParameter(node); + case 147: return checkParameter(node); + case 150: case 149: - case 148: return checkPropertyDeclaration(node); - case 160: case 161: - case 155: + case 162: case 156: - return checkSignatureDeclaration(node); case 157: return checkSignatureDeclaration(node); + case 158: + return checkSignatureDeclaration(node); + case 152: case 151: - case 150: return checkMethodDeclaration(node); - case 152: - return checkConstructorDeclaration(node); case 153: + return checkConstructorDeclaration(node); case 154: + case 155: return checkAccessorDeclaration(node); - case 159: + case 160: return checkTypeReferenceNode(node); - case 158: + case 159: return checkTypePredicate(node); - case 162: - return checkTypeQuery(node); case 163: - return checkTypeLiteral(node); + return checkTypeQuery(node); case 164: - return checkArrayType(node); + return checkTypeLiteral(node); case 165: - return checkTupleType(node); + return checkArrayType(node); case 166: + return checkTupleType(node); case 167: - return checkUnionOrIntersectionType(node); case 168: - case 170: + return checkUnionOrIntersectionType(node); + case 169: return checkSourceElement(node.type); - case 283: + case 171: + return checkTypeOperator(node); + case 282: + return checkJSDocAugmentsTag(node); + case 288: return checkJSDocTypedefTag(node); - case 279: - return checkSourceElement(node.typeExpression); - case 273: + case 284: + return checkJSDocParameterTag(node); + case 277: checkSignatureDeclaration(node); + case 275: case 274: - case 271: - case 270: - case 268: - case 269: - if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); - } + case 272: + case 273: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); return; - case 267: + case 278: + checkJSDocVariadicType(node); + return; + case 271: return checkSourceElement(node.type); - case 171: - return checkIndexedAccessType(node); case 172: + return checkIndexedAccessType(node); + case 173: return checkMappedType(node); - case 228: + case 229: return checkFunctionDeclaration(node); - case 207: - case 234: - return checkBlock(node); case 208: + case 235: + return checkBlock(node); + case 209: return checkVariableStatement(node); - case 210: - return checkExpressionStatement(node); case 211: - return checkIfStatement(node); + return checkExpressionStatement(node); case 212: - return checkDoStatement(node); + return checkIfStatement(node); case 213: - return checkWhileStatement(node); + return checkDoStatement(node); case 214: - return checkForStatement(node); + return checkWhileStatement(node); case 215: - return checkForInStatement(node); + return checkForStatement(node); case 216: - return checkForOfStatement(node); + return checkForInStatement(node); case 217: + return checkForOfStatement(node); case 218: - return checkBreakOrContinueStatement(node); case 219: - return checkReturnStatement(node); + return checkBreakOrContinueStatement(node); case 220: - return checkWithStatement(node); + return checkReturnStatement(node); case 221: - return checkSwitchStatement(node); + return checkWithStatement(node); case 222: - return checkLabeledStatement(node); + return checkSwitchStatement(node); case 223: - return checkThrowStatement(node); + return checkLabeledStatement(node); case 224: + return checkThrowStatement(node); + case 225: return checkTryStatement(node); - case 226: + case 227: return checkVariableDeclaration(node); - case 176: + case 177: return checkBindingElement(node); - case 229: - return checkClassDeclaration(node); case 230: - return checkInterfaceDeclaration(node); + return checkClassDeclaration(node); case 231: - return checkTypeAliasDeclaration(node); + return checkInterfaceDeclaration(node); case 232: - return checkEnumDeclaration(node); + return checkTypeAliasDeclaration(node); case 233: + return checkEnumDeclaration(node); + case 234: return checkModuleDeclaration(node); - case 238: + case 239: return checkImportDeclaration(node); - case 237: + case 238: return checkImportEqualsDeclaration(node); - case 244: + case 245: return checkExportDeclaration(node); - case 243: + case 244: return checkExportAssignment(node); - case 209: + case 210: checkGrammarStatementInAmbientContext(node); return; - case 225: + case 226: checkGrammarStatementInAmbientContext(node); return; - case 247: + case 248: return checkMissingDeclaration(node); } } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJavaScriptFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + var parent = node.parent; + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = parent.parent; + if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (param) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + var lastParamDeclaration = host_1 && ts.last(host_1.parameters); + if (lastParamDeclaration.symbol === param && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + return addOptionality(type); + } function checkNodeDeferred(node) { if (deferredNodes) { deferredNodes.push(node); @@ -37193,17 +37658,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 186: case 187: + case 188: + case 152: case 151: - case 150: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 153: case 154: + case 155: checkAccessorDeclaration(node); break; - case 199: + case 200: checkClassExpressionDeferred(node); break; } @@ -37229,7 +37694,7 @@ var ts; flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); - if (ts.isExternalModule(node)) { + if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile) { @@ -37289,19 +37754,8 @@ var ts; throw new Error("Trying to get diagnostics from a type checker that does not produce them."); } } - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { + if (location.flags & 4194304) { return []; } var symbols = ts.createSymbolTable(); @@ -37314,24 +37768,24 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 233: + case 234: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); break; - case 232: + case 233: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 199: + case 200: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 229: case 230: + case 231: if (!isStatic) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064); } break; - case 186: + case 187: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -37369,27 +37823,27 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 145: - case 229: + case 146: case 230: case 231: case 232: + case 233: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 143) { + while (node.parent && node.parent.kind === 144) { node = node.parent; } - return node.parent && node.parent.kind === 159; + return node.parent && node.parent.kind === 160; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 179) { + while (node.parent && node.parent.kind === 180) { node = node.parent; } - return node.parent && node.parent.kind === 201; + return node.parent && node.parent.kind === 202; } function forEachEnclosingClass(node, callback) { var result; @@ -37402,17 +37856,28 @@ var ts; } return result; } + function isNodeWithinConstructorOfClass(node, classDeclaration) { + return ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + return true; + } + else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } function isNodeWithinClass(node, classDeclaration) { return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143) { + while (nodeOnRightSide.parent.kind === 144) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 237) { + if (nodeOnRightSide.parent.kind === 238) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 243) { + if (nodeOnRightSide.parent.kind === 244) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -37437,18 +37902,18 @@ var ts; return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 && + entityName.parent.kind === 180 && entityName.parent === entityName.parent.parent.left) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); if (specialPropertyAssignmentSymbol) { return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 244 && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); } - if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 237); + if (entityName.kind !== 180 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 238); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); } @@ -37457,7 +37922,7 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 201) { + if (entityName.parent.kind === 202) { meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -37472,15 +37937,15 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 279) { + if (entityName.parent.kind === 284) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 145 && entityName.parent.parent.kind === 282) { + if (entityName.parent.kind === 146 && entityName.parent.parent.kind === 287) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } - if (ts.isPartOfExpression(entityName)) { + if (ts.isExpressionNode(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; } @@ -37490,12 +37955,12 @@ var ts; } return resolveEntityName(entityName, 107455, false, true); } - else if (entityName.kind === 179 || entityName.kind === 143) { + else if (entityName.kind === 180 || entityName.kind === 144) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 179) { + if (entityName.kind === 180) { checkPropertyAccessExpression(entityName); } else { @@ -37505,22 +37970,22 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 159 ? 793064 : 1920; + var meaning = entityName.parent.kind === 160 ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } - else if (entityName.parent.kind === 253) { + else if (entityName.parent.kind === 257) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 158) { + if (entityName.parent.kind === 159) { return resolveEntityName(entityName, 1); } return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 265) { + if (node.kind === 269) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { @@ -37533,8 +37998,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 176 && - node.parent.parent.kind === 174 && + else if (node.parent.kind === 177 && + node.parent.parent.kind === 175 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); @@ -37545,8 +38010,8 @@ var ts; } switch (node.kind) { case 71: - case 179: - case 143: + case 180: + case 144: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99: var container = ts.getThisContainer(node, false); @@ -37559,19 +38024,19 @@ var ts; if (ts.isInExpressionContext(node)) { return checkExpression(node).symbol; } - case 169: + case 170: return getTypeFromThisTypeNode(node).symbol; case 97: return checkExpression(node).symbol; case 123: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152) { + if (constructorDeclaration && constructorDeclaration.kind === 153) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 239 || node.parent.kind === 245) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } @@ -37583,13 +38048,15 @@ var ts; : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79: + case 89: + case 36: return getSymbolOfNode(node.parent); default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 262) { + if (location && location.kind === 266) { return resolveEntityName(location.name, 107455 | 2097152); } return undefined; @@ -37600,7 +38067,7 @@ var ts; resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 2097152); } function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return unknownType; } if (ts.isPartOfTypeNode(node)) { @@ -37612,7 +38079,7 @@ var ts; } return typeFromTypeNode; } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -37648,20 +38115,20 @@ var ts; return unknownType; } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 || expr.kind === 177); - if (expr.parent.kind === 216) { + ts.Debug.assert(expr.kind === 179 || expr.kind === 178); + if (expr.parent.kind === 217) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 194) { + if (expr.parent.kind === 195) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 261) { + if (expr.parent.kind === 265) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 177); + ts.Debug.assert(expr.parent.kind === 178); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); @@ -37685,7 +38152,7 @@ var ts; function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { + if (typeHasCallOrConstructSignatures(type)) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); @@ -37694,12 +38161,15 @@ var ts; } return getNamedMembers(propsByName); } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { var symbols_4 = []; - var name_3 = symbol.escapedName; + var name_4 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_3); + var symbol = getPropertyOfType(t, name_4); if (symbol) { symbols_4.push(symbol); } @@ -37729,7 +38199,7 @@ var ts; if (!ts.isGeneratedIdentifier(node)) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 180 && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -37772,7 +38242,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 269) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -37806,7 +38276,7 @@ var ts; else if (nodeLinks_1.flags & 131072) { var isDeclaredInLoop = nodeLinks_1.flags & 262144; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 208 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -37842,16 +38312,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 237: - case 239: + case 238: case 240: - case 242: - case 246: + case 241: + case 243: + case 247: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244: + case 245: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243: + case 244: return node.expression && node.expression.kind === 71 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -37861,7 +38331,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 269 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -37884,6 +38354,10 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } + var target = getSymbolLinks(symbol).target; + if (target && ts.getModifierFlags(node) & 1 && target.flags & 107455) { + return true; + } } if (checkChildren) { return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); @@ -37920,15 +38394,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 264: - case 179: + case 268: case 180: + case 181: return true; } return false; } function getConstantValue(node) { - if (node.kind === 264) { + if (node.kind === 268) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -37940,7 +38414,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 65536 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { typeName = ts.getParseTreeNode(typeName, ts.isEntityName); @@ -37973,7 +38447,7 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 1024 | 6144 | 8192)) { + else if (isTypeAssignableToKind(type, 2048 | 12288 | 16384)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } else if (isTypeAssignableToKind(type, 136)) { @@ -37982,13 +38456,13 @@ var ts; else if (isTypeAssignableToKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 262178)) { + else if (isTypeAssignableToKind(type, 524322)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 512)) { + else if (isTypeAssignableToKind(type, 1536)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -38006,8 +38480,12 @@ var ts; var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (type.flags & 1024 && + type.symbol === symbol) { + flags |= 131072; + } if (flags & 8192) { - type = getNullableType(type, 2048); + type = getOptionalType(type); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -38051,7 +38529,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 1048576); + return !!(type.flags & 96 && type.flags & 2097152); } return false; } @@ -38114,6 +38592,11 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024); + }, writeLiteralConstValue: writeLiteralConstValue, getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; @@ -38121,7 +38604,7 @@ var ts; if (!fileToDirective) { return undefined; } - var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) + var meaning = (node.kind === 180) || (node.kind === 71 && isInTypeQuery(node)) ? 107455 | 1048576 : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); @@ -38164,7 +38647,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 269 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -38183,7 +38666,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 265); + return ts.getDeclarationOfKind(moduleSymbol, 269); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -38233,6 +38716,9 @@ var ts; globalRegExpType = getGlobalType("RegExp", 0, true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", 1); @@ -38240,11 +38726,11 @@ var ts; function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 32768; helper <<= 1) { + for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); @@ -38276,6 +38762,7 @@ var ts; case 8192: return "__asyncDelegator"; case 16384: return "__asyncValues"; case 32768: return "__exportStar"; + case 65536: return "__makeTemplateObject"; default: ts.Debug.fail("Unrecognized helper"); } } @@ -38285,19 +38772,22 @@ var ts; } return externalHelpersModule; } + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } function checkGrammarDecorators(node) { if (!node.decorators) { return false; } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 152 && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 153 || node.kind === 154) { + else if (node.kind === 154 || node.kind === 155) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -38315,16 +38805,16 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 131) { - if (node.kind === 148 || node.kind === 150) { + if (node.kind === 149 || node.kind === 151) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 157) { + if (node.kind === 158) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 76: - if (node.kind !== 232 && node.parent.kind === 229) { + if (node.kind !== 233 && node.parent.kind === 230) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); } break; @@ -38344,7 +38834,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 234 || node.parent.kind === 265) { + else if (node.parent.kind === 235 || node.parent.kind === 269) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { @@ -38367,10 +38857,10 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 234 || node.parent.kind === 265) { + else if (node.parent.kind === 235 || node.parent.kind === 269) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { @@ -38383,7 +38873,7 @@ var ts; if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { + else if (node.kind !== 150 && node.kind !== 149 && node.kind !== 158 && node.kind !== 147) { return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64; @@ -38402,17 +38892,17 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; case 79: - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 ? node.parent : node.parent.parent; + if (container.kind === 234 && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512; @@ -38424,13 +38914,13 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { + else if ((node.parent.flags & 2097152) && node.parent.kind === 235) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; @@ -38440,14 +38930,14 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 229) { - if (node.kind !== 151 && - node.kind !== 149 && - node.kind !== 153 && - node.kind !== 154) { + if (node.kind !== 230) { + if (node.kind !== 152 && + node.kind !== 150 && + node.kind !== 154 && + node.kind !== 155) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 && ts.hasModifier(node.parent, 128))) { + if (!(node.parent.kind === 230 && ts.hasModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -38463,10 +38953,10 @@ var ts; if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 || node.parent.flags & 2097152) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -38474,7 +38964,7 @@ var ts; break; } } - if (node.kind === 152) { + if (node.kind === 153) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -38489,13 +38979,13 @@ var ts; } return; } - else if ((node.kind === 238 || node.kind === 237) && flags & 2) { + else if ((node.kind === 239 || node.kind === 238) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { + else if (node.kind === 147 && (flags & 92) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { + else if (node.kind === 147 && (flags & 92) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -38511,37 +39001,37 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 153: case 154: - case 152: + case 155: + case 153: + case 150: case 149: - case 148: + case 152: case 151: - case 150: - case 157: - case 233: + case 158: + case 234: + case 239: case 238: - case 237: + case 245: case 244: - case 243: - case 186: case 187: - case 146: + case 188: + case 147: return false; default: - if (node.parent.kind === 234 || node.parent.kind === 265) { + if (node.parent.kind === 235 || node.parent.kind === 269) { return false; } switch (node.kind) { - case 228: - return nodeHasAnyModifiersExcept(node, 120); case 229: - return nodeHasAnyModifiersExcept(node, 117); + return nodeHasAnyModifiersExcept(node, 120); case 230: - case 208: + return nodeHasAnyModifiersExcept(node, 117); case 231: - return true; + case 209: case 232: + return true; + case 233: return nodeHasAnyModifiersExcept(node, 76); default: ts.Debug.fail(); @@ -38554,10 +39044,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 151: - case 228: - case 186: + case 152: + case 229: case 187: + case 188: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -38611,7 +39101,7 @@ var ts; } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarClassLikeDeclaration(node) { @@ -38619,7 +39109,7 @@ var ts; return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 187) { + if (node.kind === 188) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -38662,7 +39152,7 @@ var ts; } } function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -38680,7 +39170,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 200) { + if (arg.kind === 201) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -38706,7 +39196,7 @@ var ts; function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; if (heritageClause.token === 85) { @@ -38753,20 +39243,20 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 144) { + if (node.kind !== 145) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { + if (computedPropertyName.expression.kind === 195 && computedPropertyName.expression.operatorToken.kind === 26) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 || - node.kind === 186 || - node.kind === 151); - if (ts.isInAmbientContext(node)) { + ts.Debug.assert(node.kind === 229 || + node.kind === 187 || + node.kind === 152); + if (node.flags & 2097152) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -38781,49 +39271,45 @@ var ts; } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var seen = ts.createUnderscoreEscapedMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263) { + if (prop.kind === 267) { continue; } var name = prop.name; - if (name.kind === 144) { + if (name.kind === 145) { checkGrammarComputedPropertyName(name); } - if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 266 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 151) { + if (mod.kind !== 120 || prop.kind !== 152) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } var currentKind = void 0; - if (prop.kind === 261 || prop.kind === 262) { - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151) { - currentKind = Property; - } - else if (prop.kind === 153) { - currentKind = GetAccessor; - } - else if (prop.kind === 154) { - currentKind = SetAccessor; - } - else { - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + switch (prop.kind) { + case 265: + case 266: + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8) { + checkGrammarNumericLiteral(name); + } + case 152: + currentKind = 1; + break; + case 154: + currentKind = 2; + break; + case 155: + currentKind = 4; + break; + default: + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -38834,11 +39320,11 @@ var ts; seen.set(effectiveName, currentKind); } else { - if (currentKind === Property && existingKind === Property) { + if (currentKind === 1 && existingKind === 1) { grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + else if ((currentKind & 6) && (existingKind & 6)) { + if (existingKind !== 6 && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { @@ -38855,7 +39341,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 255) { + if (attr.kind === 259) { continue; } var jsxAttr = attr; @@ -38867,7 +39353,7 @@ var ts; return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 && !initializer.expression) { + if (initializer && initializer.kind === 260 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -38876,12 +39362,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 217 && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384) === 0) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 227) { + if (forInOrOfStatement.initializer.kind === 228) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -38889,20 +39375,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -38916,7 +39402,7 @@ var ts; if (languageVersion < 1) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (ts.isInAmbientContext(accessor)) { + else if (accessor.flags & 2097152) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { @@ -38929,11 +39415,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 ? + return grammarErrorOnNode(accessor.name, kind === 154 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 154) { + else if (kind === 155) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -38952,15 +39438,50 @@ var ts; } } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 154 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 154 ? 1 : 2)) { return ts.getThisParameter(accessor); } } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 140) { + if (node.type.kind !== 137) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(137)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 227: + var decl = parent; + if (decl.name.kind !== 71) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 150: + if (!ts.hasModifier(parent, 32) || + !ts.hasModifier(parent, 64)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 149: + if (!ts.hasModifier(parent, 64)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -38970,7 +39491,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 178) { + if (node.parent.kind === 179) { if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } @@ -38979,18 +39500,18 @@ var ts; } } if (ts.isClassLike(node.parent)) { - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + if (node.flags & 2097152) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 230) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 231) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 163) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 164) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } function checkGrammarBreakOrContinueStatement(node) { @@ -39000,9 +39521,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 222: + case 223: if (node.label && current.label.escapedText === node.label.escapedText) { - var isMisplacedContinueLabel = node.kind === 217 + var isMisplacedContinueLabel = node.kind === 218 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -39010,8 +39531,8 @@ var ts; return false; } break; - case 221: - if (node.kind === 218 && !node.label) { + case 222: + if (node.kind === 219 && !node.label) { return false; } break; @@ -39024,13 +39545,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 218 + var message = node.kind === 219 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 218 + var message = node.kind === 219 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -39042,7 +39563,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 175 || node.name.kind === 174) { + if (node.name.kind === 176 || node.name.kind === 175) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -39052,12 +39573,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && + expr.kind === 193 && expr.operator === 38 && expr.operand.kind === 8; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { - if (ts.isInAmbientContext(node)) { + if (node.parent.parent.kind !== 216 && node.parent.parent.kind !== 217) { + if (node.flags & 2097152) { if (node.initializer) { if (ts.isConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { @@ -39083,8 +39604,11 @@ var ts; } } } + if (node.exclamationToken && (node.parent.parent.kind !== 209 || !node.type || node.initializer || node.flags & 2097152)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + !(node.parent.parent.flags & 2097152) && ts.hasModifier(node.parent.parent, 1)) { checkESModuleMarker(node.name); } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); @@ -39092,7 +39616,7 @@ var ts; } function checkESModuleMarker(name) { if (name.kind === 71) { - if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } } @@ -39133,15 +39657,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 211: case 212: case 213: - case 220: case 214: + case 221: case 215: case 216: + case 217: return false; - case 222: + case 223: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -39189,49 +39713,56 @@ var ts; } } function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } } function checkGrammarProperty(node) { if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } } - else if (node.parent.kind === 230) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 231) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 163) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 164) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (ts.isInAmbientContext(node) && node.initializer) { + if (node.flags & 2097152 && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } + if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 2097152 || ts.hasModifier(node, 32 | 128))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 230 || - node.kind === 231 || + if (node.kind === 231 || + node.kind === 232 || + node.kind === 239 || node.kind === 238 || - node.kind === 237 || + node.kind === 245 || node.kind === 244 || - node.kind === 243 || - node.kind === 236 || + node.kind === 237 || ts.hasModifier(node, 2 | 1 | 512)) { return false; } @@ -39240,7 +39771,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208) { + if (ts.isDeclaration(decl) || decl.kind === 209) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -39248,10 +39779,10 @@ var ts; } } function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 2097152) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152) { if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; } @@ -39259,7 +39790,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { + if (node.parent.kind === 208 || node.parent.kind === 235 || node.parent.kind === 269) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -39270,15 +39801,15 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 4) { + if (node.numericLiteralFlags & 32) { var diagnosticMessage = void 0; if (languageVersion >= 1) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 173)) { + else if (ts.isChildOfNodeWithKind(node, 174)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 264)) { + else if (ts.isChildOfNodeWithKind(node, 268)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -39297,13 +39828,15 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -39324,8 +39857,8 @@ var ts; ts.createTypeChecker = createTypeChecker; function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 242: - case 246: + case 243: + case 247: return true; default: return ts.isDeclarationName(name); @@ -39333,17 +39866,28 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 239: - case 237: case 240: - case 242: + case 238: + case 241: + case 243: return true; case 71: - return decl.parent.kind === 242; + return decl.parent.kind === 243; default: return false; } } + var JsxNames; + (function (JsxNames) { + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + })(JsxNames || (JsxNames = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -39356,9 +39900,6 @@ var ts; if (updated !== original) { setOriginalNode(updated, original); setTextRange(updated, original); - if (original.startsOnNewLine) { - updated.startsOnNewLine = true; - } ts.aggregateTransformFlags(updated); } return updated; @@ -39381,6 +39922,9 @@ var ts; } ts.createNodeArray = createNodeArray; function getSynthesizedClone(node) { + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -39400,7 +39944,7 @@ var ts; if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } - if (typeof value === "string") { + if (ts.isString(value)) { return createStringLiteral(value); } return createLiteralFromNode(value); @@ -39437,7 +39981,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -39469,11 +40013,12 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - function getGeneratedNameForNode(node) { + function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateKind = 4; name.autoGenerateId = nextAutoGenerateId; name.original = node; + name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; nextAutoGenerateId++; return name; } @@ -39503,7 +40048,7 @@ var ts; } ts.createFalse = createFalse; function createQualifiedName(left, right) { - var node = createSynthesizedNode(143); + var node = createSynthesizedNode(144); node.left = left; node.right = asName(right); return node; @@ -39517,7 +40062,7 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function createComputedPropertyName(expression) { - var node = createSynthesizedNode(144); + var node = createSynthesizedNode(145); node.expression = expression; return node; } @@ -39529,7 +40074,7 @@ var ts; } ts.updateComputedPropertyName = updateComputedPropertyName; function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(145); + var node = createSynthesizedNode(146); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -39545,7 +40090,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(146); + var node = createSynthesizedNode(147); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -39569,7 +40114,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(147); + var node = createSynthesizedNode(148); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -39581,7 +40126,7 @@ var ts; } ts.updateDecorator = updateDecorator; function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148); + var node = createSynthesizedNode(149); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -39601,7 +40146,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149); + var node = createSynthesizedNode(150); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -39623,7 +40168,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(150, typeParameters, parameters, type); + var node = createSignatureDeclaration(151, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -39640,7 +40185,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(151); + var node = createSynthesizedNode(152); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -39668,7 +40213,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(152); + var node = createSynthesizedNode(153); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -39688,7 +40233,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(153); + var node = createSynthesizedNode(154); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -39711,7 +40256,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(154); + var node = createSynthesizedNode(155); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -39732,7 +40277,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); + return createSignatureDeclaration(156, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -39740,7 +40285,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); + return createSignatureDeclaration(157, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -39748,7 +40293,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(157); + var node = createSynthesizedNode(158); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -39785,7 +40330,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(158); + var node = createSynthesizedNode(159); node.parameterName = asName(parameterName); node.type = type; return node; @@ -39799,7 +40344,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(159); + var node = createSynthesizedNode(160); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -39813,7 +40358,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); + return createSignatureDeclaration(161, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -39821,7 +40366,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); + return createSignatureDeclaration(162, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -39829,7 +40374,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(162); + var node = createSynthesizedNode(163); node.exprName = exprName; return node; } @@ -39841,7 +40386,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(163); + var node = createSynthesizedNode(164); node.members = createNodeArray(members); return node; } @@ -39853,7 +40398,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(164); + var node = createSynthesizedNode(165); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -39865,7 +40410,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(165); + var node = createSynthesizedNode(166); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -39877,7 +40422,7 @@ var ts; } ts.updateTypleTypeNode = updateTypleTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(166, types); + return createUnionOrIntersectionTypeNode(167, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -39885,7 +40430,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(167, types); + return createUnionOrIntersectionTypeNode(168, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -39904,7 +40449,7 @@ var ts; : node; } function createParenthesizedType(type) { - var node = createSynthesizedNode(168); + var node = createSynthesizedNode(169); node.type = type; return node; } @@ -39916,22 +40461,22 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(169); + return createSynthesizedNode(170); } ts.createThisTypeNode = createThisTypeNode; - function createTypeOperatorNode(type) { - var node = createSynthesizedNode(170); - node.operator = 127; - node.type = ts.parenthesizeElementTypeMember(type); + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(171); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 127; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } ts.createTypeOperatorNode = createTypeOperatorNode; function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(171); + var node = createSynthesizedNode(172); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -39945,7 +40490,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(172); + var node = createSynthesizedNode(173); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -39963,7 +40508,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(173); + var node = createSynthesizedNode(174); node.literal = literal; return node; } @@ -39975,7 +40520,7 @@ var ts; } ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(174); + var node = createSynthesizedNode(175); node.elements = createNodeArray(elements); return node; } @@ -39987,7 +40532,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(175); + var node = createSynthesizedNode(176); node.elements = createNodeArray(elements); return node; } @@ -39999,7 +40544,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(176); + var node = createSynthesizedNode(177); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -40017,7 +40562,7 @@ var ts; } ts.updateBindingElement = updateBindingElement; function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(177); + var node = createSynthesizedNode(178); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -40031,7 +40576,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(178); + var node = createSynthesizedNode(179); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -40045,7 +40590,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(179); + var node = createSynthesizedNode(180); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); setEmitFlags(node, 131072); @@ -40060,7 +40605,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(180); + var node = createSynthesizedNode(181); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -40074,7 +40619,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(181); + var node = createSynthesizedNode(182); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -40090,7 +40635,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(182); + var node = createSynthesizedNode(183); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -40106,7 +40651,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(183); + var node = createSynthesizedNode(184); node.tag = ts.parenthesizeForAccess(tag); node.template = template; return node; @@ -40120,7 +40665,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(184); + var node = createSynthesizedNode(185); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -40134,7 +40679,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(185); + var node = createSynthesizedNode(186); node.expression = expression; return node; } @@ -40146,7 +40691,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(186); + var node = createSynthesizedNode(187); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -40170,7 +40715,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(187); + var node = createSynthesizedNode(188); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -40204,7 +40749,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(188); + var node = createSynthesizedNode(189); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40216,7 +40761,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(189); + var node = createSynthesizedNode(190); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40228,7 +40773,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(190); + var node = createSynthesizedNode(191); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40240,7 +40785,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(191); + var node = createSynthesizedNode(192); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40252,7 +40797,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(192); + var node = createSynthesizedNode(193); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -40265,7 +40810,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(193); + var node = createSynthesizedNode(194); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -40278,7 +40823,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(194); + var node = createSynthesizedNode(195); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -40295,7 +40840,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(195); + var node = createSynthesizedNode(196); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -40325,7 +40870,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(196); + var node = createSynthesizedNode(197); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -40363,7 +40908,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(197); + var node = createSynthesizedNode(198); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 ? asteriskTokenOrExpression : expression; return node; @@ -40377,7 +40922,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(198); + var node = createSynthesizedNode(199); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -40389,7 +40934,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(199); + var node = createSynthesizedNode(200); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40410,11 +40955,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(200); + return createSynthesizedNode(201); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(201); + var node = createSynthesizedNode(202); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -40428,7 +40973,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(202); + var node = createSynthesizedNode(203); node.expression = expression; node.type = type; return node; @@ -40442,7 +40987,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(203); + var node = createSynthesizedNode(204); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -40454,7 +40999,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(204); + var node = createSynthesizedNode(205); node.keywordToken = keywordToken; node.name = name; return node; @@ -40467,7 +41012,7 @@ var ts; } ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(205); + var node = createSynthesizedNode(206); node.expression = expression; node.literal = literal; return node; @@ -40481,11 +41026,11 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(206); + return createSynthesizedNode(207); } ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { - var block = createSynthesizedNode(207); + var block = createSynthesizedNode(208); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -40499,7 +41044,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(208); + var node = createSynthesizedNode(209); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -40514,11 +41059,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(209); + return createSynthesizedNode(210); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(210); + var node = createSynthesizedNode(211); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -40530,7 +41075,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(211); + var node = createSynthesizedNode(212); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -40546,7 +41091,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(212); + var node = createSynthesizedNode(213); node.statement = statement; node.expression = expression; return node; @@ -40560,7 +41105,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(213); + var node = createSynthesizedNode(214); node.expression = expression; node.statement = statement; return node; @@ -40574,7 +41119,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(214); + var node = createSynthesizedNode(215); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -40592,7 +41137,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(215); + var node = createSynthesizedNode(216); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -40608,7 +41153,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(216); + var node = createSynthesizedNode(217); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -40626,7 +41171,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(217); + var node = createSynthesizedNode(218); node.label = asName(label); return node; } @@ -40638,7 +41183,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(218); + var node = createSynthesizedNode(219); node.label = asName(label); return node; } @@ -40650,7 +41195,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(219); + var node = createSynthesizedNode(220); node.expression = expression; return node; } @@ -40662,7 +41207,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(220); + var node = createSynthesizedNode(221); node.expression = expression; node.statement = statement; return node; @@ -40676,7 +41221,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(221); + var node = createSynthesizedNode(222); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -40690,7 +41235,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(222); + var node = createSynthesizedNode(223); node.label = asName(label); node.statement = statement; return node; @@ -40704,7 +41249,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(223); + var node = createSynthesizedNode(224); node.expression = expression; return node; } @@ -40716,7 +41261,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(224); + var node = createSynthesizedNode(225); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -40732,11 +41277,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(225); + return createSynthesizedNode(226); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); + var node = createSynthesizedNode(227); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -40752,7 +41297,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); + var node = createSynthesizedNode(228); node.flags |= flags & 3; node.declarations = createNodeArray(declarations); return node; @@ -40765,7 +41310,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(228); + var node = createSynthesizedNode(229); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -40791,7 +41336,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(229); + var node = createSynthesizedNode(230); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40813,7 +41358,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(230); + var node = createSynthesizedNode(231); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40835,7 +41380,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(231); + var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40855,7 +41400,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(232); + var node = createSynthesizedNode(233); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40873,7 +41418,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(233); + var node = createSynthesizedNode(234); node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -40892,7 +41437,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(234); + var node = createSynthesizedNode(235); node.statements = createNodeArray(statements); return node; } @@ -40904,7 +41449,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(235); + var node = createSynthesizedNode(236); node.clauses = createNodeArray(clauses); return node; } @@ -40916,7 +41461,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(236); + var node = createSynthesizedNode(237); node.name = asName(name); return node; } @@ -40928,7 +41473,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(237); + var node = createSynthesizedNode(238); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40946,7 +41491,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(238); + var node = createSynthesizedNode(239); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -40964,7 +41509,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(239); + var node = createSynthesizedNode(240); node.name = name; node.namedBindings = namedBindings; return node; @@ -40978,7 +41523,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(240); + var node = createSynthesizedNode(241); node.name = name; return node; } @@ -40990,7 +41535,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(241); + var node = createSynthesizedNode(242); node.elements = createNodeArray(elements); return node; } @@ -41002,7 +41547,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(242); + var node = createSynthesizedNode(243); node.propertyName = propertyName; node.name = name; return node; @@ -41016,11 +41561,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(243); + var node = createSynthesizedNode(244); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = expression; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58, expression, false, undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -41033,7 +41578,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(244); + var node = createSynthesizedNode(245); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -41051,7 +41596,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(245); + var node = createSynthesizedNode(246); node.elements = createNodeArray(elements); return node; } @@ -41063,7 +41608,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246); + var node = createSynthesizedNode(247); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -41077,7 +41622,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createExternalModuleReference(expression) { - var node = createSynthesizedNode(248); + var node = createSynthesizedNode(249); node.expression = expression; return node; } @@ -41089,7 +41634,7 @@ var ts; } ts.updateExternalModuleReference = updateExternalModuleReference; function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(249); + var node = createSynthesizedNode(250); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -41105,7 +41650,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(250); + var node = createSynthesizedNode(251); node.tagName = tagName; node.attributes = attributes; return node; @@ -41119,7 +41664,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(251); + var node = createSynthesizedNode(252); node.tagName = tagName; node.attributes = attributes; return node; @@ -41133,7 +41678,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(252); + var node = createSynthesizedNode(253); node.tagName = tagName; return node; } @@ -41144,8 +41689,24 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(254); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(253); + var node = createSynthesizedNode(257); node.name = name; node.initializer = initializer; return node; @@ -41159,7 +41720,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(254); + var node = createSynthesizedNode(258); node.properties = createNodeArray(properties); return node; } @@ -41171,7 +41732,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(255); + var node = createSynthesizedNode(259); node.expression = expression; return node; } @@ -41183,7 +41744,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(256); + var node = createSynthesizedNode(260); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -41196,7 +41757,7 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; function createCaseClause(expression, statements) { - var node = createSynthesizedNode(257); + var node = createSynthesizedNode(261); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -41210,7 +41771,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(258); + var node = createSynthesizedNode(262); node.statements = createNodeArray(statements); return node; } @@ -41222,7 +41783,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); + var node = createSynthesizedNode(263); node.token = token; node.types = createNodeArray(types); return node; @@ -41235,8 +41796,8 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(260); - node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + var node = createSynthesizedNode(264); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; } @@ -41249,7 +41810,7 @@ var ts; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(261); + var node = createSynthesizedNode(265); node.name = asName(name); node.questionToken = undefined; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -41264,7 +41825,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(262); + var node = createSynthesizedNode(266); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -41278,7 +41839,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(263); + var node = createSynthesizedNode(267); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; return node; } @@ -41290,7 +41851,7 @@ var ts; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { - var node = createSynthesizedNode(264); + var node = createSynthesizedNode(268); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -41305,7 +41866,7 @@ var ts; ts.updateEnumMember = updateEnumMember; function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createSynthesizedNode(265); + var updated = createSynthesizedNode(269); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -41374,28 +41935,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(287); + var node = createSynthesizedNode(291); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(291); + var node = createSynthesizedNode(295); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(290); + var node = createSynthesizedNode(294); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(288); + var node = createSynthesizedNode(292); node.expression = expression; node.original = original; setTextRange(node, original); @@ -41411,7 +41972,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 289) { + if (node.kind === 293) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -41421,7 +41982,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(289); + var node = createSynthesizedNode(293); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -41433,7 +41994,7 @@ var ts; } ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { - var node = ts.createNode(266); + var node = ts.createNode(270); node.sourceFiles = sourceFiles; return node; } @@ -41510,10 +42071,10 @@ var ts; } ts.createExternalModuleExport = createExternalModuleExport; function asName(name) { - return typeof name === "string" ? createIdentifier(name) : name; + return ts.isString(name) ? createIdentifier(name) : name; } function asExpression(value) { - return typeof value === "string" || typeof value === "number" ? createLiteral(value) : value; + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -41536,7 +42097,7 @@ var ts; function getOrCreateEmitNode(node) { if (!node.emitNode) { if (ts.isParseTreeNode(node)) { - if (node.kind === 265) { + if (node.kind === 269) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -41560,6 +42121,12 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; function getSourceMapRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.sourceMapRange) || node; @@ -41588,6 +42155,16 @@ var ts; return node; } ts.setTokenSourceMapRange = setTokenSourceMapRange; + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; function getCommentRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.commentRange) || node; @@ -41715,7 +42292,7 @@ var ts; } ts.setOriginalNode = setOriginalNode; function mergeEmitNode(sourceEmitNode, destEmitNode) { - var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; if (!destEmitNode) destEmitNode = {}; if (leadingComments) @@ -41734,6 +42311,8 @@ var ts; destEmitNode.constantValue = constantValue; if (helpers) destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -41822,12 +42401,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); + return createReactNamespace(ts.idText(jsxFactory), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -41847,7 +42426,7 @@ var ts; if (children.length > 1) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; - child.startsOnNewLine = true; + startOnNewLine(child); argumentsList.push(child); } } @@ -41858,6 +42437,25 @@ var ts; return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); } ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; function getHelperName(name) { return ts.setEmitFlags(ts.createIdentifier(name), 4096 | 2); } @@ -41920,7 +42518,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 222 + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 223 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -41938,13 +42536,13 @@ var ts; case 8: case 9: return false; - case 177: + case 178: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 178: + case 179: return target.properties.length > 0; default: return true; @@ -41970,7 +42568,7 @@ var ts; } else { switch (callee.kind) { - case 179: { + case 180: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = ts.createTempVariable(recordTempVariable); target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); @@ -41982,7 +42580,7 @@ var ts; } break; } - case 180: { + case 181: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = ts.createTempVariable(recordTempVariable); target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); @@ -42035,14 +42633,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 153: case 154: + case 155: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 261: + case 265: return createExpressionForPropertyAssignment(property, receiver); - case 262: + case 266: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 151: + case 152: return createExpressionForMethodDeclaration(property, receiver); } } @@ -42157,8 +42755,8 @@ var ts; var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); - if (node.startsOnNewLine) { - updated.startsOnNewLine = true; + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, true); } ts.aggregateTransformFlags(updated); return updated; @@ -42201,7 +42799,7 @@ var ts; while (statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { break; @@ -42242,7 +42840,7 @@ var ts; ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 185) { + if (skipped.kind === 186) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -42251,15 +42849,15 @@ var ts; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(194, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(194, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(195, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(195, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 197) { + && operand.kind === 198) { return false; } return true; @@ -42298,7 +42896,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 194 && node.operatorToken.kind === 37) { + if (node.kind === 195 && node.operatorToken.kind === 37) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -42313,7 +42911,7 @@ var ts; return 0; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); + var conditionalPrecedence = ts.getOperatorPrecedence(196, 55); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { @@ -42323,20 +42921,30 @@ var ts; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 194 && e.operatorToken.kind === 26 + return e.kind === 195 && e.operatorToken.kind === 26 ? ts.createParen(e) : e; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + return (check.kind === 200 || + check.kind === 187 || + check.kind === 293 || + ts.isBinaryExpression(check) && check.operatorToken.kind === 26) + ? ts.createParen(e) + : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; function parenthesizeForNew(expression) { - var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); - switch (emittedExpression.kind) { - case 181: - return ts.createParen(expression); + var leftmostExpr = getLeftmostExpression(expression, true); + switch (leftmostExpr.kind) { case 182: - return emittedExpression.arguments - ? expression - : ts.createParen(expression); + return ts.createParen(expression); + case 183: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; } return parenthesizeForAccess(expression); } @@ -42344,7 +42952,7 @@ var ts; function parenthesizeForAccess(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 182 || emittedExpression.arguments)) { + && (emittedExpression.kind !== 183 || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -42382,7 +42990,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(194, 26); + var commaPrecedence = ts.getOperatorPrecedence(195, 26); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -42393,14 +43001,14 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 186 || kind === 187) { + if (kind === 187 || kind === 188) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4); } } - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, false).kind; + if (leftmostExpressionKind === 179 || leftmostExpressionKind === 187) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; @@ -42408,10 +43016,10 @@ var ts; ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 166: case 167: - case 160: + case 168: case 161: + case 162: return ts.createParenthesizedType(member); } return member; @@ -42419,8 +43027,8 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 162: - case 170: + case 163: + case 171: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -42443,24 +43051,27 @@ var ts; } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function getLeftmostExpression(node) { + function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 193: + case 194: node = node.operand; continue; - case 194: + case 195: node = node.left; continue; - case 195: + case 196: node = node.condition; continue; + case 182: + if (stopAtCallExpressions) { + return node; + } case 181: case 180: - case 179: node = node.expression; continue; - case 288: + case 292: node = node.expression; continue; } @@ -42468,29 +43079,22 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body).kind === 178) { + if (!ts.isBlock(body) && getLeftmostExpression(body, false).kind === 179) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; - var OuterExpressionKinds; - (function (OuterExpressionKinds) { - OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; - OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; - OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; - OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; - })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7; } switch (node.kind) { - case 185: + case 186: return (kinds & 1) !== 0; - case 184: - case 202: + case 185: case 203: + case 204: return (kinds & 2) !== 0; - case 288: + case 292: return (kinds & 4) !== 0; } return false; @@ -42515,14 +43119,14 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 185) { + while (node.kind === 186) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 203) { + while (ts.isAssertionExpression(node) || node.kind === 204) { node = node.expression; } return node; @@ -42530,15 +43134,15 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 185: return ts.updateParen(outerExpression, expression); - case 184: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 202: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 203: return ts.updateNonNullExpression(outerExpression, expression); - case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 186: return ts.updateParen(outerExpression, expression); + case 185: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 203: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 204: return ts.updateNonNullExpression(outerExpression, expression); + case 292: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { - return node.kind === 185 + return node.kind === 186 && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -42554,8 +43158,7 @@ var ts; } ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { - node.startsOnNewLine = true; - return node; + return ts.setStartsOnNewLine(node, true); } ts.startOnNewLine = startOnNewLine; function getExternalHelpersModuleName(node) { @@ -42599,12 +43202,12 @@ var ts; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { var name = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 238 && node.importClause) { + if (node.kind === 239 && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 244 && node.moduleSpecifier) { + if (node.kind === 245 && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -42666,11 +43269,11 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 261: + case 265: return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 262: + case 266: return bindingElement.name; - case 263: + case 267: return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return undefined; @@ -42686,11 +43289,11 @@ var ts; ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 146: - case 176: + case 147: + case 177: return bindingElement.dotDotDotToken; - case 198: - case 263: + case 199: + case 267: return bindingElement; } return undefined; @@ -42698,7 +43301,7 @@ var ts; ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 176: + case 177: if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) @@ -42706,7 +43309,7 @@ var ts; : propertyName; } break; - case 261: + case 265: if (bindingElement.name) { var propertyName = bindingElement.name; return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) @@ -42714,7 +43317,7 @@ var ts; : propertyName; } break; - case 263: + case 267: return bindingElement.name; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); @@ -42728,11 +43331,11 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 174: case 175: - case 177: - return name.elements; + case 176: case 178: + return name.elements; + case 179: return name.properties; } } @@ -42771,11 +43374,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: - return convertToArrayAssignmentPattern(node); - case 174: + case 176: case 178: + return convertToArrayAssignmentPattern(node); + case 175: + case 179: return convertToObjectAssignmentPattern(node); } } @@ -42911,249 +43514,251 @@ var ts; return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 142) || kind === 169) { + if ((kind > 0 && kind <= 143) || kind === 170) { return node; } switch (kind) { case 71: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 143: - return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: - return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); case 146: - return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 147: - return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 148: - return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 155: - return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 156: - return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 157: - return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: - return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: - return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 164: - return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 165: - return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 166: - return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 167: - return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 169: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170: - return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); case 171: - return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); case 172: - return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 173: - return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 174: - return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); case 175: - return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 176: - return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); case 177: - return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); case 178: - return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); case 179: - return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); case 180: - return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); case 181: - return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); case 182: - return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 183: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 184: - return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 185: - return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 186: - return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188: - return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 189: - return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 190: - return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: - return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 192: - return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); case 193: - return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); case 195: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 196: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 197: - return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 198: - return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); case 199: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 201: - return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202: - return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 203: - return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 204: - return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 205: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 206: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - case 207: - return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 208: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 209: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 210: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 211: - return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 212: - return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); case 213: - return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); case 214: - return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 215: - return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 216: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217: - return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218: - return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219: - return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); case 220: - return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); case 221: - return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 222: - return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); case 223: - return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 224: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 225: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 226: - return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 227: - return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 228: - return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 229: - return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 230: - return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 231: - return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 232: - return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 233: - return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 234: - return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); case 235: - return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 236: - return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 237: - return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 238: - return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 239: - return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 240: - return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); case 241: - return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); case 242: - return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); case 243: - return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); case 244: - return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); case 245: - return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 246: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 247: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 248: - return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: - return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 250: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 251: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 252: - return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 253: - return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 254: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 257: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 258: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 255: + case 259: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 256: + case 260: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 257: + case 261: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258: + case 262: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 259: + case 263: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 260: + case 264: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); - case 261: + case 265: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 262: + case 266: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 263: + case 267: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); - case 264: + case 268: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 265: + case 269: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 288: + case 292: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 289: + case 293: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -43179,52 +43784,52 @@ var ts; var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 142)) { + if ((kind > 0 && kind <= 143)) { return initial; } - if ((kind >= 158 && kind <= 173)) { + if ((kind >= 159 && kind <= 174)) { return initial; } var result = initial; switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 287: + case 207: + case 210: + case 201: + case 226: + case 291: break; - case 143: + case 144: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 144: + case 145: result = reduceNode(node.expression, cbNode, result); break; - case 146: + case 147: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 147: + case 148: result = reduceNode(node.expression, cbNode, result); break; - case 148: + case 149: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149: + case 150: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151: + case 152: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43233,12 +43838,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 152: + case 153: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 153: + case 154: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43246,55 +43851,55 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154: + case 155: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 174: case 175: + case 176: result = reduceNodes(node.elements, cbNodes, result); break; - case 176: + case 177: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 177: + case 178: result = reduceNodes(node.elements, cbNodes, result); break; - case 178: + case 179: result = reduceNodes(node.properties, cbNodes, result); break; - case 179: + case 180: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 180: + case 181: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 181: + case 182: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 182: + case 183: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 183: + case 184: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 184: + case 185: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 186: + case 187: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -43302,121 +43907,121 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 187: + case 188: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 185: - case 188: + case 186: case 189: case 190: case 191: - case 197: + case 192: case 198: - case 203: + case 199: + case 204: result = reduceNode(node.expression, cbNode, result); break; - case 192: case 193: + case 194: result = reduceNode(node.operand, cbNode, result); break; - case 194: + case 195: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 195: + case 196: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 196: + case 197: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 199: + case 200: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 201: + case 202: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 202: + case 203: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 205: + case 206: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; - case 207: + case 208: result = reduceNodes(node.statements, cbNodes, result); break; - case 208: + case 209: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 210: + case 211: result = reduceNode(node.expression, cbNode, result); break; - case 211: + case 212: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 212: + case 213: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 213: - case 220: + case 214: + case 221: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 214: + case 215: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 215: case 216: + case 217: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219: - case 223: + case 220: + case 224: result = reduceNode(node.expression, cbNode, result); break; - case 221: + case 222: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 222: + case 223: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224: + case 225: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 226: + case 227: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 227: + case 228: result = reduceNodes(node.declarations, cbNodes, result); break; - case 228: + case 229: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43425,7 +44030,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 229: + case 230: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43433,126 +44038,131 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 232: + case 233: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 233: + case 234: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 234: + case 235: result = reduceNodes(node.statements, cbNodes, result); break; - case 235: + case 236: result = reduceNodes(node.clauses, cbNodes, result); break; - case 237: + case 238: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 238: + case 239: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 239: - result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.namedBindings, cbNode, result); - break; case 240: result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); break; case 241: - case 245: - result = reduceNodes(node.elements, cbNodes, result); + result = reduceNode(node.name, cbNode, result); break; case 242: case 246: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 243: + case 247: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 243: + case 244: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 244: + case 245: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248: + case 249: result = reduceNode(node.expression, cbNode, result); break; - case 249: + case 250: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 250: + case 254: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; case 251: + case 252: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 254: + case 258: result = reduceNodes(node.properties, cbNodes, result); break; - case 252: + case 253: result = reduceNode(node.tagName, cbNode, result); break; - case 253: + case 257: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 255: + case 259: result = reduceNode(node.expression, cbNode, result); break; - case 256: + case 260: result = reduceNode(node.expression, cbNode, result); break; - case 257: + case 261: result = reduceNode(node.expression, cbNode, result); - case 258: + case 262: result = reduceNodes(node.statements, cbNodes, result); break; - case 259: + case 263: result = reduceNodes(node.types, cbNodes, result); break; - case 260: + case 264: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; - case 261: + case 265: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262: + case 266: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 263: + case 267: result = reduceNode(node.expression, cbNode, result); break; - case 264: + case 268: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 265: + case 269: result = reduceNodes(node.statements, cbNodes, result); break; - case 288: + case 292: result = reduceNode(node.expression, cbNode, result); break; - case 289: + case 293: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -43605,7 +44215,7 @@ var ts; return subtreeFlags; } function aggregateTransformFlagsForSubtree(node) { - if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 201)) { + if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 202)) { return 0; } return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); @@ -43641,12 +44251,12 @@ var ts; if (isDebugInfoEnabled) return; Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, - "__debugObjectFlags": { get: function () { return this.flags & 32768 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, - "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 65536 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ ts.objectAllocator.getNodeConstructor(), @@ -43658,11 +44268,11 @@ var ts; var ctor = nodeConstructors_1[_i]; if (!ctor.prototype.hasOwnProperty("__debugKind")) { Object.defineProperties(ctor.prototype, { - "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, - "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, - "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, - "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, - "__debugGetText": { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { value: function (includeTrivia) { if (ts.nodeIsSynthesized(this)) return ""; @@ -43698,15 +44308,15 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 238: + case 239: externalImports.push(node); break; - case 237: - if (node.moduleReference.kind === 248) { + case 238: + if (node.moduleReference.kind === 249) { externalImports.push(node); } break; - case 244: + case 245: if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -43719,26 +44329,26 @@ var ts; else { for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + if (!uniqueExports.get(ts.idText(specifier.name))) { var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + exportSpecifiers.add(ts.idText(name), specifier); var decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + uniqueExports.set(ts.idText(specifier.name), true); exportedNames = ts.append(exportedNames, specifier.name); } } } break; - case 243: + case 244: if (node.isExportEquals && !exportEquals) { exportEquals = node; } break; - case 208: + case 209: if (ts.hasModifier(node, 1)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -43746,7 +44356,7 @@ var ts; } } break; - case 228: + case 229: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -43756,15 +44366,15 @@ var ts; } else { var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (!uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } } break; - case 229: + case 230: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -43774,9 +44384,9 @@ var ts; } else { var name = node.name; - if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } @@ -43802,8 +44412,9 @@ var ts; } } else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { - uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); exportedNames = ts.append(exportedNames, decl.name); } } @@ -43819,14 +44430,17 @@ var ts; } return values; } + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 || + expression.kind === 8 || + expression.kind === 13 || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); var ts; (function (ts) { - var FlattenLevel; - (function (FlattenLevel) { - FlattenLevel[FlattenLevel["All"] = 0] = "All"; - FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; - })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; var value; @@ -44076,7 +44690,7 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); + var name = ts.createIdentifier(ts.idText(propertyName)); return ts.createPropertyAccess(value, name); } } @@ -44147,40 +44761,19 @@ var ts; var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; - var TypeScriptSubstitutionFlags; - (function (TypeScriptSubstitutionFlags) { - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; - })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); - var ClassFacts; - (function (ClassFacts) { - ClassFacts[ClassFacts["None"] = 0] = "None"; - ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; - ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; - ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; - ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; - ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; - ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; - ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; - ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; - ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; - ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; - ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; - })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179); context.enableSubstitution(180); + context.enableSubstitution(181); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; @@ -44189,6 +44782,7 @@ var ts; var enabledSubstitutions; var classAliases; var applicableSubstitutions; + var pendingExpressions; return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -44213,15 +44807,15 @@ var ts; } function onBeforeVisitNode(node) { switch (node.kind) { - case 265: + case 269: + case 236: case 235: - case 234: - case 207: + case 208: currentScope = node; currentScopeFirstDeclarationsOfName = undefined; break; + case 230: case 229: - case 228: if (ts.hasModifier(node, 2)) { break; } @@ -44229,7 +44823,7 @@ var ts; recordEmittedDeclarationInScope(node); } else { - ts.Debug.assert(node.kind === 229 || ts.hasModifier(node, 512)); + ts.Debug.assert(node.kind === 230 || ts.hasModifier(node, 512)); } break; } @@ -44251,10 +44845,10 @@ var ts; } function sourceElementVisitorWorker(node) { switch (node.kind) { + case 239: case 238: - case 237: - case 243: case 244: + case 245: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -44263,16 +44857,19 @@ var ts; function visitEllidableStatement(node) { var parsed = ts.getParseTreeNode(node); if (parsed !== node) { + if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } return node; } switch (node.kind) { - case 238: + case 239: return visitImportDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); - case 243: - return visitExportAssignment(node); case 244: + return visitExportAssignment(node); + case 245: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -44282,11 +44879,11 @@ var ts; return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 244 || - node.kind === 238 || + if (node.kind === 245 || node.kind === 239 || - (node.kind === 237 && - node.moduleReference.kind === 248)) { + node.kind === 240 || + (node.kind === 238 && + node.moduleReference.kind === 249)) { return undefined; } else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { @@ -44302,15 +44899,15 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 152: - return undefined; - case 149: - case 157: case 153: + return undefined; + case 150: + case 158: case 154: - case 151: + case 155: + case 152: return visitorWorker(node); - case 206: + case 207: return node; default: ts.Debug.failBadSyntaxKind(node); @@ -44341,11 +44938,11 @@ var ts; case 76: case 124: case 131: - case 164: case 165: - case 163: - case 158: - case 145: + case 166: + case 164: + case 159: + case 146: case 119: case 122: case 136: @@ -44353,11 +44950,10 @@ var ts; case 130: case 105: case 137: + case 162: case 161: + case 163: case 160: - case 162: - case 159: - case 166: case 167: case 168: case 169: @@ -44365,58 +44961,61 @@ var ts; case 171: case 172: case 173: - case 157: - case 147: - case 231: - case 149: - case 236: + case 174: + case 158: + case 148: + case 232: return undefined; - case 152: + case 150: + return visitPropertyDeclaration(node); + case 237: + return undefined; + case 153: return visitConstructor(node); - case 230: + case 231: return ts.createNotEmittedStatement(node); - case 229: + case 230: return visitClassDeclaration(node); - case 199: + case 200: return visitClassExpression(node); - case 259: + case 263: return visitHeritageClause(node); - case 201: + case 202: return visitExpressionWithTypeArguments(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 153: - return visitGetAccessor(node); case 154: + return visitGetAccessor(node); + case 155: return visitSetAccessor(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: - return visitFunctionExpression(node); case 187: + return visitFunctionExpression(node); + case 188: return visitArrowFunction(node); - case 146: + case 147: return visitParameter(node); - case 185: + case 186: return visitParenthesizedExpression(node); - case 184: - case 202: + case 185: + case 203: return visitAssertionExpression(node); - case 181: - return visitCallExpression(node); case 182: + return visitCallExpression(node); + case 183: return visitNewExpression(node); - case 203: + case 204: return visitNonNullExpression(node); - case 232: + case 233: return visitEnumDeclaration(node); - case 208: + case 209: return visitVariableStatement(node); - case 226: + case 227: return visitVariableDeclaration(node); - case 233: + case 234: return visitModuleDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); default: ts.Debug.failBadSyntaxKind(node); @@ -44424,7 +45023,7 @@ var ts; } } function visitSourceFile(node) { - var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } @@ -44445,7 +45044,8 @@ var ts; var facts = 0; if (ts.some(staticProperties)) facts |= 1; - if (ts.getClassExtendsHeritageClauseElement(node)) + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95) facts |= 64; if (shouldEmitDecorateCallForClass(node)) facts |= 2; @@ -44462,6 +45062,8 @@ var ts; return facts; } function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); var facts = getClassFacts(node, staticProperties); if (facts & 128) { @@ -44472,6 +45074,10 @@ var ts; ? createClassDeclarationHeadWithDecorators(node, name, facts) : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; + if (ts.some(pendingExpressions)) { + statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; if (facts & 1) { addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); } @@ -44549,13 +45155,15 @@ var ts; return statement; } function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85; })); var classExpression = ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, node); - if (staticProperties.length > 0) { + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; var temp = ts.createTempVariable(hoistVariableDeclaration); if (resolver.getNodeCheckFlags(node) & 8388608) { @@ -44564,22 +45172,25 @@ var ts; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } + pendingExpressions = savedPendingExpressions; return classExpression; } - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(ts.createNodeArray(members), node.members); } - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); @@ -44587,14 +45198,14 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); } function transformConstructorParameters(constructor) { return ts.visitParameterList(constructor && constructor.parameters, visitor, context) || []; } - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -44603,7 +45214,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); @@ -44622,7 +45233,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -44656,7 +45267,7 @@ var ts; return isInitializedProperty(member, false); } function isInitializedProperty(member, isStatic) { - return member.kind === 149 + return member.kind === 150 && isStatic === ts.hasModifier(member, 32) && member.initializer !== undefined; } @@ -44674,7 +45285,7 @@ var ts; for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); expressions.push(expression); @@ -44682,22 +45293,24 @@ var ts; return expressions; } function transformInitializedProperty(property, receiver) { - var propertyName = visitPropertyNameOfClassElement(property); + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32))) + : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); return ts.createAssignment(memberAccess, initializer); } function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); } - function isStaticDecoratedClassElement(member) { - return isDecoratedClassElement(member, true); + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, true, parent); } - function isInstanceDecoratedClassElement(member) { - return isDecoratedClassElement(member, false); + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, false, parent); } - function isDecoratedClassElement(member, isStatic) { - return ts.nodeOrChildIsDecorated(member) + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) && isStatic === ts.hasModifier(member, 32); } function getDecoratorsOfParameters(node) { @@ -44729,12 +45342,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 153: case 154: + case 155: return getAllDecoratorsOfAccessors(node, member); - case 151: + case 152: return getAllDecoratorsOfMethod(member); - case 149: + case 150: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -44790,8 +45403,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { - var member = members_3[_i]; + for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { + var member = members_4[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -44813,7 +45426,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 149 + ? member.kind === 150 ? ts.createVoidZero() : ts.createNull() : undefined; @@ -44897,37 +45510,37 @@ var ts; } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 151 - || kind === 153 + return kind === 152 || kind === 154 - || kind === 149; + || kind === 155 + || kind === 150; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 151; + return node.kind === 152; } function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 229: - case 199: + case 230: + case 200: return ts.getFirstConstructorWithBody(node) !== undefined; - case 151: - case 153: + case 152: case 154: + case 155: return true; } return false; } function serializeTypeOfNode(node) { switch (node.kind) { - case 149: - case 146: - case 153: - return serializeTypeNode(node.type); + case 150: + case 147: case 154: + return serializeTypeNode(node.type); + case 155: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 229: - case 199: - case 151: + case 230: + case 200: + case 152: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -44959,7 +45572,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 153) { + if (container && node.kind === 154) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -44986,22 +45599,22 @@ var ts; case 95: case 130: return ts.createVoidZero(); - case 168: + case 169: return serializeTypeNode(node.type); - case 160: case 161: + case 162: return ts.createIdentifier("Function"); - case 164: case 165: + case 166: return ts.createIdentifier("Array"); - case 158: + case 159: case 122: return ts.createIdentifier("Boolean"); case 136: return ts.createIdentifier("String"); case 134: return ts.createIdentifier("Object"); - case 173: + case 174: switch (node.literal.kind) { case 9: return ts.createIdentifier("String"); @@ -45021,18 +45634,18 @@ var ts; return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 159: + case 160: return serializeTypeReferenceNode(node); + case 168: case 167: - case 166: return serializeUnionOrIntersectionType(node); - case 162: - case 170: + case 163: case 171: case 172: - case 163: + case 173: + case 164: case 119: - case 169: + case 170: break; default: ts.Debug.failBadSyntaxKind(node); @@ -45044,6 +45657,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169) { + typeNode = typeNode.type; + } + if (typeNode.kind === 130) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 139)) { + continue; + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; @@ -45059,7 +45681,7 @@ var ts; serializedUnion = serializedIndividual; } } - return serializedUnion; + return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { @@ -45103,7 +45725,7 @@ var ts; return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } return name; - case 143: + case 144: return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -45124,30 +45746,46 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; if (ts.isComputedPropertyName(name)) { - return generateNameForComputedPropertyName + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? ts.getGeneratedNameForNode(name) : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.getSynthesizedClone(name); } } - function visitPropertyNameOfClassElement(member) { - var name = member.name; + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { if (ts.isComputedPropertyName(name)) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - if (member.decorators) { + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { var generatedName = ts.getGeneratedNameForNode(name); hoistVariableDeclaration(generatedName); - expression = ts.createAssignment(generatedName, expression); + return ts.createAssignment(generatedName, expression); } - return ts.updateComputedPropertyName(name, expression); + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), false); + if (expr) { + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); } else { return name; @@ -45166,6 +45804,13 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -45390,11 +46035,11 @@ var ts; function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ], currentScope.kind === 265 ? 0 : 1)); + ], currentScope.kind === 269 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { - if (node.kind === 232) { + if (node.kind === 233) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -45455,7 +46100,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 234) { + if (body.kind === 235) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -45479,13 +46124,13 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true); ts.setTextRange(block, blockLocation); - if (body.kind !== 234) { + if (body.kind !== 235) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 233) { + if (moduleDeclaration.body.kind === 234) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -45505,7 +46150,7 @@ var ts; return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; } function visitNamedImportBindings(node) { - if (node.kind === 240) { + if (node.kind === 241) { return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } else { @@ -45609,7 +46254,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -45640,15 +46285,15 @@ var ts; if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; context.enableSubstitution(71); - context.enableSubstitution(262); - context.enableEmitNotification(233); + context.enableSubstitution(266); + context.enableEmitNotification(234); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 233; + return ts.getOriginalNode(node).kind === 234; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 232; + return ts.getOriginalNode(node).kind === 233; } function onEmitNode(hint, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; @@ -45694,9 +46339,9 @@ var ts; switch (node.kind) { case 71: return substituteExpressionIdentifier(node); - case 179: - return substitutePropertyAccessExpression(node); case 180: + return substitutePropertyAccessExpression(node); + case 181: return substituteElementAccessExpression(node); } return node; @@ -45726,9 +46371,9 @@ var ts; function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container && container.kind !== 265) { - var substitute = (applicableSubstitutions & 2 && container.kind === 233) || - (applicableSubstitutions & 8 && container.kind === 232); + if (container && container.kind !== 269) { + var substitute = (applicableSubstitutions & 2 && container.kind === 234) || + (applicableSubstitutions & 8 && container.kind === 233); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), node); } @@ -45815,10 +46460,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ES2017SubstitutionFlags; - (function (ES2017SubstitutionFlags) { - ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; - })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; var resolver = context.getEmitResolver(); @@ -45846,15 +46487,15 @@ var ts; switch (node.kind) { case 120: return undefined; - case 191: + case 192: return visitAwaitExpression(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: - return visitFunctionExpression(node); case 187: + return visitFunctionExpression(node); + case 188: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -45888,7 +46529,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 187; + var isArrowFunction = node.kind === 188; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; if (!isArrowFunction) { var statements = []; @@ -45944,14 +46585,14 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(181); - context.enableSubstitution(179); + context.enableSubstitution(182); context.enableSubstitution(180); - context.enableEmitNotification(229); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); + context.enableSubstitution(181); + context.enableEmitNotification(230); context.enableEmitNotification(152); + context.enableEmitNotification(154); + context.enableEmitNotification(155); + context.enableEmitNotification(153); } } function onEmitNode(hint, node, emitCallback) { @@ -45976,18 +46617,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179: - return substitutePropertyAccessExpression(node); case 180: - return substituteElementAccessExpression(node); + return substitutePropertyAccessExpression(node); case 181: + return substituteElementAccessExpression(node); + case 182: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -46011,11 +46652,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 - || kind === 152 - || kind === 151 + return kind === 230 || kind === 153 - || kind === 154; + || kind === 152 + || kind === 154 + || kind === 155; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { @@ -46036,7 +46677,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288; return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ ts.createThis(), hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), @@ -46057,10 +46698,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ESNextSubstitutionFlags; - (function (ESNextSubstitutionFlags) { - ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; - })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); function transformESNext(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -46099,45 +46736,45 @@ var ts; return node; } switch (node.kind) { - case 191: + case 192: return visitAwaitExpression(node); - case 197: + case 198: return visitYieldExpression(node); - case 222: + case 223: return visitLabeledStatement(node); - case 178: + case 179: return visitObjectLiteralExpression(node); - case 194: + case 195: return visitBinaryExpression(node, noDestructuringValue); - case 226: + case 227: return visitVariableDeclaration(node); - case 216: + case 217: return visitForOfStatement(node, undefined); - case 214: + case 215: return visitForStatement(node); - case 190: + case 191: return visitVoidExpression(node); - case 152: + case 153: return visitConstructorDeclaration(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 153: - return visitGetAccessorDeclaration(node); case 154: + return visitGetAccessorDeclaration(node); + case 155: return visitSetAccessorDeclaration(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: - return visitFunctionExpression(node); case 187: + return visitFunctionExpression(node); + case 188: return visitArrowFunction(node); - case 146: + case 147: return visitParameter(node); - case 210: + case 211: return visitExpressionStatement(node); - case 185: + case 186: return visitParenthesizedExpression(node, noDestructuringValue); - case 260: + case 264: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -46159,7 +46796,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 216 && statement.awaitModifier) { + if (statement.kind === 217 && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); @@ -46171,7 +46808,7 @@ var ts; var objects = []; for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { var e = elements_3[_i]; - if (e.kind === 263) { + if (e.kind === 267) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -46183,7 +46820,7 @@ var ts; if (!chunkObject) { chunkObject = []; } - if (e.kind === 261) { + if (e.kind === 265) { var p = e; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } @@ -46200,7 +46837,7 @@ var ts; function visitObjectLiteralExpression(node) { if (node.transformFlags & 1048576) { var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 178) { + if (objects.length && objects[0].kind !== 179) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -46451,14 +47088,14 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(181); - context.enableSubstitution(179); + context.enableSubstitution(182); context.enableSubstitution(180); - context.enableEmitNotification(229); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); + context.enableSubstitution(181); + context.enableEmitNotification(230); context.enableEmitNotification(152); + context.enableEmitNotification(154); + context.enableEmitNotification(155); + context.enableEmitNotification(153); } } function onEmitNode(hint, node, emitCallback) { @@ -46483,18 +47120,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179: - return substitutePropertyAccessExpression(node); case 180: - return substituteElementAccessExpression(node); + return substitutePropertyAccessExpression(node); case 181: + return substituteElementAccessExpression(node); + case 182: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -46518,11 +47155,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 - || kind === 152 - || kind === 151 + return kind === 230 || kind === 153 - || kind === 154; + || kind === 152 + || kind === 154 + || kind === 155; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { @@ -46596,11 +47233,13 @@ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { return node; } + currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; @@ -46615,11 +47254,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 249: - return visitJsxElement(node, false); case 250: + return visitJsxElement(node, false); + case 251: return visitJsxSelfClosingElement(node, false); - case 256: + case 254: + return visitJsxFragment(node, false); + case 260: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -46629,12 +47270,14 @@ var ts; switch (node.kind) { case 10: return visitJsxText(node); - case 256: + case 260: return visitJsxExpression(node); - case 249: - return visitJsxElement(node, true); case 250: + return visitJsxElement(node, true); + case 251: return visitJsxSelfClosingElement(node, true); + case 254: + return visitJsxFragment(node, true); default: ts.Debug.failBadSyntaxKind(node); return undefined; @@ -46646,6 +47289,9 @@ var ts; function visitJsxSelfClosingElement(node, isChild) { return visitJsxOpeningLikeElement(node, undefined, isChild, node); } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, node); + } function visitJsxOpeningLikeElement(node, children, isChild, location) { var tagName = getTagName(node); var objectProperties; @@ -46671,6 +47317,13 @@ var ts; } return element; } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -46684,10 +47337,11 @@ var ts; return ts.createTrue(); } else if (node.kind === 9) { - var decoded = tryDecodeEntities(node.text); - return decoded ? ts.setTextRange(ts.createLiteral(decoded), node) : node; + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); } - else if (node.kind === 256) { + else if (node.kind === 260) { if (node.expression === undefined) { return ts.createTrue(); } @@ -46747,13 +47401,13 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 249) { + if (node.kind === 250) { return getTagName(node.openingElement); } else { var name = node.tagName; if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.createExpressionFromEntityName(name); @@ -46762,11 +47416,12 @@ var ts; } function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { return name; } else { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(text); } } function visitJsxExpression(node) { @@ -46775,259 +47430,259 @@ var ts; } ts.transformJsx = transformJsx; var entities = ts.createMapFromTemplate({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 }); })(ts || (ts = {})); var ts; @@ -47046,7 +47701,7 @@ var ts; return node; } switch (node.kind) { - case 194: + case 195: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -47094,75 +47749,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ES2015SubstitutionFlags; - (function (ES2015SubstitutionFlags) { - ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; - ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; - })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); - var CopyDirection; - (function (CopyDirection) { - CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; - CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; - })(CopyDirection || (CopyDirection = {})); - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); - var HierarchyFacts; - (function (HierarchyFacts) { - HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; - HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; - HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; - HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement"; - HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis"; - HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement"; - HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel"; - HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block"; - HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement"; - HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock"; - HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; - HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; - HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; - HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; - HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; - HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; - HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; - HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; - HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; - HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; - HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; - HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; - HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; - HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; - HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; - HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; - HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; - HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; - HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; - })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); @@ -47174,6 +47760,10 @@ var ts; var currentSourceFile; var currentText; var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } var convertedLoopState; var enabledSubstitutions; return transformSourceFile; @@ -47187,6 +47777,7 @@ var ts; ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; currentText = undefined; + taggedTemplateStringDeclarations = undefined; hierarchyFacts = 0; return visited; } @@ -47200,13 +47791,13 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return hierarchyFacts & 4096 - && node.kind === 219 + && node.kind === 220 && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 208))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432) !== 0; } @@ -47234,63 +47825,63 @@ var ts; switch (node.kind) { case 115: return undefined; - case 229: + case 230: return visitClassDeclaration(node); - case 199: + case 200: return visitClassExpression(node); - case 146: + case 147: return visitParameter(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 187: + case 188: return visitArrowFunction(node); - case 186: + case 187: return visitFunctionExpression(node); - case 226: + case 227: return visitVariableDeclaration(node); case 71: return visitIdentifier(node); - case 227: + case 228: return visitVariableDeclarationList(node); - case 221: + case 222: return visitSwitchStatement(node); - case 235: + case 236: return visitCaseBlock(node); - case 207: + case 208: return visitBlock(node, false); + case 219: case 218: - case 217: return visitBreakOrContinueStatement(node); - case 222: + case 223: return visitLabeledStatement(node); - case 212: case 213: - return visitDoOrWhileStatement(node, undefined); case 214: - return visitForStatement(node, undefined); + return visitDoOrWhileStatement(node, undefined); case 215: - return visitForInStatement(node, undefined); + return visitForStatement(node, undefined); case 216: + return visitForInStatement(node, undefined); + case 217: return visitForOfStatement(node, undefined); - case 210: + case 211: return visitExpressionStatement(node); - case 178: + case 179: return visitObjectLiteralExpression(node); - case 260: + case 264: return visitCatchClause(node); - case 262: + case 266: return visitShorthandPropertyAssignment(node); - case 144: + case 145: return visitComputedPropertyName(node); - case 177: + case 178: return visitArrayLiteralExpression(node); - case 181: - return visitCallExpression(node); case 182: + return visitCallExpression(node); + case 183: return visitNewExpression(node); - case 185: + case 186: return visitParenthesizedExpression(node, true); - case 194: + case 195: return visitBinaryExpression(node, true); case 13: case 14: @@ -47301,28 +47892,28 @@ var ts; return visitStringLiteral(node); case 8: return visitNumericLiteral(node); - case 183: + case 184: return visitTaggedTemplateExpression(node); - case 196: - return visitTemplateExpression(node); case 197: - return visitYieldExpression(node); + return visitTemplateExpression(node); case 198: + return visitYieldExpression(node); + case 199: return visitSpreadElement(node); case 97: return visitSuperKeyword(false); case 99: return visitThisKeyword(node); - case 204: + case 205: return visitMetaProperty(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 153: case 154: + case 155: return visitAccessorDeclaration(node); - case 208: + case 209: return visitVariableStatement(node); - case 219: + case 220: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -47336,6 +47927,9 @@ var ts; addCaptureThisForNodeIfNeeded(statements, node); statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } ts.addRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); @@ -47400,13 +47994,13 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 218 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || + var jump = node.kind === 219 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 218) { + if (node.kind === 219) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; } @@ -47416,13 +48010,13 @@ var ts; } } else { - if (node.kind === 218) { + if (node.kind === 219) { labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, true, ts.idText(node.label), labelMarker); } else { labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, false, ts.idText(node.label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -47477,9 +48071,7 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (ts.getEmitFlags(node) & 65536) { - ts.setEmitFlags(classFunction, 65536); - } + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536) | 524288); var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; ts.setEmitFlags(inner, 1536); @@ -47582,17 +48174,17 @@ var ts; return block; } function isSufficientlyCoveredByReturnStatements(statement) { - if (statement.kind === 219) { + if (statement.kind === 220) { return true; } - else if (statement.kind === 211) { + else if (statement.kind === 212) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 207) { + else if (statement.kind === 208) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -47621,7 +48213,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 210 && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 211 && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -47629,8 +48221,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 | 32768))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 194 - || superCallExpression.left.kind !== 181) { + if (superCallExpression.kind !== 195 + || superCallExpression.left.kind !== 182) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); @@ -47698,7 +48290,7 @@ var ts; var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer))), parameter)) ]), parameter), 1 | 32 | 384)); - statement.startsOnNewLine = true; + ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 | 32 | 1048576); statements.push(statement); @@ -47731,7 +48323,7 @@ var ts; statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 && node.kind !== 187) { + if (node.transformFlags & 32768 && node.kind !== 188) { captureThisForNode(statements, node, ts.createThis()); } } @@ -47749,18 +48341,18 @@ var ts; if (hierarchyFacts & 16384) { var newTarget = void 0; switch (node.kind) { - case 187: + case 188: return statements; - case 151: - case 153: + case 152: case 154: + case 155: newTarget = ts.createVoidZero(); break; - case 152: + case 153: newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"); break; - case 228: - case 186: + case 229: + case 187: newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4), 93, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"), ts.createVoidZero()); break; default: @@ -47781,20 +48373,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 206: + case 207: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 151: + case 152: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 153: case 154: + case 155: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 152: + case 153: break; default: ts.Debug.failBadSyntaxKind(node); @@ -47859,7 +48451,7 @@ var ts; ts.createObjectLiteral(properties, true) ]); if (startsOnNewLine) { - call.startsOnNewLine = true; + ts.startOnNewLine(call); } exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return call; @@ -47919,7 +48511,7 @@ var ts; : enterSubtree(16286, 65); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 && !name && (node.kind === 228 || node.kind === 186)) { + if (hierarchyFacts & 16384 && !name && (node.kind === 229 || node.kind === 187)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152, 0); @@ -47953,7 +48545,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 187); + ts.Debug.assert(node.kind === 188); statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -48005,9 +48597,9 @@ var ts; } function visitExpressionStatement(node) { switch (node.expression.kind) { - case 185: + case 186: return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); - case 194: + case 195: return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); } return ts.visitEachChild(node, visitor, context); @@ -48015,9 +48607,9 @@ var ts; function visitParenthesizedExpression(node, needsDestructuringValue) { if (!needsDestructuringValue) { switch (node.expression.kind) { - case 185: + case 186: return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); - case 194: + case 195: return ts.updateParen(node, visitBinaryExpression(node.expression, false)); } } @@ -48127,10 +48719,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); + convertedLoopState.labels.set(ts.idText(node.label), true); } function resetLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); + convertedLoopState.labels.set(ts.idText(node.label), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -48143,14 +48735,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 212: case 213: - return visitDoOrWhileStatement(node, outermostLabeledStatement); case 214: - return visitForStatement(node, outermostLabeledStatement); + return visitDoOrWhileStatement(node, outermostLabeledStatement); case 215: - return visitForInStatement(node, outermostLabeledStatement); + return visitForStatement(node, outermostLabeledStatement); case 216: + return visitForInStatement(node, outermostLabeledStatement); + case 217: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -48276,7 +48868,7 @@ var ts; && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 144) { + if (property.name.kind === 145) { numInitialProperties = i; break; } @@ -48289,7 +48881,7 @@ var ts; var expressions = []; var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); if (node.multiLine) { - assignment.startsOnNewLine = true; + ts.startOnNewLine(assignment); } expressions.push(assignment); addObjectLiteralMembers(expressions, node, temp, numInitialProperties); @@ -48338,11 +48930,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 214: case 215: case 216: + case 217: var initializer = node.initializer; - if (initializer && initializer.kind === 227) { + if (initializer && initializer.kind === 228) { loopInitializer = initializer; } break; @@ -48557,7 +49149,7 @@ var ts; else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -48568,20 +49160,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 153: case 154: + case 155: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); } break; - case 151: + case 152: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 261: + case 265: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 262: + case 266: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -48594,7 +49186,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -48602,7 +49194,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -48611,7 +49203,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return expression; @@ -48655,7 +49247,7 @@ var ts; if (node.transformFlags & 32768) { var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 153) { + if (node.kind === 154) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -48783,7 +49375,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 178 ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -48817,15 +49409,14 @@ var ts; return node; } function visitNumericLiteral(node) { - if (node.numericLiteralFlags & 48) { + if (node.numericLiteralFlags & 384) { return ts.setTextRange(ts.createNumericLiteral(node.text), node); } return node; } function visitTaggedTemplateExpression(node) { var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - var temp = ts.createTempVariable(hoistVariableDeclaration); - var templateArguments = [temp]; + var templateArguments = [undefined]; var cookedStrings = []; var rawStrings = []; var template = node.template; @@ -48843,11 +49434,16 @@ var ts; templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); } } - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, undefined, templateArguments) - ])); + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, undefined, templateArguments); } function getRawLiteral(node) { var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); @@ -48925,13 +49521,13 @@ var ts; if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; context.enableSubstitution(99); - context.enableEmitNotification(152); - context.enableEmitNotification(151); context.enableEmitNotification(153); + context.enableEmitNotification(152); context.enableEmitNotification(154); + context.enableEmitNotification(155); + context.enableEmitNotification(188); context.enableEmitNotification(187); - context.enableEmitNotification(186); - context.enableEmitNotification(228); + context.enableEmitNotification(229); } } function onSubstituteNode(hint, node) { @@ -48956,10 +49552,10 @@ var ts; function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 176: - case 229: - case 232: - case 226: + case 177: + case 230: + case 233: + case 227: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -49020,11 +49616,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 210) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 211) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 181) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 182) { return false; } var callTarget = statementExpression.expression; @@ -49032,7 +49628,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 198) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 199) { return false; } var expression = callArgument.expression; @@ -49047,12 +49643,25 @@ var ts; ts.createIdentifier("_super") ]); } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), undefined, [ + cooked, + raw + ]); + } var extendsHelper = { name: "typescript:extends", scoped: false, priority: 0, text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -49063,24 +49672,24 @@ var ts; if (compilerOptions.jsx === 1 || compilerOptions.jsx === 3) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(251); context.enableEmitNotification(252); - context.enableEmitNotification(250); + context.enableEmitNotification(253); + context.enableEmitNotification(251); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179); - context.enableSubstitution(261); + context.enableSubstitution(180); + context.enableSubstitution(265); return transformSourceFile; function transformSourceFile(node) { return node; } function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 251: case 252: - case 250: + case 253: + case 251: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -49115,7 +49724,7 @@ var ts; return node; } function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); if (token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -49126,51 +49735,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var OpCode; - (function (OpCode) { - OpCode[OpCode["Nop"] = 0] = "Nop"; - OpCode[OpCode["Statement"] = 1] = "Statement"; - OpCode[OpCode["Assign"] = 2] = "Assign"; - OpCode[OpCode["Break"] = 3] = "Break"; - OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue"; - OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse"; - OpCode[OpCode["Yield"] = 6] = "Yield"; - OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; - OpCode[OpCode["Return"] = 8] = "Return"; - OpCode[OpCode["Throw"] = 9] = "Throw"; - OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; - })(OpCode || (OpCode = {})); - var BlockAction; - (function (BlockAction) { - BlockAction[BlockAction["Open"] = 0] = "Open"; - BlockAction[BlockAction["Close"] = 1] = "Close"; - })(BlockAction || (BlockAction = {})); - var CodeBlockKind; - (function (CodeBlockKind) { - CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; - CodeBlockKind[CodeBlockKind["With"] = 1] = "With"; - CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch"; - CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; - CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; - })(CodeBlockKind || (CodeBlockKind = {})); - var ExceptionBlockState; - (function (ExceptionBlockState) { - ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; - ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch"; - ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; - ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; - })(ExceptionBlockState || (ExceptionBlockState = {})); - var Instruction; - (function (Instruction) { - Instruction[Instruction["Next"] = 0] = "Next"; - Instruction[Instruction["Throw"] = 1] = "Throw"; - Instruction[Instruction["Return"] = 2] = "Return"; - Instruction[Instruction["Break"] = 3] = "Break"; - Instruction[Instruction["Yield"] = 4] = "Yield"; - Instruction[Instruction["YieldStar"] = 5] = "YieldStar"; - Instruction[Instruction["Catch"] = 6] = "Catch"; - Instruction[Instruction["Endfinally"] = 7] = "Endfinally"; - })(Instruction || (Instruction = {})); function getInstructionName(instruction) { switch (instruction) { case 2: return "return"; @@ -49241,13 +49805,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 212: - return visitDoStatement(node); case 213: + return visitDoStatement(node); + case 214: return visitWhileStatement(node); - case 221: - return visitSwitchStatement(node); case 222: + return visitSwitchStatement(node); + case 223: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -49255,24 +49819,24 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: + case 187: return visitFunctionExpression(node); - case 153: case 154: + case 155: return visitAccessorDeclaration(node); - case 208: + case 209: return visitVariableStatement(node); - case 214: - return visitForStatement(node); case 215: + return visitForStatement(node); + case 216: return visitForInStatement(node); - case 218: + case 219: return visitBreakStatement(node); - case 217: + case 218: return visitContinueStatement(node); - case 219: + case 220: return visitReturnStatement(node); default: if (node.transformFlags & 16777216) { @@ -49288,21 +49852,21 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 194: - return visitBinaryExpression(node); case 195: + return visitBinaryExpression(node); + case 196: return visitConditionalExpression(node); - case 197: + case 198: return visitYieldExpression(node); - case 177: - return visitArrayLiteralExpression(node); case 178: + return visitArrayLiteralExpression(node); + case 179: return visitObjectLiteralExpression(node); - case 180: - return visitElementAccessExpression(node); case 181: - return visitCallExpression(node); + return visitElementAccessExpression(node); case 182: + return visitCallExpression(node); + case 183: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -49310,9 +49874,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: + case 187: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -49469,10 +50033,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 179: + case 180: target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 180: + case 181: target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -49618,7 +50182,7 @@ var ts; var visited = ts.visitNode(expression, visitor, ts.isExpression); if (visited) { if (multiLine) { - visited.startsOnNewLine = true; + ts.startOnNewLine(visited); } expressions.push(visited); } @@ -49635,7 +50199,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } @@ -49673,35 +50237,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 207: + case 208: return transformAndEmitBlock(node); - case 210: - return transformAndEmitExpressionStatement(node); case 211: - return transformAndEmitIfStatement(node); + return transformAndEmitExpressionStatement(node); case 212: - return transformAndEmitDoStatement(node); + return transformAndEmitIfStatement(node); case 213: - return transformAndEmitWhileStatement(node); + return transformAndEmitDoStatement(node); case 214: - return transformAndEmitForStatement(node); + return transformAndEmitWhileStatement(node); case 215: + return transformAndEmitForStatement(node); + case 216: return transformAndEmitForInStatement(node); - case 217: - return transformAndEmitContinueStatement(node); case 218: - return transformAndEmitBreakStatement(node); + return transformAndEmitContinueStatement(node); case 219: - return transformAndEmitReturnStatement(node); + return transformAndEmitBreakStatement(node); case 220: - return transformAndEmitWithStatement(node); + return transformAndEmitReturnStatement(node); case 221: - return transformAndEmitSwitchStatement(node); + return transformAndEmitWithStatement(node); case 222: - return transformAndEmitLabeledStatement(node); + return transformAndEmitSwitchStatement(node); case 223: - return transformAndEmitThrowStatement(node); + return transformAndEmitLabeledStatement(node); case 224: + return transformAndEmitThrowStatement(node); + case 225: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -49933,7 +50497,7 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, node); } @@ -49943,7 +50507,7 @@ var ts; } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findContinueTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, node); } @@ -49951,7 +50515,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, node); } @@ -49961,7 +50525,7 @@ var ts; } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findBreakTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, node); } @@ -49995,7 +50559,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 258 && defaultClauseIndex === -1) { + if (clause.kind === 262 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -50005,7 +50569,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 257) { + if (clause.kind === 261) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -50056,7 +50620,7 @@ var ts; } function transformAndEmitLabeledStatement(node) { if (containsYield(node)) { - beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginLabeledBlock(ts.idText(node.label)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -50066,7 +50630,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginScriptLabeledBlock(ts.idText(node.label)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -50121,7 +50685,7 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); @@ -50235,7 +50799,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); + var text = ts.idText(variable.name); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -50540,8 +51104,7 @@ var ts; if (clauses) { var labelExpression = ts.createPropertyAccess(state, "label"); var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); - switchStatement.startsOnNewLine = true; - return [switchStatement]; + return [ts.startOnNewLine(switchStatement)]; } if (statements) { return statements; @@ -50811,7 +51374,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -50822,11 +51385,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); - context.enableSubstitution(194); - context.enableSubstitution(192); + context.enableSubstitution(195); context.enableSubstitution(193); - context.enableSubstitution(262); - context.enableEmitNotification(265); + context.enableSubstitution(194); + context.enableSubstitution(266); + context.enableEmitNotification(269); var moduleInfoMap = []; var deferredExports = []; var currentSourceFile; @@ -50835,7 +51398,7 @@ var ts; var needUMDDynamicImportHelper; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; } currentSourceFile = node; @@ -50857,7 +51420,7 @@ var ts; function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); @@ -50993,23 +51556,23 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 238: + case 239: return visitImportDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); - case 244: + case 245: return visitExportDeclaration(node); - case 243: + case 244: return visitExportAssignment(node); - case 208: + case 209: return visitVariableStatement(node); - case 228: - return visitFunctionDeclaration(node); case 229: + return visitFunctionDeclaration(node); + case 230: return visitClassDeclaration(node); - case 290: + case 294: return visitMergeDeclarationMarker(node); - case 291: + case 295: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, importCallExpressionVisitor, context); @@ -51027,28 +51590,65 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { needUMDDynamicImportHelper = true; - return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536); + return ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(arg, containsLexicalThis), createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(temp, containsLexicalThis), createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), - ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + var parameters = [ + ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, parameters, undefined, undefined, body); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, parameters, undefined, body); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); + var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock([ts.createReturn(requireCall)])); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } function visitImportDeclaration(node) { var statements; @@ -51151,10 +51751,10 @@ var ts; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } return ts.singleOrMany(statements); } @@ -51238,7 +51838,7 @@ var ts; } } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -51270,10 +51870,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240: + case 241: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241: + case 242: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -51331,7 +51931,7 @@ var ts; } function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -51381,7 +51981,7 @@ var ts; return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265) { + if (node.kind === 269) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -51423,10 +52023,10 @@ var ts; switch (node.kind) { case 71: return substituteExpressionIdentifier(node); - case 194: + case 195: return substituteBinaryExpression(node); + case 194: case 193: - case 192: return substituteUnaryExpression(node); } return node; @@ -51441,7 +52041,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 265) { + if (exportContainer && exportContainer.kind === 269) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); @@ -51484,7 +52084,7 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 + var expression = node.kind === 194 ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 ? 59 : 60), ts.createLiteral(1)), node) : node; for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { @@ -51538,10 +52138,10 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); - context.enableSubstitution(194); - context.enableSubstitution(192); + context.enableSubstitution(195); context.enableSubstitution(193); - context.enableEmitNotification(265); + context.enableSubstitution(194); + context.enableEmitNotification(269); var moduleInfoMap = []; var deferredExports = []; var exportFunctionsMap = []; @@ -51596,8 +52196,8 @@ var ts; function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); if (externalModuleName) { var text = externalModuleName.text; @@ -51619,7 +52219,7 @@ var ts; function createSystemModuleBody(node, dependencyGroups) { var statements = []; startLexicalEnvironment(); - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) @@ -51645,7 +52245,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 244 && externalImport.exportClause) { + if (externalImport.kind === 245 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -51668,7 +52268,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 244) { + if (externalImport.kind !== 245) { continue; } var exportDecl = externalImport; @@ -51677,7 +52277,7 @@ var ts; } for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -51720,21 +52320,21 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { - case 238: + case 239: if (!entry.importClause) { break; } - case 237: + case 238: ts.Debug.assert(importVariableName !== undefined); statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 244: + case 245: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); } @@ -51750,13 +52350,13 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 238: + case 239: return visitImportDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); - case 244: + case 245: return undefined; - case 243: + case 244: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -51877,14 +52477,14 @@ var ts; } function shouldHoistVariableDeclarationList(node) { return (ts.getEmitFlags(node) & 2097152) === 0 - && (enclosingBlockScopedContainer.kind === 265 + && (enclosingBlockScopedContainer.kind === 269 || (ts.getOriginalNode(node).flags & 3) === 0); } function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; } function createExportedVariableAssignment(name, value, location) { return createVariableAssignment(name, value, location, true); @@ -51899,7 +52499,7 @@ var ts; : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -51932,10 +52532,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240: + case 241: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241: + case 242: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -51979,7 +52579,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); + excludeName = ts.idText(decl.name); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -52005,7 +52605,7 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; @@ -52035,43 +52635,43 @@ var ts; } function nestedElementVisitor(node) { switch (node.kind) { - case 208: + case 209: return visitVariableStatement(node); - case 228: - return visitFunctionDeclaration(node); case 229: + return visitFunctionDeclaration(node); + case 230: return visitClassDeclaration(node); - case 214: - return visitForStatement(node); case 215: - return visitForInStatement(node); + return visitForStatement(node); case 216: + return visitForInStatement(node); + case 217: return visitForOfStatement(node); - case 212: - return visitDoStatement(node); case 213: + return visitDoStatement(node); + case 214: return visitWhileStatement(node); - case 222: + case 223: return visitLabeledStatement(node); - case 220: - return visitWithStatement(node); case 221: + return visitWithStatement(node); + case 222: return visitSwitchStatement(node); - case 235: + case 236: return visitCaseBlock(node); - case 257: + case 261: return visitCaseClause(node); - case 258: + case 262: return visitDefaultClause(node); - case 224: + case 225: return visitTryStatement(node); - case 260: + case 264: return visitCatchClause(node); - case 207: + case 208: return visitBlock(node); - case 290: + case 294: return visitMergeDeclarationMarker(node); - case 291: + case 295: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -52111,6 +52711,9 @@ var ts; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } } return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); } @@ -52165,7 +52768,7 @@ var ts; } function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 - && node.kind === 194) { + && node.kind === 195) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -52179,7 +52782,7 @@ var ts; } } function visitImportCallExpression(node) { - return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { @@ -52208,7 +52811,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 265; + return container !== undefined && container.kind === 269; } else { return false; @@ -52223,7 +52826,7 @@ var ts; return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265) { + if (node.kind === 269) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -52256,10 +52859,10 @@ var ts; switch (node.kind) { case 71: return substituteExpressionIdentifier(node); - case 194: + case 195: return substituteBinaryExpression(node); - case 192: case 193: + case 194: return substituteUnaryExpression(node); } return node; @@ -52311,14 +52914,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 + var expression = node.kind === 194 ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 193) { + if (node.kind === 194) { expression = node.operator === 43 ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -52335,7 +52938,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, false); - if (exportContainer && exportContainer.kind === 265) { + if (exportContainer && exportContainer.kind === 269) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -52363,7 +52966,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(265); + context.enableEmitNotification(269); context.enableSubstitution(71); var currentSourceFile; return transformSourceFile; @@ -52388,9 +52991,9 @@ var ts; } function visitor(node) { switch (node.kind) { - case 237: + case 238: return undefined; - case 243: + case 244: return visitExportAssignment(node); } return node; @@ -52440,18 +53043,6 @@ var ts; return ts.transformModule; } } - var TransformationState; - (function (TransformationState) { - TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized"; - TransformationState[TransformationState["Initialized"] = 1] = "Initialized"; - TransformationState[TransformationState["Completed"] = 2] = "Completed"; - TransformationState[TransformationState["Disposed"] = 3] = "Disposed"; - })(TransformationState || (TransformationState = {})); - var SyntaxKindFeatureFlags; - (function (SyntaxKindFeatureFlags) { - SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution"; - SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications"; - })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {})); function getTransformers(compilerOptions, customTransformers) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -52462,7 +53053,7 @@ var ts; if (jsx === 2) { transformers.push(ts.transformJsx); } - if (languageVersion < 5) { + if (languageVersion < 6) { transformers.push(ts.transformESNext); } if (languageVersion < 4) { @@ -52484,7 +53075,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(292); + var enabledSyntaxKindFeatures = new Array(296); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -52744,7 +53335,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 265) { + if (sourceFileOrBundle.kind === 269) { sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { @@ -52851,7 +53442,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 287 + if (node.kind !== 291 && (emitFlags & 16) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -52868,7 +53459,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 287 + if (node.kind !== 291 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); @@ -53010,7 +53601,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287; + var isEmittedNode = node.kind !== 291; var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { @@ -53024,7 +53615,7 @@ var ts; } if (!skipTrailingComments) { containerEnd = end; - if (node.kind === 227) { + if (node.kind === 228) { declarationListContainerEnd = end; } } @@ -53160,7 +53751,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -53173,7 +53764,7 @@ var ts; if (hasTrailingNewLine) { writer.writeLine(); } - else { + else if (kind === 3) { writer.write(" "); } } @@ -53304,8 +53895,8 @@ var ts; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 266; + var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var isBundledEmit = sourceFileOrBundle.kind === 270; var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -53367,7 +53958,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 238); + ts.Debug.assert(aliasEmitInfo.node.kind === 239); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -53402,7 +53993,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -53417,6 +54008,7 @@ var ts; var writer = ts.createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; + writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; @@ -53440,10 +54032,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 226) { + if (declaration.kind === 227) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 241 || declaration.kind === 242 || declaration.kind === 239) { + else if (declaration.kind === 242 || declaration.kind === 243 || declaration.kind === 240) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -53454,7 +54046,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 238) { + if (moduleElementEmitInfo.node.kind === 239) { moduleElementEmitInfo.isVisible = true; } else { @@ -53462,12 +54054,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 233) { + if (nodeToCheck.kind === 234) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 233) { + if (nodeToCheck.kind === 234) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -53520,16 +54112,22 @@ var ts; emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } function reportInaccessibleThisError() { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - var shouldUseResolverType = declaration.kind === 146 && + var shouldUseResolverType = declaration.kind === 147 && (resolver.isRequiredInitializedParameter(declaration) || resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { @@ -53601,41 +54199,41 @@ var ts; case 139: case 95: case 130: - case 169: - case 173: + case 170: + case 174: return writeTextOfNode(currentText, type); - case 201: + case 202: return emitExpressionWithTypeArguments(type); - case 159: + case 160: return emitTypeReference(type); - case 162: + case 163: return emitTypeQuery(type); - case 164: - return emitArrayType(type); case 165: - return emitTupleType(type); + return emitArrayType(type); case 166: - return emitUnionType(type); + return emitTupleType(type); case 167: - return emitIntersectionType(type); + return emitUnionType(type); case 168: + return emitIntersectionType(type); + case 169: return emitParenType(type); - case 170: - return emitTypeOperator(type); case 171: - return emitIndexedAccessType(type); + return emitTypeOperator(type); case 172: + return emitIndexedAccessType(type); + case 173: return emitMappedType(type); - case 160: case 161: + case 162: return emitSignatureDeclarationWithJsDocComments(type); - case 163: + case 164: return emitTypeLiteral(type); case 71: return emitEntityName(type); - case 143: + case 144: return emitEntityName(type); - case 158: + case 159: return emitTypePredicate(type); } function writeEntityName(entityName) { @@ -53643,22 +54241,22 @@ var ts; writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 143 ? entityName.left : entityName.expression; - var right = entityName.kind === 143 ? entityName.right : entityName.name; + var left = entityName.kind === 144 ? entityName.left : entityName.expression; + var right = entityName.kind === 144 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 237 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 238 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 || node.expression.kind === 179); + ts.Debug.assert(node.expression.kind === 71 || node.expression.kind === 180); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -53814,10 +54412,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 237 || - (node.parent.kind === 265 && isCurrentFileExternalModule)) { + else if (node.kind === 238 || + (node.parent.kind === 269 && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 265) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 269) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -53826,7 +54424,7 @@ var ts; }); } else { - if (node.kind === 238) { + if (node.kind === 239) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -53844,30 +54442,30 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 228: + case 229: return writeFunctionDeclaration(node); - case 208: + case 209: return writeVariableStatement(node); - case 230: + case 231: return writeInterfaceDeclaration(node); - case 229: + case 230: return writeClassDeclaration(node); - case 231: - return writeTypeAliasDeclaration(node); case 232: - return writeEnumDeclaration(node); + return writeTypeAliasDeclaration(node); case 233: + return writeEnumDeclaration(node); + case 234: return writeModuleDeclaration(node); - case 237: - return writeImportEqualsDeclaration(node); case 238: + return writeImportEqualsDeclaration(node); + case 239: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 265) { + if (node.parent.kind === 269) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { write("export "); @@ -53875,7 +54473,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && needsDeclare) { + else if (node.kind !== 231 && needsDeclare) { write("declare "); } } @@ -53925,7 +54523,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 240) { + if (namedBindings.kind === 241) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -53948,7 +54546,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 240) { + if (node.importClause.namedBindings.kind === 241) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -53965,13 +54563,13 @@ var ts; writer.writeLine(); } function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 233; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 234; var moduleSpecifier; - if (parent.kind === 237) { + if (parent.kind === 238) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 233) { + else if (parent.kind === 234) { moduleSpecifier = parent.name; } else { @@ -54039,7 +54637,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 234) { + while (node.body && node.body.kind !== 235) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -54109,7 +54707,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 151 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 152 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -54119,15 +54717,15 @@ var ts; writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - (node.parent.parent && node.parent.parent.kind === 163)) { - ts.Debug.assert(node.parent.kind === 151 || - node.parent.kind === 150 || - node.parent.kind === 160 || + if (node.parent.kind === 161 || + node.parent.kind === 162 || + (node.parent.parent && node.parent.parent.kind === 164)) { + ts.Debug.assert(node.parent.kind === 152 || + node.parent.kind === 151 || node.parent.kind === 161 || - node.parent.kind === 155 || - node.parent.kind === 156); + node.parent.kind === 162 || + node.parent.kind === 156 || + node.parent.kind === 157); emitType(node.constraint); } else { @@ -54136,15 +54734,15 @@ var ts; } if (node.default && !isPrivateMethodTypeParameter(node)) { write(" = "); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - (node.parent.parent && node.parent.parent.kind === 163)) { - ts.Debug.assert(node.parent.kind === 151 || - node.parent.kind === 150 || - node.parent.kind === 160 || + if (node.parent.kind === 161 || + node.parent.kind === 162 || + (node.parent.parent && node.parent.parent.kind === 164)) { + ts.Debug.assert(node.parent.kind === 152 || + node.parent.kind === 151 || node.parent.kind === 161 || - node.parent.kind === 155 || - node.parent.kind === 156); + node.parent.kind === 162 || + node.parent.kind === 156 || + node.parent.kind === 157); emitType(node.default); } else { @@ -54154,34 +54752,34 @@ var ts; function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 229: + case 230: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 230: + case 231: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 156: + case 157: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 155: + case 156: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; + case 152: case 151: - case 150: if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229) { + else if (node.parent.parent.kind === 230) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 228: + case 229: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 231: + case 232: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -54214,7 +54812,7 @@ var ts; } function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 229) { + if (node.parent.parent.kind === 230) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -54251,7 +54849,7 @@ var ts; diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + }, !ts.findAncestor(node, function (n) { return n.kind === 234; })); } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -54308,7 +54906,7 @@ var ts; enclosingDeclaration = prevEnclosingDeclaration; } function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } emitJsDocComments(node); @@ -54317,18 +54915,24 @@ var ts; write(";"); writeLine(); } + function bindingNameContainsVisibleBindingElement(node) { + return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); + } + function isVariableDeclarationVisible(node) { + return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); + } function emitVariableDeclaration(node) { - if (node.kind !== 226 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 227 || isVariableDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - writeTextOfNode(currentText, node.name); - if ((node.kind === 149 || node.kind === 148 || - (node.kind === 146 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); + if ((node.kind === 150 || node.kind === 149 || + (node.kind === 147 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 149 || node.kind === 148) && node.parent.kind === 163) { + if ((node.kind === 150 || node.kind === 149) && node.parent.kind === 164) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -54341,15 +54945,15 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 226) { + if (node.kind === 227) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148 || - (node.kind === 146 && ts.hasModifier(node.parent, 8))) { + else if (node.kind === 150 || node.kind === 149 || + (node.kind === 147 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -54357,7 +54961,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 || node.kind === 146) { + else if (node.parent.kind === 230 || node.kind === 147) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54383,7 +54987,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 200) { + if (element.kind !== 201 && isVariableDeclarationVisible(element)) { elements.push(element); } } @@ -54416,7 +55020,7 @@ var ts; } } function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { @@ -54433,12 +55037,12 @@ var ts; else { write("var "); } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, resolver.isDeclarationVisible); + emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); write(";"); writeLine(); } function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -54447,12 +55051,12 @@ var ts; emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getAccessorNameVisibilityError); if (!ts.hasModifier(node, 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 153 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 154 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -54465,82 +55069,152 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 153 + return accessor.kind === 154 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : undefined; } } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 154) { - if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { + if (accessorWithTypeAnnotation.kind === 155) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - typeName: accessorWithTypeAnnotation.name - }; } else { if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: accessorWithTypeAnnotation.name + }; } } function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 228) { + if (node.kind === 229) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 151 || node.kind === 152) { + else if (node.kind === 152 || node.kind === 153) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 228) { + if (node.kind === 229) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 152) { + else if (node.kind === 153) { write("constructor"); } else { - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getMethodNameVisibilityError); if (ts.hasQuestionToken(node)) { write("?"); } } emitSignatureDeclaration(node); } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + if (ts.hasDynamicName(node)) { + ts.Debug.assert(resolver.isLateBound(node)); + writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); + } + else { + writeTextOfNode(currentText, node.name); + } + } + function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + var entityName = node.name.expression; + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + writeTextOfNode(currentText, node.name); } function emitSignatureDeclarationWithJsDocComments(node) { emitJsDocComments(node); @@ -54550,20 +55224,20 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 157) { + if (node.kind === 158) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 && ts.hasModifier(node, 8)) { + if (node.kind === 153 && ts.hasModifier(node, 8)) { write("();"); writeLine(); return; } - if (node.kind === 156 || node.kind === 161) { + if (node.kind === 157 || node.kind === 162) { write("new "); } - else if (node.kind === 160) { + else if (node.kind === 161) { var currentOutput = writer.getText(); if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { closeParenthesizedFunctionType = true; @@ -54574,20 +55248,20 @@ var ts; write("("); } emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 157) { + if (node.kind === 158) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 160 || node.kind === 161; - if (isFunctionTypeOrConstructorType || node.parent.kind === 163) { + var isFunctionTypeOrConstructorType = node.kind === 161 || node.kind === 162; + if (isFunctionTypeOrConstructorType || node.parent.kind === 164) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 152 && !ts.hasModifier(node, 8)) { + else if (node.kind !== 153 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -54601,23 +55275,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 156: + case 157: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 155: + case 156: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 157: + case 158: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; + case 152: case 151: - case 150: if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -54625,7 +55299,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54638,7 +55312,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 228: + case 229: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54670,9 +55344,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - node.parent.parent.kind === 163) { + if (node.parent.kind === 161 || + node.parent.kind === 162 || + node.parent.parent.kind === 164) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8)) { @@ -54688,26 +55362,26 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 152: + case 153: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 156: + case 157: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 155: + case 156: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157: + case 158: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 152: case 151: - case 150: if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -54715,7 +55389,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229) { + else if (node.parent.parent.kind === 230) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54727,7 +55401,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 228: + case 229: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54738,12 +55412,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 174) { + if (bindingPattern.kind === 175) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 175) { + else if (bindingPattern.kind === 176) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -54754,10 +55428,10 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 200) { + if (bindingElement.kind === 201) { write(" "); } - else if (bindingElement.kind === 176) { + else if (bindingElement.kind === 177) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -54779,39 +55453,39 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 228: - case 233: - case 237: - case 230: case 229: + case 234: + case 238: case 231: + case 230: case 232: + case 233: return emitModuleElement(node, isModuleElementVisible(node)); - case 208: + case 209: return emitModuleElement(node, isVariableStatementVisible(node)); - case 238: + case 239: return emitModuleElement(node, !node.importClause); - case 244: + case 245: return emitExportDeclaration(node); + case 153: case 152: case 151: - case 150: return writeFunctionDeclaration(node); - case 156: - case 155: case 157: + case 156: + case 158: return emitSignatureDeclarationWithJsDocComments(node); - case 153: case 154: + case 155: return emitAccessorDeclaration(node); + case 150: case 149: - case 148: return emitPropertyDeclaration(node); - case 264: + case 268: return emitEnumMemberDeclaration(node); - case 243: + case 244: return emitExportAssignment(node); - case 265: + case 269: return emitSourceFile(node); } } @@ -54830,7 +55504,7 @@ var ts; } return addedBundledEmitReference; function getDeclFileName(emitFileNames, sourceFileOrBundle) { - var isBundledEmit = sourceFileOrBundle.kind === 266; + var isBundledEmit = sourceFileOrBundle.kind === 270; if (isBundledEmit && !addBundledFileReference) { return; } @@ -54844,7 +55518,7 @@ var ts; var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { - var sourceFiles = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); @@ -54909,7 +55583,7 @@ var ts; return ".js"; } function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266) { + if (sourceFileOrBundle.kind === 270) { return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); } return ts.getOriginalSourceFile(sourceFileOrBundle); @@ -54975,8 +55649,8 @@ var ts; } } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 265 ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 269 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); if (bundle) { @@ -55012,7 +55686,7 @@ var ts; } function emitHelpers(node, writeLines) { var helpersEmitted = false; - var bundle = node.kind === 266 ? node : undefined; + var bundle = node.kind === 270 ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -55085,8 +55759,8 @@ var ts; break; } switch (node.kind) { - case 265: return printFile(node); - case 266: return printBundle(node); + case 269: return printFile(node); + case 270: return printBundle(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -55236,192 +55910,210 @@ var ts; return emitLiteral(node); case 71: return emitIdentifier(node); - case 143: - return emitQualifiedName(node); case 144: - return emitComputedPropertyName(node); + return emitQualifiedName(node); case 145: - return emitTypeParameter(node); + return emitComputedPropertyName(node); case 146: - return emitParameter(node); + return emitTypeParameter(node); case 147: - return emitDecorator(node); + return emitParameter(node); case 148: - return emitPropertySignature(node); + return emitDecorator(node); case 149: - return emitPropertyDeclaration(node); + return emitPropertySignature(node); case 150: - return emitMethodSignature(node); + return emitPropertyDeclaration(node); case 151: - return emitMethodDeclaration(node); + return emitMethodSignature(node); case 152: - return emitConstructor(node); + return emitMethodDeclaration(node); case 153: + return emitConstructor(node); case 154: - return emitAccessorDeclaration(node); case 155: - return emitCallSignature(node); + return emitAccessorDeclaration(node); case 156: - return emitConstructSignature(node); + return emitCallSignature(node); case 157: - return emitIndexSignature(node); + return emitConstructSignature(node); case 158: - return emitTypePredicate(node); + return emitIndexSignature(node); case 159: - return emitTypeReference(node); + return emitTypePredicate(node); case 160: - return emitFunctionType(node); + return emitTypeReference(node); case 161: - return emitConstructorType(node); + return emitFunctionType(node); + case 277: + return emitJSDocFunctionType(node); case 162: - return emitTypeQuery(node); + return emitConstructorType(node); case 163: - return emitTypeLiteral(node); + return emitTypeQuery(node); case 164: - return emitArrayType(node); + return emitTypeLiteral(node); case 165: - return emitTupleType(node); + return emitArrayType(node); case 166: - return emitUnionType(node); + return emitTupleType(node); case 167: - return emitIntersectionType(node); + return emitUnionType(node); case 168: + return emitIntersectionType(node); + case 169: return emitParenthesizedType(node); - case 201: + case 202: return emitExpressionWithTypeArguments(node); - case 169: - return emitThisType(); case 170: - return emitTypeOperator(node); + return emitThisType(); case 171: - return emitIndexedAccessType(node); + return emitTypeOperator(node); case 172: - return emitMappedType(node); + return emitIndexedAccessType(node); case 173: - return emitLiteralType(node); + return emitMappedType(node); case 174: - return emitObjectBindingPattern(node); + return emitLiteralType(node); + case 272: + write("*"); + return; + case 273: + write("?"); + return; + case 274: + return emitJSDocNullableType(node); + case 275: + return emitJSDocNonNullableType(node); + case 276: + return emitJSDocOptionalType(node); + case 278: + return emitJSDocVariadicType(node); case 175: - return emitArrayBindingPattern(node); + return emitObjectBindingPattern(node); case 176: + return emitArrayBindingPattern(node); + case 177: return emitBindingElement(node); - case 205: - return emitTemplateSpan(node); case 206: - return emitSemicolonClassElement(); + return emitTemplateSpan(node); case 207: - return emitBlock(node); + return emitSemicolonClassElement(); case 208: - return emitVariableStatement(node); + return emitBlock(node); case 209: - return emitEmptyStatement(); + return emitVariableStatement(node); case 210: - return emitExpressionStatement(node); + return emitEmptyStatement(); case 211: - return emitIfStatement(node); + return emitExpressionStatement(node); case 212: - return emitDoStatement(node); + return emitIfStatement(node); case 213: - return emitWhileStatement(node); + return emitDoStatement(node); case 214: - return emitForStatement(node); + return emitWhileStatement(node); case 215: - return emitForInStatement(node); + return emitForStatement(node); case 216: - return emitForOfStatement(node); + return emitForInStatement(node); case 217: - return emitContinueStatement(node); + return emitForOfStatement(node); case 218: - return emitBreakStatement(node); + return emitContinueStatement(node); case 219: - return emitReturnStatement(node); + return emitBreakStatement(node); case 220: - return emitWithStatement(node); + return emitReturnStatement(node); case 221: - return emitSwitchStatement(node); + return emitWithStatement(node); case 222: - return emitLabeledStatement(node); + return emitSwitchStatement(node); case 223: - return emitThrowStatement(node); + return emitLabeledStatement(node); case 224: - return emitTryStatement(node); + return emitThrowStatement(node); case 225: - return emitDebuggerStatement(node); + return emitTryStatement(node); case 226: - return emitVariableDeclaration(node); + return emitDebuggerStatement(node); case 227: - return emitVariableDeclarationList(node); + return emitVariableDeclaration(node); case 228: - return emitFunctionDeclaration(node); + return emitVariableDeclarationList(node); case 229: - return emitClassDeclaration(node); + return emitFunctionDeclaration(node); case 230: - return emitInterfaceDeclaration(node); + return emitClassDeclaration(node); case 231: - return emitTypeAliasDeclaration(node); + return emitInterfaceDeclaration(node); case 232: - return emitEnumDeclaration(node); + return emitTypeAliasDeclaration(node); case 233: - return emitModuleDeclaration(node); + return emitEnumDeclaration(node); case 234: - return emitModuleBlock(node); + return emitModuleDeclaration(node); case 235: - return emitCaseBlock(node); + return emitModuleBlock(node); case 236: - return emitNamespaceExportDeclaration(node); + return emitCaseBlock(node); case 237: - return emitImportEqualsDeclaration(node); + return emitNamespaceExportDeclaration(node); case 238: - return emitImportDeclaration(node); + return emitImportEqualsDeclaration(node); case 239: - return emitImportClause(node); + return emitImportDeclaration(node); case 240: - return emitNamespaceImport(node); + return emitImportClause(node); case 241: - return emitNamedImports(node); + return emitNamespaceImport(node); case 242: - return emitImportSpecifier(node); + return emitNamedImports(node); case 243: - return emitExportAssignment(node); + return emitImportSpecifier(node); case 244: - return emitExportDeclaration(node); + return emitExportAssignment(node); case 245: - return emitNamedExports(node); + return emitExportDeclaration(node); case 246: - return emitExportSpecifier(node); + return emitNamedExports(node); case 247: - return; + return emitExportSpecifier(node); case 248: + return; + case 249: return emitExternalModuleReference(node); case 10: return emitJsxText(node); - case 251: - return emitJsxOpeningElement(node); case 252: - return emitJsxClosingElement(node); + case 255: + return emitJsxOpeningElementOrFragment(node); case 253: + case 256: + return emitJsxClosingElementOrFragment(node); + case 257: return emitJsxAttribute(node); - case 254: + case 258: return emitJsxAttributes(node); - case 255: + case 259: return emitJsxSpreadAttribute(node); - case 256: + case 260: return emitJsxExpression(node); - case 257: + case 261: return emitCaseClause(node); - case 258: + case 262: return emitDefaultClause(node); - case 259: + case 263: return emitHeritageClause(node); - case 260: + case 264: return emitCatchClause(node); - case 261: + case 265: return emitPropertyAssignment(node); - case 262: + case 266: return emitShorthandPropertyAssignment(node); - case 263: + case 267: return emitSpreadAssignment(node); - case 264: + case 268: return emitEnumMember(node); } if (ts.isExpression(node)) { @@ -55451,67 +56143,69 @@ var ts; case 91: writeTokenNode(node); return; - case 177: - return emitArrayLiteralExpression(node); case 178: - return emitObjectLiteralExpression(node); + return emitArrayLiteralExpression(node); case 179: - return emitPropertyAccessExpression(node); + return emitObjectLiteralExpression(node); case 180: - return emitElementAccessExpression(node); + return emitPropertyAccessExpression(node); case 181: - return emitCallExpression(node); + return emitElementAccessExpression(node); case 182: - return emitNewExpression(node); + return emitCallExpression(node); case 183: - return emitTaggedTemplateExpression(node); + return emitNewExpression(node); case 184: - return emitTypeAssertionExpression(node); + return emitTaggedTemplateExpression(node); case 185: - return emitParenthesizedExpression(node); + return emitTypeAssertionExpression(node); case 186: - return emitFunctionExpression(node); + return emitParenthesizedExpression(node); case 187: - return emitArrowFunction(node); + return emitFunctionExpression(node); case 188: - return emitDeleteExpression(node); + return emitArrowFunction(node); case 189: - return emitTypeOfExpression(node); + return emitDeleteExpression(node); case 190: - return emitVoidExpression(node); + return emitTypeOfExpression(node); case 191: - return emitAwaitExpression(node); + return emitVoidExpression(node); case 192: - return emitPrefixUnaryExpression(node); + return emitAwaitExpression(node); case 193: - return emitPostfixUnaryExpression(node); + return emitPrefixUnaryExpression(node); case 194: - return emitBinaryExpression(node); + return emitPostfixUnaryExpression(node); case 195: - return emitConditionalExpression(node); + return emitBinaryExpression(node); case 196: - return emitTemplateExpression(node); + return emitConditionalExpression(node); case 197: - return emitYieldExpression(node); + return emitTemplateExpression(node); case 198: - return emitSpreadExpression(node); + return emitYieldExpression(node); case 199: - return emitClassExpression(node); + return emitSpreadExpression(node); case 200: + return emitClassExpression(node); + case 201: return; - case 202: - return emitAsExpression(node); case 203: - return emitNonNullExpression(node); + return emitAsExpression(node); case 204: + return emitNonNullExpression(node); + case 205: return emitMetaProperty(node); - case 249: - return emitJsxElement(node); case 250: + return emitJsxElement(node); + case 251: return emitJsxSelfClosingElement(node); - case 288: + case 254: + return emitJsxFragment(node); + case 292: return emitPartiallyEmittedExpression(node); - case 289: + case 293: return emitCommaList(node); } } @@ -55567,9 +56261,16 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); - emit(node.name); + if (node.name) { + emit(node.name); + } emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); + if (node.parent && node.parent.kind === 277 && !node.name) { + emit(node.type); + } + else { + emitWithPrefix(": ", node.type); + } emitExpressionWithPrefix(" = ", node.initializer); } function emitDecorator(decorator) { @@ -55619,7 +56320,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 153 ? "get " : "set "); + write(node.kind === 154 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -55665,6 +56366,24 @@ var ts; write(" => "); emit(node.type); } + function emitJSDocFunctionType(node) { + write("function"); + emitParameters(node, node.parameters); + write(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + write("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + write("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + write("="); + } function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); @@ -55686,6 +56405,10 @@ var ts; emit(node.elementType); write("[]"); } + function emitJSDocVariadicType(node) { + write("..."); + emit(node.type); + } function emitTupleType(node) { write("["); emitList(node, node.elementTypes, 336); @@ -55819,7 +56542,7 @@ var ts; if (ts.isNumericLiteral(expression)) { var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23)) < 0; + && !ts.stringContains(text, ts.tokenToString(23)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); @@ -55901,7 +56624,7 @@ var ts; } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 192 + return operand.kind === 193 && ((node.operator === 37 && (operand.operator === 37 || operand.operator === 43)) || (node.operator === 38 && (operand.operator === 38 || operand.operator === 44))); } @@ -56013,7 +56736,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); writeToken(82, node.thenStatement.end, node); - if (node.elseStatement.kind === 211) { + if (node.elseStatement.kind === 212) { write(" "); emit(node.elseStatement); } @@ -56076,7 +56799,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 227) { + if (node.kind === 228) { emit(node); } else { @@ -56184,26 +56907,15 @@ var ts; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 524288) { - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + pushNameGenerationScope(node); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4, body, emitBlockCallback); } else { - pushNameGenerationScope(); - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } - popNameGenerationScope(); + emitBlockFunctionBody(body); } + popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); } @@ -56293,11 +57005,9 @@ var ts; } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 65); write("}"); - popNameGenerationScope(); if (indentedFlag) { decreaseIndent(); } @@ -56327,11 +57037,9 @@ var ts; emitModifiers(node, node.modifiers); write("enum "); emit(node.name); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 81); write("}"); - popNameGenerationScope(); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); @@ -56340,7 +57048,7 @@ var ts; } emit(node.name); var body = node.body; - while (body.kind === 233) { + while (body.kind === 234) { write("."); emit(body.name); body = body.body; @@ -56349,11 +57057,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - pushNameGenerationScope(); + pushNameGenerationScope(node); write("{"); emitBlockStatements(node, isEmptyBlock(node)); write("}"); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitCaseBlock(node) { writeToken(17, node.pos); @@ -56464,21 +57172,30 @@ var ts; } write("/>"); } - function emitJsxOpeningElement(node) { + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 131072); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { write("<"); - emitJsxTagName(node.tagName); - writeIfAny(node.attributes.properties, " "); - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + write(" "); + emit(node.attributes); + } } write(">"); } function emitJsxText(node) { writer.writeLiteral(getTextOfNode(node, true)); } - function emitJsxClosingElement(node) { + function emitJsxClosingElementOrFragment(node) { write(""); } function emitJsxAttributes(node) { @@ -56594,11 +57311,11 @@ var ts; } function emitSourceFileWorker(node) { var statements = node.statements; - pushNameGenerationScope(); + pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitList(node, statements, 1, index === -1 ? statements.length : index); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); @@ -56858,11 +57575,6 @@ var ts; function decreaseIndent() { writer.decreaseIndent(); } - function writeIfAny(nodes, text) { - if (ts.some(nodes)) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -56893,8 +57605,9 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = guessIndentation(lines); - for (var i = 0; i < lines.length; i++) { - var line = indentation ? lines[i].slice(indentation) : lines[i]; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var lineText = lines_1[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); @@ -56904,8 +57617,8 @@ var ts; } function guessIndentation(lines) { var indentation; - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var line = lines_1[_a]; + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { if (indentation === undefined || i < indentation) { @@ -56973,7 +57686,7 @@ var ts; } } else { - return nextNode.startsOnNewLine; + return ts.getStartsOnNewLine(nextNode); } } function shouldWriteClosingLineTerminator(parentNode, children, format) { @@ -57001,7 +57714,7 @@ var ts; } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { - var startsOnNewLine = node.startsOnNewLine; + var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { return (format & 32768) !== 0; } @@ -57013,7 +57726,7 @@ var ts; parent = skipSynthesizedParentheses(parent); node1 = skipSynthesizedParentheses(node1); node2 = skipSynthesizedParentheses(node2); - if (node2.startsOnNewLine) { + if (ts.getStartsOnNewLine(node2)) { return true; } return !ts.nodeIsSynthesized(parent) @@ -57026,7 +57739,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 185 && ts.nodeIsSynthesized(node)) { + while (node.kind === 186 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -57036,7 +57749,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } else if (node.kind === 9 && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -57060,17 +57773,32 @@ var ts; } return ts.getLiteralText(node, currentSourceFile); } - function pushNameGenerationScope() { + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288) { + return; + } tempFlagsStack.push(tempFlags); tempFlags = 0; } - function popNameGenerationScope() { + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288) { + return; + } tempFlags = tempFlagsStack.pop(); } function generateName(name) { if (name.autoGenerateKind === 4) { - var node = getNodeForGeneratedName(name); - return generateNameCached(node); + if (name.skipNameGenerationScope) { + var savedTempFlags = tempFlags; + popNameGenerationScope(undefined); + var result = generateNameCached(getNodeForGeneratedName(name)); + pushNameGenerationScope(undefined); + tempFlags = savedTempFlags; + return result; + } + else { + return generateNameCached(getNodeForGeneratedName(name)); + } } else { var autoGenerateId = name.autoGenerateId; @@ -57158,21 +57886,21 @@ var ts; switch (node.kind) { case 71: return makeUniqueName(getTextOfNode(node)); + case 234: case 233: - case 232: return generateNameForModuleOrEnum(node); - case 238: - case 244: + case 239: + case 245: return generateNameForImportOrExportDeclaration(node); - case 228: case 229: - case 243: + case 230: + case 244: return generateNameForExportDefault(); - case 199: + case 200: return generateNameForClassExpression(); - case 151: - case 153: + case 152: case 154: + case 155: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0); @@ -57185,7 +57913,7 @@ var ts; case 2: return makeTempVariableName(268435456); case 3: - return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); + return makeUniqueName(ts.idText(name)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -57231,96 +57959,468 @@ var ts; function getClosingBracket(format) { return brackets[format & 7680][1]; } - var TempFlags; - (function (TempFlags) { - TempFlags[TempFlags["Auto"] = 0] = "Auto"; - TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; - TempFlags[TempFlags["_i"] = 268435456] = "_i"; - })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); var ts; (function (ts) { - var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } - while (true) { - var fileName = ts.combinePaths(searchPath, configName); - if (fileExists(fileName)) { - return fileName; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + createNewValue: createMissingFileWatch, + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + createNewValue: createWildcardDirectoryWatcher, + onDeleteValue: closeFileWatcherOf, + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + if (existingWatcher.flags === flags) { + return; } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } + watcher.close(); } - searchPath = parentPath; + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; + function createBuilder(options) { + var isModuleEmit; + var fileInfos = ts.createMap(); + var semanticDiagnosticsPerFile = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; + var emitHandler; + return { + updateProgram: updateProgram, + getFilesAffectedBy: getFilesAffectedBy, + emitChangedFiles: emitChangedFiles, + getSemanticDiagnostics: getSemanticDiagnostics, + clear: clear + }; + function createProgramGraph(program) { + var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; + if (isModuleEmit !== currentIsModuleEmit) { + isModuleEmit = currentIsModuleEmit; + emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; + ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { + createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, + onDeleteValue: removeExistingFileInfo, + onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } + }); } - return undefined; + function registerChangedFile(path) { + changedFilesSet.set(path, true); + semanticDiagnosticsPerFile.delete(path); + } + function addNewFileInfo(program, sourceFile) { + registerChangedFile(sourceFile.path); + emitHandler.onAddSourceFile(program, sourceFile); + return { version: sourceFile.version, signature: undefined }; + } + function removeExistingFileInfo(_existingFileInfo, path) { + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); + emitHandler.onRemoveSourceFile(path); + } + function updateExistingFileInfo(program, existingInfo, sourceFile) { + if (existingInfo.version !== sourceFile.version) { + registerChangedFile(sourceFile.path); + existingInfo.version = sourceFile.version; + emitHandler.onUpdateSourceFile(program, sourceFile); + } + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + registerChangedFile(sourceFile.path); + } + } + function ensureProgramGraph(program) { + if (!emitHandler) { + createProgramGraph(program); + } + } + function updateProgram(newProgram) { + if (emitHandler) { + createProgramGraph(newProgram); + } + } + function getFilesAffectedBy(program, path) { + ensureProgramGraph(program); + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); + } + function emitChangedFiles(program, writeFileCallback) { + ensureProgramGraph(program); + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(undefined, writeFileCallback)]; + } + var seenFiles = ts.createMap(); + var result; + changedFilesSet.forEach(function (_true, path) { + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); + } + }); + }); + changedFilesSet.clear(); + return result || ts.emptyArray; + } + function getSemanticDiagnostics(program, cancellationToken) { + ensureProgramGraph(program); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + return program.getSemanticDiagnostics(undefined, cancellationToken); + } + var diagnostics; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + function clear() { + isModuleEmit = undefined; + emitHandler = undefined; + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + info.signature = latestSignature; + } + else { + var emitOutput = getFileEmitOutput(program, sourceFile, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = options.computeHash(emitOutput.outputFiles[0].text); + info.signature = latestSignature; + } + else { + latestSignature = prevSignature; + } + } + return !prevSignature || latestSignature !== prevSignature; + } + function getReferencedFiles(program, sourceFile) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getNonModuleEmitHandler() { + return { + onAddSourceFile: ts.noop, + onRemoveSourceFile: ts.noop, + onUpdateSourceFile: ts.noop, + onUpdateSourceFileWithSameVersion: ts.returnFalse, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function getFilesAffectedByUpdatedShape(program, sourceFile) { + var options = program.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return [sourceFile]; + } + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + } + function getModuleEmitHandler() { + var references = ts.createMap(); + return { + onAddSourceFile: setReferences, + onRemoveSourceFile: onRemoveSourceFile, + onUpdateSourceFile: updateReferences, + onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function setReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + } + function updateReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + else { + references.delete(sourceFile.path); + } + } + function updateReferencesTrackingChangedReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (!newReferences) { + return references.delete(sourceFile.path); + } + var oldReferences = references.get(sourceFile.path); + references.set(sourceFile.path, newReferences); + if (!oldReferences || oldReferences.size !== newReferences.size) { + return true; + } + return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || + !!oldReferences.size; + } + function onRemoveSourceFile(removedFilePath) { + references.forEach(function (referencesInFile, filePath) { + if (referencesInFile.has(removedFilePath)) { + var referencedByInfo = fileInfos.get(filePath); + if (referencedByInfo) { + registerChangedFile(filePath); + } + } + }); + references.delete(removedFilePath); + } + function getReferencedByPaths(referencedFilePath) { + return ts.mapDefinedIter(references.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + }); + } + function getFilesAffectedByUpdatedShape(program, sourceFile) { + if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFile]; + } + var seenFileNamesMap = ts.createMap(); + var path = sourceFile.path; + seenFileNamesMap.set(path, sourceFile); + var queue = getReferencedByPaths(path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = program.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { + queue.push.apply(queue, getReferencedByPaths(currentPath)); + } + } + } + return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); + } + } + } + ts.createBuilder = createBuilder; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); } ts.findConfigFile = findConfigFile; function resolveTripleslashReference(moduleName, containingFile) { @@ -57478,18 +58578,23 @@ var ts; var output = ""; for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { var diagnostic = diagnostics_1[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + output += formatDiagnostic(diagnostic, host); } return output; } ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; @@ -57517,6 +58622,7 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; + var context = ""; if (diagnostic.file) { var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; @@ -57528,10 +58634,10 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += host.getNewLine(); + context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -57539,23 +58645,22 @@ var ts; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + host.getNewLine(); - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; + context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += redForegroundEscapeSequence; if (i === firstLine) { var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { - output += lineContent.replace(/./g, "~"); + context += lineContent.replace(/./g, "~"); } - output += resetEscapeSequence; - output += host.getNewLine(); + context += resetEscapeSequence; } output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; @@ -57563,13 +58668,17 @@ var ts; var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += context; + } output += host.getNewLine(); } return output; } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { - if (typeof messageText === "string") { + if (ts.isString(messageText)) { return messageText; } else { @@ -57610,6 +58719,45 @@ var ts; } return resolutions; } + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function shouldProgramCreateNewSourceFiles(program, newOptions) { + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57638,8 +58786,9 @@ var ts; var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -57665,7 +58814,9 @@ var ts; var sourceFileToPackageName = ts.createMap(); var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); + var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); @@ -57688,9 +58839,19 @@ var ts; }); } } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); } - var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + ts.Debug.assert(!!missingFilePaths); moduleResolutionCache = undefined; + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } oldProgram = undefined; program = { getRootFileNames: function () { return rootNames; }, @@ -57721,7 +58882,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57749,8 +58910,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var sourceFile = files_2[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var sourceFile = files_1[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -57762,26 +58923,28 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + var result_3 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_3.push(resolvedModule); } - return result_4; + return result_3; } var unknownModuleNames; var result; + var reusedNames; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - if (file === oldSourceFile) { + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); if (oldResolvedModule) { if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); } (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); continue; } } @@ -57803,7 +58966,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) : ts.emptyArray; if (!result) { ts.Debug.assert(resolutions.length === moduleNames.length); @@ -57865,18 +59028,16 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2; + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0; + } var oldSourceFiles = oldProgram.getSourceFiles(); - var SeenPackageName; - (function (SeenPackageName) { - SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists"; - SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; - })(SeenPackageName || (SeenPackageName = {})); var seenPackageNames = ts.createMap(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) - : host.getSourceFile(oldSourceFile.fileName, options.target); + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0; } @@ -57931,6 +59092,10 @@ var ts; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + oldProgram.structureIsReused = 1; + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } newSourceFiles.push(newSourceFile); } if (oldProgram.structureIsReused !== 2) { @@ -57969,20 +59134,20 @@ var ts; if (oldProgram.structureIsReused !== 2) { return oldProgram.structureIsReused; } - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + if (host.hasChangedAutomaticTypeDirectiveNames) { return oldProgram.structureIsReused = 1; } - for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { - var p = _d[_c]; - filesByName.set(p, undefined); - } + missingFilePaths = oldProgram.getMissingFilePaths(); for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { - var modifiedFile = modifiedSourceFiles_2[_e]; + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -58012,10 +59177,16 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); @@ -58095,9 +59266,6 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - if (ts.isCheckJsEnabledForFile(sourceFile, options)) { - sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); - } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -58125,12 +59293,17 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || + sourceFile.scriptKind === 5 || isCheckJs; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); + if (isCheckJs) { + diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + } return ts.filter(diagnostics, shouldReportDiagnostic); }); } @@ -58161,62 +59334,62 @@ var ts; return diagnostics; function walk(node) { switch (parent.kind) { - case 146: - case 149: + case 147: + case 150: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: - case 226: + case 229: + case 188: + case 227: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); return; } } switch (node.kind) { - case 237: + case 238: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 243: + case 244: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 259: + case 263: var heritageClause = node; if (heritageClause.token === 108) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 230: + case 231: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 233: + case 234: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 231: + case 232: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 232: + case 233: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 203: + case 204: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 202: + case 203: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 184: + case 185: ts.Debug.fail(); } var prevParent = parent; @@ -58229,25 +59402,25 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } switch (parent.kind) { - case 229: - case 151: - case 150: + case 230: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: + case 229: + case 188: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } - case 208: + case 209: if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 208); + return checkModifiers(nodes, parent.kind === 209); } break; - case 149: + case 150: if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -58258,15 +59431,15 @@ var ts; return; } break; - case 146: + case 147: if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 181: case 182: - case 201: + case 183: + case 202: if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return; @@ -58388,9 +59561,9 @@ var ts; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { + case 239: case 238: - case 237: - case 244: + case 245: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; @@ -58402,7 +59575,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 233: + case 234: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); @@ -58452,7 +59625,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } return sourceFile; @@ -58536,7 +59709,7 @@ var ts; else { fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } - }); + }, shouldCreateNewSourceFile); if (packageId) { var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); @@ -58799,7 +59972,7 @@ var ts; if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } - if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0; @@ -58987,7 +60160,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -59008,6 +60181,917 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution() { + if (allFilesHaveInvalidatedResolution) { + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); + } + else { + watchFailedLookupLocationOfResolution(resolution, 0); + } + } + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, dirPath.charCodeAt(0) === 47 ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + return { dir: rootDir, dirPath: rootPath }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + } + } + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; + } + } + } + function createDirectoryWatcher(directory, dirPath) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (resolutionHost.getCachedDirectoryStructureHost) { + resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && + dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + } + }, 1); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions(function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions(hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (resolutionHost.getCachedDirectoryStructureHost) { + resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1); + } + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + closeTypeRootsWatch(); + return; + } + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +var ts; +(function (ts) { + var defaultFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; + function createDiagnosticReporter(system, worker, formatDiagnosticsHost) { + if (system === void 0) { system = ts.sys; } + if (worker === void 0) { worker = reportDiagnosticSimply; } + return function (diagnostic) { return worker(diagnostic, getFormatDiagnosticsHost(), system); }; + function getFormatDiagnosticsHost() { + return formatDiagnosticsHost || (formatDiagnosticsHost = system === ts.sys ? defaultFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }); + } + } + ts.createDiagnosticReporter = createDiagnosticReporter; + function createWatchDiagnosticReporter(system) { + if (system === void 0) { system = ts.sys; } + return function (diagnostic) { + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine + system.newLine); + system.write(output); + }; + } + ts.createWatchDiagnosticReporter = createWatchDiagnosticReporter; + function reportDiagnostics(diagnostics, reportDiagnostic) { + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + reportDiagnostic(diagnostic); + } + } + ts.reportDiagnostics = reportDiagnostics; + function reportDiagnosticSimply(diagnostic, host, system) { + system.write(ts.formatDiagnostic(diagnostic, host)); + } + ts.reportDiagnosticSimply = reportDiagnosticSimply; + function reportDiagnosticWithColorAndContext(diagnostic, host, system) { + system.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + host.getNewLine()); + } + ts.reportDiagnosticWithColorAndContext = reportDiagnosticWithColorAndContext; + function parseConfigFile(configFileName, optionsToExtend, system, reportDiagnostic, reportWatchDiagnostic) { + var configFileText; + try { + configFileText = system.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + reportWatchDiagnostic(error); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + reportDiagnostics([error], reportDiagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return; + } + var result = ts.parseJsonText(configFileName, configFileText); + reportDiagnostics(result.parseDiagnostics, reportDiagnostic); + var cwd = system.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, system, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + reportDiagnostics(configParseResult.errors, reportDiagnostic); + return configParseResult; + } + ts.parseConfigFile = parseConfigFile; + function reportEmittedFiles(files, system) { + if (!files || files.length === 0) { + return; + } + var currentDir = system.getCurrentDirectory(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var file = files_2[_i]; + var filepath = ts.getNormalizedAbsolutePath(file, currentDir); + system.write("TSFILE: " + filepath + system.newLine); + } + } + function handleEmitOutputAndReportErrors(system, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic) { + reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), reportDiagnostic); + reportEmittedFiles(emittedFiles, system); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + system.write(file.fileName + system.newLine); + }); + } + if (emitSkipped && diagnostics.length > 0) { + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.handleEmitOutputAndReportErrors = handleEmitOutputAndReportErrors; + function createWatchingSystemHost(pretty, system, parseConfigFile, reportDiagnostic, reportWatchDiagnostic) { + if (system === void 0) { system = ts.sys; } + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system, pretty ? reportDiagnosticWithColorAndContext : reportDiagnosticSimply); + reportWatchDiagnostic = reportWatchDiagnostic || createWatchDiagnosticReporter(system); + parseConfigFile = parseConfigFile || ts.parseConfigFile; + return { + system: system, + parseConfigFile: parseConfigFile, + reportDiagnostic: reportDiagnostic, + reportWatchDiagnostic: reportWatchDiagnostic, + beforeCompile: ts.noop, + afterCompile: compileWatchedProgram, + }; + function compileWatchedProgram(host, program, builder) { + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } + } + var emittedFiles = program.getCompilerOptions().listEmittedFiles ? [] : undefined; + var sourceMaps; + var emitSkipped; + var result = builder.emitChangedFiles(program, writeFile); + if (result.length === 0) { + emitSkipped = true; + } + else { + for (var _i = 0, result_4 = result; _i < result_4.length; _i++) { + var emitOutput = result_4[_i]; + if (emitOutput.emitSkipped) { + emitSkipped = true; + } + ts.addRange(diagnostics, emitOutput.diagnostics); + sourceMaps = ts.concatenate(sourceMaps, emitOutput.sourceMaps); + } + } + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, builder.getSemanticDiagnostics(program)); + } + return handleEmitOutputAndReportErrors(host, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + if (emittedFiles) { + emittedFiles.push(fileName); + } + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + } + ts.createWatchingSystemHost = createWatchingSystemHost; + function createWatchModeWithConfigFile(configParseResult, optionsToExtend, watchingHost) { + if (optionsToExtend === void 0) { optionsToExtend = {}; } + return createWatchMode(configParseResult.fileNames, configParseResult.options, watchingHost, configParseResult.options.configFilePath, configParseResult.configFileSpecs, configParseResult.wildcardDirectories, optionsToExtend); + } + ts.createWatchModeWithConfigFile = createWatchModeWithConfigFile; + function createWatchModeWithoutConfigFile(rootFileNames, compilerOptions, watchingHost) { + return createWatchMode(rootFileNames, compilerOptions, watchingHost); + } + ts.createWatchModeWithoutConfigFile = createWatchModeWithoutConfigFile; + function createWatchMode(rootFileNames, compilerOptions, watchingHost, configFileName, configFileSpecs, configFileWildCardDirectories, optionsToExtendForConfigFile) { + var program; + var reloadLevel; + var missingFilesMap; + var watchedWildcardDirectories; + var timerToUpdateProgram; + var sourceFilesCache = ts.createMap(); + var missingFilePathsRequestedForRelease; + var hasChangedCompilerOptions = false; + var hasChangedAutomaticTypeDirectiveNames = false; + var loggingEnabled = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; + var writeLog = loggingEnabled ? function (s) { system.write(s); system.write(system.newLine); } : ts.noop; + var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; + var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; + var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + watchingHost = watchingHost || createWatchingSystemHost(compilerOptions.pretty); + var system = watchingHost.system, parseConfigFile = watchingHost.parseConfigFile, reportDiagnostic = watchingHost.reportDiagnostic, reportWatchDiagnostic = watchingHost.reportWatchDiagnostic, beforeCompile = watchingHost.beforeCompile, afterCompile = watchingHost.afterCompile; + var directoryStructureHost = configFileName ? ts.createCachedDirectoryStructureHost(system) : system; + if (configFileName) { + watchFile(system, configFileName, scheduleProgramReload, writeLog); + } + var getCurrentDirectory = ts.memoize(function () { return directoryStructureHost.getCurrentDirectory(); }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); + var getCachedDirectoryStructureHost = configFileName && (function () { return directoryStructureHost; }); + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); + var newLine = ts.getNewLineCharacter(compilerOptions, system); + var compilerHost = { + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: ts.notImplemented, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return directoryStructureHost.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return directoryStructureHost.getDirectories(path); }, + realpath: realpath, + resolveTypeReferenceDirectives: function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }, + resolveModuleNames: function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, false); }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: watchDirectory, + watchTypeRootsDirectory: watchDirectory, + getCachedDirectoryStructureHost: getCachedDirectoryStructureHost, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + writeLog: writeLog + }; + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, getCurrentDirectory())) : + getCurrentDirectory()); + var builder = ts.createBuilder({ getCanonicalFileName: getCanonicalFileName, computeHash: computeHash }); + synchronizeProgram(); + watchConfigFileWildCardDirectories(); + return function () { return program; }; + function synchronizeProgram() { + writeLog("Synchronizing program"); + if (hasChangedCompilerOptions) { + newLine = ts.getNewLineCharacter(compilerOptions, system); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(); + if (ts.isProgramUptoDate(program, rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return; + } + beforeCompile(compilerOptions); + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + program = ts.createProgram(rootFileNames, compilerOptions, compilerHost, program); + resolutionCache.finishCachingPerDirectoryResolution(); + builder.updateProgram(program); + ts.updateMissingFilePathsWatch(program, missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + afterCompile(directoryStructureHost, program, builder); + reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); + } + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function fileExists(fileName) { + var path = toPath(fileName); + var hostSourceFileInfo = sourceFilesCache.get(path); + if (hostSourceFileInfo !== undefined) { + return !ts.isString(hostSourceFileInfo); + } + return directoryStructureHost.fileExists(fileName); + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + if (ts.isString(hostSourceFile)) { + return undefined; + } + if (!hostSourceFile || shouldCreateNewSourceFile || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(system, fileName, onSourceFileChange, path, writeLog); + } + } + else { + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, hostSourceFile.version.toString()); + } + } + else { + var fileWatcher = void 0; + if (sourceFile) { + sourceFile.version = "0"; + fileWatcher = watchFilePath(system, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 0, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, "0"); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = system.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function removeSourceFile(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + resolutionCache.invalidateResolutionOfFile(path); + } + sourceFilesCache.delete(path); + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || ts.isString(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + if (hostSourceFileInfo) { + if (ts.isString(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + sourceFilesCache.delete(oldSourceFile.path); + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + function scheduleProgramUpdate() { + if (!system.setTimeout || !system.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + system.clearTimeout(timerToUpdateProgram); + } + timerToUpdateProgram = system.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation)); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + return synchronizeProgram(); + } + } + function reloadFileNamesFromConfigFile() { + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, directoryStructureHost); + if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { + reportDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + rootFileNames = result.fileNames; + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + var cachedHost = directoryStructureHost; + cachedHost.clearCache(); + var configParseResult = parseConfigFile(configFileName, optionsToExtendForConfigFile, cachedHost, reportDiagnostic, reportWatchDiagnostic); + rootFileNames = configParseResult.fileNames; + compilerOptions = configParseResult.options; + hasChangedCompilerOptions = true; + configFileSpecs = configParseResult.configFileSpecs; + configFileWildCardDirectories = configParseResult.wildcardDirectories; + synchronizeProgram(); + watchConfigFileWildCardDirectories(); + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile) { + if (eventKind === ts.FileWatcherEventKind.Deleted) { + resolutionCache.invalidateResolutionOfFile(path); + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, (hostSourceFile.version++).toString()); + } + } + else { + if (ts.isString(hostSourceFile)) { + sourceFilesCache.delete(path); + } + else { + hostSourceFile.version++; + } + } + } + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (configFileName) { + directoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchDirectory(directory, cb, flags) { + return watchDirectoryWorker(system, directory, cb, flags, writeLog); + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(system, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + removeSourceFile(missingFilePath); + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + var result = directoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); + if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { + hostSourceFile.version++; + } + else { + removeSourceFile(fileOrDirectoryPath); + } + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + scheduleProgramUpdate(); + } + }, flags); + } + function computeHash(data) { + return system.createHash ? system.createHash(data) : data; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ @@ -59075,31 +61159,32 @@ var ts; name: "target", shortName: "t", type: ts.createMapFromTemplate({ - "es3": 0, - "es5": 1, - "es6": 2, - "es2015": 2, - "es2016": 3, - "es2017": 4, - "esnext": 5, + es3: 0, + es5: 1, + es6: 2, + es2015: 2, + es2016: 3, + es2017: 4, + es2018: 5, + esnext: 6, }), paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", shortName: "m", type: ts.createMapFromTemplate({ - "none": ts.ModuleKind.None, - "commonjs": ts.ModuleKind.CommonJS, - "amd": ts.ModuleKind.AMD, - "system": ts.ModuleKind.System, - "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES2015, - "es2015": ts.ModuleKind.ES2015, - "esnext": ts.ModuleKind.ESNext + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -59118,6 +61203,7 @@ var ts; "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", "dom": "lib.dom.d.ts", "dom.iterable": "lib.dom.iterable.d.ts", @@ -59137,6 +61223,7 @@ var ts; "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", + "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -59263,6 +61350,20 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, { name: "noImplicitThis", type: "boolean", @@ -59308,8 +61409,8 @@ var ts; { name: "moduleResolution", type: ts.createMapFromTemplate({ - "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic, + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, }), paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, @@ -59492,8 +61593,8 @@ var ts; { name: "newLine", type: ts.createMapFromTemplate({ - "crlf": 0, - "lf": 1 + crlf: 0, + lf: 1 }), paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Advanced_Options, @@ -59828,7 +61929,7 @@ var ts; } function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; function parseConfigFileTextToJson(fileName, jsonText) { @@ -59841,7 +61942,7 @@ var ts; ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function readJsonConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; function tryReadFile(fileName, readFile) { @@ -59925,7 +62026,7 @@ var ts; var result = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 261) { + if (element.kind !== 265) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -59982,9 +62083,9 @@ var ts; if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); var text = valueExpression.text; - if (option && typeof option.type !== "string") { + if (option && !ts.isString(option.type)) { var customOption = option; if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); @@ -59994,7 +62095,13 @@ var ts; case 8: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 178: + case 193: + if (valueExpression.operator !== 38 || valueExpression.operand.kind !== 8) { + break; + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 179: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; if (option) { @@ -60004,7 +62111,7 @@ var ts; else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); } - case 177: + case 178: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -60022,13 +62129,13 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : - typeof option.type === "string" ? option.type : "string"; + ts.isString(option.type) ? option.type : "string"; } function isCompilerOptionsValue(option, value) { if (option) { @@ -60037,7 +62144,7 @@ var ts; if (option.type === "list") { return ts.isArray(value); } - var expectedType = typeof option.type === "string" ? option.type : "string"; + var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } } @@ -60198,12 +62305,13 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -60211,14 +62319,15 @@ var ts; raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec }; function getFileNames() { - var fileNames; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - fileNames = raw["files"]; - if (fileNames.length === 0) { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -60227,35 +62336,35 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } } - if (fileNames === undefined && includeSpecs === undefined) { + if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } return result; } @@ -60265,12 +62374,20 @@ var ts; } } } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); @@ -60307,11 +62424,11 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { - if (typeof json.extends !== "string") { + if (!ts.isString(json.extends)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { @@ -60399,7 +62516,7 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } @@ -60423,7 +62540,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -60483,7 +62600,7 @@ var ts; if (optType === "list" && ts.isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors); } - else if (typeof optType !== "string") { + else if (!ts.isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); } return normalizeNonListOptionValue(opt, basePath, value); @@ -60497,13 +62614,13 @@ var ts; return undefined; if (option.type === "list") { var listOption_1 = option; - if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else if (typeof option.type !== "string") { - return option.type.get(typeof value === "string" ? value.toLowerCase() : value); + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -60539,28 +62656,36 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); + } + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); - if (include) { - include = validateSpecs(include, errors, false, jsonSourceFile, "include"); - } - if (exclude) { - exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); - } - var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); - if (fileNames) { - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } - if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -60576,9 +62701,11 @@ var ts; var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); return { fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + spec: spec }; } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter(function (spec) { var diag = specToDiagnostic(spec, allowTrailingRecursion); @@ -60729,32 +62856,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var defaultFormatDiagnosticsHost = { - getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, - getNewLine: function () { return ts.sys.newLine; }, - getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - }; - var reportDiagnosticWorker = reportDiagnosticSimply; - function reportDiagnostic(diagnostic, host) { - reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); - } - function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - reportDiagnostic(diagnostic, host); - } - } - function reportEmittedFiles(files) { - if (!files || files.length === 0) { - return; - } - var currentDir = ts.sys.getCurrentDirectory(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var file = files_3[_i]; - var filepath = ts.getNormalizedAbsolutePath(file, currentDir); - ts.sys.write("TSFILE: " + filepath + ts.sys.newLine); - } - } function countLines(program) { var count = 0; ts.forEach(program.getSourceFiles(), function (file) { @@ -60770,20 +62871,11 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - function reportDiagnosticSimply(diagnostic, host) { - ts.sys.write(ts.formatDiagnostics([diagnostic], host)); - } - function reportDiagnosticWithColorAndContext(diagnostic, host) { - ts.sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + ts.sys.newLine); - } - function reportWatchDiagnostic(diagnostic) { - var output = new Date().toLocaleTimeString() + " - "; - if (diagnostic.file) { - var loc = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - output += diagnostic.file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + "): "; + var reportDiagnostic = ts.createDiagnosticReporter(ts.sys, ts.reportDiagnosticSimply); + function udpateReportDiagnostic(options) { + if (options.pretty) { + reportDiagnostic = ts.createDiagnosticReporter(ts.sys, ts.reportDiagnosticWithColorAndContext); } - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + (ts.sys.newLine + ts.sys.newLine + ts.sys.newLine); - ts.sys.write(output); } function padLeft(s, length) { while (s.length < length) { @@ -60797,32 +62889,14 @@ var ts; } return s; } - function isJSONSupported() { - return typeof JSON === "object" && typeof JSON.parse === "function"; - } function executeCommandLine(args) { var commandLine = ts.parseCommandLine(args); var configFileName; - var cachedConfigFileText; - var directoryWatcher; - var cachedProgram; - var rootFileNames; - var compilerOptions; - var compilerHost; - var hostGetSourceFile; - var timerHandleForRecompilation; - var timerHandleForDirectoryChanges; - var cachedExistingFiles; - var hostFileExists; if (commandLine.options.locale) { - if (!isJSONSupported()) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), undefined); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - } ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); } if (commandLine.errors.length > 0) { - reportDiagnostics(commandLine.errors, compilerHost); + ts.reportDiagnostics(commandLine.errors, reportDiagnostic); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.init) { @@ -60839,31 +62913,27 @@ var ts; return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.project) { - if (!isJSONSupported()) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), undefined); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - } if (commandLine.fileNames.length !== 0) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), undefined); + 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); } var fileOrDirectory = ts.normalizePath(commandLine.options.project); if (!fileOrDirectory || ts.sys.directoryExists(fileOrDirectory)) { configFileName = ts.combinePaths(fileOrDirectory, "tsconfig.json"); if (!ts.sys.fileExists(configFileName)) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), undefined); + 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); } } else { configFileName = fileOrDirectory; if (!ts.sys.fileExists(configFileName)) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), undefined); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } } - else if (commandLine.fileNames.length === 0 && isJSONSupported()) { + else if (commandLine.fileNames.length === 0) { var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); } @@ -60872,194 +62942,78 @@ var ts; printHelp(commandLine.options.all); return ts.sys.exit(ts.ExitStatus.Success); } - if (ts.isWatchSet(commandLine.options)) { - if (!ts.sys.watchFile) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), undefined); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - if (configFileName) { - ts.sys.watchFile(configFileName, configFileChanged); - } - if (ts.sys.watchDirectory && configFileName) { - var directory = ts.getDirectoryPath(configFileName); - directoryWatcher = ts.sys.watchDirectory(directory === "" ? "." : directory, watchedDirectoryChanged, true); - } - } - performCompilation(); - function parseConfigFile() { - if (!cachedConfigFileText) { - try { - cachedConfigFileText = ts.sys.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - reportWatchDiagnostic(error); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; - } - } - if (!cachedConfigFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - reportDiagnostics([error], undefined); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; - } - var result = ts.parseJsonText(configFileName, cachedConfigFileText); - reportDiagnostics(result.parseDiagnostics, undefined); - var cwd = ts.sys.getCurrentDirectory(); - var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd)); - reportDiagnostics(configParseResult.errors, undefined); + var commandLineOptions = commandLine.options; + if (configFileName) { + var reportWatchDiagnostic = ts.createWatchDiagnosticReporter(); + var configParseResult = ts.parseConfigFile(configFileName, commandLineOptions, ts.sys, reportDiagnostic, reportWatchDiagnostic); + udpateReportDiagnostic(configParseResult.options); if (ts.isWatchSet(configParseResult.options)) { - if (!ts.sys.watchFile) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), undefined); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - if (!directoryWatcher && ts.sys.watchDirectory && configFileName) { - var directory = ts.getDirectoryPath(configFileName); - directoryWatcher = ts.sys.watchDirectory(directory === "" ? "." : directory, watchedDirectoryChanged, true); - } - } - return configParseResult; - } - function performCompilation() { - if (!cachedProgram) { - if (configFileName) { - var configParseResult = parseConfigFile(); - rootFileNames = configParseResult.fileNames; - compilerOptions = configParseResult.options; - } - else { - rootFileNames = commandLine.fileNames; - compilerOptions = commandLine.options; - } - compilerHost = ts.createCompilerHost(compilerOptions); - hostGetSourceFile = compilerHost.getSourceFile; - compilerHost.getSourceFile = getSourceFile; - hostFileExists = compilerHost.fileExists; - compilerHost.fileExists = cachedFileExists; - } - if (compilerOptions.pretty) { - reportDiagnosticWorker = reportDiagnosticWithColorAndContext; - } - cachedExistingFiles = ts.createMap(); - var compileResult = compile(rootFileNames, compilerOptions, compilerHost); - if (!ts.isWatchSet(compilerOptions)) { - return ts.sys.exit(compileResult.exitStatus); - } - setCachedProgram(compileResult.program); - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); - var missingPaths = compileResult.program.getMissingFilePaths(); - missingPaths.forEach(function (path) { - var fileWatcher = ts.sys.watchFile(path, function (_fileName, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Created) { - fileWatcher.close(); - startTimerForRecompilation(); - } - }); - }); - } - function cachedFileExists(fileName) { - var fileExists = cachedExistingFiles.get(fileName); - if (fileExists === undefined) { - cachedExistingFiles.set(fileName, fileExists = hostFileExists(fileName)); - } - return fileExists; - } - function getSourceFile(fileName, languageVersion, onError) { - if (cachedProgram) { - var sourceFile_1 = cachedProgram.getSourceFile(fileName); - if (sourceFile_1 && sourceFile_1.fileWatcher) { - return sourceFile_1; - } - } - var sourceFile = hostGetSourceFile(fileName, languageVersion, onError); - if (sourceFile && ts.isWatchSet(compilerOptions) && ts.sys.watchFile) { - sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.fileName, function (_fileName, eventKind) { return sourceFileChanged(sourceFile, eventKind); }); - } - return sourceFile; - } - function setCachedProgram(program) { - if (cachedProgram) { - var newSourceFiles_1 = program ? program.getSourceFiles() : undefined; - ts.forEach(cachedProgram.getSourceFiles(), function (sourceFile) { - if (!(newSourceFiles_1 && ts.contains(newSourceFiles_1, sourceFile))) { - if (sourceFile.fileWatcher) { - sourceFile.fileWatcher.close(); - sourceFile.fileWatcher = undefined; - } - } - }); + reportWatchModeWithoutSysSupport(); + ts.createWatchModeWithConfigFile(configParseResult, commandLineOptions, createWatchingSystemHost(reportWatchDiagnostic)); } - cachedProgram = program; - } - function sourceFileChanged(sourceFile, eventKind) { - sourceFile.fileWatcher.close(); - sourceFile.fileWatcher = undefined; - if (eventKind === ts.FileWatcherEventKind.Deleted) { - ts.unorderedRemoveItem(rootFileNames, sourceFile.fileName); - } - startTimerForRecompilation(); - } - function configFileChanged() { - setCachedProgram(undefined); - cachedConfigFileText = undefined; - startTimerForRecompilation(); - } - function watchedDirectoryChanged(fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, compilerOptions)) { - return; + else { + performCompilation(configParseResult.fileNames, configParseResult.options); } - startTimerForHandlingDirectoryChanges(); } - function startTimerForHandlingDirectoryChanges() { - if (!ts.sys.setTimeout || !ts.sys.clearTimeout) { - return; - } - if (timerHandleForDirectoryChanges) { - ts.sys.clearTimeout(timerHandleForDirectoryChanges); + else { + udpateReportDiagnostic(commandLineOptions); + if (ts.isWatchSet(commandLineOptions)) { + reportWatchModeWithoutSysSupport(); + ts.createWatchModeWithoutConfigFile(commandLine.fileNames, commandLineOptions, createWatchingSystemHost()); } - timerHandleForDirectoryChanges = ts.sys.setTimeout(directoryChangeHandler, 250); - } - function directoryChangeHandler() { - var parsedCommandLine = parseConfigFile(); - var newFileNames = ts.map(parsedCommandLine.fileNames, compilerHost.getCanonicalFileName); - var canonicalRootFileNames = ts.map(rootFileNames, compilerHost.getCanonicalFileName); - if (!ts.arrayIsEqualTo(newFileNames && newFileNames.sort(), canonicalRootFileNames && canonicalRootFileNames.sort())) { - setCachedProgram(undefined); - startTimerForRecompilation(); + else { + performCompilation(commandLine.fileNames, commandLineOptions); } } - function startTimerForRecompilation() { - if (!ts.sys.setTimeout || !ts.sys.clearTimeout) { - return; - } - if (timerHandleForRecompilation) { - ts.sys.clearTimeout(timerHandleForRecompilation); + } + ts.executeCommandLine = executeCommandLine; + function reportWatchModeWithoutSysSupport() { + if (!ts.sys.watchFile || !ts.sys.watchDirectory) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); + ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + function performCompilation(rootFileNames, compilerOptions) { + var compilerHost = ts.createCompilerHost(compilerOptions); + enableStatistics(compilerOptions); + var program = ts.createProgram(rootFileNames, compilerOptions, compilerHost); + var exitStatus = compileProgram(program); + reportStatistics(program); + return ts.sys.exit(exitStatus); + } + function createWatchingSystemHost(reportWatchDiagnostic) { + var watchingHost = ts.createWatchingSystemHost(undefined, ts.sys, ts.parseConfigFile, reportDiagnostic, reportWatchDiagnostic); + watchingHost.beforeCompile = enableStatistics; + var afterCompile = watchingHost.afterCompile; + watchingHost.afterCompile = function (host, program, builder) { + afterCompile(host, program, builder); + reportStatistics(program); + }; + return watchingHost; + } + function compileProgram(program) { + var diagnostics; + diagnostics = program.getSyntacticDiagnostics().slice(); + if (diagnostics.length === 0) { + diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + diagnostics = program.getSemanticDiagnostics().slice(); } - timerHandleForRecompilation = ts.sys.setTimeout(recompile, 250); } - function recompile() { - timerHandleForRecompilation = undefined; - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation)); - performCompilation(); + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + return ts.handleEmitOutputAndReportErrors(ts.sys, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); + } + function enableStatistics(compilerOptions) { + if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + ts.performance.enable(); } } - ts.executeCommandLine = executeCommandLine; - function compile(fileNames, compilerOptions, compilerHost) { - var hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; + function reportStatistics(program) { var statistics; - if (hasDiagnostics) { - ts.performance.enable(); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { statistics = []; - } - var program = ts.createProgram(fileNames, compilerOptions, compilerHost); - var exitStatus = compileProgram(); - if (compilerOptions.listFiles) { - ts.forEach(program.getSourceFiles(), function (file) { - ts.sys.write(file.fileName + ts.sys.newLine); - }); - } - if (hasDiagnostics) { var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); @@ -61089,28 +63043,6 @@ var ts; reportStatistics(); ts.performance.disable(); } - return { program: program, exitStatus: exitStatus }; - function compileProgram() { - var diagnostics; - diagnostics = program.getSyntacticDiagnostics().slice(); - if (diagnostics.length === 0) { - diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { - diagnostics = program.getSemanticDiagnostics().slice(); - } - } - var emitOutput = program.emit(); - ts.addRange(diagnostics, emitOutput.diagnostics); - reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), compilerHost); - reportEmittedFiles(emitOutput.emittedFiles); - if (emitOutput.emitSkipped && diagnostics.length > 0) { - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - else if (diagnostics.length > 0) { - return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; - } - return ts.ExitStatus.Success; - } function reportStatistics() { var nameSize = 0; var valueSize = 0; @@ -61157,14 +63089,14 @@ var ts; output.push(ts.sys.newLine); output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); var optsList = showAllOptions ? - ts.optionDeclarations.slice().sort(function (a, b) { return ts.compareValues(a.name.toLowerCase(), b.name.toLowerCase()); }) : + ts.sort(ts.optionDeclarations, function (a, b) { return ts.compareStringsCaseInsensitive(a.name, b.name); }) : ts.filter(ts.optionDeclarations.slice(), function (v) { return v.showInSimplifiedHelpView; }); marginLength = 0; var usageColumn = []; var descriptionColumn = []; var optionsDescriptionMap = ts.createMap(); - for (var i = 0; i < optsList.length; i++) { - var option = optsList[i]; + for (var _i = 0, optsList_1 = optsList; _i < optsList_1.length; _i++) { + var option = optsList_1[_i]; if (!option.description) { continue; } @@ -61201,15 +63133,15 @@ var ts; output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); if (kindsList) { output.push(makePadding(marginLength + 4)); - for (var _i = 0, kindsList_1 = kindsList; _i < kindsList_1.length; _i++) { - var kind = kindsList_1[_i]; + 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 _a = 0, output_1 = output; _a < output_1.length; _a++) { - var line = output_1[_a]; + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; ts.sys.write(line); } return; @@ -61227,16 +63159,15 @@ var ts; var currentDirectory = ts.sys.getCurrentDirectory(); var file = ts.normalizePath(ts.combinePaths(currentDirectory, "tsconfig.json")); if (ts.sys.fileExists(file)) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), undefined); + 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)); - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file), undefined); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file)); } return; } })(ts || (ts = {})); -ts.setStackTraceLimit(); if (ts.Debug.isDebugging) { ts.Debug.enableDebugInfo(); } @@ -61244,5 +63175,3 @@ if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnviron ts.sys.tryEnableSourceMapsForHost(); } ts.executeCommandLine(ts.sys.args); - -//# sourceMappingURL=tsc.js.map diff --git a/lib/tsserver.js b/lib/tsserver.js index cf8cbbea28146..30fde91af76cf 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -34,6 +34,12 @@ var __extends = (this && this.__extends) || (function () { })(); var ts; (function (ts) { + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); var SyntaxKind; (function (SyntaxKind) { SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; @@ -176,159 +182,163 @@ var ts; SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; - SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; - SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; - SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; - SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; - SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; - SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; - SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; - SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; - SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; - SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; - SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 270] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 140] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 141] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 142] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 143] = "OfKeyword"; + SyntaxKind[SyntaxKind["QualifiedName"] = 144] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 145] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 146] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 147] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 148] = "Decorator"; + SyntaxKind[SyntaxKind["PropertySignature"] = 149] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 150] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 151] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 152] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 153] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 154] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 155] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 156] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 157] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 158] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypePredicate"] = 159] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 160] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 161] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 162] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 163] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 164] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 165] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 166] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 167] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 168] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 169] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 170] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 171] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 172] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 173] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 174] = "LiteralType"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 175] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 176] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 177] = "BindingElement"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 178] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 179] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 180] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 181] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 182] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 183] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 184] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 185] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 186] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 187] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 188] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 189] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 190] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 191] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 192] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 193] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 194] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 195] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 196] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 197] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 198] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 199] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 200] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 201] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 202] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 203] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 204] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 205] = "MetaProperty"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 206] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 207] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["Block"] = 208] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 209] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 210] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 211] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 212] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 213] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 214] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 215] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 216] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 217] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 218] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 219] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 220] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 221] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 222] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 223] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 224] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 225] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 226] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 227] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 228] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 229] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 230] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 231] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 232] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 233] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 234] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 235] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 236] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 237] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 238] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 239] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 240] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 241] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 242] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 243] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 244] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 245] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 246] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 247] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 248] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 249] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["JsxElement"] = 250] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 251] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 252] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 253] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 254] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 255] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 256] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 257] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 258] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 259] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 260] = "JsxExpression"; + SyntaxKind[SyntaxKind["CaseClause"] = 261] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 262] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 263] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 264] = "CatchClause"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 265] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 266] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 267] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 268] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 269] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 270] = "Bundle"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 271] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 272] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 273] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 274] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 275] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 276] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 277] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 278] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 279] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 280] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocTag"] = 281] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 282] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 283] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 284] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 285] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 286] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 287] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 288] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 289] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["SyntaxList"] = 290] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 291] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 292] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 293] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 294] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 295] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 296] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -336,15 +346,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 143] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 159] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 174] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 143] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -353,11 +363,13 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 144] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 271] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 289] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 281] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 289] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; + SyntaxKind[SyntaxKind["LastContextualKeyword"] = 143] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -383,10 +395,12 @@ var ts; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; + NodeFlags[NodeFlags["Ambient"] = 2097152] = "Ambient"; + NodeFlags[NodeFlags["InWithStatement"] = 4194304] = "InWithStatement"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; - NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 6387712] = "ContextFlags"; NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); var ModifierFlags; @@ -431,16 +445,21 @@ var ts; GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); - var NumericLiteralFlags; - (function (NumericLiteralFlags) { - NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; - NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; - NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; - NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; - NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; - })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -513,6 +532,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -579,6 +599,8 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -611,7 +633,8 @@ var ts; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; - SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); var EnumKind; (function (EnumKind) { @@ -630,6 +653,7 @@ var ts; CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -687,42 +711,46 @@ var ts; TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 32768] = "Object"; - TypeFlags[TypeFlags["Union"] = 65536] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 262144] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; - TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 2048] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 8192] = "Null"; + TypeFlags[TypeFlags["Never"] = 16384] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 65536] = "Object"; + TypeFlags[TypeFlags["Union"] = 131072] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 524288] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; + TypeFlags[TypeFlags["FreshLiteral"] = 2097152] = "FreshLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 4194304] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 8388608] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 16777216] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 33554432] = "NonPrimitive"; + TypeFlags[TypeFlags["JsxAttributes"] = 67108864] = "JsxAttributes"; + TypeFlags[TypeFlags["MarkerType"] = 134217728] = "MarkerType"; + TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; + TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; - TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Intrinsic"] = 33585807] = "Intrinsic"; + TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 524322] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; - TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 2064384] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; + TypeFlags[TypeFlags["Narrowable"] = 35620607] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 33620481] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["RequiresWidening"] = 12582912] = "RequiresWidening"; + TypeFlags[TypeFlags["PropagatingFlags"] = 29360128] = "PropagatingFlags"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -736,8 +764,17 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -750,9 +787,11 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -825,8 +864,9 @@ var ts; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; (function (LanguageVariant) { @@ -977,6 +1017,7 @@ var ts; Extension["Dts"] = ".d.ts"; Extension["Js"] = ".js"; Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; })(Extension = ts.Extension || (ts.Extension = {})); var TransformFlags; (function (TransformFlags) { @@ -1086,13 +1127,14 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1110,9 +1152,7 @@ var ts; (function (ts) { var performance; (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (_markName) { }; + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; var enabled = false; var profilerStart = 0; var counts; @@ -1164,7 +1204,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.6"; + ts.versionMajorMinor = "2.7"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { @@ -1174,12 +1214,10 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { - ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; - ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } function createMap() { @@ -1284,12 +1322,6 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -1306,6 +1338,16 @@ var ts; return undefined; } ts.forEach = forEach; + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1321,10 +1363,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1357,6 +1401,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -1376,11 +1430,12 @@ var ts; Debug.fail(); } ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (equalityComparer(v, value)) { return true; } } @@ -1443,22 +1498,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1485,6 +1524,14 @@ var ts; return result; } ts.map = map; + function mapIterator(iter, mapFn) { + return { next: next }; + function next() { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + } + ts.mapIterator = mapIterator; function sameMap(array, f) { var result; if (array) { @@ -1509,8 +1556,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1550,8 +1597,14 @@ var ts; if (done) break; var res = mapfn(value); - if (res) - result.push.apply(result, res); + if (res) { + if (isArray(res)) { + result.push.apply(result, res); + } + else { + result.push(res); + } + } } return result; } @@ -1592,6 +1645,20 @@ var ts; return result; } ts.mapDefined = mapDefined; + function mapDefinedIter(iter, mapFn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapFn(value); + if (res !== undefined) { + result.push(res); + } + } + return result; + } + ts.mapDefinedIter = mapDefinedIter; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1654,8 +1721,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1676,25 +1743,64 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - function deduplicate(array, areEqual) { - var result; - if (array) { - result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } - } - result.push(item); - } + function deduplicateRelational(array, equalityComparer, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); } return result; } + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } ts.deduplicate = deduplicate; - function arrayIsEqualTo(array1, array2, equaler) { + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + case true: + case 0: + continue; + case -1: + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (!array1 || !array2) { return array1 === array2; } @@ -1702,8 +1808,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { + if (!equalityComparer(array1[i], array2[i])) { return false; } } @@ -1747,30 +1852,36 @@ var ts; return result || array; } ts.compact = compact; - function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { - if (comparer === void 0) { comparer = compareValues; } - if (offsetA === void 0) { offsetA = 0; } - if (offsetB === void 0) { offsetB = 0; } + function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; var result = []; - outer: for (; offsetB < arrayB.length; offsetB++) { - inner: for (; offsetA < arrayA.length; offsetA++) { + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0); + } switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1: break inner; - case 0: continue outer; - case 1: continue inner; + case -1: + result.push(arrayB[offsetB]); + continue loopB; + case 0: + continue loopB; + case 1: + continue loopA; } } - result.push(arrayB[offsetB]); } return result; } ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result += v[prop]; } return result; @@ -1789,23 +1900,22 @@ var ts; return offset < 0 ? array.length + offset : offset; } function addRange(to, from, start, end) { - if (from === undefined) + if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); end = end === undefined ? from.length : toOffset(from, end); for (var i = start; i < end && i < from.length; i++) { - var v = from[i]; - if (v !== undefined) { + if (from[i] !== undefined) { to.push(from[i]); } } return to; } ts.addRange = addRange; - function pushIfUnique(array, toAdd) { - if (contains(array, toAdd)) { + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { return false; } else { @@ -1814,9 +1924,9 @@ var ts; } } ts.pushIfUnique = pushIfUnique; - function appendIfUnique(array, toAdd) { + function appendIfUnique(array, toAdd, equalityComparer) { if (array) { - pushIfUnique(array, toAdd); + pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -1824,12 +1934,47 @@ var ts; } } ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function best(iter, isBetter) { + var x = iter.next(); + if (x.done) { + return undefined; + } + var best = x.value; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return best; + } + if (isBetter(value, best)) { + best = value; + } + } + } + ts.best = best; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; function stableSort(array, comparer) { - if (comparer === void 0) { comparer = compareValues; } - return array - .map(function (_, i) { return i; }) - .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) - .map(function (i) { return array[i]; }); + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); } ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { @@ -1856,10 +2001,20 @@ var ts; return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; function lastOrUndefined(array) { return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -1878,26 +2033,25 @@ var ts; return result; } ts.replaceElement = replaceElement; - function binarySearch(array, value, comparer, offset) { + function binarySearch(array, value, keySelector, keyComparer, offset) { if (!array || array.length === 0) { return -1; } var low = offset || 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; + var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); - var midValue = array[middle]; - if (comparer(midValue, value) === 0) { - return middle; - } - else if (comparer(midValue, value) > 0) { - high = middle - 1; - } - else { - low = middle + 1; + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1: + low = middle + 1; + break; + case 0: + return middle; + case 1: + high = middle - 1; + break; } } return ~low; @@ -1927,30 +2081,6 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial, start, count) { - if (array) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start > size - 1 ? size - 1 : start; - var end = count === undefined || pos - count < 0 ? 0 : pos - count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos--; - } - else { - result = initial; - } - while (pos >= end) { - result = f(result, array[pos], pos); - pos--; - } - return result; - } - } - return initial; - } - ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; function hasProperty(map, key) { return hasOwnProperty.call(map, key); @@ -2037,6 +2167,7 @@ var ts; } ts.assign = assign; function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (left === right) return true; if (!left || !right) @@ -2045,7 +2176,7 @@ var ts; if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + if (!equalityComparer(left[key], right[key])) return false; } } @@ -2060,13 +2191,22 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2132,6 +2272,14 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -2142,8 +2290,12 @@ var ts; Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } ts.cast = cast; - function noop() { } + function noop(_) { } ts.noop = noop; + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + function returnTrue() { return true; } + ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; function notImplemented() { @@ -2298,47 +2450,137 @@ var ts; return headChain; } ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + a < b ? -1 : + 1; + } function compareValues(a, b) { - if (a === b) - return 0; - if (a === undefined) - return -1; - if (b === undefined) - return 1; - return a < b ? -1 : 1; + return compareComparableValues(a, b); } ts.compareValues = compareValues; - function compareStrings(a, b, ignoreCase) { + function compareStringsCaseInsensitive(a, b) { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; - if (ignoreCase) { - if (ts.collator) { - var result = ts.localeCompareIsCorrect ? - ts.collator.compare(a, b) : - a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); - return result < 0 ? -1 : result > 0 ? 1 : 0; - } - a = a.toUpperCase(); - b = b.toUpperCase(); + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 : a > b ? 1 : 0; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { if (a === b) return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var value = comparer(a, b); + return value < 0 ? -1 : value > 0 ? 1 : 0; } - return a < b ? -1 : 1; - } - ts.compareStrings = compareStrings; - function compareStringsCaseInsensitive(a, b) { - return compareStrings(a, b, true); - } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function createIntlCollatorStringComparer(locale) { + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 : a > b ? 1 : 0; + } + } + function getStringComparerFactory() { + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + return createFallbackStringComparer; + } + function createStringComparer(locale) { + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } function compareDiagnostics(d1, d2) { - return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2348,14 +2590,14 @@ var ts; ts.compareDiagnostics = compareDiagnostics; function compareMessageText(text1, text2) { while (text1 && text2) { - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + var string1 = isString(text1) ? text1 : text1.messageText; + var string2 = isString(text2) ? text2 : text2.messageText; + var res = compareStringsCaseSensitive(string1, string2); if (res) { return res; } - text1 = typeof text1 === "string" ? undefined : text1.next; - text2 = typeof text2 === "string" ? undefined : text2.next; + text1 = isString(text1) ? undefined : text1.next; + text2 = isString(text2) ? undefined : text2.next; } if (!text1 && !text2) { return 0; @@ -2363,26 +2605,9 @@ var ts; return text1 ? 1 : -1; } function sortAndDeduplicateDiagnostics(diagnostics) { - return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + return sortAndDeduplicate(diagnostics, compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function deduplicateSortedDiagnostics(diagnostics) { - if (diagnostics.length < 2) { - return diagnostics; - } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; - if (!isDupe) { - newDiagnostics.push(currentDiagnostic); - previousDiagnostic = currentDiagnostic; - } - } - return newDiagnostics; - } - ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; function normalizeSlashes(path) { return path.replace(/\\/g, "/"); } @@ -2402,7 +2627,6 @@ var ts; if (path.charCodeAt(1) === 58) { if (path.charCodeAt(2) === 47) return 3; - return 2; } if (path.lastIndexOf("file:///", 0) === 0) { return "file:///".length; @@ -2461,7 +2685,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -2490,6 +2714,17 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2645,8 +2880,9 @@ var ts; var aComponents = getNormalizedPathComponents(a, currentDirectory); var bComponents = getNormalizedPathComponents(b, currentDirectory); var sharedLength = Math.min(aComponents.length, bComponents.length); + var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; for (var i = 0; i < sharedLength; i++) { - var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + var result = comparer(aComponents[i], bComponents[i]); if (result !== 0) { return result; } @@ -2668,9 +2904,9 @@ var ts; if (childComponents.length < parentComponents.length) { return false; } + var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { - var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); - if (result !== 0) { + if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } } @@ -2690,8 +2926,16 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -2833,13 +3077,13 @@ var ts; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); + var comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive; var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var regexFlag = useCaseSensitiveFileNames ? "" : "i"; var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -2847,7 +3091,6 @@ var ts; return flatten(results); function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - files = files.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -2865,8 +3108,8 @@ var ts; } } }; - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; + for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + var current = _b[_i]; _loop_1(current); } if (depth !== undefined) { @@ -2875,9 +3118,8 @@ var ts; return; } } - directories = directories.slice().sort(comparer); - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var current = directories_1[_b]; + for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && @@ -2897,7 +3139,7 @@ var ts; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); @@ -2950,7 +3192,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3035,6 +3277,11 @@ var ts; return (removeFileExtension(path) + newExtension); } ts.changeExtension = changeExtension; + function removeMinAndVersionNumbers(fileName) { + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; function Symbol(flags, name) { this.flags = flags; this.escapedName = name; @@ -3046,8 +3293,7 @@ var ts; this.checker = checker; } } - function Signature() { - } + function Signature() { } function Node(kind, pos, end) { this.id = 0; this.kind = kind; @@ -3269,6 +3515,14 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3279,6 +3533,168 @@ var ts; ts.and = and; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; + function createCachedDirectoryStructureHost(host) { + var cachedReadDirectoryResult = createMap(); + var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); + var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, + newLine: host.newLine, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + write: function (s) { return host.write(s); }, + writeFile: writeFile, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: createDirectory, + getCurrentDirectory: getCurrentDirectory, + getDirectories: getDirectories, + readDirectory: readDirectory, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache, + exit: function (code) { return host.exit(code); } + }; + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + } + else { + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (parentResult) { + var baseName = getBaseNameOfFileName(fileOrDirectory); + if (parentResult) { + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + } + } + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; })(ts || (ts = {})); var ts; (function (ts) { @@ -3310,12 +3726,13 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { + var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); var fileWatcherCallbacks = ts.createMultiMap(); @@ -3337,7 +3754,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3358,7 +3775,7 @@ var ts; fileWatcherCallbacks.remove(filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = typeof relativeFileName !== "string" + var fileName = !ts.isString(relativeFileName) ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); if ((eventName === "change" || eventName === "rename")) { @@ -3389,6 +3806,65 @@ var ts; } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { + return; + } + callback(fileName, eventKind); + } + } + function fsWatchDirectory(directoryName, callback, recursive) { + var options; + var watcher = !directoryExists(directoryName) ? + watchMissingDirectory() : + watchPresentDirectory(); + return { + close: function () { + watcher.close(); + } + }; + function watchPresentDirectory() { + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + var dirWatcher = _fs.watch(directoryName, options, callback); + dirWatcher.on("error", function () { + if (!directoryExists(directoryName)) { + watcher = watchMissingDirectory(); + callback("rename", ""); + } + }); + return dirWatcher; + } + function watchMissingDirectory() { + return fsWatchFile(directoryName, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { + watcher.close(); + watcher = watchPresentDirectory(); + callback("rename", ""); + } + }); + } + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -3414,7 +3890,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } var fd; try { @@ -3487,7 +3963,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -3505,43 +3980,15 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); - return { - close: function () { return _fs.unwatchFile(fileName, fileChanged); } - }; - } - function fileChanged(curr, prev) { - var isCurrZero = +curr.mtime === 0; - var isPrevZero = +prev.mtime === 0; - var created = !isCurrZero && isPrevZero; - var deleted = isCurrZero && !isPrevZero; - var eventKind = created - ? FileWatcherEventKind.Created - : deleted - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { - return; - } - callback(fileName, eventKind); + return fsWatchFile(fileName, callback, pollingInterval); } }, watchDirectory: function (directoryName, callback, recursive) { - var options; - if (!directoryExists(directoryName)) { - return noOpFileWatcher; - } - if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - return _fs.watch(directoryName, options, function (eventName, relativeFileName) { + return fsWatchDirectory(directoryName, function (eventName, relativeFileName) { if (eventName === "rename") { callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); } - }); + }, recursive); }, resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, @@ -3588,7 +4035,7 @@ var ts; return stat.size; } } - catch (e) { } + catch (_a) { } return 0; }, exit: function (exitCode) { @@ -3602,7 +4049,7 @@ var ts; try { require("source-map-support").install(); } - catch (e) { + catch (_a) { } }, setTimeout: setTimeout, @@ -3622,7 +4069,7 @@ var ts; }, writeFile: function (path, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } ChakraHost.writeFile(path, data); }, @@ -3644,7 +4091,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -3809,11 +4256,11 @@ var ts; An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), @@ -3894,6 +4341,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "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."), @@ -3913,6 +4361,13 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4114,7 +4569,7 @@ var ts; No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), - Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), @@ -4130,7 +4585,7 @@ var ts; await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), @@ -4159,14 +4614,16 @@ var ts; Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), - Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4240,6 +4697,11 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "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."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4263,16 +4725,16 @@ var ts; Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), @@ -4315,6 +4777,14 @@ var ts; Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4343,6 +4813,7 @@ var ts; File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -4356,7 +4827,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -4458,7 +4929,6 @@ var ts; Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), - The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), @@ -4514,6 +4984,8 @@ var ts; Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), 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."), @@ -4563,6 +5035,13 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4580,37 +5059,50 @@ var ts; super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), - Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), - Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), - Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), - Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), - Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), - Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), - Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), - Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), - Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), - Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), - Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), - Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), - Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), - Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), - Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), + Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), }; })(ts || (ts = {})); var ts; @@ -4658,7 +5150,7 @@ var ts; return; } var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { + if (!ts.isString(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); } @@ -4701,7 +5193,7 @@ var ts; return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; } var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -5030,8 +5522,8 @@ var ts; matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -5232,14 +5724,14 @@ var ts; var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; - return { packageJsonContent: packageJsonContent, packageId: packageId }; + return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } failedLookupLocations.push(packageJsonPath); - return { packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined }; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { @@ -5283,10 +5775,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var packageJsonContent; + var packageId; + var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); + if (packageInfo.found) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); + } + else { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + } + } var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); @@ -5298,6 +5800,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); } @@ -5306,7 +5809,7 @@ var ts; } function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); if (resolutionFromCache) { @@ -5340,23 +5843,30 @@ var ts; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); } } - return moduleName; + return packageName; } function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -5386,7 +5896,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -5422,19 +5932,6 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } - 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 || (ts = {})); var ts; (function (ts) { @@ -5474,6 +5971,7 @@ var ts; clear: function () { return str = ""; }, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; } @@ -5556,7 +6054,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 265) { + while (node && node.kind !== 269) { node = node.parent; } return node; @@ -5564,11 +6062,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 207: - case 235: - case 214: + case 208: + case 236: case 215: case 216: + case 217: return true; } return false; @@ -5644,7 +6142,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { + if (node.kind === 290 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -5678,15 +6176,13 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } function indexOfNode(nodeArray, node) { - return ts.binarySearch(nodeArray, node, compareNodePos); + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } ts.indexOfNode = indexOfNode; - function compareNodePos(_a, _b) { - var aPos = _a.pos; - var bPos = _b.pos; - return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; - } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -5721,7 +6217,7 @@ var ts; } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { - return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; function escapeLeadingUnderscores(identifier) { @@ -5743,14 +6239,18 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 226 && node.parent.kind === 260; + return node.kind === 227 && node.parent.kind === 264; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 233 && + return node && node.kind === 234 && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 9; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } @@ -5760,11 +6260,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node && node.kind === 233 && (!node.body); + return node && node.kind === 234 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 || - node.kind === 233 || + return node.kind === 269 || + node.kind === 234 || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -5777,36 +6277,36 @@ var ts; return false; } switch (node.parent.kind) { - case 265: + case 269: return ts.isExternalModule(node.parent); - case 234: + case 235: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 265: - case 235: - case 260: - case 233: - case 214: + case 269: + case 236: + case 264: + case 234: case 215: case 216: - case 152: - case 151: + case 217: case 153: + case 152: case 154: - case 228: - case 186: + case 155: + case 229: case 187: + case 188: return true; - case 207: + case 208: return parentNode && !ts.isFunctionLike(parentNode); } return false; @@ -5814,25 +6314,25 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 155: case 156: - case 150: case 157: - case 160: + case 151: + case 158: case 161: - case 273: - case 229: - case 199: + case 162: + case 277: case 230: + case 200: case 231: - case 282: - case 228: - case 151: + case 232: + case 287: + case 229: case 152: case 153: case 154: - case 186: + case 155: case 187: + case 188: return true; default: ts.assertTypeIsNever(node); @@ -5840,6 +6340,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 239: + case 238: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -5865,7 +6375,7 @@ var ts; case 9: case 8: return escapeLeadingUnderscores(name.text); - case 144: + case 145: if (isStringOrNumericLiteral(name.expression)) { return escapeLeadingUnderscores(name.expression.text); } @@ -5876,22 +6386,22 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71: - return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); - case 143: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 144: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179: + case 180: return entityNameToString(name.expression) + "." + entityNameToString(name.name); } } ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { @@ -5916,7 +6426,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207) { + if (node.body && node.body.kind === 208) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -5928,29 +6438,29 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 265: + case 269: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 226: - case 176: - case 229: - case 199: + case 227: + case 177: case 230: + case 200: + case 231: + case 234: case 233: - case 232: - case 264: - case 228: - case 186: - case 151: - case 153: + case 268: + case 229: + case 187: + case 152: case 154: - case 231: + case 155: + case 232: errorNode = node.name; break; - case 187: + case 188: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -5967,7 +6477,7 @@ var ts; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isConstEnumDeclaration(node) { - return node.kind === 232 && isConst(node); + return node.kind === 233 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -5980,15 +6490,15 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 181 && n.expression.kind === 97; + return n.kind === 182 && n.expression.kind === 97; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 181 && n.expression.kind === 91; + return n.kind === 182 && n.expression.kind === 91; } ts.isImportCall = isImportCall; function isPrologueDirective(node) { - return node.kind === 210 + return node.kind === 211 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; @@ -5997,11 +6507,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 || - node.kind === 145 || - node.kind === 186 || + var commentRanges = (node.kind === 147 || + node.kind === 146 || node.kind === 187 || - node.kind === 185) ? + node.kind === 188 || + node.kind === 186) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { @@ -6016,7 +6526,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (158 <= node.kind && node.kind <= 173) { + if (159 <= node.kind && node.kind <= 174) { return true; } switch (node.kind) { @@ -6029,56 +6539,56 @@ var ts; case 130: return true; case 105: - return node.parent.kind !== 190; - case 201: + return node.parent.kind !== 191; + case 202: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 71: - if (node.parent.kind === 143 && node.parent.right === node) { + if (node.parent.kind === 144 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 179 && node.parent.name === node) { + else if (node.parent.kind === 180 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 143: - case 179: + ts.Debug.assert(node.kind === 71 || node.kind === 144 || node.kind === 180, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 144: + case 180: case 99: var parent = node.parent; - if (parent.kind === 162) { + if (parent.kind === 163) { return false; } - if (158 <= parent.kind && parent.kind <= 173) { + if (159 <= parent.kind && parent.kind <= 174) { return true; } switch (parent.kind) { - case 201: + case 202: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 145: + case 146: return node === parent.constraint; + case 150: case 149: - case 148: - case 146: - case 226: + case 147: + case 227: return node === parent.type; - case 228: - case 186: + case 229: case 187: + case 188: + case 153: case 152: case 151: - case 150: - case 153: case 154: - return node === parent.type; case 155: + return node === parent.type; case 156: case 157: + case 158: return node === parent.type; - case 184: + case 185: return node === parent.type; - case 181: case 182: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; case 183: + return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + case 184: return false; } } @@ -6099,23 +6609,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219: + case 220: return visitor(node); - case 235: - case 207: - case 211: + case 236: + case 208: case 212: case 213: case 214: case 215: case 216: - case 220: + case 217: case 221: - case 257: - case 258: case 222: - case 224: - case 260: + case 261: + case 262: + case 223: + case 225: + case 264: return ts.forEachChild(node, traverse); } } @@ -6125,24 +6635,24 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 197: + case 198: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 232: - case 230: case 233: case 231: - case 229: - case 199: + case 234: + case 232: + case 230: + case 200: return; default: if (ts.isFunctionLike(node)) { var name = node.name; - if (name && name.kind === 144) { + if (name && name.kind === 145) { traverse(name.expression); return; } @@ -6155,10 +6665,10 @@ var ts; } ts.forEachYieldExpression = forEachYieldExpression; function getRestParameterElementType(node) { - if (node && node.kind === 164) { + if (node && node.kind === 165) { return node.elementType; } - else if (node && node.kind === 159) { + else if (node && node.kind === 160) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -6166,32 +6676,55 @@ var ts; } } ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 231: + case 230: + case 200: + case 164: + return node.members; + case 179: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; function isVariableLike(node) { if (node) { switch (node.kind) { - case 176: - case 264: - case 146: - case 261: + case 177: + case 268: + case 147: + case 265: + case 150: case 149: - case 148: - case 262: - case 226: + case 266: + case 227: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 228 + && node.parent.parent.kind === 209; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 228: - case 186: + case 155: + case 229: + case 187: return true; } return false; @@ -6202,7 +6735,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 222) { + if (node.statement.kind !== 223) { return node.statement; } node = node.statement; @@ -6210,17 +6743,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 && ts.isFunctionLike(node.parent); + return node && node.kind === 208 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 151 && node.parent.kind === 178; + return node && node.kind === 152 && node.parent.kind === 179; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 && - (node.parent.kind === 178 || - node.parent.kind === 199); + return node.kind === 152 && + (node.parent.kind === 179 || + node.parent.kind === 200); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -6233,7 +6766,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 261) { + if (property.kind === 265) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); } @@ -6255,39 +6788,39 @@ var ts; return undefined; } switch (node.kind) { - case 144: + case 145: if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148: + if (node.parent.kind === 147 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { node = node.parent; } break; - case 187: + case 188: if (!includeArrowFunctions) { continue; } - case 228: - case 186: - case 233: - case 149: - case 148: - case 151: + case 229: + case 187: + case 234: case 150: + case 149: case 152: + case 151: case 153: case 154: case 155: case 156: case 157: - case 232: - case 265: + case 158: + case 233: + case 269: return node; } } @@ -6297,9 +6830,9 @@ var ts; var container = getThisContainer(node, false); if (container) { switch (container.kind) { - case 152: - case 228: - case 186: + case 153: + case 229: + case 187: return container; } } @@ -6313,25 +6846,25 @@ var ts; return node; } switch (node.kind) { - case 144: + case 145: node = node.parent; break; - case 228: - case 186: + case 229: case 187: + case 188: if (!stopOnFunctions) { continue; } - case 149: - case 148: - case 151: case 150: + case 149: case 152: + case 151: case 153: case 154: + case 155: return node; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148: + if (node.parent.kind === 147 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { @@ -6343,14 +6876,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 || func.kind === 187) { + if (func.kind === 187 || func.kind === 188) { var prev = func; var parent = func.parent; - while (parent.kind === 185) { + while (parent.kind === 186) { prev = parent; parent = parent.parent; } - if (parent.kind === 181 && parent.expression === prev) { + if (parent.kind === 182 && parent.expression === prev) { return parent; } } @@ -6358,27 +6891,33 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 179 || kind === 180) + return (kind === 180 || kind === 181) && node.expression.kind === 97; } ts.isSuperProperty = isSuperProperty; + function isThisProperty(node) { + var kind = node.kind; + return (kind === 180 || kind === 181) + && node.expression.kind === 99; + } + ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 159: + case 160: return node.typeName; - case 201: + case 202: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71: - case 143: + case 144: return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 183) { + if (node.kind === 184) { return node.tag; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -6387,101 +6926,102 @@ var ts; return node.expression; } ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { + function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 229: + case 230: return true; - case 149: - return node.parent.kind === 229; - case 153: + case 150: + return parent.kind === 230; case 154: - case 151: + case 155: + case 152: return node.body !== undefined - && node.parent.kind === 229; - case 146: - return node.parent.body !== undefined - && (node.parent.kind === 152 - || node.parent.kind === 151 - || node.parent.kind === 154) - && node.parent.parent.kind === 229; + && parent.kind === 230; + case 147: + return parent.body !== undefined + && (parent.kind === 153 + || parent.kind === 152 + || parent.kind === 155) + && grandparent.kind === 230; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { + function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node); + && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { + function childIsDecorated(node, parent) { switch (node.kind) { - case 229: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151: - case 154: - return ts.forEach(node.parameters, nodeIsDecorated); + case 230: + return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 152: + case 155: + return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 251 || - parent.kind === 250 || - parent.kind === 252) { + if (parent.kind === 252 || + parent.kind === 251 || + parent.kind === 253) { return parent.tagName === node; } return false; } ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { + function isExpressionNode(node) { switch (node.kind) { case 97: case 95: case 101: case 86: case 12: - case 177: case 178: case 179: case 180: case 181: case 182: case 183: - case 202: case 184: case 203: case 185: + case 204: case 186: - case 199: case 187: - case 190: + case 200: case 188: + case 191: case 189: - case 192: + case 190: case 193: case 194: case 195: - case 198: case 196: + case 199: + case 197: case 13: - case 200: - case 249: + case 201: case 250: - case 197: - case 191: - case 204: + case 251: + case 254: + case 198: + case 192: + case 205: return true; - case 143: - while (node.parent.kind === 143) { + case 144: + while (node.parent.kind === 144) { node = node.parent; } - return node.parent.kind === 162 || isJSXTagName(node); + return node.parent.kind === 163 || isJSXTagName(node); case 71: - if (node.parent.kind === 162 || isJSXTagName(node)) { + if (node.parent.kind === 163 || isJSXTagName(node)) { return true; } case 8: @@ -6492,59 +7032,59 @@ var ts; return false; } } - ts.isPartOfExpression = isPartOfExpression; + ts.isExpressionNode = isExpressionNode; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 226: - case 146: + case 227: + case 147: + case 150: case 149: - case 148: - case 264: - case 261: - case 176: + case 268: + case 265: + case 177: return parent.initializer === node; - case 210: case 211: case 212: case 213: - case 219: + case 214: case 220: case 221: - case 257: - case 223: + case 222: + case 261: + case 224: return parent.expression === node; - case 214: + case 215: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 228) || forStatement.condition === node || forStatement.incrementor === node; - case 215: case 216: + case 217: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 228) || forInStatement.expression === node; - case 184: - case 202: + case 185: + case 203: return node === parent.expression; - case 205: + case 206: return node === parent.expression; - case 144: + case 145: return node === parent.expression; - case 147: - case 256: - case 255: - case 263: + case 148: + case 260: + case 259: + case 267: return true; - case 201: + case 202: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: - return isPartOfExpression(parent); + return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind === 248; + return node.kind === 238 && node.moduleReference.kind === 249; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -6553,7 +7093,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind !== 248; + return node.kind === 238 && node.moduleReference.kind !== 249; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -6568,8 +7108,16 @@ var ts; return node && !!(node.flags & 1048576); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 || node.typeArguments[0].kind === 133); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181) { + if (callExpression.kind !== 182) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -6587,10 +7135,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226) { + if (s.valueDeclaration && s.valueDeclaration.kind === 227) { var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); + return declaration.initializer && (declaration.initializer.kind === 187 || declaration.initializer.kind === 200); } return false; } @@ -6610,12 +7162,11 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { + function getSpecialPropertyAssignmentKind(expr) { + if (!isInJavaScriptFile(expr)) { return 0; } - var expr = expression; - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { + if (expr.operatorToken.kind !== 58 || expr.left.kind !== 180) { return 0; } var lhs = expr.left; @@ -6634,7 +7185,7 @@ var ts; else if (lhs.expression.kind === 99) { return 4; } - else if (lhs.expression.kind === 179) { + else if (lhs.expression.kind === 180) { var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; @@ -6649,36 +7200,42 @@ var ts; return 0; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isSpecialPropertyDeclaration(expr) { + return isInJavaScriptFile(expr) && + expr.parent && expr.parent.kind === 211 && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function getExternalModuleName(node) { - if (node.kind === 238) { + if (node.kind === 239) { return node.moduleSpecifier; } - if (node.kind === 237) { + if (node.kind === 238) { var reference = node.moduleReference; - if (reference.kind === 248) { + if (reference.kind === 249) { return reference.expression; } } - if (node.kind === 244) { + if (node.kind === 245) { return node.moduleSpecifier; } - if (node.kind === 233 && node.name.kind === 9) { + if (isModuleWithStringLiteralName(node)) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 237) { + if (node.kind === 238) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 241) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 238 + return node.kind === 239 && node.importClause && !!node.importClause.name; } @@ -6686,13 +7243,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 146: + case 147: + case 152: case 151: + case 266: + case 265: case 150: - case 262: - case 261: case 149: - case 148: return node.questionToken !== undefined; } } @@ -6700,7 +7257,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 273 && + return node.kind === 277 && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; @@ -6713,37 +7270,55 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 58 && + node.expression.right; + } + ts.getSourceOfAssignment = getSourceOfAssignment; + function getSingleInitializerOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0].initializer === child) && + node.declarationList.declarations[0].initializer; + } + ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; + function getSingleVariableOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0] === child) && + node.declarationList.declarations[0]; + } + ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; + function getNestedModuleDeclaration(node) { + return node.kind === 234 && + node.body && + node.body.kind === 234 && + node.body; + } + ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocCommentsAndTagsWorker(variableStatementNode); - } - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 && - parent.operatorToken.kind === 58 && - parent.parent.kind === 210; - if (isSourceOfAssignmentExpressionStatement) { + if (parent && (parent.kind === 265 || getNestedModuleDeclaration(parent))) { + getJSDocCommentsAndTagsWorker(parent); + } + if (parent && parent.parent && + (getSingleVariableOfVariableStatement(parent.parent, node) || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - var isModuleDeclaration = node.kind === 233 && - parent && parent.kind === 233; - var isPropertyAssignmentExpression = parent && parent.kind === 261; - if (isModuleDeclaration || isPropertyAssignmentExpression) { + if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatement(parent.parent.parent, node)) { + getJSDocCommentsAndTagsWorker(parent.parent.parent); + } + if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || + node.kind === 180 && node.parent && node.parent.kind === 211) { getJSDocCommentsAndTagsWorker(parent); } - if (node.kind === 146) { + if (node.kind === 147) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { @@ -6763,17 +7338,29 @@ var ts; return undefined; } var name = node.name.escapedText; - ts.Debug.assert(node.parent.kind === 275); - var func = node.parent.parent; - if (!ts.isFunctionLike(func)) { + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { return undefined; } - var parameter = ts.find(func.parameters, function (p) { - return p.name.kind === 71 && p.name.escapedText === name; - }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + var host = getJSDocHost(node); + var decl = getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatement(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getJSDocHost(node) { + ts.Debug.assert(node.parent.kind === 279); + return node.parent.parent; + } + ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { var name = node.name.escapedText; var typeParameters = node.parent.parent.parent.typeParameters; @@ -6781,27 +7368,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -6812,30 +7386,30 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 194: + case 195: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 ? 1 : 2 : 0; - case 192: case 193: + case 194: var unaryOperator = parent.operator; return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; - case 215: case 216: + case 217: return parent.initializer === node ? 1 : 0; - case 185: - case 177: - case 198: + case 186: + case 178: + case 199: node = parent; break; - case 262: + case 266: if (parent.name !== node) { return 0; } node = parent.parent; break; - case 261: + case 265: if (parent.name === node) { return 0; } @@ -6852,15 +7426,26 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 169); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 186); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function isDeleteTarget(node) { - if (node.kind !== 179 && node.kind !== 180) { + if (node.kind !== 180 && node.kind !== 181) { return false; } - node = node.parent; - while (node && node.kind === 185) { - node = node.parent; - } - return node && node.kind === 188; + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 189; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -6872,16 +7457,6 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { switch (name.kind) { case 71: @@ -6910,49 +7485,49 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 144 && + node.parent.kind === 145 && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { + case 150: case 149: - case 148: + case 152: case 151: - case 150: - case 153: case 154: - case 264: - case 261: - case 179: + case 155: + case 268: + case 265: + case 180: return parent.name === node; - case 143: + case 144: if (parent.right === node) { - while (parent.kind === 143) { + while (parent.kind === 144) { parent = parent.parent; } - return parent.kind === 162; + return parent.kind === 163; } return false; - case 176: - case 242: + case 177: + case 243: return parent.propertyName === node; - case 246: - case 253: + case 247: + case 257: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 237 || - node.kind === 236 || - node.kind === 239 && !!node.name || - node.kind === 240 || - node.kind === 242 || - node.kind === 246 || - node.kind === 243 && exportAssignmentIsAlias(node); + return node.kind === 238 || + node.kind === 237 || + node.kind === 240 && !!node.name || + node.kind === 241 || + node.kind === 243 || + node.kind === 247 || + node.kind === 244 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7036,9 +7611,22 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 72 <= token && token <= 142; + return 72 <= token && token <= 143; } ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 117 <= token && token <= 143; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; function isTrivia(token) { return 2 <= token && token <= 7; } @@ -7057,13 +7645,13 @@ var ts; } var flags = 0; switch (node.kind) { - case 228: - case 186: - case 151: + case 229: + case 187: + case 152: if (node.asteriskToken) { flags |= 1; } - case 187: + case 188: if (hasModifier(node, 256)) { flags |= 2; } @@ -7077,10 +7665,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 228: - case 186: + case 229: case 187: - case 151: + case 188: + case 152: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256); @@ -7100,7 +7688,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 144 && + return name.kind === 145 && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -7116,11 +7704,10 @@ var ts; if (name.kind === 9 || name.kind === 8) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 144) { + if (name.kind === 145) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.escapedText; - return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } else if (nameExpression.kind === 9 || nameExpression.kind === 8) { return escapeLeadingUnderscores(nameExpression.text); @@ -7132,7 +7719,7 @@ var ts; function getTextOfIdentifierOrLiteral(node) { if (node) { if (node.kind === 71) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } if (node.kind === 9 || node.kind === 8) { @@ -7169,11 +7756,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 146; + return root.kind === 147; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 176) { + while (node.kind === 177) { node = node.parent.parent; } return node; @@ -7181,15 +7768,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 152 - || kind === 186 - || kind === 228 + return kind === 153 || kind === 187 - || kind === 151 - || kind === 153 + || kind === 229 + || kind === 188 + || kind === 152 || kind === 154 - || kind === 233 - || kind === 265; + || kind === 155 + || kind === 234 + || kind === 269; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -7208,23 +7795,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 182: + case 183: return hasArguments ? 0 : 1; - case 192: - case 189: + case 193: case 190: - case 188: case 191: - case 195: - case 197: + case 189: + case 192: + case 196: + case 198: return 1; - case 194: + case 195: switch (operator) { case 40: case 58: @@ -7248,15 +7835,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 194) { + if (expression.kind === 195) { return expression.operatorToken.kind; } - else if (expression.kind === 192 || expression.kind === 193) { + else if (expression.kind === 193 || expression.kind === 194) { return expression.operator; } else { @@ -7274,36 +7861,37 @@ var ts; case 86: case 8: case 9: - case 177: case 178: - case 186: + case 179: case 187: - case 199: - case 249: + case 188: + case 200: case 250: + case 251: + case 254: case 12: case 13: - case 196: - case 185: - case 200: + case 197: + case 186: + case 201: return 19; - case 183: - case 179: + case 184: case 180: + case 181: return 18; - case 182: + case 183: return hasArguments ? 18 : 17; - case 181: + case 182: return 17; - case 193: + case 194: return 16; - case 192: - case 189: + case 193: case 190: - case 188: case 191: + case 189: + case 192: return 15; - case 194: + case 195: switch (operatorKind) { case 51: case 52: @@ -7361,13 +7949,13 @@ var ts; default: return -1; } - case 195: + case 196: return 4; - case 197: - return 2; case 198: + return 2; + case 199: return 1; - case 289: + case 293: return 0; default: return -1; @@ -7377,6 +7965,7 @@ var ts; function createDiagnosticCollection() { var nonFileDiagnostics = []; var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; var diagnosticsModified = false; var modificationCount = 0; return { @@ -7402,6 +7991,10 @@ var ts; } } else { + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); @@ -7410,6 +8003,7 @@ var ts; } function getGlobalDiagnostics() { sortAndDeduplicate(); + hasReadNonFileDiagnostics = true; return nonFileDiagnostics; } function getDiagnostics(fileName) { @@ -7473,8 +8067,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; + var ch = name.charCodeAt(0); + return (ch >= 97 && ch <= 122) || name.indexOf("-") > -1; } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -7657,7 +8251,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 152 && nodeIsPresent(member.body)) { + if (member.kind === 153 && nodeIsPresent(member.body)) { return member; } }); @@ -7702,10 +8296,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 153) { + if (accessor.kind === 154) { getAccessor = accessor; } - else if (accessor.kind === 154) { + else if (accessor.kind === 155) { setAccessor = accessor; } else { @@ -7714,7 +8308,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 153 || member.kind === 154) + if ((member.kind === 154 || member.kind === 155) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -7725,10 +8319,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 153 && !getAccessor) { + if (member.kind === 154 && !getAccessor) { getAccessor = member; } - if (member.kind === 154 && !setAccessor) { + if (member.kind === 155 && !setAccessor) { setAccessor = member; } } @@ -7743,37 +8337,37 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node) { + function getEffectiveTypeAnnotationNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node) { + function getEffectiveReturnTypeNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node) { + function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node) { + function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter); + return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -7932,6 +8526,14 @@ var ts; return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64); + } + ts.hasReadonlyModifier = hasReadonlyModifier; function getSelectedModifierFlags(node, flags) { return getModifierFlags(node) & flags; } @@ -7987,7 +8589,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 && + if (node.kind === 202 && node.parent.token === 85 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -8005,8 +8607,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, true)) { var kind = node.left.kind; - return kind === 178 - || kind === 177; + return kind === 179 + || kind === 178; } return false; } @@ -8016,7 +8618,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 + return node.kind === 202 && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 @@ -8026,21 +8628,21 @@ var ts; ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 || - node.kind === 179 && isEntityNameExpression(node.expression); + node.kind === 180 && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 && node.parent.right === node) || - (node.parent.kind === 179 && node.parent.name === node); + return (node.parent.kind === 144 && node.parent.right === node) || + (node.parent.kind === 180 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 178 && + return expression.kind === 179 && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 177 && + return expression.kind === 178 && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -8110,17 +8712,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options) { + function getNewLineCharacter(options, system) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; + return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -8256,8 +8855,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 232: case 233: + case 234: return parseNode === parseNode.parent.name; } } @@ -8298,25 +8897,6 @@ var ts; return 0; } ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; - function levenshtein(s1, s2) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - for (var i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (var i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (var j = 1; j < s2.length + 1; j++) { - current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - var tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; function skipAlias(symbol, checker) { return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; } @@ -8344,27 +8924,108 @@ var ts; if (!parent) return 0; switch (parent.kind) { + case 194: case 193: - case 192: var operator = parent.operator; return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; - case 194: + case 195: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; - case 179: + case 180: return parent.name !== node ? 0 : accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 210 ? 1 : 2; + return parent.parent && parent.parent.kind === 211 ? 1 : 2; + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function clearMap(map, onDeleteValue) { + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + 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); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128); } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 65536 ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 5: + case 6: return "lib.esnext.full.d.ts"; case 4: return "lib.es2017.full.d.ts"; @@ -8493,9 +9154,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 145) { + if (d && d.kind === 146) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 231) { return current; } } @@ -8503,7 +9164,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 153 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -8521,7 +9182,7 @@ var ts; } ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 || ts.isBindingPattern(node))) { + while (node && (node.kind === 177 || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -8529,14 +9190,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 226) { + if (node.kind === 227) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209) { flags |= ts.getModifierFlags(node); } return flags; @@ -8545,14 +9206,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 226) { + if (node.kind === 227) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209) { flags |= node.flags; } return flags; @@ -8571,6 +9232,7 @@ var ts; if (!trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, undefined, errors); } + ts.setUILocale(locale); function trySetLanguageAndTerritory(language, territory, errors) { var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); @@ -8634,6 +9296,14 @@ var ts; return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; } ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; function unescapeIdentifier(id) { return id; } @@ -8647,18 +9317,18 @@ var ts; return getDeclarationIdentifier(hostNode); } switch (hostNode.kind) { - case 208: + case 209: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 210: + case 211: var expr = hostNode.expression; switch (expr.kind) { - case 179: - return expr.name; case 180: + return expr.name; + case 181: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -8667,10 +9337,10 @@ var ts; return undefined; case 1: return undefined; - case 185: { + case 186: { return getDeclarationIdentifier(hostNode.expression); } - case 222: { + case 223: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -8692,27 +9362,37 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 71: + return declaration; + case 289: + case 284: { + var name = declaration.name; + if (name.kind === 144) { + return name.right; + } + break; + } + case 195: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + case 288: + return getNameOfJSDocTypedef(declaration); + case 244: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; function getJSDocParameterTags(param) { @@ -8724,27 +9404,27 @@ var ts; } ts.getJSDocParameterTags = getJSDocParameterTags; function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); + return !!getFirstJSDocTag(node, 284); } ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); + return getFirstJSDocTag(node, 282); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); + return getFirstJSDocTag(node, 283); } ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); + return getFirstJSDocTag(node, 285); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); + return getFirstJSDocTag(node, 287); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 281); + var tag = getFirstJSDocTag(node, 286); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -8752,8 +9432,8 @@ var ts; } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { + var tag = getFirstJSDocTag(node, 286); + if (!tag && node.kind === 147) { var paramTags = getJSDocParameterTags(node); if (paramTags) { tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); @@ -8779,6 +9459,11 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -8818,584 +9503,600 @@ var ts; } ts.isIdentifier = isIdentifier; function isQualifiedName(node) { - return node.kind === 143; + return node.kind === 144; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 144; + return node.kind === 145; } ts.isComputedPropertyName = isComputedPropertyName; function isTypeParameterDeclaration(node) { - return node.kind === 145; + return node.kind === 146; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 146; + return node.kind === 147; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 147; + return node.kind === 148; } ts.isDecorator = isDecorator; function isPropertySignature(node) { - return node.kind === 148; + return node.kind === 149; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 149; + return node.kind === 150; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 150; + return node.kind === 151; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 151; + return node.kind === 152; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 152; + return node.kind === 153; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 153; + return node.kind === 154; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 154; + return node.kind === 155; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 155; + return node.kind === 156; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 156; + return node.kind === 157; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 157; + return node.kind === 158; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isTypePredicateNode(node) { - return node.kind === 158; + return node.kind === 159; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 159; + return node.kind === 160; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 160; + return node.kind === 161; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 161; + return node.kind === 162; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 162; + return node.kind === 163; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 163; + return node.kind === 164; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 164; + return node.kind === 165; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 165; + return node.kind === 166; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 166; + return node.kind === 167; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 167; + return node.kind === 168; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 168; + return node.kind === 169; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 169; + return node.kind === 170; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 170; + return node.kind === 171; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 171; + return node.kind === 172; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 172; + return node.kind === 173; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 173; + return node.kind === 174; } ts.isLiteralTypeNode = isLiteralTypeNode; function isObjectBindingPattern(node) { - return node.kind === 174; + return node.kind === 175; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 175; + return node.kind === 176; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 176; + return node.kind === 177; } ts.isBindingElement = isBindingElement; function isArrayLiteralExpression(node) { - return node.kind === 177; + return node.kind === 178; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 178; + return node.kind === 179; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 179; + return node.kind === 180; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 180; + return node.kind === 181; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 181; + return node.kind === 182; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 182; + return node.kind === 183; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 183; + return node.kind === 184; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 184; + return node.kind === 185; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 185; + return node.kind === 186; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 292) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 186; + return node.kind === 187; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 187; + return node.kind === 188; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 188; + return node.kind === 189; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 191; + return node.kind === 192; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 190; + return node.kind === 191; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 191; + return node.kind === 192; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 192; + return node.kind === 193; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 193; + return node.kind === 194; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 194; + return node.kind === 195; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 195; + return node.kind === 196; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 196; + return node.kind === 197; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 197; + return node.kind === 198; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 198; + return node.kind === 199; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 199; + return node.kind === 200; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 200; + return node.kind === 201; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 201; + return node.kind === 202; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 202; + return node.kind === 203; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 203; + return node.kind === 204; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 204; + return node.kind === 205; } ts.isMetaProperty = isMetaProperty; function isTemplateSpan(node) { - return node.kind === 205; + return node.kind === 206; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 206; + return node.kind === 207; } ts.isSemicolonClassElement = isSemicolonClassElement; function isBlock(node) { - return node.kind === 207; + return node.kind === 208; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 208; + return node.kind === 209; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 209; + return node.kind === 210; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 210; + return node.kind === 211; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 211; + return node.kind === 212; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 212; + return node.kind === 213; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 213; + return node.kind === 214; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 214; + return node.kind === 215; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 215; + return node.kind === 216; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 216; + return node.kind === 217; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 217; + return node.kind === 218; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 218; + return node.kind === 219; } ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 219 || node.kind === 218; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 219; + return node.kind === 220; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 220; + return node.kind === 221; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 221; + return node.kind === 222; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 222; + return node.kind === 223; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 223; + return node.kind === 224; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 224; + return node.kind === 225; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 225; + return node.kind === 226; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 226; + return node.kind === 227; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 227; + return node.kind === 228; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 228; + return node.kind === 229; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 229; + return node.kind === 230; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 230; + return node.kind === 231; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 231; + return node.kind === 232; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 232; + return node.kind === 233; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 233; + return node.kind === 234; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 234; + return node.kind === 235; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 235; + return node.kind === 236; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 236; + return node.kind === 237; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 237; + return node.kind === 238; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 238; + return node.kind === 239; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 239; + return node.kind === 240; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 240; + return node.kind === 241; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 241; + return node.kind === 242; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 242; + return node.kind === 243; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 243; + return node.kind === 244; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 244; + return node.kind === 245; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 245; + return node.kind === 246; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 246; + return node.kind === 247; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 247; + return node.kind === 248; } ts.isMissingDeclaration = isMissingDeclaration; function isExternalModuleReference(node) { - return node.kind === 248; + return node.kind === 249; } ts.isExternalModuleReference = isExternalModuleReference; function isJsxElement(node) { - return node.kind === 249; + return node.kind === 250; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 250; + return node.kind === 251; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 251; + return node.kind === 252; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 252; + return node.kind === 253; } ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 254; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 255; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 256; + } + ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 253; + return node.kind === 257; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 254; + return node.kind === 258; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 255; + return node.kind === 259; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 256; + return node.kind === 260; } ts.isJsxExpression = isJsxExpression; function isCaseClause(node) { - return node.kind === 257; + return node.kind === 261; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 258; + return node.kind === 262; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 259; + return node.kind === 263; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 260; + return node.kind === 264; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 261; + return node.kind === 265; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 262; + return node.kind === 266; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 263; + return node.kind === 267; } ts.isSpreadAssignment = isSpreadAssignment; function isEnumMember(node) { - return node.kind === 264; + return node.kind === 268; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 265; + return node.kind === 269; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 266; + return node.kind === 270; } ts.isBundle = isBundle; function isJSDocTypeExpression(node) { - return node.kind === 267; + return node.kind === 271; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 268; + return node.kind === 272; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 269; + return node.kind === 273; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 270; + return node.kind === 274; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 271; + return node.kind === 275; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 272; + return node.kind === 276; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 273; + return node.kind === 277; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 274; + return node.kind === 278; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 275; + return node.kind === 279; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 277; + return node.kind === 282; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocParameterTag(node) { - return node.kind === 279; + return node.kind === 284; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 280; + return node.kind === 285; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 281; + return node.kind === 286; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 282; + return node.kind === 287; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 283; + return node.kind === 288; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 284; + return node.kind === 289; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 284 || node.kind === 279; + return node.kind === 289 || node.kind === 284; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 285; + return node.kind === 280; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 286; + return n.kind === 290; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -9403,11 +10104,11 @@ var ts; } ts.isNode = isNode; function isNodeKind(kind) { - return kind >= 143; + return kind >= 144; } ts.isNodeKind = isNodeKind; function isToken(n) { - return n.kind >= 0 && n.kind <= 142; + return n.kind >= 0 && n.kind <= 143; } ts.isToken = isToken; function isNodeArray(array) { @@ -9433,16 +10134,7 @@ var ts; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isStringTextContainingNode(node) { - switch (node.kind) { - case 9: - case 14: - case 15: - case 16: - case 13: - return true; - default: - return false; - } + return node.kind === 9 || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { @@ -9473,7 +10165,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 143 + return kind === 144 || kind === 71; } ts.isEntityName = isEntityName; @@ -9482,14 +10174,14 @@ var ts; return kind === 71 || kind === 9 || kind === 8 - || kind === 144; + || kind === 145; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 - || kind === 174 - || kind === 175; + || kind === 175 + || kind === 176; } ts.isBindingName = isBindingName; function isFunctionLike(node) { @@ -9502,13 +10194,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 228: - case 151: + case 229: case 152: case 153: case 154: - case 186: + case 155: case 187: + case 188: return true; default: return false; @@ -9516,13 +10208,13 @@ var ts; } function isFunctionLikeKind(kind) { switch (kind) { - case 150: - case 155: + case 151: case 156: case 157: - case 160: - case 273: + case 158: case 161: + case 277: + case 162: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -9535,47 +10227,47 @@ var ts; ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 + return kind === 153 + || kind === 150 + || kind === 152 || kind === 154 - || kind === 157 - || kind === 206 - || kind === 247; + || kind === 155 + || kind === 158 + || kind === 207 + || kind === 248; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); + return node && (node.kind === 230 || node.kind === 200); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); + return node && (node.kind === 154 || node.kind === 155); } ts.isAccessor = isAccessor; function isTypeElement(node) { var kind = node.kind; - return kind === 156 - || kind === 155 - || kind === 148 - || kind === 150 - || kind === 157 - || kind === 247; + return kind === 157 + || kind === 156 + || kind === 149 + || kind === 151 + || kind === 158 + || kind === 248; } ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 261 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 + return kind === 265 + || kind === 266 + || kind === 267 + || kind === 152 || kind === 154 - || kind === 247; + || kind === 155 + || kind === 248; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) + return (kind >= 159 && kind <= 174) || kind === 119 || kind === 133 || kind === 134 @@ -9587,7 +10279,14 @@ var ts; || kind === 139 || kind === 95 || kind === 130 - || kind === 201; + || kind === 202 + || kind === 272 + || kind === 273 + || kind === 274 + || kind === 275 + || kind === 276 + || kind === 277 + || kind === 278; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -9595,8 +10294,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 160: case 161: + case 162: return true; } return false; @@ -9605,29 +10304,29 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 175 - || kind === 174; + return kind === 176 + || kind === 175; } return false; } ts.isBindingPattern = isBindingPattern; function isAssignmentPattern(node) { var kind = node.kind; - return kind === 177 - || kind === 178; + return kind === 178 + || kind === 179; } ts.isAssignmentPattern = isAssignmentPattern; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 176 - || kind === 200; + return kind === 177 + || kind === 201; } ts.isArrayBindingElement = isArrayBindingElement; function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 226: - case 146: - case 176: + case 227: + case 147: + case 177: return true; } return false; @@ -9640,8 +10339,8 @@ var ts; ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 174: - case 178: + case 175: + case 179: return true; } return false; @@ -9649,8 +10348,8 @@ var ts; ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: + case 176: + case 178: return true; } return false; @@ -9658,18 +10357,18 @@ var ts; ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 179 - || kind === 143; + return kind === 180 + || kind === 144; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { + case 252: case 251: - case 250: - case 181: case 182: case 183: - case 147: + case 184: + case 148: return true; default: return false; @@ -9677,12 +10376,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 181 || node.kind === 182; + return node.kind === 182 || node.kind === 183; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 196 + return kind === 197 || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; @@ -9692,31 +10391,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 179: case 180: - case 182: case 181: - case 249: - case 250: case 183: - case 177: - case 185: + case 182: + case 250: + case 251: + case 254: + case 184: case 178: - case 199: case 186: + case 179: + case 200: + case 187: case 71: case 12: case 8: case 9: case 13: - case 196: + case 197: case 86: case 95: case 99: case 101: case 97: - case 203: case 204: + case 205: case 91: return true; default: @@ -9729,13 +10429,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 192: case 193: - case 188: + case 194: case 189: case 190: case 191: - case 184: + case 192: + case 185: return true; default: return isLeftHandSideExpressionKind(kind); @@ -9743,9 +10443,9 @@ var ts; } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 193: + case 194: return true; - case 192: + case 193: return expr.operator === 43 || expr.operator === 44; default: @@ -9759,15 +10459,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 195: - case 197: - case 187: - case 194: + case 196: case 198: - case 202: - case 200: - case 289: - case 288: + case 188: + case 195: + case 199: + case 203: + case 201: + case 293: + case 292: return true; default: return isUnaryExpressionKind(kind); @@ -9775,16 +10475,16 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 184 - || kind === 202; + return kind === 185 + || kind === 203; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 292; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 291; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -9794,20 +10494,20 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 214: case 215: case 216: - case 212: + case 217: case 213: + case 214: return true; - case 222: + case 223: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isForInOrOfStatement(node) { - return node.kind === 215 || node.kind === 216; + return node.kind === 216 || node.kind === 217; } ts.isForInOrOfStatement = isForInOrOfStatement; function isConciseBody(node) { @@ -9826,106 +10526,106 @@ var ts; ts.isForInitializer = isForInitializer; function isModuleBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233 + return kind === 235 + || kind === 234 || kind === 71; } ts.isModuleBody = isModuleBody; function isNamespaceBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233; + return kind === 235 + || kind === 234; } ts.isNamespaceBody = isNamespaceBody; function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 - || kind === 233; + || kind === 234; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 241 - || kind === 240; + return kind === 242 + || kind === 241; } ts.isNamedImportBindings = isNamedImportBindings; function isModuleOrEnumDeclaration(node) { - return node.kind === 233 || node.kind === 232; + return node.kind === 234 || node.kind === 233; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 + return kind === 188 + || kind === 177 + || kind === 230 + || kind === 200 + || kind === 153 + || kind === 233 + || kind === 268 + || kind === 247 || kind === 229 - || kind === 199 + || kind === 187 + || kind === 154 + || kind === 240 + || kind === 238 + || kind === 243 + || kind === 231 + || kind === 257 || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 || kind === 151 + || kind === 234 + || kind === 237 + || kind === 241 + || kind === 147 + || kind === 265 || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 283; + || kind === 155 + || kind === 266 + || kind === 232 + || kind === 146 + || kind === 227 + || kind === 288; } function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 + return kind === 229 + || kind === 248 || kind === 230 || kind === 231 || kind === 232 || kind === 233 + || kind === 234 + || kind === 239 || kind === 238 - || kind === 237 + || kind === 245 || kind === 244 - || kind === 243 - || kind === 236; + || kind === 237; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 + return kind === 219 + || kind === 218 + || kind === 226 + || kind === 213 + || kind === 211 + || kind === 210 + || kind === 216 || kind === 217 - || kind === 225 + || kind === 215 || kind === 212 - || kind === 210 + || kind === 223 + || kind === 220 + || kind === 222 + || kind === 224 + || kind === 225 || kind === 209 - || kind === 215 - || kind === 216 || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 287 || kind === 291 - || kind === 290; + || kind === 295 + || kind === 294; } function isDeclaration(node) { - if (node.kind === 145) { - return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + if (node.kind === 146) { + return node.parent.kind !== 287 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -9946,10 +10646,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 207) + if (node.kind !== 208) return false; if (node.parent !== undefined) { - if (node.parent.kind === 224 || node.parent.kind === 260) { + if (node.parent.kind === 225 || node.parent.kind === 264) { return false; } } @@ -9957,8 +10657,8 @@ var ts; } function isModuleReference(node) { var kind = node.kind; - return kind === 248 - || kind === 143 + return kind === 249 + || kind === 144 || kind === 71; } ts.isModuleReference = isModuleReference; @@ -9966,53 +10666,62 @@ var ts; var kind = node.kind; return kind === 99 || kind === 71 - || kind === 179; + || kind === 180; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; + return kind === 250 + || kind === 260 + || kind === 251 + || kind === 10 + || kind === 254; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 253 - || kind === 255; + return kind === 257 + || kind === 259; } ts.isJsxAttributeLike = isJsxAttributeLike; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 - || kind === 256; + || kind === 260; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 251 - || kind === 250; + return kind === 252 + || kind === 251; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 257 - || kind === 258; + return kind === 261 + || kind === 262; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 285; + return node.kind >= 271 && node.kind <= 289; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 275 || isJSDocTag(node); + return node.kind === 279 || isJSDocTag(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 276 && node.kind <= 285; + return node.kind >= 281 && node.kind <= 289; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 155; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 154; + } + ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } @@ -10024,6 +10733,10 @@ var ts; return token >= 71; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 29 || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; var textToToken = ts.createMapFromTemplate({ "abstract": 117, "any": 119, @@ -10048,7 +10761,7 @@ var ts; "false": 86, "finally": 87, "for": 88, - "from": 140, + "from": 141, "function": 89, "get": 125, "if": 90, @@ -10073,7 +10786,7 @@ var ts; "public": 114, "readonly": 131, "require": 132, - "global": 141, + "global": 142, "return": 96, "set": 135, "static": 115, @@ -10088,6 +10801,7 @@ var ts; "type": 138, "typeof": 103, "undefined": 139, + "unique": 140, "var": 104, "void": 105, "while": 106, @@ -10095,7 +10809,7 @@ var ts; "yield": 116, "async": 120, "await": 121, - "of": 142, + "of": 143, "{": 17, "}": 18, "(": 19, @@ -10253,7 +10967,7 @@ var ts; } ts.getLineStarts = getLineStarts; function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position); + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); if (lineNumber < 0) { lineNumber = ~lineNumber - 1; ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); @@ -10608,10 +11322,7 @@ var ts; var tokenPos; var token; var tokenValue; - var precedingLineBreak; - var hasExtendedUnicodeEscape; - var tokenIsUnterminated; - var numericLiteralFlags; + var tokenFlags; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -10620,12 +11331,12 @@ var ts; getTokenPos: function () { return tokenPos; }, getTokenText: function () { return text.substring(tokenPos, pos); }, getTokenValue: function () { return tokenValue; }, - hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, - hasPrecedingLineBreak: function () { return precedingLineBreak; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1) !== 0; }, isIdentifier: function () { return token === 71 || token > 107; }, isReservedWord: function () { return token >= 72 && token <= 107; }, - isUnterminated: function () { return tokenIsUnterminated; }, - getNumericLiteralFlags: function () { return numericLiteralFlags; }, + isUnterminated: function () { return (tokenFlags & 4) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, @@ -10662,7 +11373,7 @@ var ts; var end = pos; if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { pos++; - numericLiteralFlags = 2; + tokenFlags |= 16; if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; if (isDigit(text.charCodeAt(pos))) { @@ -10715,8 +11426,8 @@ var ts; } return value; } - function scanString(allowEscapes) { - if (allowEscapes === void 0) { allowEscapes = true; } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -10724,7 +11435,7 @@ var ts; while (true) { if (pos >= end) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -10734,15 +11445,15 @@ var ts; pos++; break; } - if (ch === 92 && allowEscapes) { + if (ch === 92 && !jsxAttributeString) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; continue; } - if (isLineBreak(ch)) { + if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -10759,7 +11470,7 @@ var ts; while (true) { if (pos >= end) { contents += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_template_literal); resultingToken = startedWithBacktick ? 13 : 16; break; @@ -10828,7 +11539,7 @@ var ts; return "\""; case 117: if (pos < end && text.charCodeAt(pos) === 123) { - hasExtendedUnicodeEscape = true; + tokenFlags |= 8; pos++; return scanExtendedUnicodeEscape(); } @@ -10962,10 +11673,7 @@ var ts; } function scan() { startPos = pos; - hasExtendedUnicodeEscape = false; - precedingLineBreak = false; - tokenIsUnterminated = false; - numericLiteralFlags = 0; + tokenFlags = 0; while (true) { tokenPos = pos; if (pos >= end) { @@ -10984,7 +11692,7 @@ var ts; switch (ch) { case 10: case 13: - precedingLineBreak = true; + tokenFlags |= 1; if (skipTrivia) { pos++; continue; @@ -11109,6 +11817,9 @@ var ts; } if (text.charCodeAt(pos + 1) === 42) { pos += 2; + if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) !== 47) { + tokenFlags |= 2; + } var commentClosed = false; while (pos < end) { var ch_1 = text.charCodeAt(pos); @@ -11118,7 +11829,7 @@ var ts; break; } if (isLineBreak(ch_1)) { - precedingLineBreak = true; + tokenFlags |= 1; } pos++; } @@ -11129,7 +11840,9 @@ var ts; continue; } else { - tokenIsUnterminated = !commentClosed; + if (!commentClosed) { + tokenFlags |= 4; + } return token = 3; } } @@ -11147,7 +11860,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 8; + tokenFlags |= 64; return token = 8; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) { @@ -11158,7 +11871,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 16; + tokenFlags |= 128; return token = 8; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) { @@ -11169,12 +11882,12 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 32; + tokenFlags |= 256; return token = 8; } if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); - numericLiteralFlags = 4; + tokenFlags |= 32; return token = 8; } case 49: @@ -11324,7 +12037,7 @@ var ts; continue; } else if (isLineBreak(ch)) { - precedingLineBreak = true; + tokenFlags |= 1; pos++; continue; } @@ -11363,13 +12076,13 @@ var ts; var inCharacterClass = false; while (true) { if (p >= end) { - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } var ch = text.charCodeAt(p); if (isLineBreak(ch)) { - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } @@ -11471,7 +12184,7 @@ var ts; switch (text.charCodeAt(pos)) { case 34: case 39: - tokenValue = scanString(false); + tokenValue = scanString(true); return token = 9; default: return scan(); @@ -11515,6 +12228,12 @@ var ts; case 93: pos++; return token = 22; + case 60: + pos++; + return token = 27; + case 62: + pos++; + return token = 29; case 61: pos++; return token = 58; @@ -11523,13 +12242,24 @@ var ts; return token = 26; case 46: pos++; + if (text.substr(tokenPos, pos + 2) === "...") { + pos += 2; + return token = 24; + } return token = 23; + case 33: + pos++; + return token = 51; + case 63: + pos++; + return token = 55; } - if (isIdentifierStart(ch, 5)) { + if (isIdentifierStart(ch, 6)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } + tokenValue = text.substring(tokenPos, pos); return token = 71; } else { @@ -11542,7 +12272,7 @@ var ts; var saveTokenPos = tokenPos; var saveToken = token; var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; + var saveTokenFlags = tokenFlags; var result = callback(); if (!result || isLookahead) { pos = savePos; @@ -11550,7 +12280,7 @@ var ts; tokenPos = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; - precedingLineBreak = savePrecedingLineBreak; + tokenFlags = saveTokenFlags; } return result; } @@ -11560,10 +12290,8 @@ var ts; var saveStartPos = startPos; var saveTokenPos = tokenPos; var saveToken = token; - var savePrecedingLineBreak = precedingLineBreak; var saveTokenValue = tokenValue; - var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - var saveTokenIsUnterminated = tokenIsUnterminated; + var saveTokenFlags = tokenFlags; setText(text, start, length); var result = callback(); end = saveEnd; @@ -11571,10 +12299,8 @@ var ts; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; - precedingLineBreak = savePrecedingLineBreak; tokenValue = saveTokenValue; - hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; - tokenIsUnterminated = saveTokenIsUnterminated; + tokenFlags = saveTokenFlags; return result; } function lookAhead(callback) { @@ -11606,10 +12332,8 @@ var ts; startPos = textPos; tokenPos = textPos; token = 0; - precedingLineBreak = false; tokenValue = undefined; - hasExtendedUnicodeEscape = false; - tokenIsUnterminated = false; + tokenFlags = 0; } } ts.createScanner = createScanner; @@ -11631,7 +12355,7 @@ var ts; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 265) { + if (kind === 269) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71) { @@ -11663,59 +12387,60 @@ var ts; } } function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 142) { + if (!node || node.kind <= 143) { return; } switch (node.kind) { - case 143: + case 144: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 145: + case 146: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 262: + case 266: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 263: + case 267: return visitNode(cbNode, node.expression); - case 146: + case 147: + case 150: case 149: - case 148: - case 261: - case 226: - case 176: + case 265: + case 227: + case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 160: case 161: - case 155: + case 162: case 156: case 157: + case 158: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: + case 229: + case 188: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -11726,287 +12451,291 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 159: + case 160: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 158: + case 159: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 162: - return visitNode(cbNode, node.exprName); case 163: - return visitNodes(cbNode, cbNodes, node.members); + return visitNode(cbNode, node.exprName); case 164: - return visitNode(cbNode, node.elementType); + return visitNodes(cbNode, cbNodes, node.members); case 165: - return visitNodes(cbNode, cbNodes, node.elementTypes); + return visitNode(cbNode, node.elementType); case 166: + return visitNodes(cbNode, cbNodes, node.elementTypes); case 167: - return visitNodes(cbNode, cbNodes, node.types); case 168: - case 170: - return visitNode(cbNode, node.type); + return visitNodes(cbNode, cbNodes, node.types); + case 169: case 171: + return visitNode(cbNode, node.type); + case 172: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 172: + case 173: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 173: - return visitNode(cbNode, node.literal); case 174: + return visitNode(cbNode, node.literal); case 175: - return visitNodes(cbNode, cbNodes, node.elements); - case 177: + case 176: return visitNodes(cbNode, cbNodes, node.elements); case 178: - return visitNodes(cbNode, cbNodes, node.properties); + return visitNodes(cbNode, cbNodes, node.elements); case 179: + return visitNodes(cbNode, cbNodes, node.properties); + case 180: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 180: + case 181: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 181: case 182: + case 183: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 183: + case 184: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 184: + case 185: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.expression); - case 188: + case 186: return visitNode(cbNode, node.expression); case 189: return visitNode(cbNode, node.expression); case 190: return visitNode(cbNode, node.expression); - case 192: - return visitNode(cbNode, node.operand); - case 197: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 191: return visitNode(cbNode, node.expression); case 193: return visitNode(cbNode, node.operand); + case 198: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.expression); case 194: + return visitNode(cbNode, node.operand); + case 195: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 202: + case 203: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 203: - return visitNode(cbNode, node.expression); case 204: + return visitNode(cbNode, node.expression); + case 205: return visitNode(cbNode, node.name); - case 195: + case 196: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 198: + case 199: return visitNode(cbNode, node.expression); - case 207: - case 234: + case 208: + case 235: return visitNodes(cbNode, cbNodes, node.statements); - case 265: + case 269: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 208: + case 209: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 227: + case 228: return visitNodes(cbNode, cbNodes, node.declarations); - case 210: - return visitNode(cbNode, node.expression); case 211: + return visitNode(cbNode, node.expression); + case 212: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 212: + case 213: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 213: + case 214: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 214: + case 215: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 215: + case 216: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 216: + case 217: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 217: case 218: - return visitNode(cbNode, node.label); case 219: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.label); case 220: + return visitNode(cbNode, node.expression); + case 221: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221: + case 222: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 235: + case 236: return visitNodes(cbNode, cbNodes, node.clauses); - case 257: + case 261: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 258: + case 262: return visitNodes(cbNode, cbNodes, node.statements); - case 222: + case 223: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 223: - return visitNode(cbNode, node.expression); case 224: + return visitNode(cbNode, node.expression); + case 225: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 260: + case 264: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 147: + case 148: return visitNode(cbNode, node.expression); - case 229: - case 199: + case 230: + case 200: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 230: + case 231: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 231: + case 232: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 232: + case 233: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 264: + case 268: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 233: + case 234: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 237: + case 238: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 238: + case 239: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 239: + case 240: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 236: - return visitNode(cbNode, node.name); - case 240: + case 237: return visitNode(cbNode, node.name); case 241: - case 245: + return visitNode(cbNode, node.name); + case 242: + case 246: return visitNodes(cbNode, cbNodes, node.elements); - case 244: + case 245: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: + case 243: + case 247: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 243: + case 244: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 196: + case 197: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 205: + case 206: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: + case 145: return visitNode(cbNode, node.expression); - case 259: + case 263: return visitNodes(cbNode, cbNodes, node.types); - case 201: + case 202: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 248: + case 249: return visitNode(cbNode, node.expression); - case 247: + case 248: return visitNodes(cbNode, cbNodes, node.decorators); - case 289: + case 293: return visitNodes(cbNode, cbNodes, node.elements); - case 249: + case 250: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 250: + case 254: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); case 251: + case 252: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.attributes); - case 254: + case 258: return visitNodes(cbNode, cbNodes, node.properties); - case 253: + case 257: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 255: + case 259: return visitNode(cbNode, node.expression); - case 256: + case 260: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 252: + case 253: return visitNode(cbNode, node.tagName); - case 267: - return visitNode(cbNode, node.type); case 271: return visitNode(cbNode, node.type); - case 270: + case 275: return visitNode(cbNode, node.type); - case 272: + case 274: return visitNode(cbNode, node.type); - case 273: + case 276: + return visitNode(cbNode, node.type); + case 277: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 274: + case 278: return visitNode(cbNode, node.type); - case 275: - return visitNodes(cbNode, cbNodes, node.tags); case 279: + return visitNodes(cbNode, cbNodes, node.tags); case 284: + case 289: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -12015,17 +12744,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 280: + case 285: return visitNode(cbNode, node.typeExpression); - case 281: - return visitNode(cbNode, node.typeExpression); - case 277: + case 286: return visitNode(cbNode, node.typeExpression); case 282: + return visitNode(cbNode, node.class); + case 287: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 283: + case 288: if (node.typeExpression && - node.typeExpression.kind === 267) { + node.typeExpression.kind === 271) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -12033,7 +12762,7 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 285: + case 280: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -12041,7 +12770,7 @@ var ts; } } return; - case 288: + case 292: return visitNode(cbNode, node.expression); } } @@ -12087,7 +12816,7 @@ var ts; ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; var Parser; (function (Parser) { - var scanner = ts.createScanner(5, true); + var scanner = ts.createScanner(6, true); var disallowInAndDecoratorContext = 2048 | 8192; var NodeConstructor; var TokenConstructor; @@ -12123,7 +12852,7 @@ var ts; Parser.parseIsolatedEntityName = parseIsolatedEntityName; function parseJsonText(fileName, sourceText) { initializeState(sourceText, 2, undefined, 6); - sourceFile = createSourceFile(fileName, 2, 6); + sourceFile = createSourceFile(fileName, 2, 6, false); var result = sourceFile; nextToken(); if (token() === 1) { @@ -12157,7 +12886,16 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + switch (scriptKind) { + case 1: + case 2: + case 6: + contextFlags = 65536; + break; + default: + contextFlags = 0; + break; + } parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -12174,7 +12912,11 @@ var ts; sourceText = undefined; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 2097152; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; nextToken(); processReferenceComments(sourceFile); @@ -12197,13 +12939,14 @@ var ts; for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; + if (jsDoc) { + if (!node.jsDoc) { + node.jsDoc = [jsDoc]; + } + else { + node.jsDoc.push(jsDoc); + } } - node.jsDoc.push(jsDoc); } } return node; @@ -12231,15 +12974,15 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + var sourceFile = new SourceFileConstructor(269, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.isDeclarationFile = isDeclarationFile; sourceFile.scriptKind = scriptKind; return sourceFile; } @@ -12453,12 +13196,17 @@ var ts; } function createNode(kind, pos) { nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 ? new NodeConstructor(kind, p, p) : + kind === 71 ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind) { + var node = createNode(kind); + if (scanner.getTokenFlags() & 2) { + addJSDocComment(node); } - return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return node; } function createNodeArray(elements, pos, end) { var length = elements.length; @@ -12485,7 +13233,7 @@ var ts; else { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); + var result = createNode(kind); if (kind === 71) { result.escapedText = ""; } @@ -12518,8 +13266,8 @@ var ts; function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || @@ -12541,7 +13289,7 @@ var ts; return parsePropertyNameWorker(true); } function parseComputedPropertyName() { - var node = createNode(144); + var node = createNode(145); parseExpected(21); node.expression = allowInAnd(parseExpression); parseExpected(22); @@ -12669,6 +13417,10 @@ var ts; nextToken(); return ts.tokenIsIdentifierOrKeyword(token()); } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } function isHeritageClauseExtendsOrImplementsKeyword() { if (token() === 108 || token() === 85) { @@ -12785,7 +13537,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 96256; + var nodeContextFlags = node.flags & 6387712; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -12834,14 +13586,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 152: - case 157: case 153: + case 158: case 154: - case 149: - case 206: + case 155: + case 150: + case 207: return true; - case 151: + case 152: var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 71 && methodDeclaration.name.originalKeywordKind === 123; @@ -12853,8 +13605,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 257: - case 258: + case 261: + case 262: return true; } } @@ -12863,65 +13615,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 228: + case 229: + case 209: case 208: - case 207: + case 212: case 211: - case 210: - case 223: + case 224: + case 220: + case 222: case 219: - case 221: case 218: + case 216: case 217: case 215: - case 216: case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: + case 221: + case 210: case 225: + case 223: + case 213: + case 226: + case 239: case 238: - case 237: + case 245: case 244: - case 243: - case 233: - case 229: + case 234: case 230: - case 232: case 231: + case 233: + case 232: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 264; + return node.kind === 268; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 156: - case 150: case 157: - case 148: - case 155: + case 151: + case 158: + case 149: + case 156: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { + if (node.kind !== 227) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 146) { + if (node.kind !== 147) { return false; } var parameter = node; @@ -13015,7 +13767,7 @@ var ts; return createMissingList(); } function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); while (parseOptional(23)) { if (token() === 27) { @@ -13028,7 +13780,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(143, entity.pos); + var node = createNode(144, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -13043,7 +13795,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(196); + var template = createNode(197); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); var list = []; @@ -13055,7 +13807,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(205); + var span = createNode(206); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18) { @@ -13092,15 +13844,15 @@ var ts; node.isUnterminated = true; } if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + node.numericLiteralFlags = scanner.getTokenFlags() & 496; } nextToken(); finishNode(node); return node; } function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + var node = createNode(160); + node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27) { node.typeArguments = parseBracketedList(19, parseType, 27, 29); } @@ -13108,18 +13860,18 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(158, lhs.pos); + var node = createNode(159, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(169); + var node = createNode(170); nextToken(); return finishNode(node); } function parseJSDocAllType() { - var result = createNode(268); + var result = createNode(272); nextToken(); return finishNode(result); } @@ -13132,28 +13884,28 @@ var ts; token() === 29 || token() === 58 || token() === 49) { - var result = createNode(269, pos); + var result = createNode(273, pos); return finishNode(result); } else { - var result = createNode(270, pos); + var result = createNode(274, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNode(273); + var result = createNodeWithJSDoc(277); nextToken(); fillSignature(56, 4 | 32, result); - return addJSDocComment(finishNode(result)); + return finishNode(result); } - var node = createNode(159); + var node = createNode(160); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(146); + var parameter = createNode(147); if (token() === 99 || token() === 94) { parameter.name = parseIdentifierName(); parseExpected(56); @@ -13164,17 +13916,17 @@ var ts; function parseJSDocNodeWithType(kind) { var result = createNode(kind); nextToken(); - result.type = parseType(); + result.type = parseNonArrayType(); return finishNode(result); } function parseTypeQuery() { - var node = createNode(162); + var node = createNode(163); parseExpected(103); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(145); + var node = createNode(146); node.name = parseIdentifier(); if (parseOptional(85)) { if (isStartOfType() || !isStartOfExpression()) { @@ -13207,8 +13959,8 @@ var ts; token() === 57 || isStartOfType(true); } - function parseParameter(requireEqualsToken) { - var node = createNode(146); + function parseParameter() { + var node = createNodeWithJSDoc(147); if (token() === 99) { node.name = createIdentifier(true); node.type = parseParameterType(); @@ -13223,8 +13975,8 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseInitializer(true, requireEqualsToken); - return addJSDocComment(finishNode(node)); + node.initializer = parseInitializer(); + return finishNode(node); } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { @@ -13257,7 +14009,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -13274,19 +14026,16 @@ var ts; parseSemicolon(); } function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { + var node = createNodeWithJSDoc(kind); + if (kind === 157) { parseExpected(94); } fillSignature(56, 4, node); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); + return token() === 21 && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); @@ -13314,39 +14063,29 @@ var ts; nextToken(); return token() === 56 || token() === 26 || token() === 22; } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseIndexSignatureDeclaration(node) { + node.kind = 158; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, 4, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); + node.kind = 151; + fillSignature(56, 4, node); } else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + node.kind = 149; + node.type = parseTypeAnnotation(); if (token() === 58) { - property.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); } + parseTypeMemberSemicolon(); + return finishNode(node); } function isTypeMemberStart() { if (token() === 19 || token() === 27) { @@ -13376,24 +14115,24 @@ var ts; } function parseTypeMember() { if (token() === 19 || token() === 27) { - return parseSignatureMember(155); + return parseSignatureMember(156); } if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(156); + return parseSignatureMember(157); } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0); + node.modifiers = parseModifiers(); if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + return parseIndexSignatureDeclaration(node); } - return parsePropertyOrMethodSignature(fullStart, modifiers); + return parsePropertyOrMethodSignature(node); } function nextTokenIsOpenParenOrLessThan() { nextToken(); return token() === 19 || token() === 27; } function parseTypeLiteral() { - var node = createNode(163); + var node = createNode(164); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -13416,14 +14155,14 @@ var ts; return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; } function parseMappedTypeParameter() { - var node = createNode(145); + var node = createNode(146); node.name = parseIdentifier(); parseExpected(92); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(172); + var node = createNode(173); parseExpected(17); node.readonlyToken = parseOptionalToken(131); parseExpected(21); @@ -13436,34 +14175,34 @@ var ts; return finishNode(node); } function parseTupleType() { - var node = createNode(165); + var node = createNode(166); node.elementTypes = parseBracketedList(20, parseType, 21, 22); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(168); + var node = createNode(169); parseExpected(19); node.type = parseType(); parseExpected(20); return finishNode(node); } function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { + var node = createNodeWithJSDoc(kind); + if (kind === 162) { parseExpected(94); } fillSignature(36, 4, node); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); return token() === 23 ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(173); + var node = createNode(174); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(192); + unaryMinusExpression = createNode(193); unaryMinusExpression.operator = 38; nextToken(); } @@ -13486,8 +14225,8 @@ var ts; case 119: case 136: case 133: - case 122: case 137: + case 122: case 139: case 130: case 134: @@ -13498,10 +14237,8 @@ var ts; return parseJSDocUnknownOrNullableType(); case 89: return parseJSDocFunctionType(); - case 24: - return parseJSDocNodeWithType(274); case 51: - return parseJSDocNodeWithType(271); + return parseJSDocNodeWithType(275); case 13: case 9: case 8: @@ -13541,6 +14278,7 @@ var ts; case 133: case 122: case 137: + case 140: case 105: case 139: case 95: @@ -13575,58 +14313,71 @@ var ts; nextToken(); return token() === 20 || isStartOfParameter() || isStartOfType(); } - function parseJSDocPostfixTypeOrHigher() { + function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); - var kind = getKind(token()); - if (!kind) - return type; - nextToken(); - var postfix = createNode(kind, type.pos); - postfix.type = type; - return finishNode(postfix); - function getKind(tokenKind) { - switch (tokenKind) { + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { case 58: - return contextFlags & 1048576 ? 272 : undefined; + if (!(contextFlags & 1048576)) { + return type; + } + type = createJSDocPostfixType(276, type); + break; case 51: - return 271; + type = createJSDocPostfixType(275, type); + break; case 55: - return 270; - } - } - } - function parseArrayTypeOrHigher() { - var type = parseJSDocPostfixTypeOrHigher(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); + type = createJSDocPostfixType(274, type); + break; + case 21: + parseExpected(21); + if (isStartOfType()) { + var node = createNode(172, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(165, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + break; + default: + return type; } } return type; } + function createJSDocPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } function parseTypeOperator(operator) { - var node = createNode(170); + var node = createNode(171); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseTypeOperatorOrHigher() { - switch (token()) { + var operator = token(); + switch (operator) { case 127: - return parseTypeOperator(127); + case 140: + return parseTypeOperator(operator); + case 24: { + var result = createNode(278); + nextToken(); + result.type = parsePostfixTypeOrHigher(); + return finishNode(result); + } } - return parseArrayTypeOrHigher(); + return parsePostfixTypeOrHigher(); } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { parseOptional(operator); @@ -13643,10 +14394,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + return parseUnionOrIntersectionType(168, parseTypeOperatorOrHigher, 48); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + return parseUnionOrIntersectionType(167, parseIntersectionTypeOrHigher, 49); } function isStartOfFunctionType() { if (token() === 27) { @@ -13692,7 +14443,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); + var node = createNode(159, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -13713,10 +14464,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); + return parseFunctionOrConstructorType(161); } if (token() === 94) { - return parseFunctionOrConstructorType(161); + return parseFunctionOrConstructorType(162); } return parseUnionTypeOrHigher(); } @@ -13797,19 +14548,8 @@ var ts; } return expr; } - function parseInitializer(inParameter, requireEqualsToken) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - if (inParameter && requireEqualsToken) { - var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); - result.escapedText = "= not found"; - return result; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); + function parseInitializer() { + return parseOptional(58) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { if (isYieldExpression()) { @@ -13842,7 +14582,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(197); + var node = createNode(198); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 39 || isStartOfExpression())) { @@ -13858,13 +14598,13 @@ var ts; ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(187, asyncModifier.pos); + node = createNode(188, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(187, identifier.pos); + node = createNode(188, identifier.pos); } - var parameter = createNode(146, identifier.pos); + var parameter = createNode(147, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -13889,7 +14629,7 @@ var ts; arrowFunction.body = (lastToken === 36 || lastToken === 17) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); + return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { if (token() === 19 || token() === 27 || token() === 120) { @@ -13930,13 +14670,27 @@ var ts; if (second === 24) { return 1; } + if (ts.isModifierKind(second) && second !== 120 && lookAhead(nextTokenIsIdentifier)) { + return 1; + } if (!isIdentifier()) { return 0; } - if (nextToken() === 56) { - return 1; + switch (nextToken()) { + case 56: + return 1; + case 55: + nextToken(); + if (token() === 56 || token() === 26 || token() === 58 || token() === 20) { + return 1; + } + return 0; + case 26: + case 58: + case 20: + return 2; } - return 2; + return 0; } else { ts.Debug.assert(first === 27); @@ -13996,15 +14750,14 @@ var ts; return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); + var node = createNodeWithJSDoc(188); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || - ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { + if (!allowAmbiguity && token() !== 36 && token() !== 17) { return undefined; } return node; @@ -14029,7 +14782,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(195, leftOperand.pos); + var node = createNode(196, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -14042,7 +14795,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 || t === 142; + return t === 92 || t === 143; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -14120,39 +14873,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); + var node = createNode(195, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(202, left.pos); + var node = createNode(203, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(192); + var node = createNode(193); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(188); + var node = createNode(189); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(189); + var node = createNode(190); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(190); + var node = createNode(191); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -14167,7 +14920,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(191); + var node = createNode(192); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -14183,7 +14936,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { + if (simpleUnaryExpression.kind === 185) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -14236,19 +14989,19 @@ var ts; } function parseUpdateExpression() { if (token() === 43 || token() === 44) { - var node = createNode(192); + var node = createNode(193); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + return parseJsxElementOrSelfClosingElementOrFragment(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); + var node = createNode(194, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -14276,7 +15029,7 @@ var ts; if (token() === 19 || token() === 23 || token() === 21) { return expression; } - var node = createNode(179, expression.pos); + var node = createNode(180, expression.pos); node.expression = expression; parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); @@ -14295,28 +15048,35 @@ var ts; return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); + if (opening.kind === 252) { + var node = createNode(250, opening.pos); node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); + node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } + else if (opening.kind === 255) { + var node = createNode(254, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } else { - ts.Debug.assert(opening.kind === 250); + ts.Debug.assert(opening.kind === 251); result = opening; } if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); + var badNode = createNode(195, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -14328,7 +15088,7 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); + var node = createNode(10); node.containsOnlyWhiteSpaces = currentToken === 11; currentToken = scanner.scanJsxToken(); return finishNode(node); @@ -14341,11 +15101,11 @@ var ts; case 17: return parseJsxExpression(false); case 27: - return parseJsxElementOrSelfClosingElement(false); + return parseJsxElementOrSelfClosingElementOrFragment(false); } ts.Debug.fail("Unknown JSX child kind " + token()); } - function parseJsxChildren(openingTagName) { + function parseJsxChildren(openingTag) { var list = []; var listPos = getNodePos(); var saveParsingContext = parsingContext; @@ -14356,7 +15116,13 @@ var ts; break; } else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + var openingTagName = openingTag.tagName; + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + } break; } else if (token() === 7) { @@ -14371,18 +15137,23 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(254); + var jsxAttributes = createNode(258); jsxAttributes.properties = parseList(13, parseJsxAttribute); return finishNode(jsxAttributes); } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); parseExpected(27); + if (token() === 29) { + parseExpected(29); + var node_1 = createNode(255, fullStart); + return finishNode(node_1); + } var tagName = parseJsxElementName(); var attributes = parseJsxAttributes(); var node; if (token() === 29) { - node = createNode(251, fullStart); + node = createNode(252, fullStart); scanJsxText(); } else { @@ -14394,7 +15165,7 @@ var ts; parseExpected(29, undefined, false); scanJsxText(); } - node = createNode(250, fullStart); + node = createNode(251, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -14405,7 +15176,7 @@ var ts; var expression = token() === 99 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -14413,7 +15184,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(256); + var node = createNode(260); parseExpected(17); if (token() !== 18) { node.dotDotDotToken = parseOptionalToken(24); @@ -14433,7 +15204,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(253); + var node = createNode(257); node.name = parseIdentifierName(); if (token() === 58) { switch (scanJsxAttributeValue()) { @@ -14448,7 +15219,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(255); + var node = createNode(259); parseExpected(17); parseExpected(24); node.expression = parseExpression(); @@ -14456,7 +15227,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); + var node = createNode(253); parseExpected(28); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -14468,8 +15239,24 @@ var ts; } return finishNode(node); } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(256); + parseExpected(28); + if (ts.tokenIsIdentifierOrKeyword(token())) { + var unexpectedTagName = parseJsxElementName(); + parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } function parseTypeAssertion() { - var node = createNode(184); + var node = createNode(185); parseExpected(27); node.type = parseType(); parseExpected(29); @@ -14480,7 +15267,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23); if (dotToken) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -14488,13 +15275,13 @@ var ts; } if (token() === 51 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(203, expression.pos); + var nonNullExpression = createNode(204, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); + var indexedAccess = createNode(181, expression.pos); indexedAccess.expression = expression; if (token() !== 22) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -14508,7 +15295,7 @@ var ts; continue; } if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); + var tagExpression = createNode(184, expression.pos); tagExpression.tag = expression; tagExpression.template = token() === 13 ? parseLiteralNode() @@ -14527,7 +15314,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -14535,7 +15322,7 @@ var ts; continue; } else if (token() === 19) { - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -14630,28 +15417,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(185); + var node = createNodeWithJSDoc(186); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseSpreadElement() { - var node = createNode(198); + var node = createNode(199); parseExpected(24); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : + token() === 26 ? createNode(201) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(177); + var node = createNode(178); parseExpected(21); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -14660,60 +15447,46 @@ var ts; parseExpected(22); return finishNode(node); } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0); + if (parseOptionalToken(24)) { + node.kind = 267; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(node, 154); } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + if (parseContextualModifier(135)) { + return parseAccessorDeclaration(node, 155); } var asteriskToken = parseOptionalToken(39); var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + return parseMethodDeclaration(node, asteriskToken); } var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; + node.kind = 266; var equalsToken = parseOptionalToken(58); if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; + node.kind = 265; parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } + return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(178); + var node = createNode(179); parseExpected(17); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -14727,7 +15500,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(186); + var node = createNodeWithJSDoc(187); node.modifiers = parseModifiers(); parseExpected(89); node.asteriskToken = parseOptionalToken(39); @@ -14743,7 +15516,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(true); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; @@ -14752,12 +15525,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(94); if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); + var node_2 = createNode(205, fullStart); + node_2.keywordToken = 94; + node_2.name = parseIdentifierName(); + return finishNode(node_2); } - var node = createNode(182, fullStart); + var node = createNode(183, fullStart); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); if (node.typeArguments || token() === 19) { @@ -14766,7 +15539,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); + var node = createNode(208); if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -14797,12 +15570,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(209); + var node = createNode(210); parseExpected(25); return finishNode(node); } function parseIfStatement() { - var node = createNode(211); + var node = createNode(212); parseExpected(90); parseExpected(19); node.expression = allowInAnd(parseExpression); @@ -14812,7 +15585,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(212); + var node = createNode(213); parseExpected(81); node.statement = parseStatement(); parseExpected(106); @@ -14823,7 +15596,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(213); + var node = createNode(214); parseExpected(106); parseExpected(19); node.expression = allowInAnd(parseExpression); @@ -14846,8 +15619,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); + if (awaitToken ? parseExpected(143) : parseOptional(143)) { + var forOfStatement = createNode(217, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -14855,14 +15628,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); + var forInStatement = createNode(216, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(214, pos); + var forStatement = createNode(215, pos); forStatement.initializer = initializer; parseExpected(25); if (token() !== 25 && token() !== 20) { @@ -14880,7 +15653,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); + parseExpected(kind === 219 ? 72 : 77); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -14888,7 +15661,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(219); + var node = createNode(220); parseExpected(96); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -14897,16 +15670,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(220); + var node = createNode(221); parseExpected(107); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - node.statement = parseStatement(); + node.statement = doInsideOfContext(4194304, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(257); + var node = createNode(261); parseExpected(73); node.expression = allowInAnd(parseExpression); parseExpected(56); @@ -14914,7 +15687,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(258); + var node = createNode(262); parseExpected(79); parseExpected(56); node.statements = parseList(3, parseStatement); @@ -14924,12 +15697,12 @@ var ts; return token() === 73 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(221); + var node = createNode(222); parseExpected(98); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); + var caseBlock = createNode(236); parseExpected(17); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(18); @@ -14937,14 +15710,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(223); + var node = createNode(224); parseExpected(100); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(224); + var node = createNode(225); parseExpected(102); node.tryBlock = parseBlock(false); node.catchClause = token() === 74 ? parseCatchClause() : undefined; @@ -14955,7 +15728,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(260); + var result = createNode(264); parseExpected(74); if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); @@ -14968,26 +15741,25 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(225); + var node = createNode(226); parseExpected(78); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); + var node = createNodeWithJSDoc(0); var expression = allowInAnd(parseExpression); if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); + node.kind = 223; + node.label = expression; + node.statement = parseStatement(); } else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; + node.kind = 211; + node.expression = expression; parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); } + return finishNode(node); } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); @@ -15033,7 +15805,7 @@ var ts; return false; } continue; - case 141: + case 142: nextToken(); return token() === 17 || token() === 71 || token() === 84; case 91: @@ -15095,7 +15867,7 @@ var ts; case 128: case 129: case 138: - case 141: + case 142: return true; case 114: case 112: @@ -15121,16 +15893,16 @@ var ts; case 17: return parseBlock(false); case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227)); case 110: if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227)); } break; case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + return parseFunctionDeclaration(createNodeWithJSDoc(229)); case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + return parseClassDeclaration(createNodeWithJSDoc(230)); case 90: return parseIfStatement(); case 81: @@ -15140,9 +15912,9 @@ var ts; case 88: return parseForOrForInOrForOfStatement(); case 77: - return parseBreakOrContinueStatement(217); - case 72: return parseBreakOrContinueStatement(218); + case 72: + return parseBreakOrContinueStatement(219); case 96: return parseReturnStatement(); case 107: @@ -15175,7 +15947,7 @@ var ts; case 117: case 115: case 131: - case 141: + case 142: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -15183,49 +15955,64 @@ var ts; } return parseExpressionOrLabeledStatement(); } + function isDeclareModifier(modifier) { + return modifier.kind === 124; + } function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 2097152; + } + return doInsideOfContext(2097152, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { switch (token()) { case 104: case 110: case 76: - return parseVariableStatement(fullStart, decorators, modifiers); + return parseVariableStatement(node); case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); + return parseFunctionDeclaration(node); case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); + return parseClassDeclaration(node); case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); + return parseInterfaceDeclaration(node); case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + return parseTypeAliasDeclaration(node); case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: + return parseEnumDeclaration(node); + case 142: case 128: case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); + return parseModuleDeclaration(node); case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + return parseImportDeclarationOrImportEqualsDeclaration(node); case 84: nextToken(); switch (token()) { case 79: case 58: - return parseExportAssignment(fullStart, decorators, modifiers); + return parseExportAssignment(node); case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + return parseNamespaceExportDeclaration(node); default: - return parseExportDeclaration(fullStart, decorators, modifiers); + return parseExportDeclaration(node); } default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); + if (node.decorators || node.modifiers) { + var missing = createMissingNode(248, true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); } } } @@ -15242,16 +16029,16 @@ var ts; } function parseArrayBindingElement() { if (token() === 26) { - return createNode(200); + return createNode(201); } - var node = createNode(176); + var node = createNode(177); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(176); + var node = createNode(177); node.dotDotDotToken = parseOptionalToken(24); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -15263,18 +16050,18 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(174); + var node = createNode(175); parseExpected(17); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(18); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(175); + var node = createNode(176); parseExpected(21); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(22); @@ -15292,17 +16079,24 @@ var ts; } return parseIdentifier(); } - function parseVariableDeclaration() { - var node = createNode(226); + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(227); node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 71 && + token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); + var node = createNode(228); switch (token()) { case 104: break; @@ -15316,13 +16110,13 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 143 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); + node.declarations = parseDelimitedList(8, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -15330,18 +16124,14 @@ var ts; function canFollowContextualOfKeyword() { return nextTokenIsIdentifier() && nextToken() === 20; } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseVariableStatement(node) { + node.kind = 209; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseFunctionDeclaration(node) { + node.kind = 229; parseExpected(89); node.asteriskToken = parseOptionalToken(39); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); @@ -15349,65 +16139,51 @@ var ts; var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; + function parseConstructorDeclaration(node) { + node.kind = 153; parseExpected(123); fillSignature(56, 0, node); node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 152; + node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 : 0; - var isAsync = ts.hasModifier(method, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 150; + if (!node.questionToken && token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + node.initializer = ts.hasModifier(node, 32) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 | 2048, parseInitializer); parseSemicolon(); - return addJSDocComment(finishNode(property)); + return finishNode(node); } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + function parsePropertyOrMethodDeclaration(node) { var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); - } - } - function parseNonParameterInitializer() { - return parseInitializer(false); + return parsePropertyDeclaration(node); } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseAccessorDeclaration(node, kind) { + node.kind = kind; node.name = parsePropertyName(); fillSignature(56, 0, node); node.body = parseFunctionBlockOrSemicolon(0); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -15468,7 +16244,7 @@ var ts; if (!parseOptional(57)) { break; } - var decorator = createNode(147, decoratorStart); + var decorator = createNode(148, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -15509,46 +16285,46 @@ var ts; } function parseClassElement() { if (token() === 25) { - var result = createNode(206); + var result = createNode(207); nextToken(); return finishNode(result); } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(true); + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(node, 154); + } + if (parseContextualModifier(135)) { + return parseAccessorDeclaration(node, 155); } if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); + return parseConstructorDeclaration(node); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + return parseIndexSignatureDeclaration(node); } if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 || token() === 8 || token() === 39 || token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + return parsePropertyOrMethodDeclaration(node); } - if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + if (node.decorators || node.modifiers) { + node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 200); } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 230); } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; parseExpected(75); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -15560,7 +16336,7 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseNameOfClassDeclarationOrExpression() { return isIdentifier() && !isImplementsClause() @@ -15579,7 +16355,7 @@ var ts; function parseHeritageClause() { var tok = token(); if (tok === 85 || tok === 108) { - var node = createNode(259); + var node = createNode(263); node.token = tok; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -15588,52 +16364,49 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(201); + var node = createNode(202); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } + node.typeArguments = tryParseTypeArguments(); return finishNode(node); } + function tryParseTypeArguments() { + return token() === 27 + ? parseBracketedList(19, parseType, 27, 29) + : undefined; + } function isHeritageClause() { return token() === 85 || token() === 108; } function parseClassMembers() { return parseList(5, parseClassElement); } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseInterfaceDeclaration(node) { + node.kind = 231; parseExpected(109); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseTypeAliasDeclaration(node) { + node.kind = 232; parseExpected(138); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(58); node.type = parseType(); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); + var node = createNodeWithJSDoc(268); node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseEnumDeclaration(node) { + node.kind = 233; parseExpected(83); node.name = parseIdentifier(); if (parseExpected(17)) { @@ -15643,10 +16416,10 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); + var node = createNode(235); if (parseExpected(17)) { node.statements = parseList(1, parseStatement); parseExpected(18); @@ -15656,23 +16429,19 @@ var ts; } return finishNode(node); } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 234; var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(createNode(0), 4 | namespaceFlag) : parseModuleBlock(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 234; + if (token() === 142) { node.name = parseIdentifier(); node.flags |= 512; } @@ -15688,10 +16457,10 @@ var ts; } return finishNode(node); } - function parseModuleDeclaration(fullStart, decorators, modifiers) { + function parseModuleDeclaration(node) { var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + if (token() === 142) { + return parseAmbientExternalModuleDeclaration(node); } else if (parseOptional(129)) { flags |= 16; @@ -15699,10 +16468,10 @@ var ts; else { parseExpected(128); if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { return token() === 132 && @@ -15714,57 +16483,51 @@ var ts; function nextTokenIsSlash() { return nextToken() === 41; } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; + function parseNamespaceExportDeclaration(node) { + node.kind = 237; parseExpected(118); parseExpected(129); - exportDeclaration.name = parseIdentifier(); + node.name = parseIdentifier(); parseSemicolon(); - return finishNode(exportDeclaration); + return finishNode(node); } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + function parseImportDeclarationOrImportEqualsDeclaration(node) { parseExpected(91); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + if (token() !== 26 && token() !== 141) { + return parseImportEqualsDeclaration(node, identifier); } } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; + node.kind = 239; if (identifier || token() === 39 || token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(141); } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); + node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); - return finishNode(importDeclaration); + return finishNode(node); } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 238; + node.name = identifier; parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); + node.moduleReference = parseModuleReference(); parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); + return finishNode(node); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); + var importClause = createNode(240, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(242); } return finishNode(importClause); } @@ -15774,7 +16537,7 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(248); + var node = createNode(249); parseExpected(132); parseExpected(19); node.expression = parseModuleSpecifier(); @@ -15792,7 +16555,7 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(240); + var namespaceImport = createNode(241); parseExpected(39); parseExpected(118); namespaceImport.name = parseIdentifier(); @@ -15800,14 +16563,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + node.elements = parseBracketedList(22, kind === 242 ? parseImportSpecifier : parseExportSpecifier, 17, 18); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); + return parseImportOrExportSpecifier(247); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); + return parseImportOrExportSpecifier(243); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -15826,33 +16589,29 @@ var ts; else { node.name = identifierName; } - if (kind === 242 && checkIdentifierIsKeyword) { + if (kind === 243 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportDeclaration(node) { + node.kind = 245; if (parseOptional(39)) { - parseExpected(140); + parseExpected(141); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); + node.exportClause = parseNamedImportsOrExports(246); + if (token() === 141 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(141); node.moduleSpecifier = parseModuleSpecifier(); } } parseSemicolon(); return finishNode(node); } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportAssignment(node) { + node.kind = 244; if (parseOptional(58)) { node.isExportEquals = true; } @@ -15928,7 +16687,7 @@ var ts; var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment); if (checkJsDirectiveMatchResult) { checkJsDirective = { - enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", true) === 0, + enabled: ts.equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"), end: range.end, pos: range.pos }; @@ -15944,10 +16703,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1) - || node.kind === 237 && node.moduleReference.kind === 248 - || node.kind === 238 - || node.kind === 243 + || node.kind === 238 && node.moduleReference.kind === 249 + || node.kind === 239 || node.kind === 244 + || node.kind === 245 ? node : undefined; }); @@ -15988,8 +16747,8 @@ var ts; var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = createSourceFile("file.js", 5, 1); + initializeState(content, 6, undefined, 1); + sourceFile = createSourceFile("file.js", 6, 1, false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -15998,19 +16757,19 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression(requireBraces) { - var result = createNode(267, scanner.getTokenPos()); - if (!parseExpected(17) && requireBraces) { - return undefined; - } + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(271, scanner.getTokenPos()); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(1048576, parseType); - parseExpected(18); + if (!mayOmitBraces || hasBrace) { + parseExpected(18); + } fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); + initializeState(content, 6, undefined, 1); sourceFile = { languageVariant: 0, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -16026,7 +16785,7 @@ var ts; if (comment) { comment.parent = parent; } - if (ts.isInJavaScriptFile(parent)) { + if (contextFlags & 65536) { if (!sourceFile.jsDocDiagnostics) { sourceFile.jsDocDiagnostics = []; } @@ -16168,7 +16927,7 @@ var ts; content.charCodeAt(start + 3) !== 42; } function createJSDocComment() { - var result = createNode(275, start); + var result = createNode(279, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -16192,6 +16951,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -16284,7 +17044,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(276, atToken.pos); + var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -16320,7 +17080,7 @@ var ts; switch (node.kind) { case 134: return true; - case 164: + case 165: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; @@ -16336,8 +17096,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(279, atToken.pos) : - createNode(284, atToken.pos); + createNode(284, atToken.pos) : + createNode(289, atToken.pos); var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -16353,7 +17113,7 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var typeLiteralExpression = createNode(271, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); @@ -16365,9 +17125,9 @@ var ts; children.push(child); } if (children) { - jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral = createNode(280, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 164) { + if (typeExpression.type.kind === 165) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -16376,35 +17136,55 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + if (ts.forEach(tags, function (t) { return t.kind === 285; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(280, atToken.pos); + var result = createNode(285, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + if (ts.forEach(tags, function (t) { return t.kind === 286; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(281, atToken.pos); + var result = createNode(286, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = parseJSDocTypeExpression(true); - var result = createNode(277, atToken.pos); + var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = typeExpression; + result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(17); + var node = createNode(202); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(18); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(true); + while (parseOptional(23)) { + var prop = createNode(180, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } function parseClassTag(atToken, tagName) { - var tag = createNode(278, atToken.pos); + var tag = createNode(283, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); @@ -16412,7 +17192,7 @@ var ts; function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(283, atToken.pos); + var typedefTag = createNode(288, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); @@ -16435,9 +17215,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(285, start_3); + jsdocTypeLiteral = createNode(280, start_3); } - if (child.kind === 281) { + if (child.kind === 286) { if (childTypeTag) { break; } @@ -16453,10 +17233,10 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 164) { + if (typeExpression && typeExpression.type.kind === 165) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -16466,7 +17246,7 @@ var ts; var pos = scanner.getTokenPos(); var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); + var jsDocNamespaceNode = createNode(234, pos); jsDocNamespaceNode.flags |= flags; jsDocNamespaceNode.name = typeNameOrNamespaceName; jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); @@ -16499,7 +17279,7 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 279 && + if (child && child.kind === 284 && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -16527,7 +17307,7 @@ var ts; } function tryParseChildTag(target) { ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); + var atToken = createNode(57); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -16549,7 +17329,7 @@ var ts; return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + if (ts.forEach(tags, function (t) { return t.kind === 287; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; @@ -16561,7 +17341,7 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145, name.pos); + var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -16573,7 +17353,7 @@ var ts; break; } } - var result = createNode(282, atToken.pos); + var result = createNode(287, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -16908,6 +17688,9 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts"); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -16918,43 +17701,53 @@ var ts; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { - if (node.kind === 230 || node.kind === 231) { - return 0; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { - return 0; - } - else if (node.kind === 234) { - var state_1 = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state_1 = 2; - return false; - case 1: - state_1 = 1; - return true; + return node.body ? getModuleInstanceStateWorker(node.body) : 1; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + switch (node.kind) { + case 231: + case 232: + return 0; + case 233: + if (ts.isConst(node)) { + return 2; + } + break; + case 239: + case 238: + if (!(ts.hasModifier(node, 1))) { + return 0; + } + break; + case 235: { + var state_1 = 0; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0: + return; + case 2: + state_1 = 2; + return; + case 1: + state_1 = 1; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 234: + return getModuleInstanceState(node); + case 71: + if (node.isInJSDocNamespace) { + return 0; } - }); - return state_1; - } - else if (node.kind === 233) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1; - } - else if (node.kind === 71 && node.isInJSDocNamespace) { - return 0; - } - else { - return 1; } + return 1; } - ts.getModuleInstanceState = getModuleInstanceState; var ContainerFlags; (function (ContainerFlags) { ContainerFlags[ContainerFlags["None"] = 0] = "None"; @@ -17002,6 +17795,9 @@ var ts; var reportedUnreachableFlow = { flags: 1 }; var subtreeTransformFlags = 0; var skipTransformFlagAggregation; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -17037,7 +17833,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { return true; } else { @@ -17066,60 +17862,61 @@ var ts; if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 234)) { symbol.valueDeclaration = node; } } } function getDeclarationName(node) { + if (node.kind === 244) { + return node.isExportEquals ? "export=" : "default"; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 144) { + if (name.kind === 145) { var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } return ts.getEscapedTextOfIdentifierOrLiteral(name); } switch (node.kind) { - case 152: + case 153: return "__constructor"; - case 160: - case 155: - return "__call"; case 161: case 156: - return "__new"; + return "__call"; + case 162: case 157: + return "__new"; + case 158: return "__index"; - case 244: + case 245: return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; - case 194: + case 195: if (ts.getSpecialPropertyAssignmentKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 228: case 229: + case 230: return (ts.hasModifier(node, 512) ? "default" : undefined); - case 273: + case 277: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); - case 146: - ts.Debug.assert(node.parent.kind === 273); + case 147: + ts.Debug.assert(node.parent.kind === 277); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 283: + case 288: var name_2 = ts.getNameOfJSDocTypedef(node); return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } @@ -17137,7 +17934,7 @@ var ts; } else { symbol = symbolTable.get(name); - if (includes & 788448) { + if (includes & 2885600) { classifiableNames.set(name, true); } if (!symbol) { @@ -17165,15 +17962,15 @@ var ts; } else { if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { + (isDefaultExport || (node.kind === 244 && !node.isExportEquals))) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -17185,7 +17982,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; if (symbolFlags & 2097152) { - if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { + if (node.kind === 247 || (node.kind === 238 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -17193,9 +17990,9 @@ var ts; } } else { - if (node.kind === 283) + if (node.kind === 288) ts.Debug.assert(ts.isInJavaScriptFile(node)); - var isJSDocTypedefInJSDocNamespace = node.kind === 283 && + var isJSDocTypedefInJSDocNamespace = node.kind === 288 && node.name && node.name.kind === 71 && node.name.isInJSDocNamespace; @@ -17233,16 +18030,13 @@ var ts; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { + if (!isIIFE) { currentFlow = { flags: 2 }; if (containerFlags & (16 | 128)) { currentFlow.container = node; } - currentReturnTarget = undefined; } + currentReturnTarget = isIIFE || node.kind === 153 ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -17254,14 +18048,17 @@ var ts; if (hasExplicitReturn) node.flags |= 256; } - if (node.kind === 265) { + if (node.kind === 269) { node.flags |= emitFlags; } - if (isIIFE) { + if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 153) { + node.returnFlowNode = currentFlow; + } } - else { + if (!isIIFE) { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; @@ -17341,70 +18138,70 @@ var ts; return; } switch (node.kind) { - case 213: + case 214: bindWhileStatement(node); break; - case 212: + case 213: bindDoStatement(node); break; - case 214: + case 215: bindForStatement(node); break; - case 215: case 216: + case 217: bindForInOrForOfStatement(node); break; - case 211: + case 212: bindIfStatement(node); break; - case 219: - case 223: + case 220: + case 224: bindReturnOrThrow(node); break; + case 219: case 218: - case 217: bindBreakOrContinueStatement(node); break; - case 224: + case 225: bindTryStatement(node); break; - case 221: + case 222: bindSwitchStatement(node); break; - case 235: + case 236: bindCaseBlock(node); break; - case 257: + case 261: bindCaseClause(node); break; - case 222: + case 223: bindLabeledStatement(node); break; - case 192: + case 193: bindPrefixUnaryExpressionFlow(node); break; - case 193: + case 194: bindPostfixUnaryExpressionFlow(node); break; - case 194: + case 195: bindBinaryExpressionFlow(node); break; - case 188: + case 189: bindDeleteExpressionFlow(node); break; - case 195: + case 196: bindConditionalExpressionFlow(node); break; - case 226: + case 227: bindVariableDeclarationFlow(node); break; - case 181: + case 182: bindCallExpressionFlow(node); break; - case 275: + case 279: bindJSDocComment(node); break; - case 283: + case 288: bindJSDocTypedefTag(node); break; default: @@ -17416,15 +18213,15 @@ var ts; switch (expr.kind) { case 71: case 99: - case 179: + case 180: return isNarrowableReference(expr); - case 181: + case 182: return hasNarrowableArgument(expr); - case 185: + case 186: return isNarrowingExpression(expr.expression); - case 194: + case 195: return isNarrowingBinaryExpression(expr); - case 192: + case 193: return expr.operator === 51 && isNarrowingExpression(expr.operand); } return false; @@ -17433,7 +18230,7 @@ var ts; return expr.kind === 71 || expr.kind === 99 || expr.kind === 97 || - expr.kind === 179 && isNarrowableReference(expr.expression); + expr.kind === 180 && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -17444,14 +18241,14 @@ var ts; } } } - if (expr.expression.kind === 179 && + if (expr.expression.kind === 180 && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -17472,9 +18269,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 185: + case 186: return isNarrowableOperand(expr.expression); - case 194: + case 195: switch (expr.operatorToken.kind) { case 58: return isNarrowableOperand(expr.left); @@ -17551,33 +18348,33 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 211: - case 213: case 212: - return parent.expression === node; case 214: - case 195: + case 213: + return parent.expression === node; + case 215: + case 196: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 185) { + if (node.kind === 186) { node = node.expression; } - else if (node.kind === 192 && node.operator === 51) { + else if (node.kind === 193 && node.operator === 51) { node = node.operand; } else { - return node.kind === 194 && (node.operatorToken.kind === 53 || + return node.kind === 195 && (node.operatorToken.kind === 53 || node.operatorToken.kind === 54); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 || - node.parent.kind === 192 && + while (node.parent.kind === 186 || + node.parent.kind === 193 && node.parent.operator === 51) { node = node.parent; } @@ -17619,7 +18416,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 + var enclosingLabeledStatement = node.parent.kind === 223 ? ts.lastOrUndefined(activeLabels) : undefined; var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); @@ -17651,13 +18448,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 216) { + if (node.kind === 217) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 227) { + if (node.initializer.kind !== 228) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -17679,7 +18476,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 219) { + if (node.kind === 220) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -17699,7 +18496,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 ? breakTarget : continueTarget; + var flowLabel = node.kind === 219 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -17762,7 +18559,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 262; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -17825,15 +18622,15 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - if (!node.statement || node.statement.kind !== 212) { + if (!node.statement || node.statement.kind !== 213) { addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 194 && node.operatorToken.kind === 58) { + if (node.kind === 195 && node.operatorToken.kind === 58) { bindAssignmentTargetFlow(node.left); } else { @@ -17844,10 +18641,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 177) { + else if (node.kind === 178) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 198) { + if (e.kind === 199) { bindAssignmentTargetFlow(e.expression); } else { @@ -17855,16 +18652,16 @@ var ts; } } } - else if (node.kind === 178) { + else if (node.kind === 179) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 261) { + if (p.kind === 265) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 262) { + else if (p.kind === 266) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 263) { + else if (p.kind === 267) { bindAssignmentTargetFlow(p.expression); } } @@ -17920,7 +18717,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 180) { + if (operator === 58 && node.left.kind === 181) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -17931,7 +18728,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 179) { + if (node.expression.kind === 180) { bindAssignmentTargetFlow(node.expression); } } @@ -17970,7 +18767,7 @@ var ts; } function bindJSDocComment(node) { ts.forEachChild(node, function (n) { - if (n.kind !== 283) { + if (n.kind !== 288) { bind(n); } }); @@ -17985,10 +18782,10 @@ var ts; } function bindCallExpressionFlow(node) { var expr = node.expression; - while (expr.kind === 185) { + while (expr.kind === 186) { expr = expr.expression; } - if (expr.kind === 186 || expr.kind === 187) { + if (expr.kind === 187 || expr.kind === 188) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -17996,7 +18793,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 179) { + if (node.expression.kind === 180) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -18005,52 +18802,52 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 199: - case 229: - case 232: - case 178: - case 163: - case 285: - case 254: - return 1; + case 200: case 230: - return 1 | 64; case 233: + case 179: + case 164: + case 280: + case 258: + return 1; case 231: - case 172: + return 1 | 64; + case 234: + case 232: + case 173: return 1 | 32; - case 265: + case 269: return 1 | 4 | 32; - case 151: + case 152: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 | 4 | 32 | 8 | 128; } - case 152: - case 228: - case 150: case 153: + case 229: + case 151: case 154: case 155: - case 273: - case 160: case 156: - case 157: + case 277: case 161: + case 157: + case 158: + case 162: return 1 | 4 | 32 | 8; - case 186: case 187: + case 188: return 1 | 4 | 32 | 8 | 16; - case 234: + case 235: return 4; - case 149: + case 150: return node.initializer ? 4 : 0; - case 260: - case 214: + case 264: case 215: case 216: - case 235: + case 217: + case 236: return 2; - case 207: + case 208: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -18063,37 +18860,37 @@ var ts; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 233: + case 234: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265: + case 269: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199: - case 229: + case 200: + case 230: return declareClassMember(node, symbolFlags, symbolExcludes); - case 232: + case 233: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 285: - case 178: - case 230: - case 254: + case 164: + case 280: + case 179: + case 231: + case 258: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160: case 161: - case 155: + case 162: case 156: case 157: - case 151: - case 150: + case 158: case 152: + case 151: case 153: case 154: - case 228: - case 186: + case 155: + case 229: case 187: - case 273: - case 231: - case 172: + case 188: + case 277: + case 232: + case 173: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -18108,11 +18905,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 265 ? node : node.body; - if (body && (body.kind === 265 || body.kind === 234)) { + var body = node.kind === 269 ? node : node.body; + if (body && (body.kind === 269 || body.kind === 235)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 244 || stat.kind === 243) { + if (stat.kind === 245 || stat.kind === 244) { return true; } } @@ -18120,7 +18917,7 @@ var ts; return false; } function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + if (node.flags & 2097152 && !hasExportDeclarations(node)) { node.flags |= 32; } else { @@ -18156,18 +18953,10 @@ var ts; else { var state = declareModuleSymbol(node); if (state !== 0) { - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } + var symbol = node.symbol; + symbol.constEnumOnlyModule = (!(symbol.flags & (16 | 32 | 256))) + && state === 2 + && symbol.constEnumOnlyModule !== false; } } } @@ -18195,11 +18984,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 || prop.name.kind !== 71) { + if (prop.kind === 267 || prop.name.kind !== 71) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 + var currentKind = prop.kind === 265 || prop.kind === 266 || prop.kind === 152 ? 1 : 2; var existingKind = seen.get(identifier.escapedText); @@ -18223,17 +19012,17 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & 8) { + if (symbolFlags & (8 | 106500)) { symbol.parent = container.symbol; } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 233: + case 234: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 265: + case 269: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -18254,9 +19043,9 @@ var ts; node.originalKeywordKind >= 108 && node.originalKeywordKind <= 116 && !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { + !(node.flags & 2097152)) { if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -18293,7 +19082,7 @@ var ts; var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -18322,8 +19111,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 265 && - blockScopeContainer.kind !== 233 && + if (blockScopeContainer.kind !== 269 && + blockScopeContainer.kind !== 234 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -18331,8 +19120,8 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + if (inStrictMode && node.numericLiteralFlags & 32) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -18365,7 +19154,7 @@ var ts; if (ts.isInJavaScriptFile(node)) bindJSDocTypedefTagIfAny(node); bindWorker(node); - if (node.kind > 142) { + if (node.kind > 143) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -18393,7 +19182,7 @@ var ts; } for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; - if (tag.kind === 283) { + if (tag.kind === 288) { var savedParent = parent; parent = jsDoc; bind(tag); @@ -18425,23 +19214,26 @@ var ts; case 71: if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 283) { + while (parentNode && parentNode.kind !== 288) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288, 793064); break; } case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 266)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 179: + case 180: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } break; - case 194: + case 195: var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { case 1: @@ -18465,122 +19257,122 @@ var ts; ts.Debug.fail("Unknown special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 260: + case 264: return checkStrictModeCatchClause(node); - case 188: + case 189: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 193: + case 194: return checkStrictModePostfixUnaryExpression(node); - case 192: + case 193: return checkStrictModePrefixUnaryExpression(node); - case 220: + case 221: return checkStrictModeWithStatement(node); - case 169: + case 170: seenThisKeyword = true; return; - case 158: + case 159: return checkTypePredicate(node); - case 145: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); case 146: + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + case 147: return bindParameter(node); - case 226: + case 227: return bindVariableDeclarationOrBindingElement(node); - case 176: + case 177: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); + case 150: case 149: - case 148: return bindPropertyWorker(node); - case 261: - case 262: + case 265: + case 266: return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 264: + case 268: return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 155: case 156: case 157: + case 158: return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 152: case 151: - case 150: return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 228: + case 229: return bindFunctionDeclaration(node); - case 152: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 153: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 154: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 155: return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 160: - case 273: case 161: + case 277: + case 162: return bindFunctionOrConstructorType(node); - case 163: - case 285: - case 172: + case 164: + case 280: + case 173: return bindAnonymousTypeWorker(node); - case 178: + case 179: return bindObjectLiteralExpression(node); - case 186: case 187: + case 188: return bindFunctionExpression(node); - case 181: + case 182: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 199: - case 229: + case 200: + case 230: inStrictMode = true; return bindClassLikeDeclaration(node); - case 230: - return bindBlockScopedDeclaration(node, 64, 792968); case 231: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 64, 792968); case 232: - return bindEnumDeclaration(node); + return bindBlockScopedDeclaration(node, 524288, 793064); case 233: + return bindEnumDeclaration(node); + case 234: return bindModuleDeclaration(node); - case 254: + case 258: return bindJsxAttributes(node); - case 253: + case 257: return bindJsxAttribute(node, 4, 0); - case 237: - case 240: - case 242: - case 246: + case 238: + case 241: + case 243: + case 247: return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); - case 236: + case 237: return bindNamespaceExportDeclaration(node); - case 239: + case 240: return bindImportClause(node); - case 244: + case 245: return bindExportDeclaration(node); - case 243: + case 244: return bindExportAssignment(node); - case 265: + case 269: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 207: + case 208: if (!ts.isFunctionLike(node.parent)) { return; } - case 234: + case 235: return updateStrictModeStatementList(node.statements); - case 279: - if (node.parent.kind !== 285) { + case 284: + if (node.parent.kind !== 280) { break; } - case 284: + case 289: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 276 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 283: { + case 288: { var fullName = node.fullName; if (!fullName || fullName.kind === 71) { return bindBlockScopedDeclaration(node, 524288, 793064); @@ -18600,7 +19392,7 @@ var ts; if (parameterName && parameterName.kind === 71) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 169) { + if (parameterName && parameterName.kind === 170) { seenThisKeyword = true; } bind(type); @@ -18619,28 +19411,28 @@ var ts; bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); } else { - var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 244 && ts.exportAssignmentIsAlias(node) ? 2097152 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 2097152 | 32 | 16); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + if (node.parent.kind !== 269) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -18675,15 +19467,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -18702,22 +19491,32 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var container = ts.getThisContainer(node, false); switch (container.kind) { - case 228: - case 186: + case 229: + case 187: container.symbol.members = container.symbol.members || ts.createSymbolTable(); declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); break; - case 152: - case 149: - case 151: case 153: + case 150: + case 152: case 154: + case 155: var containingClass = container.parent; var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); break; } } + function bindSpecialPropertyDeclaration(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (node.expression.kind === 99) { + bindThisPropertyAssignment(node); + } + else if ((node.expression.kind === 71 || node.expression.kind === 180) && + node.parent.parent.kind === 269) { + bindStaticPropertyAssignment(node); + } + } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; var classPrototype = leftSideOfAssignment.expression; @@ -18728,32 +19527,62 @@ var ts; bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); } function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.left; + var leftSideOfAssignment = node.kind === 180 ? node : node.left; var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + if (ts.isIdentifier(target)) { + target.parent = leftSideOfAssignment; + if (node.kind === 195) { + leftSideOfAssignment.parent = node; + } + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + } } } function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { + var symbol = lookupSymbolForName(functionName); + var targetSymbol = symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol) ? + symbol.valueDeclaration.initializer.symbol : + symbol; + ts.Debug.assert(propertyAccess.parent.kind === 195 || propertyAccess.parent.kind === 211); + var isLegalPosition; + if (propertyAccess.parent.kind === 195) { + var initializerKind = propertyAccess.parent.right.kind; + isLegalPosition = (initializerKind === 200 || initializerKind === 187) && + propertyAccess.parent.parent.parent.kind === 269; + } + else { + isLegalPosition = propertyAccess.parent.parent.kind === 269; + } + if (!isPrototypeProperty && (!targetSymbol || !(targetSymbol.flags & 1920)) && isLegalPosition) { + ts.Debug.assert(ts.isIdentifier(propertyAccess.expression)); + var identifier = propertyAccess.expression; + var flags = 1536 | 67108864; + var excludeFlags = 106639 & ~67108864; + if (targetSymbol) { + addDeclarationToSymbol(symbol, identifier, flags); + } + else { + targetSymbol = declareSymbol(container.locals, undefined, identifier, flags, excludeFlags); + } } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { + if (!targetSymbol || !(targetSymbol.flags & (16 | 32 | 1024))) { return; } var symbolTable = isPrototypeProperty ? (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); + declareSymbol(symbolTable, targetSymbol, propertyAccess, 4, 0); } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -18761,7 +19590,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 229) { + if (node.kind === 230) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -18778,7 +19607,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -18805,7 +19634,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { + if (inStrictMode && !(node.flags & 2097152)) { checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { @@ -18820,7 +19649,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -18835,7 +19664,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024; } @@ -18848,7 +19677,7 @@ var ts; return bindAnonymousDeclaration(node, 16, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152) && ts.isAsyncFunction(node)) { emitFlags |= 1024; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { @@ -18867,15 +19696,15 @@ var ts; return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || - node.kind === 229 || - (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 210) || + node.kind === 230 || + (node.kind === 234 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 233 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 || + !(node.flags & 2097152) && + (node.kind !== 209 || ts.getCombinedNodeFlags(node.declarationList) & 3 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -18889,56 +19718,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 181: - return computeCallExpression(node, subtreeFlags); case 182: + return computeCallExpression(node, subtreeFlags); + case 183: return computeNewExpression(node, subtreeFlags); - case 233: + case 234: return computeModuleDeclaration(node, subtreeFlags); - case 185: + case 186: return computeParenthesizedExpression(node, subtreeFlags); - case 194: + case 195: return computeBinaryExpression(node, subtreeFlags); - case 210: + case 211: return computeExpressionStatement(node, subtreeFlags); - case 146: + case 147: return computeParameter(node, subtreeFlags); - case 187: + case 188: return computeArrowFunction(node, subtreeFlags); - case 186: + case 187: return computeFunctionExpression(node, subtreeFlags); - case 228: + case 229: return computeFunctionDeclaration(node, subtreeFlags); - case 226: - return computeVariableDeclaration(node, subtreeFlags); case 227: + return computeVariableDeclaration(node, subtreeFlags); + case 228: return computeVariableDeclarationList(node, subtreeFlags); - case 208: + case 209: return computeVariableStatement(node, subtreeFlags); - case 222: + case 223: return computeLabeledStatement(node, subtreeFlags); - case 229: + case 230: return computeClassDeclaration(node, subtreeFlags); - case 199: + case 200: return computeClassExpression(node, subtreeFlags); - case 259: + case 263: return computeHeritageClause(node, subtreeFlags); - case 260: + case 264: return computeCatchClause(node, subtreeFlags); - case 201: + case 202: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152: + case 153: return computeConstructor(node, subtreeFlags); - case 149: + case 150: return computePropertyDeclaration(node, subtreeFlags); - case 151: + case 152: return computeMethod(node, subtreeFlags); - case 153: case 154: + case 155: return computeAccessor(node, subtreeFlags); - case 237: + case 238: return computeImportEquals(node, subtreeFlags); - case 179: + case 180: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -18958,6 +19787,9 @@ var ts; } if (expression.kind === 91) { transformFlags |= 67108864; + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } } node.transformFlags = transformFlags | 536870912; return transformFlags & ~537396545; @@ -18966,8 +19798,8 @@ var ts; switch (kind) { case 97: return true; - case 179: case 180: + case 181: var expression = node.expression; var expressionKind = expression.kind; return expressionKind === 97; @@ -18989,10 +19821,10 @@ var ts; var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 178) { + if (operatorTokenKind === 58 && leftKind === 179) { transformFlags |= 8 | 192 | 3072; } - else if (operatorTokenKind === 58 && leftKind === 177) { + else if (operatorTokenKind === 58 && leftKind === 178) { transformFlags |= 192 | 3072; } else if (operatorTokenKind === 40 @@ -19030,8 +19862,8 @@ var ts; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 202 - || expressionKind === 184) { + if (expressionKind === 203 + || expressionKind === 185) { transformFlags |= 3; } if (expressionTransformFlags & 1024) { @@ -19123,6 +19955,7 @@ var ts; || ts.hasModifier(node, 2270) || node.typeParameters || node.type + || (node.name && ts.isComputedPropertyName(node.name)) || !node.body) { transformFlags |= 3; } @@ -19143,6 +19976,7 @@ var ts; if (node.decorators || ts.hasModifier(node, 2270) || node.type + || (node.name && ts.isComputedPropertyName(node.name)) || !node.body) { transformFlags |= 3; } @@ -19318,7 +20152,7 @@ var ts; var excludeFlags = 536872257; switch (kind) { case 120: - case 191: + case 192: transformFlags |= 8 | 16; break; case 114: @@ -19327,34 +20161,37 @@ var ts; case 117: case 124: case 76: - case 232: - case 264: - case 184: - case 202: + case 233: + case 268: + case 185: case 203: + case 204: case 131: transformFlags |= 3; break; - case 249: case 250: case 251: - case 10: case 252: + case 10: case 253: case 254: case 255: case 256: + case 257: + case 258: + case 259: + case 260: transformFlags |= 4; break; case 13: case 14: case 15: case 16: - case 196: - case 183: - case 262: + case 197: + case 184: + case 266: case 115: - case 204: + case 205: transformFlags |= 192; break; case 9: @@ -19363,17 +20200,17 @@ var ts; } break; case 8: - if (node.numericLiteralFlags & 48) { + if (node.numericLiteralFlags & 384) { transformFlags |= 192; } break; - case 216: + case 217: if (node.awaitModifier) { transformFlags |= 8; } transformFlags |= 192; break; - case 197: + case 198: transformFlags |= 8 | 192 | 16777216; break; case 119: @@ -19384,10 +20221,9 @@ var ts; case 122: case 137: case 105: - case 145: - case 148: - case 150: - case 155: + case 146: + case 149: + case 151: case 156: case 157: case 158: @@ -19401,27 +20237,28 @@ var ts; case 166: case 167: case 168: - case 230: - case 231: case 169: + case 231: + case 232: case 170: case 171: case 172: case 173: - case 236: + case 174: + case 237: transformFlags = 3; excludeFlags = -3; break; - case 144: + case 145: transformFlags |= 2097152; if (subtreeFlags & 16384) { transformFlags |= 65536; } break; - case 198: + case 199: transformFlags |= 192 | 524288; break; - case 263: + case 267: transformFlags |= 8 | 1048576; break; case 97: @@ -19430,27 +20267,27 @@ var ts; case 99: transformFlags |= 16384; break; - case 174: + case 175: transformFlags |= 192 | 8388608; if (subtreeFlags & 524288) { transformFlags |= 8 | 1048576; } excludeFlags = 537396545; break; - case 175: + case 176: transformFlags |= 192 | 8388608; excludeFlags = 537396545; break; - case 176: + case 177: transformFlags |= 192; if (node.dotDotDotToken) { transformFlags |= 524288; } break; - case 147: + case 148: transformFlags |= 3 | 4096; break; - case 178: + case 179: excludeFlags = 540087617; if (subtreeFlags & 2097152) { transformFlags |= 192; @@ -19462,29 +20299,29 @@ var ts; transformFlags |= 8; } break; - case 177: - case 182: + case 178: + case 183: excludeFlags = 537396545; if (subtreeFlags & 524288) { transformFlags |= 192; } break; - case 212: case 213: case 214: case 215: + case 216: if (subtreeFlags & 4194304) { transformFlags |= 192; } break; - case 265: + case 269: if (subtreeFlags & 32768) { transformFlags |= 192; } break; - case 219: - case 217: + case 220: case 218: + case 219: transformFlags |= 33554432; break; } @@ -19492,33 +20329,33 @@ var ts; return transformFlags & ~excludeFlags; } function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 && kind <= 173) { + if (kind >= 159 && kind <= 174) { return -3; } switch (kind) { - case 181: case 182: - case 177: + case 183: + case 178: return 537396545; - case 233: + case 234: return 574674241; - case 146: + case 147: return 536872257; - case 187: + case 188: return 601249089; - case 186: - case 228: + case 187: + case 229: return 601281857; - case 227: + case 228: return 546309441; - case 229: - case 199: + case 230: + case 200: return 539358529; - case 152: - return 601015617; - case 151: case 153: + return 601015617; + case 152: case 154: + case 155: return 601015617; case 119: case 133: @@ -19528,21 +20365,21 @@ var ts; case 122: case 137: case 105: - case 145: - case 148: - case 150: - case 155: + case 146: + case 149: + case 151: case 156: case 157: - case 230: + case 158: case 231: + case 232: return -3; - case 178: + case 179: return 540087617; - case 260: + case 264: return 537920833; - case 174: case 175: + case 176: return 537396545; default: return 536872257; @@ -19595,7 +20432,7 @@ var ts; var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; - if (type.flags & 32768) { + if (type.flags & 65536) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4) { @@ -19611,16 +20448,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 16384) { + if (type.flags & 32768) { visitTypeParameter(type); } - if (type.flags & 196608) { + if (type.flags & 393216) { visitUnionOrIntersectionType(type); } - if (type.flags & 262144) { + if (type.flags & 524288) { visitIndexType(type); } - if (type.flags & 524288) { + if (type.flags & 1048576) { visitIndexedAccessType(type); } } @@ -19703,7 +20540,7 @@ var ts; symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { - if (d.type && d.type.kind === 162) { + if (d.type && d.type.kind === 163) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -19760,10 +20597,12 @@ var ts; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4, "undefined"); @@ -19908,15 +20747,34 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, - getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -19924,25 +20782,27 @@ var ts; var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4, "unknown"); var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1, "any"); var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); + var undefinedType = createIntrinsicType(4096, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 | 4194304, "undefined"); + var nullType = createIntrinsicType(8192, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 | 4194304, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var trueType = createIntrinsicType(128, "true"); var falseType = createIntrinsicType(128, "false"); var booleanType = createBooleanType([trueType, falseType]); var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); - var silentNeverType = createIntrinsicType(8192, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var voidType = createIntrinsicType(2048, "void"); + var neverType = createIntrinsicType(16384, "never"); + var silentNeverType = createIntrinsicType(16384, "never"); + var implicitNeverType = createIntrinsicType(16384, "never"); + var nonPrimitiveType = createIntrinsicType(33554432, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); @@ -19950,9 +20810,14 @@ var ts; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; + anyFunctionType.flags |= 16777216; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(32768); + var markerSubType = createType(32768); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(32768); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); @@ -19960,6 +20825,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); + var ambientModulesCache; var patternAmbientModules; var globalObjectType; var globalFunctionType; @@ -20076,29 +20942,29 @@ var ts; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ - "string": 1, - "number": 2, - "boolean": 4, - "symbol": 8, - "undefined": 16384, - "object": 16, - "function": 32 + string: 1, + number: 2, + boolean: 4, + symbol: 8, + undefined: 16384, + object: 16, + function: 32 }); var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128, - "number": 256, - "boolean": 512, - "symbol": 1024, - "undefined": 131072, - "object": 2048, - "function": 4096 + string: 128, + number: 256, + boolean: 512, + symbol: 1024, + undefined: 131072, + object: 2048, + function: 4096 }); var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType + string: stringType, + number: numberType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType }); var typeofType = createTypeofType(); var _jsxNamespace; @@ -20108,16 +20974,6 @@ var ts; var _jsxElementChildrenPropertyName; var _hasComputedJsxElementChildrenPropertyName = false; var jsxTypes = ts.createUnderscoreEscapedMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); @@ -20137,6 +20993,29 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["Readonly"] = 1] = "Readonly"; + MappedTypeModifiers[MappedTypeModifiers["Optional"] = 2] = "Optional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -20161,16 +21040,16 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } - function error(location, message, arg0, arg1, arg2) { + function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); } - function createSymbol(flags, name) { + function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432, name)); - symbol.checkFlags = 0; + symbol.checkFlags = checkFlags || 0; return symbol; } function isTransientSymbol(symbol) { @@ -20235,14 +21114,15 @@ var ts; return result; } function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + source.flags & 67108864 || target.flags & 67108864) { if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; } target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { + (target.valueDeclaration.kind === 234 && source.valueDeclaration.kind !== 234))) { target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -20272,6 +21152,16 @@ var ts; }); } } + function combineSymbolTables(first, second) { + if (!first || first.size === 0) + return second; + if (!second || second.size === 0) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); @@ -20297,7 +21187,7 @@ var ts; mergeSymbolTable(globals, moduleAugmentation.symbol.exports); } else { - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); @@ -20338,11 +21228,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } - function getObjectFlags(type) { - return type.flags & 32768 ? type.objectFlags : 0; - } function isGlobalSourceFile(node) { - return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 269 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -20365,7 +21252,7 @@ var ts; var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -20378,7 +21265,7 @@ var ts; if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - ts.isInAmbientContext(declaration)) { + declaration.flags & 2097152) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -20388,23 +21275,23 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - if (declaration.kind === 176) { - var errorBindingElement = ts.getAncestor(usage, 176); + if (declaration.kind === 177) { + var errorBindingElement = ts.getAncestor(usage, 177); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 227), usage); } - else if (declaration.kind === 226) { + else if (declaration.kind === 227) { return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return true; } - if (usage.parent.kind === 246 || (usage.parent.kind === 243 && usage.parent.isExportEquals)) { + if (usage.parent.kind === 247 || (usage.parent.kind === 244 && usage.parent.isExportEquals)) { return true; } - if (usage.kind === 243 && usage.isExportEquals) { + if (usage.kind === 244 && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -20412,9 +21299,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 208: - case 214: - case 216: + case 209: + case 215: + case 217: if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } @@ -20431,16 +21318,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 149 && + current.parent.kind === 150 && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32)) { - if (declaration.kind === 151) { + if (declaration.kind === 152) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !ts.hasModifier(declaration, 32); + var isDeclarationInstanceProperty = declaration.kind === 150 && !ts.hasModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -20456,6 +21343,7 @@ var ts; var originalLocation = location; var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -20465,18 +21353,18 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 275) { + if (meaning & result.flags & 793064 && lastLocation.kind !== 279) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 146 || - lastLocation.kind === 145 + lastLocation.kind === 147 || + lastLocation.kind === 146 : false; } if (meaning & 107455 && result.flags & 1) { useResult = - lastLocation.kind === 146 || + lastLocation.kind === 147 || (lastLocation === location.type && - result.valueDeclaration.kind === 146); + result.valueDeclaration.kind === 147); } } if (useResult) { @@ -20488,13 +21376,13 @@ var ts; } } switch (location.kind) { - case 265: + case 269: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 233: + case 234: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 || ts.isAmbientModule(location)) { + if (location.kind === 269 || ts.isAmbientModule(location)) { if (result = moduleExports.get("default")) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { @@ -20505,7 +21393,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 && - ts.getDeclarationOfKind(moduleExport, 246)) { + ts.getDeclarationOfKind(moduleExport, 247)) { break; } } @@ -20513,13 +21401,13 @@ var ts; break loop; } break; - case 232: + case 233: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; + case 150: case 149: - case 148: if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -20529,10 +21417,10 @@ var ts; } } break; - case 229: - case 199: case 230: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { + case 200: + case 231: + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -20543,7 +21431,7 @@ var ts; } break loop; } - if (location.kind === 199 && meaning & 32) { + if (location.kind === 200 && meaning & 32) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -20551,7 +21439,7 @@ var ts; } } break; - case 201: + case 202: if (lastLocation === location.expression && location.parent.token === 85) { var container = location.parent.parent; if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064))) { @@ -20562,28 +21450,28 @@ var ts; } } break; - case 144: + case 145: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230) { + if (ts.isClassLike(grandparent) || grandparent.kind === 231) { if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 228: - case 187: + case 155: + case 229: + case 188: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 186: + case 187: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -20596,8 +21484,8 @@ var ts; } } break; - case 147: - if (location.parent && location.parent.kind === 146) { + case 148: + if (location.parent && location.parent.kind === 147) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -20605,15 +21493,18 @@ var ts; } break; } + if (location.kind !== 208) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 265); + ts.Debug.assert(lastLocation.kind === 269); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -20632,7 +21523,7 @@ var ts; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); } } if (!suggestion) { @@ -20659,7 +21550,7 @@ var ts; } if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236) { + if (decls && decls.length === 1 && decls[0].kind === 237) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -20667,12 +21558,12 @@ var ts; return result; } function diagnosticName(nameArg) { - return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 145 && decl.parent === container) { + if (decl.kind === 146 && decl.parent === container) { return true; } } @@ -20718,18 +21609,19 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71: - case 179: + case 180: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; + case 202: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } default: return undefined; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~1920, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -20770,7 +21662,7 @@ var ts; } } else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~793064, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -20780,9 +21672,9 @@ var ts; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 233) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + if (!(declaration.flags & 2097152) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } @@ -20799,13 +21691,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 237: + case 238: return node; - case 239: - return node.parent; case 240: + return node.parent; + case 241: return node.parent.parent; - case 242: + case 243: return node.parent.parent.parent; default: return undefined; @@ -20815,7 +21707,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248) { + if (node.moduleReference.kind === 249) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -20924,19 +21816,19 @@ var ts; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { - case 237: + case 238: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239: - return getTargetOfImportClause(node, dontRecursivelyResolve); case 240: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 241: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242: + case 243: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246: + case 247: return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); - case 243: + case 244: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236: + case 237: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); } } @@ -20985,10 +21877,10 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 243) { + if (node.kind === 244) { checkExpressionCached(node.expression); } - else if (node.kind === 246) { + else if (node.kind === 247) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -21000,11 +21892,11 @@ var ts; if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 71 || entityName.parent.kind === 143) { + if (entityName.kind === 71 || entityName.parent.kind === 144) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 237); + ts.Debug.assert(entityName.parent.kind === 238); return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); } } @@ -21023,19 +21915,19 @@ var ts; return undefined; } } - else if (name.kind === 143 || name.kind === 179) { + else if (name.kind === 144 || name.kind === 180) { var left = void 0; - if (name.kind === 143) { + if (name.kind === 144) { left = name.left; } - else if (name.kind === 179 && - (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { + else if (name.kind === 180 && + (name.expression.kind === 186 || ts.isEntityNameExpression(name.expression))) { left = name.expression; } else { return undefined; } - var right = name.kind === 143 ? name.right : name.name; + var right = name.kind === 144 ? name.right : name.name; var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -21043,6 +21935,9 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } + if (ts.isInJavaScriptFile(name) && ts.isDeclarationOfFunctionOrClassExpression(namespace)) { + namespace = getSymbolOfNode(namespace.valueDeclaration.initializer); + } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { @@ -21051,7 +21946,7 @@ var ts; return undefined; } } - else if (name.kind === 185) { + else if (name.kind === 186) { return ts.isEntityNameExpression(name.expression) ? resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : undefined; @@ -21166,23 +22061,29 @@ var ts; } function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); - if (!symbol) { - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); - } + if (symbol) { + return symbol; } - return symbol; + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 16382 ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + return symbol.flags & 32 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports") : + symbol.flags & 1536 ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; } function getExportsOfModule(moduleSymbol) { var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); } function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { if (id === "default") return; var targetSymbol = target.get(id); @@ -21244,10 +22145,10 @@ var ts; return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; } function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); } function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576) !== 0 @@ -21261,7 +22162,7 @@ var ts; var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 152 && ts.nodeIsPresent(member.body)) { + if (member.kind === 153 && ts.nodeIsPresent(member.body)) { return member; } } @@ -21284,7 +22185,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(32768); + var type = createType(65536); type.objectFlags = objectFlags; type.symbol = symbol; return type; @@ -21334,11 +22235,11 @@ var ts; } } switch (location.kind) { - case 265: + case 269: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 233: + case 234: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -21383,7 +22284,6 @@ var ts; return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246) && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -21408,7 +22308,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 247)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -21422,10 +22322,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 149: - case 151: - case 153: + case 150: + case 152: case 154: + case 155: continue; default: return false; @@ -21482,7 +22382,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 269 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -21509,11 +22409,13 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 163 || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 145) { meaning = 107455 | 1048576; } - else if (entityName.kind === 143 || entityName.kind === 179 || - entityName.parent.kind === 237) { + else if (entityName.kind === 144 || entityName.kind === 180 || + entityName.parent.kind === 238) { meaning = 1920; } else { @@ -21586,18 +22488,21 @@ var ts; function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; @@ -21631,10 +22536,10 @@ var ts; if (type.flags & 8) { return ts.createKeywordTypeNode(122); } - if (type.flags & 256 && !(type.flags & 65536)) { + if (type.flags & 256 && !(type.flags & 131072)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 793064, false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 272) { @@ -21651,24 +22556,27 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024) { - return ts.createKeywordTypeNode(105); + return ts.createTypeOperatorNode(140, ts.createKeywordTypeNode(137)); } if (type.flags & 2048) { - return ts.createKeywordTypeNode(139); + return ts.createKeywordTypeNode(105); } if (type.flags & 4096) { - return ts.createKeywordTypeNode(95); + return ts.createKeywordTypeNode(139); } if (type.flags & 8192) { + return ts.createKeywordTypeNode(95); + } + if (type.flags & 16384) { return ts.createKeywordTypeNode(130); } if (type.flags & 512) { return ts.createKeywordTypeNode(137); } - if (type.flags & 16777216) { + if (type.flags & 33554432) { return ts.createKeywordTypeNode(134); } - if (type.flags & 16384 && type.isThisType) { + if (type.flags & 32768 && type.isThisType) { if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; @@ -21676,13 +22584,13 @@ var ts; } return ts.createThis(); } - var objectFlags = getObjectFlags(type); + var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 32768)); + ts.Debug.assert(!!(type.flags & 65536)); return typeReferenceToTypeNode(type); } - if (type.flags & 16384 || objectFlags & 3) { - var name = symbolToName(type.symbol, context, 793064, false); + if (type.flags & 32768 || objectFlags & 3) { + var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { @@ -21690,11 +22598,11 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - if (type.flags & (65536 | 131072)) { - var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + if (type.flags & (131072 | 262144)) { + var types = type.flags & 131072 ? formatUnionTypes(type.types) : type.types; var typeNodes = mapToTypeNodes(types, context); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 ? 167 : 168, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -21705,22 +22613,22 @@ var ts; } } if (objectFlags & (16 | 32)) { - ts.Debug.assert(!!(type.flags & 32768)); + ts.Debug.assert(!!(type.flags & 65536)); return createAnonymousTypeNode(type); } - if (type.flags & 262144) { + if (type.flags & 524288) { var indexedType = type.type; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 524288) { + if (type.flags & 1048576) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768)); + ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); @@ -21765,7 +22673,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; + return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return ts.contains(context.symbolStack, symbol); @@ -21783,12 +22691,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 162, context); return signatureNode; } } @@ -21898,11 +22806,11 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 157, context)); } if (resolvedType.stringIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); @@ -21926,7 +22834,7 @@ var ts; var signatures = getSignaturesOfType(propertyType, 0); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 151, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); @@ -21945,8 +22853,8 @@ var ts; function mapToTypeNodes(types, context) { if (ts.some(types)) { var result = []; - for (var i = 0; i < types.length; ++i) { - var type = types[i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -22001,23 +22909,23 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); - if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { - return ts.createParameter(undefined, undefined, parameterSymbol.isRestParameter ? ts.createToken(24) : undefined, "args", undefined, typeToTypeNodeHelper(anyArrayType, context), undefined); - } - var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; - var name = parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : - cloneBindingName(parameterDeclaration.name) : - ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); - var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 147); + ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); var parameterType = getTypeOfSymbol(parameterSymbol); - if (isRequiredInitializedParameter(parameterDeclaration)) { - parameterType = getNullableType(parameterType, 2048); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); return parameterNode; function cloneBindingName(node) { @@ -22025,7 +22933,7 @@ var ts; function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 176) { + if (clone.kind === 177) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 | 16777216); @@ -22066,8 +22974,7 @@ var ts; } typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol, context); - var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } function getSymbolChain(symbol, meaning, endOfChain) { @@ -22106,10 +23013,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 6144)) { + if (!(t.flags & 12288)) { if (t.flags & (128 | 256)) { var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 65536) { + if (baseType.flags & 131072) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -22121,9 +23028,9 @@ var ts; result.push(t); } } - if (flags & 4096) + if (flags & 8192) result.push(nullType); - if (flags & 2048) + if (flags & 4096) result.push(undefinedType); return result || types; } @@ -22138,8 +23045,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); - if (node.kind === 231) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 169; }); + if (node.kind === 232) { return getSymbolOfNode(node); } } @@ -22147,30 +23054,30 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 234 && + node.parent.kind === 235 && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol, context) { + function getNameOfSymbolAsWritten(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 226) { + if (declaration.parent && declaration.parent.kind === 227) { return ts.declarationNameToString(declaration.parent.name); } if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { context.encounteredError = true; } switch (declaration.kind) { - case 199: + case 200: return "(Anonymous class)"; - case 186: case 187: + case 188: return "(Anonymous function)"; } } @@ -22180,25 +23087,29 @@ var ts; return "\"" + ts.escapeString(stringValue, 34) + "\""; } } - return ts.unescapeLeadingUnderscores(symbol.escapedName); + return ts.symbolName(symbol); } function getSymbolDisplayBuilder() { function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); + writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); } function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); + var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 21); + if (firstChar !== 91) { + writePunctuation(writer, 21); + } if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 22); + if (firstChar !== 91) { + writePunctuation(writer, 22); + } } else { writePunctuation(writer, 23); @@ -22262,21 +23173,21 @@ var ts; return writeType(type, globalFlags); function writeType(type, flags) { var nextFlags = flags & ~1024; - if (type.flags & 16793231) { + if (type.flags & 33585807) { writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 16384 && type.isThisType) { + else if (type.flags & 32768 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (getObjectFlags(type) & 4) { + else if (ts.getObjectFlags(type) & 4) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 && !(type.flags & 65536)) { + else if (type.flags & 256 && !(type.flags & 131072)) { var parent = getParentOfSymbol(type.symbol); buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); if (getDeclaredTypeOfSymbol(parent) !== type) { @@ -22284,7 +23195,7 @@ var ts; appendSymbolNameOnly(type.symbol, writer); } } - else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { + else if (ts.getObjectFlags(type) & 3 || type.flags & (272 | 32768)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } else if (!(flags & 1024) && type.aliasSymbol && @@ -22292,16 +23203,26 @@ var ts; var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } - else if (type.flags & 196608) { + else if (type.flags & 393216) { writeUnionOrIntersectionType(type, nextFlags); } - else if (getObjectFlags(type) & (16 | 32)) { + else if (ts.getObjectFlags(type) & (16 | 32)) { writeAnonymousType(type, nextFlags); } + else if (type.flags & 1024) { + if (flags & 131072) { + writeKeyword(writer, 140); + writeSpace(writer); + } + else { + writer.reportInaccessibleUniqueSymbolError(); + } + writeKeyword(writer, 137); + } else if (type.flags & 96) { writer.writeStringLiteral(literalTypeToString(type)); } - else if (type.flags & 262144) { + else if (type.flags & 524288) { if (flags & 128) { writePunctuation(writer, 19); } @@ -22312,7 +23233,7 @@ var ts; writePunctuation(writer, 20); } } - else if (type.flags & 524288) { + else if (type.flags & 1048576) { writeType(type.objectType, 128); writePunctuation(writer, 21); writeType(type.indexType, 0); @@ -22369,8 +23290,8 @@ var ts; } else if (flags & 16384 && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 199) { - writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + type.symbol.valueDeclaration.kind === 200) { + writeAnonymousType(type, flags); } else { var outerTypeParameters = type.target.outerTypeParameters; @@ -22397,7 +23318,7 @@ var ts; if (flags & 128) { writePunctuation(writer, 19); } - if (type.flags & 65536) { + if (type.flags & 131072) { writeTypeList(formatUnionTypes(type.types), 49); } else { @@ -22412,12 +23333,12 @@ var ts; if (symbol) { if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 199 && flags & 16384) || + !(symbol.valueDeclaration.kind === 200 && flags & 16384) || symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); @@ -22452,7 +23373,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; + return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 4) || @@ -22460,13 +23381,13 @@ var ts; } } } - function writeTypeOfSymbol(type, typeFormatFlags) { + function writeTypeOfSymbol(symbol, typeFormatFlags) { if (typeFormatFlags & 32768) { writePunctuation(writer, 19); } writeKeyword(writer, 103); writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); if (typeFormatFlags & 32768) { writePunctuation(writer, 20); } @@ -22476,6 +23397,13 @@ var ts; writeKeyword(writer, 131); writeSpace(writer); } + if (ts.getCheckFlags(prop) & 1024) { + var decl = ts.firstOrUndefined(prop.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + if (name) { + writer.trackSymbol(name, enclosingDeclaration, 107455); + } + } buildSymbolDisplay(prop, writer); if (prop.flags & 16777216) { writePunctuation(writer, 55); @@ -22560,7 +23488,7 @@ var ts; continue; } if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); } } var t = getTypeOfSymbol(p); @@ -22652,17 +23580,17 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048); + type = getOptionalType(type); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 174) { + if (bindingPattern.kind === 175) { writePunctuation(writer, 17); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); writePunctuation(writer, 18); } - else if (bindingPattern.kind === 175) { + else if (bindingPattern.kind === 176) { writePunctuation(writer, 21); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); @@ -22676,7 +23604,7 @@ var ts; if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 176); + ts.Debug.assert(bindingElement.kind === 177); if (bindingElement.propertyName) { writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 56); @@ -22834,87 +23762,92 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 176: + case 177: return isDeclarationVisible(node.parent.parent); - case 226: + case 227: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 233: - case 229: + case 234: case 230: case 231: - case 228: case 232: - case 237: + case 229: + case 233: + case 238: if (ts.isExternalModuleAugmentation(node)) { return true; } var parent = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { + !(node.kind !== 238 && parent.kind !== 269 && parent.flags & 2097152)) { return isGlobalSourceFile(parent); } return isDeclarationVisible(parent); + case 150: case 149: - case 148: - case 153: case 154: + case 155: + case 152: case 151: - case 150: if (ts.hasModifier(node, 8 | 16)) { return false; } - case 152: - case 156: - case 155: + case 153: case 157: - case 146: - case 234: - case 160: + case 156: + case 158: + case 147: + case 235: case 161: - case 163: - case 159: + case 162: case 164: + case 160: case 165: case 166: case 167: case 168: + case 169: return isDeclarationVisible(node.parent); - case 239: case 240: - case 242: + case 241: + case 243: return false; - case 145: - case 265: - case 236: + case 146: + case 269: + case 237: return true; - case 243: + case 244: return false; default: return false; } } } - function collectLinkedAliases(node) { + function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node, false); + if (node.parent && node.parent.kind === 244) { + exportSymbol = resolveName(node, node.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, node, false); } - else if (node.parent.kind === 246) { + else if (node.parent.kind === 247) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); } - var result = []; + var result; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } return result; function buildVisibleNodeList(declarations) { ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - ts.pushIfUnique(result, resultNode); + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); @@ -22974,12 +23907,12 @@ var ts; function getDeclarationContainer(node) { node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 226: case 227: + case 228: + case 243: case 242: case 241: case 240: - case 239: return false; default: return true; @@ -23003,14 +23936,14 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function isComputedNonLiteralName(name) { - return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 145 && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144); }); - if (source.flags & 8192) { + source = filterType(source, function (t) { return !(t.flags & 12288); }); + if (source.flags & 16384) { return emptyObjectType; } - if (source.flags & 65536) { + if (source.flags & 131072) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); @@ -23038,14 +23971,14 @@ var ts; if (parentType === unknownType) { return unknownType; } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; - if (pattern.kind === 174) { + if (pattern.kind === 175) { if (declaration.dotDotDotToken) { if (!isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -23065,10 +23998,10 @@ var ts; if (isComputedNonLiteralName(name)) { return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } var text = ts.getTextOfPropertyName(name); + if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || @@ -23100,7 +24033,7 @@ var ts; } } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096)) { type = getTypeWithFacts(type, 131072); } return declaration.initializer ? @@ -23120,17 +24053,18 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 177 && expr.elements.length === 0; + return expr.kind === 178 && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048) : type; + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.parent.parent.kind === 215) { + if (declaration.parent.parent.kind === 216) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 | 262144) ? indexType : stringType; + return indexType.flags & (32768 | 524288) ? indexType : stringType; } - if (declaration.parent.parent.kind === 216) { + if (declaration.parent.parent.kind === 217) { var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } @@ -23140,11 +24074,11 @@ var ts; var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, declaration.questionToken && includeOptionality); + return addOptionality(declaredType, !!declaration.questionToken && includeOptionality); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + declaration.kind === 227 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 2097152)) { if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { return autoType; } @@ -23152,10 +24086,10 @@ var ts; return autoArrayType; } } - if (declaration.kind === 146) { + if (declaration.kind === 147) { var func = declaration.parent; - if (func.kind === 154 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); + if (func.kind === 155 && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 154); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -23174,17 +24108,17 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, declaration.questionToken && includeOptionality); + return addOptionality(type, !!declaration.questionToken && includeOptionality); } } if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, declaration.questionToken && includeOptionality); + return addOptionality(type, !!declaration.questionToken && includeOptionality); } if (ts.isJsxAttribute(declaration)) { return trueType; } - if (declaration.kind === 262) { + if (declaration.kind === 266) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -23199,14 +24133,14 @@ var ts; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = declaration.kind === 194 ? declaration : - declaration.kind === 179 ? ts.getAncestor(declaration, 194) : + var expression = declaration.kind === 195 ? declaration : + declaration.kind === 180 ? ts.getAncestor(declaration, 195) : undefined; if (!expression) { return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 152) { + if (ts.getThisContainer(expression, false).kind === 153) { definedInConstructor = true; } else { @@ -23219,9 +24153,10 @@ var ts; if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { - var name = ts.getNameOfDeclaration(declaration); - error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); + else if (jsDocType !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(jsDocType, declarationType) && + !(symbol.flags & 67108864)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } else if (!jsDocType) { @@ -23288,7 +24223,7 @@ var ts; return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 + return pattern.kind === 175 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -23298,7 +24233,10 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (declaration.kind === 261) { + if (type.flags & 1024 && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + if (declaration.kind === 265) { return type; } return getWidenedType(type); @@ -23313,7 +24251,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 ? root.parent : root; + var memberDeclaration = root.kind === 147 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -23326,7 +24264,7 @@ var ts; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } - if (declaration.kind === 243) { + if (declaration.kind === 244) { return links.type = checkExpression(declaration.expression); } if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { @@ -23336,8 +24274,8 @@ var ts; return unknownType; } var type = void 0; - if (declaration.kind === 194 || - declaration.kind === 179 && declaration.parent.kind === 194) { + if (declaration.kind === 195 || + declaration.kind === 180 && declaration.parent.kind === 195) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } else { @@ -23352,7 +24290,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 153) { + if (accessor.kind === 154) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -23373,8 +24311,8 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153); - var setter = ts.getDeclarationOfKind(symbol, 154); + var getter = ts.getDeclarationOfKind(symbol, 154); + var setter = ts.getDeclarationOfKind(symbol, 155); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { @@ -23415,7 +24353,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153); + var getter_1 = ts.getDeclarationOfKind(symbol, 154); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -23425,7 +24363,7 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; + return baseConstructorType.flags & 1081344 ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -23440,7 +24378,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 16777216 ? getNullableType(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 16777216 ? getOptionalType(type) : type; } } } @@ -23519,20 +24457,20 @@ var ts; function isReferenceToType(type, target) { return type !== undefined && target !== undefined - && (getObjectFlags(type) & 4) !== 0 + && (ts.getObjectFlags(type) & 4) !== 0 && type.target === target; } function getTargetType(type) { - return getObjectFlags(type) & 4 ? type.target : type; + return ts.getObjectFlags(type) & 4 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); function check(type) { - if (getObjectFlags(type) & (3 | 4)) { + if (ts.getObjectFlags(type) & (3 | 4)) { var target = getTargetType(type); return target === checkBase || ts.forEach(getBaseTypes(target), check); } - else if (type.flags & 131072) { + else if (type.flags & 262144) { return ts.forEach(type.types, check); } } @@ -23552,44 +24490,44 @@ var ts; return undefined; } switch (node.kind) { - case 229: - case 199: case 230: - case 155: + case 200: + case 231: case 156: - case 150: - case 160: - case 161: - case 273: - case 228: + case 157: case 151: - case 186: + case 161: + case 162: + case 277: + case 229: + case 152: case 187: - case 231: - case 282: - case 172: + case 188: + case 232: + case 287: + case 173: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 172) { + if (node.kind === 173) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); var thisType = includeThisTypes && - (node.kind === 229 || node.kind === 199 || node.kind === 230) && + (node.kind === 230 || node.kind === 200 || node.kind === 231) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 231); return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 230 || node.kind === 229 || - node.kind === 199 || node.kind === 231) { + if (node.kind === 231 || node.kind === 230 || + node.kind === 200 || node.kind === 232) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -23613,14 +24551,21 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { return true; } - if (type.flags & 540672) { + if (type.flags & 1081344) { var constraint = getBaseConstraintOfType(type); return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + var decl = type.symbol.valueDeclaration; + if (ts.isInJavaScriptFile(decl)) { + var tag = ts.getJSDocAugmentsTag(decl); + if (tag) { + return tag.class; + } + } + return ts.getClassExtendsHeritageClauseElement(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -23634,6 +24579,8 @@ var ts; } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getClassExtendsHeritageClauseElement(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -23642,7 +24589,11 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 | 131072)) { + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (65536 | 262144)) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -23679,7 +24630,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { + if (!(baseConstructorType.flags & (65536 | 262144 | 1))) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -23701,13 +24652,6 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag && augTag.typeExpression && augTag.typeExpression.type) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } if (baseType === unknownType) { return; } @@ -23716,7 +24660,7 @@ var ts; return; } if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); return; } type.resolvedBaseTypes = [baseType]; @@ -23724,21 +24668,21 @@ var ts; function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; + var last_1 = outerTypeParameters.length - 1; var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; } return true; } function isValidBaseType(type) { - return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || - type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return type.flags & (65536 | 33554432 | 1) && !isGenericMappedType(type) || + type.flags & 262144 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 231 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -23764,10 +24708,10 @@ var ts; } } } - function isIndependentInterface(symbol) { + function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230) { + if (declaration.kind === 231) { if (declaration.flags & 64) { return false; } @@ -23794,7 +24738,7 @@ var ts; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + if (outerTypeParameters || localTypeParameters || kind === 1 || !isThislessInterface(symbol)) { type.objectFlags |= 4; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; @@ -23803,7 +24747,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384); + type.thisType = createType(32768); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -23818,9 +24762,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 283 || d.kind === 231; + return d.kind === 288 || d.kind === 232; }); - var typeNode = declaration.kind === 283 ? declaration.typeExpression : declaration.type; + var typeNode = declaration.kind === 288 ? declaration.typeExpression : declaration.type; var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -23841,13 +24785,13 @@ var ts; function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !ts.isInAmbientContext(member); + return !(member.flags & 2097152); } switch (expr.kind) { case 9: case 8: return true; - case 192: + case 193: return expr.operator === 38 && expr.operand.kind === 8; case 71: @@ -23864,7 +24808,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232) { + if (declaration.kind === 233) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9) { @@ -23879,7 +24823,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 : 1; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 256 && !(type.flags & 131072) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -23891,7 +24835,7 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232) { + if (declaration.kind === 233) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); @@ -23902,7 +24846,7 @@ var ts; } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); - if (enumType_1.flags & 65536) { + if (enumType_1.flags & 131072) { enumType_1.flags |= 256; enumType_1.symbol = symbol; } @@ -23926,7 +24870,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384); + var type = createType(32768); type.symbol = symbol; links.declaredType = type; } @@ -23940,6 +24884,9 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { if (symbol.flags & (32 | 64)) { return getDeclaredTypeOfClassOrInterface(symbol); } @@ -23958,20 +24905,9 @@ var ts; if (symbol.flags & 2097152) { return getDeclaredTypeOfAlias(symbol); } - return unknownType; - } - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; + return undefined; } - function isIndependentType(node) { + function isThislessType(node) { switch (node.kind) { case 119: case 136: @@ -23983,46 +24919,40 @@ var ts; case 139: case 95: case 130: - case 173: + case 174: return true; - case 164: - return isIndependentType(node.elementType); - case 159: - return isIndependentTypeReference(node); + case 165: + return isThislessType(node.elementType); + case 160: + return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; } - function isIndependentVariableLikeDeclaration(node) { + function isThislessTypeParameter(node) { + return !node.constraint || isThislessType(node.constraint); + } + function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isIndependentType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !node.initializer; } - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152) { - var typeNode = ts.getEffectiveReturnTypeNode(node); - if (!typeNode || !isIndependentType(typeNode)) { - return false; - } - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + return (node.kind === 153 || (returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); } - function isIndependentMember(symbol) { + function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 149: - case 148: - return isIndependentVariableLikeDeclaration(declaration); - case 151: case 150: + case 149: + return isThislessVariableLikeDeclaration(declaration); case 152: - return isIndependentFunctionLikeDeclaration(declaration); + case 151: + case 153: + return isThislessFunctionLikeDeclaration(declaration); } } } @@ -24032,7 +24962,7 @@ var ts; var result = ts.createSymbolTable(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; - result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; } @@ -24047,23 +24977,139 @@ var ts; function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call")); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new")); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); } return type; } + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 1120); + } + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return name && isLateBindableName(name); + } + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + function getLateBoundNameFromType(type) { + if (type.flags & 1024) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & 96) { + return ts.escapeLeadingUnderscores("" + type.value); + } + } + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0, memberName, 1024)); + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0, memberName, 1024); + } + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + lateSymbol.parent = parent; + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports"; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 ? getExportsOfModuleWorker(symbol) : + symbol.exports; + links[resolutionKind] = earlySymbols || emptySymbols; + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { + var member = members_3[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers") + : symbol.members || emptySymbols; + } + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 && symbol.escapedName === "__computed") { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4) { + if (ts.getObjectFlags(type) & 4) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); } } - else if (type.flags & 131072) { + else if (type.flags & 262144) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); } return type; @@ -24077,7 +25123,7 @@ var ts; var numberIndexInfo; if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = identityMapper; - members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); callSignatures = source.declaredCallSignatures; constructSignatures = source.declaredConstructSignatures; stringIndexInfo = source.declaredStringIndexInfo; @@ -24093,7 +25139,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -24154,7 +25200,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -24222,8 +25268,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type = types_1[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -24301,7 +25347,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { - var members = symbol.members; + var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call")); var constructSignatures = getSignaturesOfSymbol(members.get("__new")); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); @@ -24317,7 +25363,7 @@ var ts; if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 | 131072 | 540672)) { + if (baseConstructorType.flags & (65536 | 262144 | 1081344)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -24350,18 +25396,20 @@ var ts; var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 171 && + constraintDeclaration.operator === 127) { for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var propertySymbol = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); } - if (getIndexInfoOfType(modifiersType, 0)) { + if (modifiersType.flags & 1 || getIndexInfoOfType(modifiersType, 0)) { addMemberForKeyType(stringType); } } else { - var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + var keyType = constraintType.flags & 1081344 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 524288 ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -24377,8 +25425,8 @@ var ts; var propName = ts.escapeLeadingUnderscores(t.value); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216); - var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + var checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName, checkFlags); prop.type = propType; if (propertySymbol) { prop.syntheticOrigin = propertySymbol; @@ -24387,7 +25435,7 @@ var ts; prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } - else if (t.flags & 2) { + else if (t.flags & (1 | 2)) { stringIndexInfo = createIndexInfo(propType, templateReadonly); } } @@ -24409,27 +25457,37 @@ var ts; function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170) { + if (constraintDeclaration.kind === 171 && + constraintDeclaration.operator === 127) { type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); } else { var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 32768 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } + function getMappedTypeModifiers(type) { + return (type.declaration.readonlyToken ? 1 : 0) | + (type.declaration.questionToken ? 2 : 0); + } + function getCombinedMappedTypeModifiers(type) { + var modifiersType = getModifiersTypeFromMappedType(type); + return getMappedTypeModifiers(type) | + (isGenericMappedType(modifiersType) ? getMappedTypeModifiers(modifiersType) : 0); + } function isPartialMappedType(type) { - return getObjectFlags(type) & 32 && !!type.declaration.questionToken; + return ts.getObjectFlags(type) & 32 && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return ts.getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 32768) { + if (type.flags & 65536) { if (type.objectFlags & 4) { resolveTypeReferenceMembers(type); } @@ -24443,23 +25501,23 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 65536) { + else if (type.flags & 131072) { resolveUnionTypeMembers(type); } - else if (type.flags & 131072) { + else if (type.flags & 262144) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -24481,7 +25539,7 @@ var ts; } } } - if (type.flags & 65536) { + if (type.flags & 131072) { break; } } @@ -24491,19 +25549,19 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 196608 ? + return type.flags & 393216 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 65536)) { - return getPropertiesOfType(unionType); + if (!(unionType.flags & 131072)) { + return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var memberType = types_2[_i]; - for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); @@ -24513,8 +25571,8 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 16384 ? getConstraintOfTypeParameter(type) : - type.flags & 524288 ? getConstraintOfIndexedAccess(type) : + return type.flags & 32768 ? getConstraintOfTypeParameter(type) : + type.flags & 1048576 ? getConstraintOfIndexedAccess(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { @@ -24530,13 +25588,13 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (540672 | 196608)) { + if (type.flags & (1081344 | 393216)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 262144) { + else if (type.flags & 524288) { return stringType; } return undefined; @@ -24564,29 +25622,29 @@ var ts; return result; } function computeBaseConstraint(t) { - if (t.flags & 16384) { + if (t.flags & 32768) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType ? constraint : constraint ? getBaseConstraint(constraint) : undefined; } - if (t.flags & 196608) { + if (t.flags & 393216) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_2 = types_4[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 131072 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 262144 && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 262144) { + if (t.flags & 524288) { return stringType; } - if (t.flags & 524288) { + if (t.flags & 1048576) { var transformed = getTransformedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); @@ -24605,39 +25663,56 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } function getApparentType(type) { - var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 ? globalStringType : + var t = type.flags & 1081344 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 262144 ? getApparentTypeOfIntersectionType(t) : + t.flags & 524322 ? globalStringType : t.flags & 84 ? globalNumberType : t.flags & 136 ? globalBooleanType : - t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : + t.flags & 1536 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 33554432 ? emptyObjectType : t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var types = containingType.types; - var isUnion = containingType.flags & 65536; + var isUnion = containingType.flags & 131072; var excludeModifiers = isUnion ? 24 : 0; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var current = types_5[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -24682,8 +25757,7 @@ var ts; } propTypes.push(type); } - var result = createSymbol(4 | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; + var result = createSymbol(4 | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; result.declarations = declarations; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -24706,7 +25780,7 @@ var ts; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -24720,13 +25794,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 196608) { + if (type.flags & 393216) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376) { + if (type.flags & 458752) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -24736,7 +25810,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376) { + if (type.flags & 458752) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -24752,7 +25826,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -24785,7 +25859,7 @@ var ts; } function isJSDocOptionalParameter(node) { if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 272) { + if (node.type && node.type.kind === 276) { return true; } var paramTags = ts.getJSDocParameterTags(node); @@ -24796,7 +25870,7 @@ var ts; return true; } if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 272; + return paramTag.typeExpression.type.kind === 276; } } } @@ -24849,29 +25923,33 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } } return minTypeArgumentCount; } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { if (!typeArguments) { typeArguments = []; } for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); } for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + defaultType = anyType; + } + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); } + typeArguments.length = typeParameters.length; } } return typeArguments; @@ -24901,7 +25979,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 173) { + if (param.type && param.type.kind === 174) { hasLiteralTypes = true; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || @@ -24912,35 +25990,46 @@ var ts; minArgumentCount = parameters.length; } } - if ((declaration.kind === 153 || declaration.kind === 154) && - !ts.hasDynamicName(declaration) && + if ((declaration.kind === 154 || declaration.kind === 155) && + !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 ? 154 : 153; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + var otherKind = declaration.kind === 154 ? 155 : 154; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 152 ? + var classType = declaration.kind === 153 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 ? + var typePredicate = declaration.type && declaration.type.kind === 159 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - var hasRestLikeParameter = ts.hasRestParameter(declaration); - if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { - hasRestLikeParameter = true; - var syntheticArgsSymbol = createSymbol(3, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - parameters.push(syntheticArgsSymbol); - } + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { + return false; + } + var syntheticArgsSymbol = createSymbol(3, "args"); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + if (lastParamVariadicType) { + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); @@ -24952,8 +26041,8 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154); + if (declaration.kind === 154 && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 155); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -24976,12 +26065,12 @@ var ts; return false; switch (node.kind) { case 71: - return node.escapedText === "arguments" && ts.isPartOfExpression(node); - case 149: - case 151: - case 153: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 150: + case 152: case 154: - return node.name.kind === 144 + case 155: + return node.name.kind === 145 && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); @@ -24995,20 +26084,20 @@ var ts; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 160: case 161: - case 228: - case 151: - case 150: + case 162: + case 229: case 152: - case 155: + case 151: + case 153: case 156: case 157: - case 153: + case 158: case 154: - case 186: + case 155: case 187: - case 273: + case 188: + case 277: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -25073,7 +26162,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 && type.target === globalArrayType) { + if (ts.getObjectFlags(type) & 4 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -25108,9 +26197,18 @@ var ts; function createCanonicalSignature(signature) { return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), true); + } + return signature; + } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; + var isConstructor = signature.declaration.kind === 153 || signature.declaration.kind === 157; var type = createObjectType(16); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -25151,7 +26249,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145).constraint; + return type.symbol && ts.getDeclarationOfKind(type.symbol, 146).constraint; } function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { @@ -25167,7 +26265,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 146).parent); } function getTypeListId(types) { var result = ""; @@ -25194,13 +26292,13 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } } - return result & 14680064; + return result & 29360128; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -25231,14 +26329,24 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJavascript = ts.isInJavaScriptFile(node); - if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); - return unknownType; + var isJs = ts.isInJavaScriptFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && node.parent.kind !== 282; + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, undefined, 1); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + return unknownType; + } } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25278,18 +26386,11 @@ var ts; } return type; } - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } function getTypeReferenceName(node) { switch (node.kind) { - case 159: + case 160: return node.typeName; - case 201: + case 202: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -25312,18 +26413,26 @@ var ts; if (type) { return type; } - if (symbol.flags & 107455 && isJSDocTypeReference(node)) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res !== undefined) { + if (typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return res; + } + if (!(symbol.flags & 107455 && isJSDocTypeReference(node))) { + return unknownType; + } + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; } - resolveTypeReferenceName(getTypeReferenceName(node), 793064); - return valueType; } - return getTypeFromNonGenericTypeReference(node, symbol); + resolveTypeReferenceName(getTypeReferenceName(node), 793064); + return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 | 64)) { @@ -25339,18 +26448,16 @@ var ts; } } function isJSDocTypeReference(node) { - return node.flags & 1048576 && node.kind === 159; + return node.flags & 1048576 && node.kind === 160; } function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -25381,7 +26488,7 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; + return strictNullChecks ? getNullableType(type, 8192) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); @@ -25418,9 +26525,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 229: case 230: - case 232: + case 231: + case 233: return declaration; } } @@ -25429,12 +26536,12 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + if (!(type.flags & 65536)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } return type; @@ -25533,12 +26640,15 @@ var ts; var typeParameters = []; var properties = []; for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); + var typeParameter = createType(32768); typeParameters.push(typeParameter); var property = createSymbol(4, "" + i); property.type = typeParameter; properties.push(property); } + var lengthSymbol = createSymbol(4, "length"); + lengthSymbol.type = getLiteralType(arity); + properties.push(lengthSymbol); var type = createObjectType(8 | 4); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; @@ -25547,7 +26657,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384); + type.thisType = createType(32768); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -25570,37 +26680,21 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; + function getTypeId(type) { + return type.id; } function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } function isEmptyIntersectionType(type) { var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6368 && combined & 6368) { + if (t.flags & 13536 && combined & 13536) { return true; } combined |= t.flags; - if (combined & 6144 && combined & (32768 | 16777216)) { + if (combined & 12288 && combined & (65536 | 33554432)) { return true; } } @@ -25608,31 +26702,33 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 65536) { + if (flags & 131072) { addTypesToUnion(typeSet, type.types); } else if (flags & 1) { typeSet.containsAny = true; } - else if (!strictNullChecks && flags & 6144) { - if (flags & 2048) - typeSet.containsUndefined = true; + else if (!strictNullChecks && flags & 12288) { if (flags & 4096) + typeSet.containsUndefined = true; + if (flags & 8192) typeSet.containsNull = true; - if (!(flags & 2097152)) + if (!(flags & 4194304)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 || flags & 131072 && isEmptyIntersectionType(type))) { + else if (!(flags & 16384 || flags & 262144 && isEmptyIntersectionType(type))) { if (flags & 2) typeSet.containsString = true; if (flags & 4) typeSet.containsNumber = true; - if (flags & 96) - typeSet.containsStringOrNumberLiteral = true; + if (flags & 512) + typeSet.containsESSymbol = true; + if (flags & 1120) + typeSet.containsLiteralOrUniqueESSymbol = true; var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 32768 && type.objectFlags & 16 && + if (!(flags & 65536 && type.objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } @@ -25640,24 +26736,26 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; if (isTypeIdenticalTo(t, type)) { return true; } } return false; } - function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - if (candidate !== type && isTypeSubtypeOf(candidate, type)) { + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || + !(ts.getObjectFlags(getTargetType(target)) & 1) || + isTypeDerivedFrom(source, target))) { return true; } } @@ -25696,7 +26794,8 @@ var ts; var t = types[i]; var remove = t.flags & 32 && types.containsString || t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); + t.flags & 1024 && types.containsESSymbol || + t.flags & 96 && t.flags & 2097152 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -25717,7 +26816,7 @@ var ts; if (subtypeReduction) { removeSubtypes(typeSet); } - else if (typeSet.containsStringOrNumberLiteral) { + else if (typeSet.containsLiteralOrUniqueESSymbol) { removeRedundantLiteralTypes(typeSet); } if (typeSet.length === 0) { @@ -25737,8 +26836,8 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = createType(65536 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, 12288); + type = createType(131072 | propagatedFlags); unionTypes.set(id, type); type.types = types; type.aliasSymbol = aliasSymbol; @@ -25754,26 +26853,26 @@ var ts; return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072) { + if (type.flags & 262144) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1) { typeSet.containsAny = true; } - else if (type.flags & 8192) { + else if (type.flags & 16384) { typeSet.containsNever = true; } - else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { + else if (ts.getObjectFlags(type) & 16 && isEmptyObjectType(type)) { typeSet.containsEmptyObject = true; } - else if ((strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768) { + else if ((strictNullChecks || !(type.flags & 12288)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536) { typeSet.containsObjectType = true; } - if (type.flags & 65536 && typeSet.unionIndex === undefined) { + if (type.flags & 131072 && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - if (!(type.flags & 32768 && type.objectFlags & 16 && + if (!(type.flags & 65536 && type.objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { typeSet.push(type); } @@ -25782,7 +26881,7 @@ var ts; function addTypesToIntersection(typeSet, types) { for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { var type = types_9[_i]; - addTypeToIntersection(typeSet, type); + addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -25811,8 +26910,8 @@ var ts; var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = createType(131072 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 12288); + type = createType(262144 | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; @@ -25829,7 +26928,7 @@ var ts; } function getIndexTypeForGenericType(type) { if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144); + type.resolvedIndexType = createType(524288); type.resolvedIndexType.type = type; } return type.resolvedIndexType; @@ -25837,40 +26936,48 @@ var ts; function getLiteralTypeFromPropertyName(prop) { return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? neverType : - getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + getLiteralType(ts.symbolName(prop)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + return maybeTypeOfKind(type, 1081344) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; + return indexType.flags & 16384 ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + switch (node.operator) { + case 127: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 140: + links.resolvedType = node.type.kind === 137 + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : unknownType; + break; + } } return links.resolvedType; } function createIndexedAccessType(objectType, indexType) { - var type = createType(524288); + var type = createType(1048576); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & 96 ? - ts.escapeLeadingUnderscores("" + indexType.value) : + var accessExpression = accessNode && accessNode.kind === 181 ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); @@ -25887,7 +26994,7 @@ var ts; return getTypeOfSymbol(prop); } } - if (!(indexType.flags & 6144) && isTypeAssignableToKind(indexType, 262178 | 84 | 512)) { + if (!(indexType.flags & 12288) && isTypeAssignableToKind(indexType, 524322 | 84 | 1536)) { if (isTypeAny(objectType)) { return anyType; } @@ -25913,7 +27020,7 @@ var ts; } } if (accessNode) { - var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = accessNode.kind === 181 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 | 64)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } @@ -25928,18 +27035,18 @@ var ts; return anyType; } function isGenericObjectType(type) { - return type.flags & 540672 ? true : - getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : - type.flags & 196608 ? ts.forEach(type.types, isGenericObjectType) : + return type.flags & 1081344 ? true : + ts.getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 393216 ? ts.forEach(type.types, isGenericObjectType) : false; } function isGenericIndexType(type) { - return type.flags & (540672 | 262144) ? true : - type.flags & 196608 ? ts.forEach(type.types, isGenericIndexType) : + return type.flags & (1081344 | 524288) ? true : + type.flags & 393216 ? ts.forEach(type.types, isGenericIndexType) : false; } function isStringIndexOnlyType(type) { - if (type.flags & 32768 && !isGenericMappedType(type)) { + if (type.flags & 65536 && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && @@ -25949,7 +27056,7 @@ var ts; } function getTransformedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 131072 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + if (objectType.flags & 262144 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { @@ -25975,7 +27082,7 @@ var ts; return undefined; } function getIndexedAccessType(objectType, indexType, accessNode) { - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; } @@ -25987,7 +27094,7 @@ var ts; return type; } var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8)) { + if (indexType.flags & 131072 && !(indexType.flags & 8)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -26024,7 +27131,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { links.resolvedType = emptyTypeLiteralType; } else { @@ -26040,32 +27147,32 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; + return node.parent.kind === 232 ? getSymbolOfNode(node.parent) : undefined; } function getAliasTypeArgumentsForTypeNode(node) { var symbol = getAliasSymbolForTypeNode(node); return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 || right.flags & 1) { return anyType; } - if (left.flags & 8192) { + if (left.flags & 16384) { return right; } - if (right.flags & 8192) { + if (right.flags & 16384) { return left; } - if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + if (left.flags & 131072) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } - if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + if (right.flags & 131072) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 16777216) { + if (right.flags & 33554432) { return nonPrimitiveType; } - if (right.flags & (136 | 84 | 262178 | 272)) { + if (right.flags & (136 | 84 | 524322 | 272)) { return left; } var members = ts.createSymbolTable(); @@ -26115,7 +27222,11 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= propagatedFlags; + spread.flags |= 2097152 | 8388608; + spread.objectFlags |= (128 | 1024); + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -26128,6 +27239,12 @@ var ts; result.syntheticOrigin = prop; return result; } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, false, index.declaration); + } + return index; + } function isClassMethod(prop) { return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } @@ -26138,9 +27255,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 && !(type.flags & 1048576)) { + if (type.flags & 96 && !(type.flags & 2097152)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 2097152, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -26149,7 +27266,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; + return type.flags & 96 && type.flags & 2097152 ? type.regularType : type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : "@"; @@ -26168,20 +27285,25 @@ var ts; } return links.resolvedType; } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; + function createUniqueESSymbolType(symbol) { + var type = createType(1024); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.type || (links.type = createUniqueESSymbolType(symbol)); } - return links.resolvedType; + return esSymbolType; } function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 231)) { if (!ts.hasModifier(container, 32) && - (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 153 || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -26198,8 +27320,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119: - case 268: - case 269: + case 272: + case 273: return anyType; case 136: return stringType; @@ -26219,52 +27341,52 @@ var ts; return neverType; case 134: return node.flags & 65536 ? anyType : nonPrimitiveType; - case 169: + case 170: case 99: return getTypeFromThisTypeNode(node); - case 173: + case 174: return getTypeFromLiteralTypeNode(node); - case 159: + case 160: return getTypeFromTypeReference(node); - case 158: + case 159: return booleanType; - case 201: + case 202: return getTypeFromTypeReference(node); - case 162: + case 163: return getTypeFromTypeQueryNode(node); - case 164: - return getTypeFromArrayTypeNode(node); case 165: - return getTypeFromTupleTypeNode(node); + return getTypeFromArrayTypeNode(node); case 166: - return getTypeFromUnionTypeNode(node); + return getTypeFromTupleTypeNode(node); case 167: + return getTypeFromUnionTypeNode(node); + case 168: return getTypeFromIntersectionTypeNode(node); - case 270: + case 274: return getTypeFromJSDocNullableTypeNode(node); - case 168: + case 169: + case 275: + case 276: case 271: - case 272: - case 267: return getTypeFromTypeNode(node.type); - case 160: + case 278: + return getTypeFromJSDocVariadicType(node); case 161: - case 163: - case 285: - case 273: + case 162: + case 164: + case 280: + case 277: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170: - return getTypeFromTypeOperatorNode(node); case 171: - return getTypeFromIndexedAccessTypeNode(node); + return getTypeFromTypeOperatorNode(node); case 172: + return getTypeFromIndexedAccessTypeNode(node); + case 173: return getTypeFromMappedTypeNode(node); case 71: - case 143: + case 144: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 274: - return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -26329,7 +27451,7 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { - var result = createType(16384); + var result = createType(32768); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -26375,8 +27497,7 @@ var ts; symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(symbol.flags, symbol.escapedName); - result.checkFlags = 1; + var result = createSymbol(symbol.flags, symbol.escapedName, 1); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -26398,7 +27519,7 @@ var ts; var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -26420,20 +27541,31 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 208 ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 170: + return tp.isThisType; + case 71: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 163: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144) { + if (constraintType.flags & 524288) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384) { + if (typeVariable_1.flags & 32768) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -26448,7 +27580,7 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (16384 | 32768 | 131072 | 524288); + return type.flags & (1 | 32768 | 65536 | 262144 | 1048576); } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64, type.symbol); @@ -26463,10 +27595,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { + if (type.flags & 32768) { return mapper(type); } - if (type.flags & 32768) { + if (type.flags & 65536) { if (type.objectFlags & 16) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? getAnonymousTypeInstantiation(type, mapper) : type; @@ -26478,16 +27610,16 @@ var ts; return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } - if (type.flags & 65536 && !(type.flags & 8190)) { + if (type.flags & 131072 && !(type.flags & 16382)) { return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 131072) { + if (type.flags & 262144) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 262144) { + if (type.flags & 524288) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 524288) { + if (type.flags & 1048576) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } @@ -26497,31 +27629,31 @@ var ts; return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 186: case 187: - case 151: + case 188: + case 152: return isContextSensitiveFunctionLikeDeclaration(node); - case 178: + case 179: return ts.forEach(node.properties, isContextSensitive); - case 177: + case 178: return ts.forEach(node.elements, isContextSensitive); - case 195: + case 196: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 194: + case 195: return node.operatorToken.kind === 54 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261: + case 265: return isContextSensitive(node.initializer); - case 185: + case 186: return isContextSensitive(node.expression); - case 254: + case 258: return ts.forEach(node.properties, isContextSensitive); - case 253: + case 257: return node.initializer && isContextSensitive(node.initializer); - case 256: + case 260: return node.expression && isContextSensitive(node.expression); } return false; @@ -26533,19 +27665,19 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 187) { + if (node.kind !== 188) { var parameter = ts.firstOrUndefined(node.parameters); if (!(parameter && ts.parameterIsThisKeyword(parameter))) { return true; } } - return node.body.kind === 207 ? false : isContextSensitive(node.body); + return node.body.kind === 208 ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(16, type.symbol); @@ -26556,7 +27688,7 @@ var ts; return result; } } - else if (type.flags & 131072) { + else if (type.flags & 262144) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -26576,8 +27708,12 @@ var ts; function isTypeAssignableTo(source, target) { return isTypeRelatedTo(source, target, assignableRelation); } - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + function isTypeDerivedFrom(source, target) { + return source.flags & 131072 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 131072 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 1081344 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + hasBaseType(source, getTargetType(target)); } function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); @@ -26592,9 +27728,9 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { if (source === target) { return -1; } @@ -26605,12 +27741,15 @@ var ts; target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } + var kind = target.declaration ? target.declaration.kind : 0; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 152 && + kind !== 151 && kind !== 153; var result = -1; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { var targetThisType = getThisTypeOfSignature(target); if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType, false) + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, false) || compareTypes(targetThisType, sourceThisType, reportErrors); if (!related) { if (reportErrors) { @@ -26629,16 +27768,16 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); + (getFalsyFlags(sourceType) & 12288) === (getFalsyFlags(targetType) & 12288); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); } return 0; } @@ -26662,7 +27801,7 @@ var ts; } } else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + result &= callbackCheck === 1 && compareTypes(targetReturnType, sourceReturnType, false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -26736,10 +27875,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 ? true : - type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 65536 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 33554432 ? true : + type.flags & 131072 ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 262144 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -26762,7 +27901,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); } enumRelation.set(id, false); return false; @@ -26775,11 +27914,11 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 8192) - return false; - if (t & 1 || s & 8192) + if (t & 1 || s & 16384) return true; - if (s & 262178 && t & 2) + if (t & 16384) + return false; + if (s & 524322 && t & 2) return true; if (s & 32 && s & 256 && t & 32 && !(t & 256) && @@ -26793,22 +27932,26 @@ var ts; return true; if (s & 136 && t & 8) return true; + if (s & 1536 && t & 512) + return true; if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 256 && t & 256) { - if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 131072 && t & 131072 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 224 && t & 224 && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) + if (s & 4096 && (!strictNullChecks || t & (4096 | 2048))) return true; - if (s & 4096 && (!strictNullChecks || t & 4096)) + if (s & 8192 && (!strictNullChecks || t & 8192)) return true; - if (s & 32768 && t & 16777216) + if (s & 65536 && t & 33554432) return true; + if (s & 1024 || t & 1024) + return false; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1) return true; @@ -26818,22 +27961,24 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 1048576) { + if (source.flags & 96 && source.flags & 2097152) { source = source.regularType; } - if (target.flags & 96 && target.flags & 1048576) { + if (target.flags & 96 && target.flags & 2097152) { target = target.regularType; } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + if (source === target || + relation === comparableRelation && !(target.flags & 16384) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 32768 && target.flags & 32768) { + if (source.flags & 65536 && target.flags & 65536) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1; } } - if (source.flags & 1032192 || target.flags & 1032192) { + if (source.flags & 2064384 || target.flags & 2064384) { return checkTypeRelatedTo(source, target, relation, undefined); } return false; @@ -26845,13 +27990,6 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var ExpandingFlags; - (function (ExpandingFlags) { - ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; - ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; - ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; - ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; - })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0; var overflow = false; var isIntersectionConstituent = false; @@ -26902,13 +28040,13 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608)) { + if (!(type.flags & 393216)) { return false; } var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6144) { + if (t.flags & 12288) { continue; } if (seenNonNullable) { @@ -26919,10 +28057,10 @@ var ts; return false; } function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 && source.flags & 1048576) { + if (source.flags & 96 && source.flags & 2097152) { source = source.regularType; } - if (target.flags & 96 && target.flags & 1048576) { + if (target.flags & 96 && target.flags & 2097152) { target = target.regularType; } if (source === target) @@ -26930,9 +28068,10 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + if (relation === comparableRelation && !(target.flags & 16384) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - if (getObjectFlags(source) & 128 && source.flags & 1048576) { + if (isObjectLiteralType(source) && source.flags & 2097152) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -26944,13 +28083,11 @@ var ts; } } if (relation !== comparableRelation && - !(source.flags & 196608) && - !(target.flags & 65536) && + !(source.flags & 393216) && + !(target.flags & 131072) && !isIntersectionConstituent && source !== globalObjectType && - (getPropertiesOfType(source).length > 0 || - getSignaturesOfType(source, 0).length > 0 || - getSignaturesOfType(source, 1).length > 0) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { @@ -26970,23 +28107,23 @@ var ts; var saveErrorInfo = errorInfo; var saveIsIntersectionConstituent = isIntersectionConstituent; isIntersectionConstituent = false; - if (source.flags & 65536) { + if (source.flags & 131072) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382)); } else { - if (target.flags & 65536) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190)); + if (target.flags & 131072) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382) && !(target.flags & 16382)); } - else if (target.flags & 131072) { + else if (target.flags & 262144) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 131072) { + else if (source.flags & 262144) { result = someTypeRelatedToType(source, target, false); } - if (!result && (source.flags & 1032192 || target.flags & 1032192)) { + if (!result && (source.flags & 2064384 || target.flags & 2064384)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } @@ -26994,10 +28131,10 @@ var ts; } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 32768 && target.flags & 8190) { + if (source.flags & 65536 && target.flags & 16382) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 32768 && globalObjectType === source) { + else if (source.symbol && source.flags & 65536 && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -27006,11 +28143,11 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 32768 && target.flags & 32768) { + if (source.flags & 65536 && target.flags & 65536) { return recursiveTypeRelatedTo(source, target, false); } - if (source.flags & 65536 && target.flags & 65536 || - source.flags & 131072 && target.flags & 131072) { + if (source.flags & 131072 && target.flags & 131072 || + source.flags & 262144 && target.flags & 262144) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; @@ -27020,12 +28157,18 @@ var ts; return 0; } function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { - var isComparingJsxAttributes = !!(source.flags & 33554432); + if (maybeTypeOfKind(target, 65536) && !(ts.getObjectFlags(target) & 512)) { + var isComparingJsxAttributes = !!(source.flags & 67108864); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 131072) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -27045,7 +28188,7 @@ var ts; } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); } else { reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); @@ -27079,7 +28222,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 65536 && containsType(targetTypes, source)) { + if (target.flags & 131072 && containsType(targetTypes, source)) { return -1; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -27096,22 +28239,30 @@ var ts; return 0; } function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { + var sourceProperty = sourcePropertiesFiltered_1[_i]; var sourceType = getTypeOfSymbol(sourceProperty); for (var _a = 0, _b = target.types; _a < _b.length; _a++) { var type = _b[_a]; var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); if (targetType && isRelatedTo(sourceType, targetType)) { - return type; + if (type === match) + continue; + if (match) { + return undefined; + } + match = type; } } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; @@ -27128,7 +28279,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 65536 && containsType(sourceTypes, target)) { + if (source.flags & 131072 && containsType(sourceTypes, target)) { return -1; } var len = sourceTypes.length; @@ -27153,7 +28304,7 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, reportErrors) { + function typeArgumentsRelatedTo(source, target, variances, reportErrors) { var sources = source.typeArguments || ts.emptyArray; var targets = target.typeArguments || ts.emptyArray; if (sources.length !== targets.length && relation === identityRelation) { @@ -27162,11 +28313,34 @@ var ts; var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1; for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0; + var variance = i < variances.length ? variances[i] : 1; + if (variance !== 4) { + var s = sources[i]; + var t = targets[i]; + var related = -1; + if (variance === 1) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3) { + related = isRelatedTo(t, s, false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0; + } + result &= related; } - result &= related; } return result; } @@ -27230,9 +28404,10 @@ var ts; } function structuredTypeRelatedTo(source, target, reportErrors) { var result; + var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 16384) { - if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (target.flags & 32768) { + if (ts.getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -27242,8 +28417,8 @@ var ts; } } } - else if (target.flags & 262144) { - if (source.flags & 262144) { + else if (target.flags & 524288) { + if (source.flags & 524288) { if (result = isRelatedTo(target.type, source.type, false)) { return result; } @@ -27255,7 +28430,7 @@ var ts; } } } - else if (target.flags & 524288) { + else if (target.flags & 1048576) { var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -27264,31 +28439,28 @@ var ts; } } } - if (source.flags & 16384) { - if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + else if (isGenericMappedType(target) && !isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + if (source.flags & 32768) { + var constraint = getConstraintOfTypeParameter(source); + if (constraint || !(target.flags & 33554432)) { + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; } } - else { - var constraint = getConstraintOfTypeParameter(source); - if (constraint || !(target.flags & 16777216)) { - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; - } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } } - else if (source.flags & 524288) { + else if (source.flags & 1048576) { var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -27296,23 +28468,33 @@ var ts; return result; } } - else if (target.flags & 524288 && source.indexType === target.indexType) { + else if (target.flags & 1048576 && source.indexType === target.indexType) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } else { - if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && + !(source.flags & 134217728 || target.flags & 134217728)) { + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { return result; } + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + if (!(reportErrors && ts.some(variances, function (v) { return v === 0; }))) { + return 0; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } } - var sourceIsPrimitive = !!(source.flags & 8190); + var sourceIsPrimitive = !!(source.flags & 16382); if (relation !== identityRelation) { source = getApparentType(source); } - if (source.flags & (32768 | 131072) && target.flags & 32768) { + if (source.flags & (65536 | 262144) && target.flags & 65536) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { result = -1; @@ -27336,26 +28518,25 @@ var ts; } } if (result) { - errorInfo = saveErrorInfo; - return result; + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; } } } return 0; } function mappedTypeRelatedTo(source, target, reportErrors) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + !(getCombinedMappedTypeModifiers(source) & 2) || + getCombinedMappedTypeModifiers(target) & 2); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_1; + if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -27364,7 +28545,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -27372,10 +28553,24 @@ var ts; } return 0; } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0; + } + } + } + } var result = -1; var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { + var targetProp = properties_3[_b]; if (!(targetProp.flags & 4194304)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -27434,20 +28629,20 @@ var ts; return result; } function isWeakType(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); } - if (type.flags & 131072) { + if (type.flags & 262144) { return ts.every(type.types, isWeakType); } return false; } function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(source.flags & 33554432); + var isComparingJsxAttributes = !!(source.flags & 67108864); for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { @@ -27457,7 +28652,7 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 && target.flags & 32768)) { + if (!(source.flags & 65536 && target.flags & 65536)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -27466,8 +28661,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0; @@ -27490,7 +28685,7 @@ var ts; var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); if (kind === 1 && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { if (reportErrors) { reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); } @@ -27502,7 +28697,7 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + if (ts.getObjectFlags(source) & 64 && ts.getObjectFlags(target) & 64 && source.symbol === target.symbol) { for (var i = 0; i < targetSignatures.length; i++) { var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], true, reportErrors); if (!related) { @@ -27538,7 +28733,7 @@ var ts; return result; } function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0, false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -27596,7 +28791,7 @@ var ts; if (isGenericMappedType(source)) { return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1; if (kind === 0) { var sourceNumberInfo = getIndexInfoOfType(source, 1); @@ -27646,11 +28841,53 @@ var ts; return false; } } + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.flags |= 134217728; + return result; + } + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + var typeParameters = type.typeParameters || ts.emptyArray; + var variances = type.variances; + if (!variances) { + if (type === globalArrayType || type === globalReadonlyArrayType) { + variances = [1]; + } + else { + type.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); + var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 : 0); + if (variance === 3 && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { + variance = 4; + } + variances.push(variance); + } + } + type.variances = variances; + } + return variances; + } + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 && type.typeArguments[i].flags & 2048) { + return true; + } + } + return false; + } function isUnconstrainedTypeParameter(type) { - return type.flags & 16384 && !getConstraintFromTypeParameter(type); + return type.flags & 32768 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return ts.getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } function getTypeReferenceId(type, typeParameters, depth) { if (depth === void 0) { depth = 0; } @@ -27717,26 +28954,14 @@ var ts; return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.hasModifier(declaration, 128)) { - return true; - } - } - } - return false; - } function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 32768) { + if (depth >= 5 && type.flags & 65536) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 32768 && t.symbol === symbol) { + if (t.flags & 65536 && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -27854,27 +29079,34 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288) : getUnionType(types, true); } + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } function isArrayType(type) { - return getObjectFlags(type) & 4 && type.target === globalArrayType; + return ts.getObjectFlags(type) & 4 && type.target === globalArrayType; } function isArrayLikeType(type) { - return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 12288) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return !!(type.flags & 6368); + return !!(type.flags & 13536); } function isLiteralType(type) { return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 131072 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -27882,19 +29114,30 @@ var ts; type.flags & 32 ? stringType : type.flags & 64 ? numberType : type.flags & 128 ? booleanType : - type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : + type.flags & 32 && type.flags & 2097152 ? stringType : + type.flags & 64 && type.flags & 2097152 ? numberType : type.flags & 128 ? booleanType : - type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 1024 ? esSymbolType : + type.flags & 131072 ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } function isTupleType(type) { - return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); + return !!(ts.getObjectFlags(type) & 4 && type.target.objectFlags & 8); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -27905,15 +29148,15 @@ var ts; return result; } function getFalsyFlags(type) { - return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 131072 ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 ? type.value === "" ? 32 : 0 : type.flags & 64 ? type.value === 0 ? 64 : 0 : type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; + type.flags & 14574; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : + return getFalsyFlags(type) & 14560 ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 14560); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -27923,25 +29166,28 @@ var ts; return type.flags & 2 ? emptyStringType : type.flags & 4 ? zeroType : type.flags & 8 || type === falseType ? falseType : - type.flags & (1024 | 2048 | 4096) || + type.flags & (2048 | 4096 | 8192) || type.flags & 32 && type.value === "" || type.flags & 64 && type.value === 0 ? type : neverType; } function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (2048 | 4096); + var missing = (flags & ~type.flags) & (4096 | 8192); return missing === 0 ? type : - missing === 2048 ? getUnionType([type, undefinedType]) : - missing === 4096 ? getUnionType([type, nullType]) : + missing === 4096 ? getUnionType([type, undefinedType]) : + missing === 8192 ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 4096 ? type : getUnionType([type, undefinedType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && - getSignaturesOfType(type, 0).length === 0 && - getSignaturesOfType(type, 1).length === 0; + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048 | 512)) !== 0 && + !typeHasCallOrConstructSignatures(type); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName); @@ -27965,7 +29211,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { + if (!(isObjectLiteralType(type) && type.flags & 2097152)) { return type; } var regularType = type.regularType; @@ -27975,39 +29221,97 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; + regularNew.flags = resolved.flags & ~2097152; regularNew.objectFlags |= 128; type.regularType = regularNew; return regularNew; } - function getWidenedProperty(prop) { + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertyNamesOfContext(context) { + if (!context.resolvedPropertyNames) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, true); + } + } + } + context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + } + return context.resolvedPropertyNames; + } + function getWidenedProperty(prop, context) { var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); + var propContext = context && createWideningContext(context, prop.escapedName, undefined); + var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getWidenedTypeOfObjectLiteral(type) { + function getUndefinedProperty(name) { + var cached = undefinedProperties.get(name); + if (cached) { + return cached; + } + var result = createSymbol(4 | 16777216, name); + result.type = undefinedType; + undefinedProperties.set(name, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; - members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop) : prop); + members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop, context) : prop); + } + if (context) { + for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { + var name = _c[_b]; + if (!members.has(name)) { + members.set(name, getUndefinedProperty(name)); + } + } } var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } - function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); - } function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 6144) { + return getWidenedTypeWithContext(type, undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 12582912) { + if (type.flags & 12288) { return anyType; } - if (getObjectFlags(type) & 128) { - return getWidenedTypeOfObjectLiteral(type); + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 65536) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + if (type.flags & 131072) { + var unionContext_1 = context || createWideningContext(undefined, undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 ? t : getWidenedTypeWithContext(t, unionContext_1); }); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -28017,31 +29321,38 @@ var ts; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 65536) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { + if (type.flags & 4194304) { + if (type.flags & 131072) { + if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } } } - } - if (getObjectFlags(type) & 128) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 4194304) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.symbolName(p), typeToString(getWidenedType(t))); + } + errorReported = true; } - errorReported = true; } } } @@ -28051,25 +29362,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 150: case 149: - case 148: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 146: + case 147: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 176: + case 177: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 228: + case 229: + case 152: case 151: - case 150: - case 153: case 154: - case 186: + case 155: case 187: + case 188: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -28082,7 +29393,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { + if (produceDiagnostics && noImplicitAny && type.flags & 4194304) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -28147,12 +29458,12 @@ var ts; }; } function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & (540672 | 262144) || + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & (1081344 | 524288) || objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || objectFlags & 32 || - type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 393216 && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -28161,9 +29472,27 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 393216 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - function inferTypeForHomomorphicMappedType(source, target) { + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 32)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4, name); + literalProp.type = emptyObjectType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 2 ? createIndexInfo(emptyObjectType, false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + } + function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { var properties = getPropertiesOfType(source); var indexInfo = getIndexInfoOfType(source, 0); if (properties.length === 0 && !indexInfo) { @@ -28178,32 +29507,28 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); - if (!inferredPropType) { + var propType = getTypeOfSymbol(prop); + if (propType.flags & 16777216) { return undefined; } - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; + inferredProp.type = inferTargetType(propType); members.set(prop.escapedName, inferredProp); } if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); } return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); function inferTargetType(sourceType) { inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType); - return inference.candidates && getUnionType(inference.candidates, true); + inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); + return inference.candidates ? getUnionType(inference.candidates, true) : emptyObjectType; } } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = getPropertiesOfObjectType(target); + var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; if (requireOptionalProperties || !(targetProp.flags & 16777216)) { @@ -28215,7 +29540,7 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; @@ -28232,8 +29557,8 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || - source.flags & 131072 && target.flags & 131072) { + if (source.flags & 131072 && target.flags & 131072 && !(source.flags & 256 && target.flags & 256) || + source.flags & 262144 && target.flags & 262144) { if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -28260,43 +29585,58 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 540672) { - if (source.flags & 8388608 || source === silentNeverType) { + if (target.flags & 1081344) { + if (source.flags & 16777216 || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - if (!inference.candidates || priority < inference.priority) { + var p = priority | (source === implicitNeverType ? 16 : 0); + if (!inference.candidates || p < inference.priority) { inference.candidates = [source]; - inference.priority = priority; + inference.priority = p; } - else if (priority === inference.priority) { + else if (p === inference.priority) { inference.candidates.push(source); } - if (!(priority & 4) && target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(p & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + else if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); + if (i < variances.length && variances[i] === 2) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } } } - else if (source.flags & 262144 && target.flags & 262144) { + else if (source.flags & 524288 && target.flags & 524288) { + priority ^= 1; inferFromTypes(source.type, target.type); + priority ^= 1; } - else if (source.flags & 524288 && target.flags & 524288) { + else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + priority ^= 1; + inferFromTypes(empty, target.type); + priority ^= 1; + } + else if (source.flags & 1048576 && target.flags & 1048576) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (target.flags & 196608) { + else if (target.flags & 393216) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -28312,12 +29652,12 @@ var ts; } if (typeVariableCount === 1) { var savePriority = priority; - priority |= 1; + priority |= 2; inferFromTypes(source, typeVariable); priority = savePriority; } } - else if (source.flags & 65536) { + else if (source.flags & 131072) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -28326,14 +29666,14 @@ var ts; } else { source = getApparentType(source); - if (source.flags & (32768 | 131072)) { + if (source.flags & (65536 | 262144)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; } (visited || (visited = ts.createMap())).set(key, true); - var isNonConstructorObject = target.flags & 32768 && - !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + var isNonConstructorObject = target.flags & 65536 && + !(ts.getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (ts.contains(symbolStack, symbol)) { @@ -28349,8 +29689,18 @@ var ts; } } } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes) { + priority ^= 1; + inferFromTypes(source, target); + priority ^= 1; + } + else { + inferFromTypes(source, target); + } + } function getInferenceInfoForType(type) { - if (type.flags & 540672) { + if (type.flags & 1081344) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -28365,22 +29715,28 @@ var ts; inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); } - if (getObjectFlags(target) & 32) { + if (ts.getObjectFlags(target) & 32) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144) { + if (constraintType.flags & 524288) { var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); + var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); + if (ts.contains(mappedTypeStack, key)) { + return; + } + (mappedTypeStack || (mappedTypeStack = [])).push(key); + var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); + mappedTypeStack.pop(); if (inferredType) { var savePriority = priority; - priority |= 2; + priority |= 4; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } } return; } - if (constraintType.flags & 16384) { + if (constraintType.flags & 32768) { inferFromTypes(getIndexType(source), constraintType); inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; @@ -28410,11 +29766,11 @@ var ts; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); } } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromContravariantTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -28459,25 +29815,40 @@ var ts; reducedTypes.push(t); } } - return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 131072 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 | 262144); + return constraint && maybeTypeOfKind(constraint, 16382 | 524288); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, true)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; } function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; if (!inferredType) { if (inference.candidates) { + var candidates = widenObjectLiteralCandidates(inference.candidates); var signature = context.signature; var widenLiteralTypes = inference.topLevel && !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; - var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? - getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unionOrSuperType); + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var unwidenedType = inference.priority & 1 ? getCommonSubtype(baseCandidates) : + context.flags & 1 || inference.priority & 8 ? getUnionType(baseCandidates, true) : + getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unwidenedType); } else if (context.flags & 2) { inferredType = silentNeverType; @@ -28491,12 +29862,13 @@ var ts; inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); } } + inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); } } } @@ -28521,7 +29893,7 @@ var ts; return links.resolvedSymbol; } function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 163 ? true : n.kind === 71 || n.kind === 144 ? false : "quit"; }); } function getFlowCacheKey(node) { if (node.kind === 71) { @@ -28531,13 +29903,13 @@ var ts; if (node.kind === 99) { return "0"; } - if (node.kind === 179) { + if (node.kind === 180) { var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + return key && key + "." + ts.idText(node.name); } - if (node.kind === 176) { + if (node.kind === 177) { var container = node.parent.parent; - var key = container.kind === 176 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 177 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -28545,12 +29917,12 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 174) { + if (element.parent.kind === 175) { var name = element.propertyName || element.name; switch (name.kind) { case 71: - return ts.unescapeLeadingUnderscores(name.escapedText); - case 144: + return ts.idText(name); + case 145: return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9: case 8: @@ -28567,26 +29939,26 @@ var ts; switch (source.kind) { case 71: return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 || target.kind === 176) && + (target.kind === 227 || target.kind === 177) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99: return target.kind === 99; case 97: return target.kind === 97; - case 179: - return target.kind === 179 && + case 180: + return target.kind === 180 && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 176: - if (target.kind !== 179) + case 177: + if (target.kind !== 180) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 176 && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 177 && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 226) { + if (source.parent.parent.kind === 227) { var maybeId = source.parent.parent.initializer; return maybeId && isMatchingReference(maybeId, t.expression); } @@ -28594,7 +29966,7 @@ var ts; return false; } function containsMatchingReference(source, target) { - while (source.kind === 179) { + while (source.kind === 180) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -28603,7 +29975,7 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 && + return target.kind === 180 && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -28611,14 +29983,14 @@ var ts; if (expr.kind === 71) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 179) { + if (expr.kind === 180) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536) { + if (type && type.flags & 131072) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { @@ -28629,6 +30001,20 @@ var ts; } return false; } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -28641,7 +30027,7 @@ var ts; } } } - if (callExpression.expression.kind === 179 && + if (callExpression.expression.kind === 180 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -28655,7 +30041,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536)) { + if (!(source.flags & 131072)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -28668,11 +30054,11 @@ var ts; } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 8192) { + if (assignedType.flags & 16384) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192)) { + if (!(reducedType.flags & 16384)) { return reducedType; } } @@ -28719,32 +30105,40 @@ var ts; type === falseType ? 3030404 : 1981828 : type === falseType ? 3145092 : 4193668; } - if (flags & 32768) { + if (flags & 65536) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 : 8376288 : strictNullChecks ? 6166480 : 8378320; } - if (flags & (1024 | 2048)) { + if (flags & (2048 | 4096)) { return 2457472; } - if (flags & 4096) { + if (flags & 8192) { return 2340752; } - if (flags & 512) { + if (flags & 1536) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 16777216) { + if (flags & 33554432) { return strictNullChecks ? 6166480 : 8378320; } - if (flags & 540672) { + if (flags & 1081344) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 196608) { + if (flags & 393216) { return getTypeFactsOfTypes(type.types); } return 8388607; } function getTypeWithFacts(type, include) { + if (type.flags & 1048576) { + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -28770,15 +30164,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 178 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 265 && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 && parent.parent.left === parent || - parent.parent.kind === 216 && parent.parent.initializer === parent; + return parent.parent.kind === 195 && parent.parent.left === parent || + parent.parent.kind === 217 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); @@ -28795,21 +30189,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 215: - return stringType; case 216: + return stringType; + case 217: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194: + case 195: return getAssignedTypeOfBinaryExpression(parent); - case 188: + case 189: return undefinedType; - case 177: + case 178: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198: + case 199: return getAssignedTypeOfSpreadExpression(parent); - case 261: + case 265: return getAssignedTypeOfPropertyAssignment(parent); - case 262: + case 266: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -28817,7 +30211,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 ? + var type = pattern.kind === 175 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : @@ -28832,35 +30226,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 215) { + if (node.parent.parent.kind === 216) { return stringType; } - if (node.parent.parent.kind === 216) { + if (node.parent.parent.kind === 217) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 226 ? + return node.kind === 227 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 226 || node.kind === 176 ? + return node.kind === 227 || node.kind === 177 ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 226 && node.initializer && + return node.kind === 227 && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 && node.parent.kind === 194 && + node.kind !== 177 && node.parent.kind === 195 && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 185: + case 186: return getReferenceCandidate(node.expression); - case 194: + case 195: switch (node.operatorToken.kind) { case 58: return getReferenceCandidate(node.left); @@ -28872,13 +30266,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 185 || - parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? + return parent.kind === 186 || + parent.kind === 195 && parent.operatorToken.kind === 58 && parent.left === node || + parent.kind === 195 && parent.operatorToken.kind === 26 && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 257) { + if (clause.kind === 261) { var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } @@ -28900,13 +30294,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 131072 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 131072 && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536) { + if (source.flags & 131072) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -28921,10 +30315,10 @@ var ts; return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + return type.flags & 131072 ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 65536) { + if (type.flags & 131072) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); @@ -28932,7 +30326,7 @@ var ts; return f(type) ? type : neverType; } function mapType(type, mapper) { - if (!(type.flags & 65536)) { + if (!(type.flags & 131072)) { return mapper(type); } var types = type.types; @@ -28991,9 +30385,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 8192 ? + return elementType.flags & 16384 ? autoArrayType : - createArrayType(elementType.flags & 65536 ? + createArrayType(elementType.flags & 131072 ? getUnionType(elementType.types, true) : elementType); } @@ -29001,17 +30395,17 @@ var ts; return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); } function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + return ts.getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; } function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? type.elementType : neverType; + return ts.getObjectFlags(type) & 256 ? type.elementType : neverType; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var t = types_15[_i]; - if (!(t.flags & 8192)) { - if (!(getObjectFlags(t) & 256)) { + if (!(t.flags & 16384)) { + if (!(ts.getObjectFlags(t) & 256)) { return false; } hasEvolvingArrayType = true; @@ -29027,11 +30421,11 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.escapedText === "length" || - parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 && + var isLengthPushOrUnshift = parent.kind === 180 && (parent.name.escapedText === "length" || + parent.parent.kind === 182 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 181 && parent.expression === root && - parent.parent.kind === 194 && + parent.parent.kind === 195 && parent.parent.operatorToken.kind === 58 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -29071,14 +30465,14 @@ var ts; if (flowAnalysisDisabled) { return unknownType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 35620607)) { return declaredType; } var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); sharedFlowCount = sharedFlowStart; - var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { + var resultType = ts.getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 204 && getTypeWithFacts(resultType, 524288).flags & 16384) { return declaredType; } return resultType; @@ -29140,7 +30534,7 @@ var ts; } else if (flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { + if (container && container !== flowContainer && reference.kind !== 180 && reference.kind !== 99) { flow = container.flowNode; continue; } @@ -29172,7 +30566,7 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 65536) { + if (declaredType.flags & 131072) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; @@ -29185,15 +30579,15 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 181 ? + var expr = node.kind === 182 ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { + if (ts.getObjectFlags(type) & 256) { var evolvedType_1 = type; - if (node.kind === 181) { + if (node.kind === 182) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -29215,7 +30609,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 8192) { + if (type.flags & 16384) { return flowType; } var assumeTrue = (flow.flags & 32) !== 0; @@ -29225,7 +30619,7 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 16384 ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -29317,8 +30711,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 179 && - computedType.flags & 65536 && + return expr.kind === 180 && + computedType.flags & 131072 && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -29351,10 +30745,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 && right_1.kind === 9) { + if (left_1.kind === 190 && right_1.kind === 9) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 189 && left_1.kind === 9) { + if (right_1.kind === 190 && left_1.kind === 9) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -29388,7 +30782,7 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144) { + if (valueType.flags & 12288) { if (!strictNullChecks) { return type; } @@ -29400,12 +30794,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 16810497) { + if (type.flags & 33620481) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 16384 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29424,13 +30818,13 @@ var ts; if (operator === 33 || operator === 35) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 65536)) { + if (assumeTrue && !(type.flags & 131072)) { var targetType = typeofTypesByName.get(literal.text); if (targetType) { if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 540672) { + if (type.flags & 1081344) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -29451,13 +30845,13 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : + var caseType = discriminantType.flags & 16384 ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 16384 ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); @@ -29484,10 +30878,10 @@ var ts; } if (!targetType) { var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2) { + if (ts.getObjectFlags(rightType) & 2) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (getObjectFlags(rightType) & 16) { + else if (ts.getObjectFlags(rightType) & 16) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -29495,7 +30889,7 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } return type; } @@ -29503,9 +30897,9 @@ var ts; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 65536) { + if (type.flags & 131072) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192)) { + if (!(assignableType.flags & 16384)) { return assignableType; } } @@ -29539,7 +30933,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { + if (invokedExpression.kind === 181 || invokedExpression.kind === 180) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -29557,15 +30951,15 @@ var ts; case 71: case 99: case 97: - case 179: + case 180: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181: + case 182: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185: + case 186: return narrowType(type, expr.expression, assumeTrue); - case 194: + case 195: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192: + case 193: if (expr.operator === 51) { return narrowType(type, expr.operand, !assumeTrue); } @@ -29580,7 +30974,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -29592,9 +30986,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 || - node.kind === 265 || - node.kind === 149; + node.kind === 235 || + node.kind === 269 || + node.kind === 150; }); } function isParameterAssigned(symbol) { @@ -29615,7 +31009,7 @@ var ts; if (node.kind === 71) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 147) { symbol.isAssigned = true; } } @@ -29629,20 +31023,20 @@ var ts; } function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 && + declaration.kind === 147 && declaration.initializer && - getFalsyFlags(declaredType) & 2048 && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); + getFalsyFlags(declaredType) & 4096 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; } function isApparentTypePosition(node) { var parent = node.parent; - return parent.kind === 179 || - parent.kind === 181 && parent.expression === node || - parent.kind === 180 && parent.expression === node; + return parent.kind === 180 || + parent.kind === 182 && parent.expression === node || + parent.kind === 181 && parent.expression === node; } function typeHasNullableConstraint(type) { - return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + return type.flags & 1081344 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } function getDeclaredOrApparentType(symbol, node) { var type = getTypeOfSymbol(symbol); @@ -29659,7 +31053,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 187) { + if (container.kind === 188) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256)) { @@ -29675,7 +31069,7 @@ var ts; var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; if (localOrExportSymbol.flags & 32) { - if (declaration.kind === 229 + if (declaration.kind === 230 && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -29687,11 +31081,11 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 199) { + else if (declaration.kind === 200) { var container = ts.getThisContainer(node, false); while (container !== undefined) { if (container.parent === declaration) { - if (container.kind === 149 && ts.hasModifier(container, 32)) { + if (container.kind === 150 && ts.hasModifier(container, 32)) { getNodeLinks(declaration).flags |= 8388608; getNodeLinks(node).flags |= 16777216; } @@ -29732,22 +31126,24 @@ var ts; if (!declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 146; + var isParameter = ts.getRootDeclaration(declaration).kind === 147; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || - flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 187 || + flowContainer.kind === 188 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } var assumeInitialized = isParameter || isAlias || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || - node.parent.kind === 203 || - ts.isInAmbientContext(declaration); + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || + isInTypeQuery(node) || node.parent.kind === 247) || + node.parent.kind === 204 || + declaration.kind === 227 && declaration.exclamationToken || + declaration.flags & 2097152; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048); + getOptionalType(type); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { @@ -29758,7 +31154,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 4096) && getFalsyFlags(flowType) & 4096) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -29770,7 +31166,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 260) { + symbol.valueDeclaration.parent.kind === 264) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -29788,8 +31184,8 @@ var ts; if (usedInFunction) { getNodeLinks(current).flags |= 65536; } - if (container.kind === 214 && - ts.getAncestor(symbol.valueDeclaration, 227).parent === container && + if (container.kind === 215 && + ts.getAncestor(symbol.valueDeclaration, 228).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152; } @@ -29801,14 +31197,14 @@ var ts; } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 185) { + while (current.parent.kind === 186) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 192 || current.parent.kind === 193)) { + else if ((current.parent.kind === 193 || current.parent.kind === 194)) { var expr = current.parent; isAssigned = expr.operator === 43 || expr.operator === 44; } @@ -29819,7 +31215,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 149 || container.kind === 152) { + if (container.kind === 150 || container.kind === 153) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -29863,32 +31259,32 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 152) { + if (container.kind === 153) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 187) { + if (container.kind === 188) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 233: + case 234: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 232: + case 233: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 152: + case 153: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; + case 150: case 149: - case 148: if (ts.hasModifier(container, 32)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 144: + case 145: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -29897,8 +31293,8 @@ var ts; } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 186 && - container.parent.kind === 194 && + if (container.kind === 187 && + container.parent.kind === 195 && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { var className = container.parent .left @@ -29932,7 +31328,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 273) { + if (jsdocType && jsdocType.kind === 277) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -29942,14 +31338,14 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 147; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 182 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 187) { + while (container && container.kind === 188) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -29957,14 +31353,14 @@ var ts; var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); - if (current && current.kind === 144) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 145; }); + if (current && current.kind === 145) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 179)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -29972,7 +31368,7 @@ var ts; } return unknownType; } - if (!isCallExpression && container.kind === 152) { + if (!isCallExpression && container.kind === 153) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32) || isCallExpression) { @@ -29982,7 +31378,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.hasModifier(container, 256)) { + if (container.kind === 152 && ts.hasModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -29993,7 +31389,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 178) { + if (container.parent.kind === 179) { if (languageVersion < 2) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -30003,15 +31399,16 @@ var ts; } } var classLikeDeclaration = container.parent; + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return unknownType; + } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } return unknownType; } - if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 153 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -30023,24 +31420,24 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 152; + return container.kind === 153; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 178) { + if (ts.isClassLike(container.parent) || container.parent.kind === 179) { if (ts.hasModifier(container, 32)) { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154; + return container.kind === 152 || + container.kind === 151 || + container.kind === 154 || + container.kind === 155; } else { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || + return container.kind === 152 || + container.kind === 151 || container.kind === 154 || + container.kind === 155 || + container.kind === 150 || container.kind === 149 || - container.kind === 148 || - container.kind === 152; + container.kind === 153; } } } @@ -30048,22 +31445,22 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 151 || - func.kind === 153 || - func.kind === 154) && func.parent.kind === 178 ? func.parent : - func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : + return (func.kind === 152 || + func.kind === 154 || + func.kind === 155) && func.parent.kind === 179 ? func.parent : + func.kind === 187 && func.parent.kind === 265 ? func.parent.parent : undefined; } function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + return ts.getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 262144 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 187) { + if (func.kind === 188) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -30087,7 +31484,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 261) { + if (literal.parent.kind !== 265) { break; } literal = literal.parent.parent; @@ -30096,9 +31493,9 @@ var ts; return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } var parent = func.parent; - if (parent.kind === 194 && parent.operatorToken.kind === 58) { + if (parent.kind === 195 && parent.operatorToken.kind === 58) { var target = parent.left; - if (target.kind === 179 || target.kind === 180) { + if (target.kind === 180 || target.kind === 181) { var expression = target.expression; if (inJs && ts.isIdentifier(expression)) { var sourceFile = ts.getSourceFileOfNode(parent); @@ -30139,6 +31536,10 @@ var ts; var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); + indexOfParameter -= 1; + } if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -30153,12 +31554,12 @@ var ts; } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer) { + if (node === declaration.initializer || node.kind === 58) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 146) { + if (declaration.kind === 147) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -30170,7 +31571,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176) { + if (parentDeclaration.kind !== 177) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -30211,16 +31612,20 @@ var ts; return undefined; } function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 && node.parent.initializer === node) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { return true; } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } node = node.parent; } return false; } function getContextualReturnType(functionDecl) { - if (functionDecl.kind === 152 || + if (functionDecl.kind === 153 || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); @@ -30241,39 +31646,51 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183) { + if (template.parent.kind === 184) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (ts.isAssignmentOperator(operator)) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 58: + return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + case 54: + var type = getContextualType(binaryExpression); + return !type && node === right ? getTypeOfExpression(left, true) : type; + case 53: + case 26: + return node === right ? getContextualType(binaryExpression) : undefined; + case 34: + case 32: + case 35: + case 33: + return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; + default: return undefined; - } - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } } - else if (operator === 54) { - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left, true); - } - return type; - } - else if (operator === 53 || operator === 26) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } + } + function isContextSensitiveAssignment(binaryExpression) { + var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + switch (kind) { + case 0: + return true; + case 5: + return !binaryExpression.left.symbol; + case 1: + case 2: + case 3: + case 4: + return false; + default: + ts.Debug.assertNever(kind); } - return undefined; } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 458752 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -30281,11 +31698,11 @@ var ts; return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 131072 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return undefined; } return getContextualTypeForObjectLiteralElement(node); @@ -30294,9 +31711,9 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { - if (!ts.hasDynamicName(element)) { - var symbolName = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (!hasNonBindableDynamicName(element)) { + var symbolName_1 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); if (propertyType) { return propertyType; } @@ -30318,7 +31735,12 @@ var ts; function getContextualTypeForJsxExpression(node) { var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? node.parent.parent : - node.parent.openingElement.attributes; + ts.isJsxElement(node.parent) ? + node.parent.openingElement.attributes : + undefined; + if (!jsxAttributes) { + return undefined; + } var attributesType = getContextualType(jsxAttributes); if (!attributesType || isTypeAny(attributesType)) { return undefined; @@ -30326,7 +31748,7 @@ var ts; if (ts.isJsxAttribute(node.parent)) { return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } - else if (node.parent.kind === 249) { + else if (node.parent.kind === 250) { var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } @@ -30347,11 +31769,39 @@ var ts; } } function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (!(contextualType && contextualType.flags & 131072 && ts.isObjectLiteralExpression(node))) { + return contextualType; + } + var match; + propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (!prop.symbol) + continue; + if (prop.kind !== 265) + continue; + if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = getTypeOfNode(prop.initializer); + for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); + if (targetType && checkTypeAssignableTo(discriminatingType, targetType, undefined)) { + if (match) { + if (type === match) + continue; + match = undefined; + break propLoop; + } + match = type; + } + } + } + } + return match || contextualType; } function getContextualType(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return undefined; } if (node.contextualType) { @@ -30359,52 +31809,61 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 226: - case 146: + case 227: + case 147: + case 150: case 149: - case 148: - case 176: + case 177: return getContextualTypeForInitializerExpression(node); - case 187: - case 219: + case 188: + case 220: return getContextualTypeForReturnExpression(node); - case 197: + case 198: return getContextualTypeForYieldOperand(parent); - case 181: + case 183: + if (node.kind === 94) { + return getContextualType(parent); + } case 182: return getContextualTypeForArgument(parent, node); - case 184: - case 202: + case 185: + case 203: return getTypeFromTypeNode(parent.type); - case 194: + case 195: return getContextualTypeForBinaryOperand(node); - case 261: - case 262: + case 265: + case 266: return getContextualTypeForObjectLiteralElement(parent); - case 263: + case 267: return getApparentTypeOfContextualType(parent.parent); - case 177: { + case 178: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 195: + case 196: return getContextualTypeForConditionalOperand(node); - case 205: - ts.Debug.assert(parent.parent.kind === 196); + case 206: + ts.Debug.assert(parent.parent.kind === 197); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: { + case 186: { var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 256: + case 260: return getContextualTypeForJsxExpression(parent); - case 253: - case 255: + case 257: + case 259: return getContextualTypeForJsxAttribute(parent); + case 252: case 251: - case 250: return getAttributesTypeFromJsxOpeningLikeElement(parent); + case 261: { + if (node.kind === 73) { + var switchStatement = parent.parent.parent; + return getTypeOfExpression(switchStatement.expression); + } + } } return undefined; } @@ -30436,7 +31895,7 @@ var ts; return sourceLength < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 || node.kind === 187; + return node.kind === 187 || node.kind === 188; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -30449,12 +31908,12 @@ var ts; getApparentTypeOfContextualType(node); } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 65536)) { + if (!(type.flags & 131072)) { return getContextualCallSignature(type, node); } var signatureList; @@ -30490,8 +31949,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); } function hasDefaultValue(node) { - return (node.kind === 176 && !!node.initializer) || - (node.kind === 194 && node.operatorToken.kind === 58); + return (node.kind === 177 && !!node.initializer) || + (node.kind === 195 && node.operatorToken.kind === 58); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; @@ -30501,7 +31960,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elements.length; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 198) { + if (inDestructuringPattern && e.kind === 199) { var restArrayType = checkExpression(e.expression, checkMode); var restElementType = getIndexTypeOfType(restArrayType, 1) || getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); @@ -30514,7 +31973,7 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 198; + hasSpreadElement = hasSpreadElement || e.kind === 199; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -30522,18 +31981,17 @@ var ts; type.pattern = node; return type; } - var contextualType_1 = getApparentTypeOfContextualType(node); - if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { - var pattern = contextualType_1.pattern; - if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + if (pattern && (pattern.kind === 176 || pattern.kind === 178)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType_1.typeArguments[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 200) { + if (patternElement.kind !== 201) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -30547,11 +32005,11 @@ var ts; } return createArrayType(elementTypes.length ? getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); + strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 144: + case 145: return isNumericComputedName(name); case 71: return isNumericLiteralName(name.escapedText); @@ -30575,8 +32033,8 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (links.resolvedType.flags & 6144 || - !isTypeAssignableToKind(links.resolvedType, 262178 | 84 | 512) && + if (links.resolvedType.flags & 12288 || + !isTypeAssignableToKind(links.resolvedType, 524322 | 84 | 1536) && !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -30605,7 +32063,7 @@ var ts; var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); + (contextualType.pattern.kind === 175 || contextualType.pattern.kind === 179); var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); var typeFlags = 0; var patternWithComputedProperties = false; @@ -30615,18 +32073,18 @@ var ts; var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; - var member = memberDecl.symbol; + var member = getSymbolOfNode(memberDecl); var literalName = void 0; - if (memberDecl.kind === 261 || - memberDecl.kind === 262 || + if (memberDecl.kind === 265 || + memberDecl.kind === 266 || ts.isObjectLiteralMethod(memberDecl)) { var jsdocType = void 0; if (isInJSFile) { jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); } var type = void 0; - if (memberDecl.kind === 261) { - if (memberDecl.name.kind === 144) { + if (memberDecl.kind === 265) { + if (memberDecl.name.kind === 145) { var t = checkComputedPropertyName(memberDecl.name); if (t.flags & 224) { literalName = ts.escapeLeadingUnderscores("" + t.value); @@ -30634,11 +32092,11 @@ var ts; } type = checkPropertyAssignment(memberDecl, checkMode); } - else if (memberDecl.kind === 151) { + else if (memberDecl.kind === 152) { type = checkObjectLiteralMethod(memberDecl, checkMode); } else { - ts.Debug.assert(memberDecl.kind === 262); + ts.Debug.assert(memberDecl.kind === 266); type = checkExpressionForMutableLocation(memberDecl.name, checkMode); } if (jsdocType) { @@ -30646,10 +32104,13 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, literalName || member.escapedName); + var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; + var prop = nameType && isTypeUsableAsLateBoundName(nameType) + ? createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) + : createSymbol(4 | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 265 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 266 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } @@ -30657,7 +32118,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.escapedName); if (impliedProp) { prop.flags |= impliedProp.flags & 16777216; @@ -30675,12 +32136,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 263) { + else if (memberDecl.kind === 267) { if (languageVersion < 2) { checkExternalEmitHelpers(memberDecl, 2); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -30692,15 +32153,15 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } else { - ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); + ts.Debug.assert(memberDecl.kind === 154 || memberDecl.kind === 155); checkNodeDeferred(memberDecl); } - if (!literalName && ts.hasDynamicName(memberDecl)) { + if (!literalName && hasNonBindableDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -30716,7 +32177,7 @@ var ts; if (contextualTypeHasPattern) { for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; - if (!propertiesTable.get(prop.escapedName)) { + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { if (!(prop.flags & 16777216)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -30727,13 +32188,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -30742,8 +32197,8 @@ var ts; var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 2097152; + result.flags |= 8388608 | freshObjectLiteralFlag | (typeFlags & 29360128); result.objectFlags |= 128; if (patternWithComputedProperties) { result.objectFlags |= 512; @@ -30751,24 +32206,24 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 6144)) { - propagatedFlags |= (result.flags & 14680064); + if (!(result.flags & 12288)) { + propagatedFlags |= (result.flags & 29360128); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 | 16777216) || - getFalsyFlags(type) & 7392 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 32768 && !isGenericMappedType(type) || - type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (1 | 33554432) || + getFalsyFlags(type) & 14560 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 65536 && !isGenericMappedType(type) || + type.flags & 393216 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); + checkJsxOpeningLikeElementOrOpeningFragment(node); return getJsxGlobalElementType() || anyType; } function checkJsxElement(node) { - checkJsxOpeningLikeElement(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); } @@ -30777,12 +32232,19 @@ var ts; } return getJsxGlobalElementType() || anyType; } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) { + error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + } + return getJsxGlobalElementType() || anyType; + } function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } function isJsxIntrinsicIdentifier(tagName) { switch (tagName.kind) { - case 179: + case 180: case 99: return false; case 71: @@ -30822,9 +32284,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 255); + ts.Debug.assert(attributeDecl.kind === 259); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -30833,7 +32295,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -30843,7 +32305,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); } attributesArray = getPropertiesOfType(spread); } @@ -30855,20 +32317,9 @@ var ts; } } } - var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 250 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { - var childrenTypes = []; - for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - if (child.kind === 10) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } + var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); @@ -30888,11 +32339,26 @@ var ts; typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 33554432 | 4194304; + result.flags |= 67108864 | 8388608; result.objectFlags |= 128; return result; } } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === 10) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + return childrenTypes; + } function checkJsxAttributes(node, checkMode) { return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); } @@ -30920,7 +32386,7 @@ var ts; links.jsxFlags |= 2; return links.resolvedSymbol = intrinsicElementsType.symbol; } - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { @@ -30933,7 +32399,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536)); + ts.Debug.assert(!(valueType.flags & 131072)); if (isTypeAny(valueType)) { return anyType; } @@ -30995,7 +32461,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 131072) { + if (propsType.flags & 262144) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -31006,7 +32472,7 @@ var ts; return getApparentType(propsType); } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); + ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { @@ -31028,7 +32494,7 @@ var ts; return undefined; } function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); + ts.Debug.assert(!(elementType.flags & 131072)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { @@ -31072,7 +32538,7 @@ var ts; } function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } - if (elementType.flags & 65536) { + if (elementType.flags & 131072) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); @@ -31084,8 +32550,8 @@ var ts; else if (elementType.flags & 32) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + var stringLiteralTypeName = elementType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); } @@ -31093,7 +32559,7 @@ var ts; if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); } return anyType; } @@ -31229,22 +32695,31 @@ var ts; } } } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace, true); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 107455, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = true; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { markAliasSymbolAsReferenced(reactSym); } } - checkJsxAttributesAssignableToTagNameAttributes(node); + if (isNodeOpeningLikeElement) { + checkJsxAttributesAssignableToTagNameAttributes(node); + } + else { + checkJsxChildren(node.parent); + } } function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 32768) { + if (targetType.flags & 65536) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -31253,7 +32728,7 @@ var ts; return true; } } - else if (targetType.flags & 196608) { + else if (targetType.flags & 393216) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -31279,7 +32754,7 @@ var ts; for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); break; } } @@ -31290,7 +32765,7 @@ var ts; if (node.expression) { var type = checkExpression(node.expression, checkMode); if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); } return type; } @@ -31299,7 +32774,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149; + return s.valueDeclaration ? s.valueDeclaration.kind : 150; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; @@ -31309,7 +32784,7 @@ var ts; } function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 || node.kind === 226 ? + var errorNode = node.kind === 180 || node.kind === 227 ? node.name : node.right; if (ts.getCheckFlags(prop) & 256) { @@ -31318,11 +32793,7 @@ var ts; } if (left.kind === 97) { if (languageVersion < 2) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 && propKind !== 150; - }); - if (hasNonMethodDeclaration) { + if (symbolHasNonMethodDeclaration(prop)) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -31332,11 +32803,18 @@ var ts; return false; } } + if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + return false; + } + } if (!(flags & 24)) { return true; } if (flags & 8) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; @@ -31357,27 +32835,33 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 16384 && type.isThisType) { - type = getConstraintOfTypeParameter(type); + if (type.flags & 32768) { + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } - if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { + if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; } + function symbolHasNonMethodDeclaration(symbol) { + return forEachProperty(symbol, function (prop) { + var propKind = getDeclarationKindFromSymbol(prop); + return propKind !== 152 && propKind !== 151; + }); + } function checkNonNullExpression(node) { return checkNonNullType(checkExpression(node), node); } function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288; if (kind) { - error(errorNode, kind & 2048 ? kind & 4096 ? + error(errorNode, kind & 4096 ? kind & 8192 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); var t = getNonNullableType(type); - return t.flags & (6144 | 8192) ? unknownType : t; + return t.flags & (12288 | 16384) ? unknownType : t; } return type; } @@ -31388,46 +32872,67 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + var propType; + var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; + var leftType = checkNonNullExpression(left); + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { return apparentType; } + var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0); - if (indexInfo && indexInfo.type) { - if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { - error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + if (!(indexInfo && indexInfo.type)) { + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 32768 && leftType.isThisType ? apparentType : leftType); } - return indexInfo.type; + return unknownType; } - if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); } - return unknownType; + propType = indexInfo.type; } - checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); - return unknownType; + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 99); + leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && + !(isNonLocalAlias(leftSymbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { + getSymbolLinks(leftSymbol).referenced = undefined; + } + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + return unknownType; + } } + propType = getDeclaredOrApparentType(prop, node); } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { + if (node.kind !== 180 || + assignmentKind === 1 || + prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 131072)) { + return propType; + } + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 99) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 153 && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 4096) && getFalsyFlags(flowType) & 4096) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); return propType; } - var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { @@ -31438,24 +32943,24 @@ var ts; if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); } - else if (valueDeclaration.kind === 229 && - node.parent.kind !== 159 && - !ts.isInAmbientContext(valueDeclaration) && + else if (valueDeclaration.kind === 230 && + node.parent.kind !== 160 && + !(valueDeclaration.flags & 2097152) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 149: + case 150: return true; - case 261: + case 265: return false; default: - return ts.isPartOfExpression(node) ? false : "quit"; + return ts.isExpressionNode(node) ? false : "quit"; } }); } @@ -31482,7 +32987,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + if (containingType.flags & 131072 && !(containingType.flags & 16382)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -31493,7 +32998,7 @@ var ts; } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -31501,76 +33006,104 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455); - return suggestion && suggestion.escapedName; + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455); + return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, undefined, name, false, function (symbols, name, meaning) { + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); - if (symbol) { - return symbol; - } - return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - if (result) { - return result.escapedName; - } + return result && ts.symbolName(result); } function getSpellingSuggestionForName(name, symbols, meaning) { - var worstDistance = name.length * 0.4; - var maximumLengthDifference = Math.min(3, name.length * 0.34); - var bestDistance = Number.MAX_VALUE; - var bestCandidate = undefined; + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; + var bestCandidate; var justCheckExactMatches = false; - if (name.length > 30) { - return undefined; - } - name = name.toLowerCase(); + var nameLowerCase = name.toLowerCase(); for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; - var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); - if (candidate.flags & meaning && - candidateName && - Math.abs(candidateName.length - name.length) < maximumLengthDifference) { - candidateName = candidateName.toLowerCase(); - if (candidateName === name) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3 || - name.length < 3 || - candidateName === "eval" || - candidateName === "intl" || - candidateName === "undefined" || - candidateName === "map" || - candidateName === "nan" || - candidateName === "set") { - continue; - } - var distance = ts.levenshtein(name, candidateName); - if (distance > worstDistance) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else if (distance < bestDistance) { - bestDistance = distance; - bestCandidate = candidate; - } + var candidateName = ts.symbolName(candidate); + if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + continue; + } + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + continue; + } + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + ts.Debug.assert(distance < bestDistance); + bestDistance = distance; + bestCandidate = candidate; } } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -31580,7 +33113,7 @@ var ts; } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 179 + var left = node.kind === 180 ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); @@ -31591,7 +33124,7 @@ var ts; if (prop) { return checkPropertyAccessibility(node, left, type, prop); } - if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + if (ts.isInJavaScriptFile(left) && (type.flags & 131072)) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var elementType = _a[_i]; if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { @@ -31605,7 +33138,7 @@ var ts; } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 227) { + if (initializer.kind === 228) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -31627,7 +33160,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 215 && + if (node.kind === 216 && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -31645,7 +33178,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 && node.parent.expression === node) { + if (node.parent.kind === 183 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -31674,7 +33207,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 512) === 0) { + if ((expressionType.flags & 1536) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -31704,10 +33237,10 @@ var ts; if (callLikeExpressionMayHaveTypeArguments(node)) { ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 183) { + if (node.kind === 184) { checkExpression(node.template); } - else if (node.kind !== 147) { + else if (node.kind !== 148) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -31758,7 +33291,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 198) { + if (arg && arg.kind === 199) { return i; } } @@ -31773,11 +33306,11 @@ var ts; if (ts.isJsxOpeningLikeElement(node)) { return true; } - if (node.kind === 183) { + if (node.kind === 184) { var tagExpression = node; argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 196) { + if (tagExpression.template.kind === 197) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -31789,14 +33322,14 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 147) { + else if (node.kind === 148) { typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); } else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 182); + ts.Debug.assert(callExpression.kind === 183); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -31812,7 +33345,8 @@ var ts; return false; } if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + return isRestParameterIndex(signature, spreadArgIndex) || + signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; } if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; @@ -31821,7 +33355,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 32768) { + if (type.flags & 65536) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -31836,7 +33370,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -31847,7 +33381,7 @@ var ts; inference.inferredType = undefined; } } - if (node.kind !== 147) { + if (node.kind !== 148) { var contextualType = getContextualType(node); if (contextualType) { var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); @@ -31856,7 +33390,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); } } var thisType = getThisTypeOfSignature(signature); @@ -31868,7 +33402,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { + if (arg === undefined || arg.kind !== 201) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); if (argType === undefined) { @@ -31889,29 +33423,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (!constraint) + continue; + var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return false; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { var callIsIncomplete = node.attributes.end === node.end; @@ -31935,7 +33467,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182) { + if (thisType && thisType !== voidType && node.kind !== 183) { var thisArgumentNode = getThisArgumentOfCall(node); var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -31948,7 +33480,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { + if (arg === undefined || arg.kind !== 201) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i) || checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); @@ -31962,28 +33494,28 @@ var ts; return true; } function getThisArgumentOfCall(node) { - if (node.kind === 181) { + if (node.kind === 182) { var callee = node.expression; - if (callee.kind === 179) { + if (callee.kind === 180) { return callee.expression; } - else if (callee.kind === 180) { + else if (callee.kind === 181) { return callee.expression; } } } function getEffectiveCallArguments(node) { - if (node.kind === 183) { + if (node.kind === 184) { var template = node.template; var args_4 = [undefined]; - if (template.kind === 196) { + if (template.kind === 197) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 147) { + else if (node.kind === 148) { return undefined; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -31994,21 +33526,21 @@ var ts; } } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147) { + if (node.kind === 148) { switch (node.parent.kind) { - case 229: - case 199: + case 230: + case 200: return 1; - case 149: + case 150: return 2; - case 151: - case 153: + case 152: case 154: + case 155: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 146: + case 147: return 3; } } @@ -32017,51 +33549,51 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 229) { + if (node.kind === 230) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 146) { + if (node.kind === 147) { node = node.parent; - if (node.kind === 152) { + if (node.kind === 153) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 150 || + node.kind === 152 || + node.kind === 154 || + node.kind === 155) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 229) { + if (node.kind === 230) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 146) { + if (node.kind === 147) { node = node.parent; - if (node.kind === 152) { + if (node.kind === 153) { return anyType; } } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 150 || + node.kind === 152 || + node.kind === 154 || + node.kind === 155) { var element = node; switch (element.name.kind) { case 71: - return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + return getLiteralType(ts.idText(element.name)); case 8: case 9: return getLiteralType(element.name.text); - case 144: + case 145: var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 512)) { + if (isTypeAssignableToKind(nameType, 1536)) { return nameType; } else { @@ -32076,20 +33608,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 229) { + if (node.kind === 230) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 146) { + if (node.kind === 147) { return numberType; } - if (node.kind === 149) { + if (node.kind === 150) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 152 || + node.kind === 154 || + node.kind === 155) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -32110,26 +33642,26 @@ var ts; return unknownType; } function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 147) { + if (node.kind === 148) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 183) { + else if (argIndex === 0 && node.kind === 184) { return getGlobalTemplateStringsArrayType(); } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 147 || - (argIndex === 0 && node.kind === 183)) { + if (node.kind === 148 || + (argIndex === 0 && node.kind === 184)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147) { + if (node.kind === 148) { return node.expression; } - else if (argIndex === 0 && node.kind === 183) { + else if (argIndex === 0 && node.kind === 184) { return node.template; } else { @@ -32137,8 +33669,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183; - var isDecorator = node.kind === 147; + var isTaggedTemplate = node.kind === 184; + var isDecorator = node.kind === 148; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { @@ -32171,7 +33703,7 @@ var ts; var candidateForArgumentError; var candidateForTypeArgumentError; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 182 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -32188,8 +33720,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -32215,10 +33746,13 @@ var ts; var paramCount = hasRestParameter_1 ? min : min < max ? min + "-" + max : min; - var argCount = args.length - (hasSpreadArgument ? 1 : 0); - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + var argCount = args.length; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1; diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); } @@ -32231,14 +33765,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -32273,10 +33807,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -32284,6 +33820,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { @@ -32361,19 +33898,8 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray); } function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 65536) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 | 16384)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { @@ -32401,9 +33927,9 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.hasModifier(valueDecl, 128)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } return resolveCall(node, constructSignatures, candidatesOutArray); @@ -32431,7 +33957,7 @@ var ts; if (!modifiers) { return true; } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); @@ -32476,16 +34002,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 229: - case 199: + case 230: + case 200: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146: + case 147: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149: + case 150: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151: - case 153: + case 152: case 154: + case 155: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -32500,6 +34026,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -32510,13 +34041,19 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + }); + } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; + ts.Debug.assert(!(elementType.flags & 131072)); + return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); } function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 65536) { + if (elementType.flags & 131072) { var types = elementType.types; var result = void 0; for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { @@ -32533,17 +34070,17 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 181: - return resolveCallExpression(node, candidatesOutArray); case 182: - return resolveNewExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray); case 183: + return resolveNewExpression(node, candidatesOutArray); + case 184: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147: + case 148: return resolveDecorator(node, candidatesOutArray); + case 252: case 251: - case 250: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -32586,31 +34123,33 @@ var ts; function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); } return links.inferredClassType; } function isInferredClassType(type) { return type.symbol - && getObjectFlags(type) & 16 + && ts.getObjectFlags(type) & 16 && getSymbolLinks(type.symbol).inferredClassType === type; } function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97) { return voidType; } - if (node.kind === 182) { + if (node.kind === 183) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 152 && - declaration.kind !== 156 && - declaration.kind !== 161 && + declaration.kind !== 153 && + declaration.kind !== 157 && + declaration.kind !== 162 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 71 ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 71) { + funcSymbol = getResolvedSymbol(node.expression); + } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { return type; @@ -32624,10 +34163,31 @@ var ts; if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } - return getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1536 && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + return returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 107455, undefined, undefined, false); } function checkImportCallExpression(node) { - checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -32636,7 +34196,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 2048 || specifierType.flags & 4096 || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 4096 || specifierType.flags & 8192 || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } var moduleSymbol = resolveExternalModuleName(node, specifier); @@ -32684,17 +34244,20 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 - ? 228 + ? 229 : resolvedRequire.flags & 3 - ? 226 + ? 227 : 0; if (targetDeclarationKind !== 0) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return ts.isInAmbientContext(decl); + return !!decl && !!(decl.flags & 2097152); } return false; } function checkTaggedTemplateExpression(node) { + if (languageVersion < 2) { + checkExternalEmitHelpers(node, 65536); + } return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { @@ -32722,7 +34285,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return unknownType; } - else if (container.kind === 152) { + else if (container.kind === 153) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -32736,7 +34299,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return getNullableType(type, 2048); + return getOptionalType(type); } } return type; @@ -32844,7 +34407,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 207) { + if (func.body.kind !== 208) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2) { type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -32878,24 +34441,40 @@ var ts; } } type = getUnionType(types, true); - if (functionFlags & 1) { - type = functionFlags & 2 - ? createAsyncIterableIteratorType(type) - : createIterableIteratorType(type); - } } if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3) { + case 3: + contextualType = getIteratedTypeOfGenerator(contextualType, true); + break; + case 1: + contextualType = getIteratedTypeOfGenerator(contextualType, false); + break; + case 2: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); } var widenedType = getWidenedType(type); - return (functionFlags & 3) === 2 - ? createPromiseReturnType(func, widenedType) - : widenedType; + switch (functionFlags & 3) { + case 3: + return createAsyncIterableIteratorType(widenedType); + case 1: + return createIterableIteratorType(widenedType); + case 2: + return createPromiseType(widenedType); + default: + return widenedType; + } } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; @@ -32935,8 +34514,7 @@ var ts; if (!(func.flags & 128)) { return false; } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 222 && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -32953,7 +34531,7 @@ var ts; if (functionFlags & 2) { type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 8192) { + if (type.flags & 16384) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -32963,7 +34541,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 || func.kind === 187)) { + func.kind === 187 || func.kind === 188)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -32975,14 +34553,14 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 2048)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 208 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 8192) { + if (returnType && returnType.flags & 16384) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -33005,13 +34583,13 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); if (checkMode === 1 && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { + if (!hasGrammarError && node.kind === 187) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -33042,7 +34620,7 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 151) { + if (produceDiagnostics && node.kind !== 152) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -33050,7 +34628,7 @@ var ts; return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnOrPromisedType = returnTypeNode && @@ -33064,7 +34642,7 @@ var ts; if (!returnTypeNode) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 207) { + if (node.body.kind === 208) { checkSourceElement(node.body); } else { @@ -33099,10 +34677,10 @@ var ts; function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { if (symbol.flags & 4 && - (expr.kind === 179 || expr.kind === 180) && + (expr.kind === 180 || expr.kind === 181) && expr.expression.kind === 99) { var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152)) { + if (!(func && func.kind === 153)) { return true; } return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); @@ -33112,13 +34690,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 || expr.kind === 180) { + if (expr.kind === 180 || expr.kind === 181) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240; + return declaration && declaration.kind === 241; } } } @@ -33126,7 +34704,7 @@ var ts; } function checkReferenceExpression(expr, invalidReferenceMessage) { var node = ts.skipOuterExpressions(expr, 2 | 1); - if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { + if (node.kind !== 71 && node.kind !== 180 && node.kind !== 181) { error(expr, invalidReferenceMessage); return false; } @@ -33135,7 +34713,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 && expr.kind !== 180) { + if (expr.kind !== 180 && expr.kind !== 181) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -33184,7 +34762,7 @@ var ts; case 38: case 52: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512)) { + if (maybeTypeOfKind(operandType, 1536)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -33218,7 +34796,7 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 196608) { + if (type.flags & 393216) { var types = type.types; for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { var t = types_18[_i]; @@ -33233,21 +34811,26 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 | 1024 | 2048 | 4096)) { + if (strict && source.flags & (1 | 2048 | 4096 | 8192)) { return false; } return (kind & 84 && isTypeAssignableTo(source, numberType)) || - (kind & 262178 && isTypeAssignableTo(source, stringType)) || + (kind & 524322 && isTypeAssignableTo(source, stringType)) || (kind & 136 && isTypeAssignableTo(source, booleanType)) || - (kind & 1024 && isTypeAssignableTo(source, voidType)) || - (kind & 8192 && isTypeAssignableTo(source, neverType)) || - (kind & 4096 && isTypeAssignableTo(source, nullType)) || - (kind & 2048 && isTypeAssignableTo(source, undefinedType)) || + (kind & 2048 && isTypeAssignableTo(source, voidType)) || + (kind & 16384 && isTypeAssignableTo(source, neverType)) || + (kind & 8192 && isTypeAssignableTo(source, nullType)) || + (kind & 4096 && isTypeAssignableTo(source, undefinedType)) || (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || - (kind & 16777216 && isTypeAssignableTo(source, nonPrimitiveType)); + (kind & 33554432 && isTypeAssignableTo(source, nonPrimitiveType)); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 131072 ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + return ts.getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; @@ -33256,13 +34839,11 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190)) { + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 16382)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0).length || - getSignaturesOfType(rightType, 1).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); } return booleanType; @@ -33273,10 +34854,10 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 512))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 1536))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { + if (!isTypeAssignableToKind(rightType, 33554432 | 1081344)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -33290,9 +34871,9 @@ var ts; return sourceType; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 || property.kind === 262) { + if (property.kind === 265 || property.kind === 266) { var name = property.name; - if (name.kind === 144) { + if (name.kind === 145) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -33305,7 +34886,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || getIndexTypeOfType(objectLiteralType, 0); if (type) { - if (property.kind === 262) { + if (property.kind === 266) { return checkDestructuringAssignment(property, type); } else { @@ -33316,8 +34897,8 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 263) { - if (languageVersion < 5) { + else if (property.kind === 267) { + if (languageVersion < 6) { checkExternalEmitHelpers(property, 4); } var nonRestNames = []; @@ -33347,8 +34928,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 200) { - if (element.kind !== 198) { + if (element.kind !== 201) { + if (element.kind !== 199) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -33374,7 +34955,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { + if (restExpression.kind === 195 && restExpression.operatorToken.kind === 58) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -33387,11 +34968,11 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 262) { + if (exprOrAssignment.kind === 266) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -33401,21 +34982,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 194 && target.operatorToken.kind === 58) { + if (target.kind === 195 && target.operatorToken.kind === 58) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 178) { + if (target.kind === 179) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 177) { + if (target.kind === 178) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 ? + var error = target.parent.kind === 267 ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -33429,35 +35010,35 @@ var ts; case 71: case 9: case 12: - case 183: - case 196: + case 184: + case 197: case 13: case 8: case 101: case 86: case 95: case 139: - case 186: - case 199: case 187: - case 177: + case 200: + case 188: case 178: - case 189: - case 203: + case 179: + case 190: + case 204: + case 251: case 250: - case 249: return true; - case 195: + case 196: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 194: + case 195: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 192: case 193: + case 194: switch (node.operator) { case 51: case 37: @@ -33466,29 +35047,22 @@ var ts; return true; } return false; - case 190: - case 184: - case 202: + case 191: + case 185: + case 203: default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); + return (target.flags & 12288) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 178 || left.kind === 177)) { + if (operator === 58 && (left.kind === 179 || left.kind === 178)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); @@ -33540,7 +35114,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 262178) && !isTypeAssignableToKind(rightType, 262178)) { + if (!isTypeAssignableToKind(leftType, 524322) && !isTypeAssignableToKind(rightType, 524322)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } @@ -33548,7 +35122,7 @@ var ts; if (isTypeAssignableToKind(leftType, 84, true) && isTypeAssignableToKind(rightType, 84, true)) { resultType = numberType; } - else if (isTypeAssignableToKind(leftType, 262178, true) || isTypeAssignableToKind(rightType, 262178, true)) { + else if (isTypeAssignableToKind(leftType, 524322, true) || isTypeAssignableToKind(rightType, 524322, true)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -33601,7 +35175,7 @@ var ts; leftType; case 54: return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], true) : leftType; case 58: checkAssignmentOperator(rightType); @@ -33616,8 +35190,8 @@ var ts; return node.kind === 71 && node.escapedText === "eval"; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536) ? left : + maybeTypeOfKind(rightType, 1536) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -33680,7 +35254,7 @@ var ts; var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { if ((functionFlags & 3) === 3 && - languageVersion < 5) { + languageVersion < 6) { checkExternalEmitHelpers(node, 26624); } if ((functionFlags & 3) === 1 && @@ -33717,7 +35291,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2], true); } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -33749,24 +35323,35 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 184 || node.kind === 202; + return node.kind === 185 || node.kind === 203; } function checkDeclarationInitializer(declaration) { var type = getTypeOfExpression(declaration.initializer, true); return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || + (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } - function isLiteralContextualType(contextualType) { + function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 540672) { + if (contextualType.flags & 131072 && !(contextualType.flags & 8)) { + var types_19 = contextualType.types; + return ts.some(types_19, function (t) { + return !(t.flags & 128 && containsType(types_19, trueType) && containsType(types_19, falseType)) && + isLiteralOfContextualType(candidateType, t); + }); + } + if (contextualType.flags & 1081344) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - if (constraint.flags & (2 | 4 | 8 | 16)) { - return true; - } - contextualType = constraint; + return constraint.flags & 2 && maybeTypeOfKind(candidateType, 32) || + constraint.flags & 4 && maybeTypeOfKind(candidateType, 64) || + constraint.flags & 8 && maybeTypeOfKind(candidateType, 128) || + constraint.flags & 512 && maybeTypeOfKind(candidateType, 1024) || + isLiteralOfContextualType(candidateType, constraint); } - return maybeTypeOfKind(contextualType, (224 | 262144)); + return contextualType.flags & (32 | 524288) && maybeTypeOfKind(candidateType, 32) || + contextualType.flags & 64 && maybeTypeOfKind(candidateType, 64) || + contextualType.flags & 128 && maybeTypeOfKind(candidateType, 128) || + contextualType.flags & 1024 && maybeTypeOfKind(candidateType, 1024); } return false; } @@ -33775,18 +35360,18 @@ var ts; contextualType = getContextualType(node); } var type = checkExpression(node, checkMode); - var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); - return shouldWiden ? type : getWidenedLiteralType(type); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); } function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node, checkMode) { checkGrammarMethod(node); - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -33808,7 +35393,7 @@ var ts; return type; } function getTypeOfExpression(node, cache) { - if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { + if (node.kind === 182 && node.expression.kind !== 97 && !ts.isRequireCall(node, true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -33826,7 +35411,7 @@ var ts; } function checkExpression(node, checkMode) { var type; - if (node.kind === 143) { + if (node.kind === 144) { type = checkQualifiedName(node); } else { @@ -33834,9 +35419,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 179 && node.parent.expression === node) || - (node.parent.kind === 180 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 180 && node.parent.expression === node) || + (node.parent.kind === 181 && node.parent.expression === node) || + ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -33870,71 +35455,73 @@ var ts; return trueType; case 86: return falseType; - case 196: + case 197: return checkTemplateExpression(node); case 12: return globalRegExpType; - case 177: - return checkArrayLiteral(node, checkMode); case 178: - return checkObjectLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode); case 179: - return checkPropertyAccessExpression(node); + return checkObjectLiteral(node, checkMode); case 180: - return checkIndexedAccess(node); + return checkPropertyAccessExpression(node); case 181: + return checkIndexedAccess(node); + case 182: if (node.expression.kind === 91) { return checkImportCallExpression(node); } - case 182: - return checkCallExpression(node); case 183: + return checkCallExpression(node); + case 184: return checkTaggedTemplateExpression(node); - case 185: + case 186: return checkParenthesizedExpression(node, checkMode); - case 199: + case 200: return checkClassExpression(node); - case 186: case 187: + case 188: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189: + case 190: return checkTypeOfExpression(node); - case 184: - case 202: - return checkAssertion(node); + case 185: case 203: - return checkNonNullAssertion(node); + return checkAssertion(node); case 204: + return checkNonNullAssertion(node); + case 205: return checkMetaProperty(node); - case 188: + case 189: return checkDeleteExpression(node); - case 190: - return checkVoidExpression(node); case 191: - return checkAwaitExpression(node); + return checkVoidExpression(node); case 192: - return checkPrefixUnaryExpression(node); + return checkAwaitExpression(node); case 193: - return checkPostfixUnaryExpression(node); + return checkPrefixUnaryExpression(node); case 194: - return checkBinaryExpression(node, checkMode); + return checkPostfixUnaryExpression(node); case 195: + return checkBinaryExpression(node, checkMode); + case 196: return checkConditionalExpression(node, checkMode); - case 198: + case 199: return checkSpreadExpression(node, checkMode); - case 200: + case 201: return undefinedWideningType; - case 197: + case 198: return checkYieldExpression(node); - case 256: + case 260: return checkJsxExpression(node, checkMode); - case 249: - return checkJsxElement(node); case 250: + return checkJsxElement(node); + case 251: return checkJsxSelfClosingElement(node); case 254: + return checkJsxFragment(node); + case 258: return checkJsxAttributes(node, checkMode); - case 251: + case 252: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -33949,6 +35536,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -33959,12 +35549,11 @@ var ts; } } function checkParameter(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92)) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 153 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -33975,7 +35564,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 152 || func.kind === 156 || func.kind === 161) { + if (func.kind === 153 || func.kind === 157 || func.kind === 162) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -34037,13 +35626,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { + case 188: + case 156: + case 229: case 187: - case 155: - case 228: - case 186: - case 160: + case 161: + case 152: case 151: - case 150: var parent = node.parent; if (node === parent.type) { return parent; @@ -34061,7 +35650,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 175 || name.kind === 174) { + else if (name.kind === 176 || name.kind === 175) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -34069,17 +35658,17 @@ var ts; } } function checkSignatureDeclaration(node) { - if (node.kind === 157) { + if (node.kind === 158) { checkGrammarIndexSignature(node); } - else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || - node.kind === 155 || node.kind === 152 || - node.kind === 156) { + else if (node.kind === 161 || node.kind === 229 || node.kind === 162 || + node.kind === 156 || node.kind === 153 || + node.kind === 157) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); if (!(functionFlags & 4)) { - if ((functionFlags & 3) === 3 && languageVersion < 5) { + if ((functionFlags & 3) === 3 && languageVersion < 6) { checkExternalEmitHelpers(node, 6144); } if ((functionFlags & 3) === 2 && languageVersion < 4) { @@ -34099,10 +35688,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 156: + case 157: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 155: + case 156: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -34143,7 +35732,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152) { + if (member.kind === 153) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -34157,16 +35746,16 @@ var ts; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 153: + case 154: addName(names, member.name, memberName, 1); break; - case 154: + case 155: addName(names, member.name, memberName, 2); break; - case 149: + case 150: addName(names, member.name, memberName, 3); break; - case 151: + case 152: addName(names, member.name, memberName, 4); break; } @@ -34207,7 +35796,7 @@ var ts; case "arguments": case "prototype": var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); error(memberNameNode, message, memberName, className); break; } @@ -34218,7 +35807,7 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 149) { var memberName = void 0; switch (member.name.kind) { case 9: @@ -34226,7 +35815,7 @@ var ts; memberName = member.name.text; break; case 71: - memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + memberName = ts.idText(member.name); break; default: continue; @@ -34242,7 +35831,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230) { + if (node.kind === 231) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -34279,11 +35868,13 @@ var ts; } } function checkPropertyDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); } function checkMethodDeclaration(node) { - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); checkFunctionOrMethodDeclaration(node); if (ts.hasModifier(node, 128) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); @@ -34291,7 +35882,8 @@ var ts; } function checkConstructorDeclaration(node) { checkSignatureDeclaration(node); - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); @@ -34322,7 +35914,7 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function isInstancePropertyWithInitializer(n) { - return n.kind === 149 && + return n.kind === 150 && !ts.hasModifier(n, 32) && !!n.initializer; } @@ -34342,7 +35934,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -34362,22 +35954,23 @@ var ts; } function checkAccessorDeclaration(node) { if (produceDiagnostics) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 153) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (node.kind === 154) { + if (!(node.flags & 2097152) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { if (!(node.flags & 256)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 153 ? 154 : 153; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (!hasNonBindableDynamicName(node)) { + var otherKind = node.kind === 154 ? 155 : 154; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); var otherFlags = ts.getModifierFlags(otherAccessor); @@ -34392,7 +35985,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153) { + if (node.kind === 154) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -34422,14 +36015,14 @@ var ts; mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, instantiateType(constraint, mapper), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 160 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -34439,11 +36032,13 @@ var ts; if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; if (!symbol) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; - if (!typeParameters && getObjectFlags(type) & 4) { + if (!typeParameters && ts.getObjectFlags(type) & 4) { typeParameters = type.target.localTypeParameters; } checkTypeArgumentConstraints(typeParameters, node.typeArguments); @@ -34480,14 +36075,14 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288)) { + if (!(type.flags & 1048576)) { return type; } var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { + if (accessNode.kind === 181 && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; @@ -34510,15 +36105,19 @@ var ts; var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8) && !!(node.flags & 2097152); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 230 && - n.parent.kind !== 229 && - n.parent.kind !== 199 && - ts.isInAmbientContext(n)) { + if (n.parent.kind !== 231 && + n.parent.kind !== 230 && + n.parent.kind !== 200 && + n.flags & 2097152) { if (!(flags & 2)) { flags |= 1; } @@ -34597,7 +36196,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 151 || node.kind === 150) && + var reportError = (node.kind === 152 || node.kind === 151) && ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); if (reportError) { var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -34629,12 +36228,12 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; + var inAmbientContext = node.flags & 2097152; + var inAmbientContextOrInterface = node.parent.kind === 231 || node.parent.kind === 164 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { + if (node.kind === 229 || node.kind === 152 || node.kind === 151 || node.kind === 153) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -34753,28 +36352,28 @@ var ts; })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(d) { switch (d.kind) { - case 230: case 231: - case 283: + case 232: + case 288: return 2; - case 233: + case 234: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4 | 1 : 4; - case 229: - case 232: + case 230: + case 233: return 2 | 1; - case 237: + case 238: + case 241: case 240: - case 239: - var result_3 = 0; + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 226: - case 176: - case 228: - case 242: + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; + case 227: + case 177: + case 229: + case 243: return 1; default: ts.Debug.fail(ts.SyntaxKind[d.kind]); @@ -34831,7 +36430,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 65536) { + if (type.flags & 131072) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -34840,7 +36439,7 @@ var ts; if (!types) { return undefined; } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { @@ -34913,7 +36512,7 @@ var ts; var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; } } @@ -34929,22 +36528,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 229: + case 230: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 146: + case 147: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 149: + case 150: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 151: - case 153: + case 152: case 154: + case 155: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -34977,11 +36576,20 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { + case 168: case 167: - case 166: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169) { + typeNode = typeNode.type; + } + if (typeNode.kind === 130) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 139)) { + continue; + } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) { return undefined; @@ -34998,9 +36606,9 @@ var ts; } } return commonEntityName; - case 168: + case 169: return getEntityNameForDecoratorMetadata(node.type); - case 159: + case 160: return node.typeName; } } @@ -35013,7 +36621,7 @@ var ts; if (!node.decorators) { return; } - if (!ts.nodeCanBeDecorated(node)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { @@ -35021,13 +36629,13 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 146) { + if (node.kind === 147) { checkExternalEmitHelpers(firstDecorator, 32); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 229: + case 230: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -35036,20 +36644,25 @@ var ts; } } break; - case 151: - case 153: + case 152: case 154: + case 155: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 149: + case 150: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 146: + case 147: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } break; } } @@ -35071,14 +36684,50 @@ var ts; error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 144 ? node.name.right : node.name)); + } + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 282); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 71: + return node; + case 180: + return node.name; + default: + return undefined; + } + } function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 144) { + if (node.name && node.name.kind === 145) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); @@ -35119,68 +36768,67 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 265: - case 233: + case 269: + case 234: checkUnusedModuleMembers(node); break; - case 229: - case 199: + case 230: + case 200: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 230: + case 231: checkUnusedTypeParameters(node); break; - case 207: - case 235: - case 214: + case 208: + case 236: case 215: case 216: + case 217: checkUnusedLocalsAndParameters(node); break; - case 152: - case 186: - case 228: - case 187: - case 151: case 153: + case 187: + case 229: + case 188: + case 152: case 154: + case 155: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 150: - case 155: + case 151: case 156: case 157: - case 160: case 161: + case 162: + case 232: checkUnusedTypeParameters(node); break; - case 231: - checkUnusedTypeParameters(node); - break; + default: + ts.Debug.fail("Node should not have been registered for unused identifiers check"); } } } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + if (noUnusedIdentifiers && !(node.flags & 2097152)) { node.locals.forEach(function (local) { if (!local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 147) { var parameter = ts.getRootDeclaration(local.valueDeclaration); var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); } } }); @@ -35197,8 +36845,8 @@ var ts; var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 226 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 145) { + if ((declaration_2.kind === 227 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 146) { return; } } @@ -35210,23 +36858,23 @@ var ts; return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95; + return node.kind === 71 && ts.idText(node).charCodeAt(0) === 95; } function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 || member.kind === 149) { + if (member.kind === 152 || member.kind === 150) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); } } - else if (member.kind === 152) { + else if (member.kind === 153) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } } @@ -35235,7 +36883,7 @@ var ts; } } function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { if (node.typeParameters) { var symbol = getSymbolOfNode(node); var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); @@ -35245,20 +36893,20 @@ var ts; for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); } } } } } function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { node.locals.forEach(function (local) { if (!local.isReferenced && !local.exportSymbol) { for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.symbolName(local)); } } } @@ -35266,7 +36914,7 @@ var ts; } } function checkBlock(node) { - if (node.kind === 207) { + if (node.kind === 208) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -35282,7 +36930,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || node.flags & 2097152 || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -35295,19 +36943,19 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 149 || - node.kind === 148 || + if (node.kind === 150 || + node.kind === 149 || + node.kind === 152 || node.kind === 151 || - node.kind === 150 || - node.kind === 153 || - node.kind === 154) { + node.kind === 154 || + node.kind === 155) { return false; } - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 147 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -35355,7 +37003,7 @@ var ts; return; } var enclosingClass = ts.getContainingClass(node); - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + if (!enclosingClass || enclosingClass.flags & 2097152) { return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { @@ -35375,11 +37023,11 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 269 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -35387,11 +37035,11 @@ var ts; if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + if (parent.kind === 269 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -35399,7 +37047,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 226 && !node.initializer) { + if (node.kind === 227 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -35411,15 +37059,15 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); - var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 228); + var container = varDeclList.parent.kind === 209 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 207 && ts.isFunctionLike(container.parent) || + (container.kind === 208 && ts.isFunctionLike(container.parent) || + container.kind === 235 || container.kind === 234 || - container.kind === 233 || - container.kind === 265); + container.kind === 269); if (!namesShareScope) { var name = symbolToString(localDeclarationSymbol); error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); @@ -35429,7 +37077,7 @@ var ts; } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146) { + if (ts.getRootDeclaration(node).kind !== 147) { return; } var func = ts.getContainingFunction(node); @@ -35438,7 +37086,7 @@ var ts; if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { return; } - if (n.kind === 179) { + if (n.kind === 180) { return visit(n.expression); } else if (n.kind === 71) { @@ -35452,8 +37100,8 @@ var ts; } var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 || - symbol.valueDeclaration.kind === 176) { + if (symbol.valueDeclaration.kind === 147 || + symbol.valueDeclaration.kind === 177) { if (symbol.valueDeclaration.pos < node.pos) { return; } @@ -35462,7 +37110,7 @@ var ts; return "quit"; } return ts.isFunctionLike(current.parent) || - (current.parent.kind === 149 && + (current.parent.kind === 150 && !(ts.hasModifier(current.parent, 32)) && ts.isClassLike(current.parent.parent)); })) { @@ -35486,40 +37134,40 @@ var ts; if (!node.name) { return; } - if (node.name.kind === 144) { + if (node.name.kind === 145) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 176) { - if (node.parent.kind === 174 && languageVersion < 5) { + if (node.kind === 177) { + if (node.parent.kind === 175 && languageVersion < 6) { checkExternalEmitHelpers(node, 4); } - if (node.propertyName && node.propertyName.kind === 144) { + if (node.propertyName && node.propertyName.kind === 145) { checkComputedPropertyName(node.propertyName); } var parent = node.parent.parent; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, undefined); + markPropertyAsReferenced(property, undefined, false); if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { + if (node.name.kind === 176 && languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512); } ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 147 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 215) { + if (node.initializer && node.parent.parent.kind !== 216) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } @@ -35528,15 +37176,17 @@ var ts; var symbol = getSymbolOfNode(node); var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 215) { + if (node.initializer && node.parent.parent.kind !== 216) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } } else { var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); + if (type !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); @@ -35546,9 +37196,9 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 149 && node.kind !== 148) { + if (node.kind !== 150 && node.kind !== 149) { checkExportsOnMergedDeclarations(node); - if (node.kind === 226 || node.kind === 176) { + if (node.kind === 227 || node.kind === 177) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -35558,9 +37208,16 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 150 || nextDeclaration.kind === 149 + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 && right.kind === 226) || - (left.kind === 226 && right.kind === 146)) { + if ((left.kind === 147 && right.kind === 227) || + (left.kind === 227 && right.kind === 147)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -35583,11 +37240,12 @@ var ts; return checkVariableLikeDeclaration(node); } function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 178) { + if (node.modifiers && node.parent.kind === 179) { if (ts.getFunctionFlags(node) & 2) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -35606,7 +37264,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209) { + if (node.thenStatement.kind === 210) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -35623,12 +37281,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227) { + if (node.initializer && node.initializer.kind === 228) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -35646,10 +37304,10 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 216) { + if (node.kind === 217) { if (node.awaitModifier) { var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 6) { checkExternalEmitHelpers(node, 16384); } } @@ -35657,13 +37315,13 @@ var ts; checkExternalEmitHelpers(node, 256); } } - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 177 || varExpr.kind === 178) { + if (varExpr.kind === 178 || varExpr.kind === 179) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { @@ -35682,7 +37340,7 @@ var ts; function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -35692,7 +37350,7 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 || varExpr.kind === 178) { + if (varExpr.kind === 178 || varExpr.kind === 179) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -35702,7 +37360,7 @@ var ts; checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { + if (!isTypeAssignableToKind(rightType, 33554432 | 1081344)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -35740,14 +37398,14 @@ var ts; var reportedError = false; var hasStringConstituent = false; if (allowStringInput) { - if (arrayType.flags & 65536) { + if (arrayType.flags & 131072) { var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, true); } } - else if (arrayType.flags & 262178) { + else if (arrayType.flags & 524322) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -35758,7 +37416,7 @@ var ts; reportedError = true; } } - if (arrayType.flags & 8192) { + if (arrayType.flags & 16384) { return stringType; } } @@ -35778,7 +37436,7 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1); if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 262178) { + if (arrayElementType.flags & 524322) { return stringType; } return getUnionType([arrayElementType, stringType], true); @@ -35895,17 +37553,18 @@ var ts; || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); } function checkBreakOrContinueStatement(node) { - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 153 - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154)) !== undefined; + return node.kind === 154 + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 155)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 ? getPromisedTypeOfPromise(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -35918,18 +37577,18 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return; + } + if (strictNullChecks || node.expression || returnType.flags & 16384) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return; - } - if (func.kind === 154) { + if (func.kind === 155) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 152) { + else if (func.kind === 153) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -35947,7 +37606,7 @@ var ts; } } } - else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 153 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } @@ -35973,7 +37632,7 @@ var ts; var expressionType = checkExpression(node.expression); var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 258 && !hasDuplicateDefaultClause) { + if (clause.kind === 262 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -35985,7 +37644,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 257) { + if (produceDiagnostics && clause.kind === 261) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); var caseIsLiteral = isLiteralType(caseType); @@ -36010,7 +37669,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 222 && current.label.escapedText === node.label.escapedText) { + if (current.kind === 223 && current.label.escapedText === node.label.escapedText) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); return true; @@ -36070,14 +37729,15 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (ts.getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!ts.hasModifier(member, 32) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + if (!ts.hasModifier(member, 32) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); } } } @@ -36085,7 +37745,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (getObjectFlags(type) & 2)) { + if (!errorNode && (ts.getObjectFlags(type) & 2)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -36103,15 +37763,15 @@ var ts; } var errorNode; if (propDeclaration && - (propDeclaration.kind === 194 || - ts.getNameOfDeclaration(propDeclaration).kind === 144 || + (propDeclaration.kind === 195 || + ts.getNameOfDeclaration(propDeclaration).kind === 145 || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (getObjectFlags(containingType) & 2) { + else if (ts.getObjectFlags(containingType) & 2) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -36243,7 +37903,7 @@ var ts; var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); - if (!ts.isInAmbientContext(node)) { + if (!(node.flags & 2097152)) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); @@ -36269,10 +37929,10 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 1081344 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 1081344)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); @@ -36305,6 +37965,7 @@ var ts; if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); } } function checkBaseTypeAccessibility(type, node) { @@ -36312,7 +37973,7 @@ var ts; if (signatures.length) { var declaration = signatures[0].declaration; if (declaration && ts.hasModifier(declaration, 8)) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } @@ -36322,12 +37983,9 @@ var ts; function getTargetSymbol(s) { return ts.getCheckFlags(s) & 1 ? s.target : s; } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); - } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 || d.kind === 230; + return d.kind === 230 || d.kind === 231; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -36343,9 +38001,9 @@ var ts; ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { if (derived === base) { - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { - if (derivedClassDecl.kind === 199) { + if (derivedClassDecl.kind === 200) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -36413,15 +38071,48 @@ var ts; } return ok; } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 1 || getFalsyFlags(type) & 4096)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 150 && + !ts.hasModifier(node, 32 | 128) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 4096); + } function checkInterfaceDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 231); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -36448,7 +38139,7 @@ var ts; } } function checkTypeAliasDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); checkTypeParameters(node.typeParameters); checkSourceElement(node.type); @@ -36480,7 +38171,7 @@ var ts; if (member.initializer) { return computeConstantValue(member); } - if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + if (member.parent.flags & 2097152 && !ts.isConst(member.parent)) { return undefined; } if (autoValue !== undefined) { @@ -36508,7 +38199,7 @@ var ts; else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (ts.isInAmbientContext(member.parent)) { + else if (member.parent.flags & 2097152) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { @@ -36517,7 +38208,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 192: + case 193: var value_1 = evaluate(expr.operand); if (typeof value_1 === "number") { switch (expr.operator) { @@ -36527,7 +38218,7 @@ var ts; } } break; - case 194: + case 195: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -36551,18 +38242,18 @@ var ts; case 8: checkGrammarNumericLiteral(expr); return +expr.text; - case 185: + case 186: return evaluate(expr.expression); case 71: return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); + case 181: case 180: - case 179: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384) { var name = void 0; - if (ex.kind === 179) { + if (ex.kind === 180) { name = ex.name.escapedText; } else { @@ -36583,7 +38274,7 @@ var ts; var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { - return getNodeLinks(declaration).enumMemberValue; + return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; @@ -36594,15 +38285,15 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 || - node.kind === 179 && isConstantMemberAccess(node.expression) || - node.kind === 180 && isConstantMemberAccess(node.expression) && + node.kind === 180 && isConstantMemberAccess(node.expression) || + node.kind === 181 && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -36611,7 +38302,7 @@ var ts; checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } var enumSymbol = getSymbolOfNode(node); @@ -36626,7 +38317,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 232) { + if (declaration.kind !== 233) { return false; } var enumDeclaration = declaration; @@ -36649,9 +38340,9 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { var declaration = declarations_7[_i]; - if ((declaration.kind === 229 || - (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 230 || + (declaration.kind === 229 && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 2097152)) { return declaration; } } @@ -36673,7 +38364,7 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContext = node.flags & 2097152; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -36684,7 +38375,7 @@ var ts; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node)) { if (!inAmbientContext && node.name.kind === 9) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -36709,7 +38400,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 229); + var mergedClass = ts.getDeclarationOfKind(symbol, 230); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -36752,22 +38443,22 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 208: + case 209: for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 243: case 244: + case 245: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 237: case 238: + case 239: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 176: - case 226: + case 177: + case 227: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -36776,12 +38467,12 @@ var ts; } break; } - case 229: - case 232: - case 228: case 230: case 233: + case 229: case 231: + case 234: + case 232: if (isGlobalAugmentation) { return; } @@ -36799,12 +38490,12 @@ var ts; switch (node.kind) { case 71: return node; - case 143: + case 144: do { node = node.left; } while (node.kind !== 71); return node; - case 179: + case 180: do { node = node.expression; } while (node.kind !== 71); @@ -36817,9 +38508,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 ? + var inAmbientExternalModule = node.parent.kind === 235 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 269 && !inAmbientExternalModule) { + error(moduleName, node.kind === 245 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -36840,15 +38531,15 @@ var ts; (symbol.flags & 793064 ? 793064 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 246 ? + var message = node.kind === 247 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } if (compilerOptions.isolatedModules - && node.kind === 246 + && node.kind === 247 && !(target.flags & 107455) - && !ts.isInAmbientContext(node)) { + && !(node.flags & 2097152)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } @@ -36863,7 +38554,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -36873,7 +38564,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { + if (importClause.namedBindings.kind === 241) { checkImportBinding(importClause.namedBindings); } else { @@ -36887,13 +38578,13 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); if (ts.hasModifier(node, 1)) { markExportAsReferenced(node); } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.moduleReference.kind !== 249) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 107455) { @@ -36908,7 +38599,7 @@ var ts; } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152)) { grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } @@ -36918,16 +38609,16 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 235 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 235 && + !node.moduleSpecifier && node.flags & 2097152; + if (node.parent.kind !== 269 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -36943,7 +38634,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; + var isInAppropriateContext = node.parent.kind === 269 || node.parent.kind === 235 || node.parent.kind === 234; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -36951,11 +38642,14 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.propertyName || node.name, true); + } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { markExportAsReferenced(node); @@ -36966,8 +38660,8 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 ? node.parent : node.parent.parent; + if (container.kind === 234 && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -36976,20 +38670,23 @@ var ts; } return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71) { markExportAsReferenced(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.expression, true); + } } else { checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 2097152) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (node.isExportEquals && !(node.flags & 2097152)) { if (modulekind >= ts.ModuleKind.ES2015) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -37013,27 +38710,29 @@ var ts; } } var exports_1 = getExportsOfModule(moduleSymbol); - exports_1 && exports_1.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - if (flags & (1920 | 64 | 384)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); - if (flags & 524288 && exportedDeclarationsCount <= 2) { - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (exports_1) { + exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + if (flags & (1920 | 64 | 384)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } - } - }); + }); + } links.exportsChecked = true; } } @@ -37041,7 +38740,7 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || + return (declaration.kind !== 229 && declaration.kind !== 152) || !!declaration.body; } function checkSourceElement(node) { @@ -37057,143 +38756,189 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 233: - case 229: + case 234: case 230: - case 228: + case 231: + case 229: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 145: - return checkTypeParameter(node); case 146: + return checkTypeParameter(node); + case 147: return checkParameter(node); + case 150: case 149: - case 148: return checkPropertyDeclaration(node); - case 160: case 161: - case 155: + case 162: case 156: - return checkSignatureDeclaration(node); case 157: return checkSignatureDeclaration(node); + case 158: + return checkSignatureDeclaration(node); + case 152: case 151: - case 150: return checkMethodDeclaration(node); - case 152: - return checkConstructorDeclaration(node); case 153: + return checkConstructorDeclaration(node); case 154: + case 155: return checkAccessorDeclaration(node); - case 159: + case 160: return checkTypeReferenceNode(node); - case 158: + case 159: return checkTypePredicate(node); - case 162: - return checkTypeQuery(node); case 163: - return checkTypeLiteral(node); + return checkTypeQuery(node); case 164: - return checkArrayType(node); + return checkTypeLiteral(node); case 165: - return checkTupleType(node); + return checkArrayType(node); case 166: + return checkTupleType(node); case 167: - return checkUnionOrIntersectionType(node); case 168: - case 170: + return checkUnionOrIntersectionType(node); + case 169: return checkSourceElement(node.type); - case 283: + case 171: + return checkTypeOperator(node); + case 282: + return checkJSDocAugmentsTag(node); + case 288: return checkJSDocTypedefTag(node); - case 279: - return checkSourceElement(node.typeExpression); - case 273: + case 284: + return checkJSDocParameterTag(node); + case 277: checkSignatureDeclaration(node); + case 275: case 274: - case 271: - case 270: - case 268: - case 269: - if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); - } + case 272: + case 273: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); return; - case 267: + case 278: + checkJSDocVariadicType(node); + return; + case 271: return checkSourceElement(node.type); - case 171: - return checkIndexedAccessType(node); case 172: + return checkIndexedAccessType(node); + case 173: return checkMappedType(node); - case 228: + case 229: return checkFunctionDeclaration(node); - case 207: - case 234: - return checkBlock(node); case 208: + case 235: + return checkBlock(node); + case 209: return checkVariableStatement(node); - case 210: - return checkExpressionStatement(node); case 211: - return checkIfStatement(node); + return checkExpressionStatement(node); case 212: - return checkDoStatement(node); + return checkIfStatement(node); case 213: - return checkWhileStatement(node); + return checkDoStatement(node); case 214: - return checkForStatement(node); + return checkWhileStatement(node); case 215: - return checkForInStatement(node); + return checkForStatement(node); case 216: - return checkForOfStatement(node); + return checkForInStatement(node); case 217: + return checkForOfStatement(node); case 218: - return checkBreakOrContinueStatement(node); case 219: - return checkReturnStatement(node); + return checkBreakOrContinueStatement(node); case 220: - return checkWithStatement(node); + return checkReturnStatement(node); case 221: - return checkSwitchStatement(node); + return checkWithStatement(node); case 222: - return checkLabeledStatement(node); + return checkSwitchStatement(node); case 223: - return checkThrowStatement(node); + return checkLabeledStatement(node); case 224: + return checkThrowStatement(node); + case 225: return checkTryStatement(node); - case 226: + case 227: return checkVariableDeclaration(node); - case 176: + case 177: return checkBindingElement(node); - case 229: - return checkClassDeclaration(node); case 230: - return checkInterfaceDeclaration(node); + return checkClassDeclaration(node); case 231: - return checkTypeAliasDeclaration(node); + return checkInterfaceDeclaration(node); case 232: - return checkEnumDeclaration(node); + return checkTypeAliasDeclaration(node); case 233: + return checkEnumDeclaration(node); + case 234: return checkModuleDeclaration(node); - case 238: + case 239: return checkImportDeclaration(node); - case 237: + case 238: return checkImportEqualsDeclaration(node); - case 244: + case 245: return checkExportDeclaration(node); - case 243: + case 244: return checkExportAssignment(node); - case 209: + case 210: checkGrammarStatementInAmbientContext(node); return; - case 225: + case 226: checkGrammarStatementInAmbientContext(node); return; - case 247: + case 248: return checkMissingDeclaration(node); } } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJavaScriptFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + var parent = node.parent; + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = parent.parent; + if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (param) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + var lastParamDeclaration = host_1 && ts.last(host_1.parameters); + if (lastParamDeclaration.symbol === param && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + return addOptionality(type); + } function checkNodeDeferred(node) { if (deferredNodes) { deferredNodes.push(node); @@ -37203,17 +38948,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 186: case 187: + case 188: + case 152: case 151: - case 150: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 153: case 154: + case 155: checkAccessorDeclaration(node); break; - case 199: + case 200: checkClassExpressionDeferred(node); break; } @@ -37239,7 +38984,7 @@ var ts; flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); - if (ts.isExternalModule(node)) { + if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile) { @@ -37299,19 +39044,8 @@ var ts; throw new Error("Trying to get diagnostics from a type checker that does not produce them."); } } - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { + if (location.flags & 4194304) { return []; } var symbols = ts.createSymbolTable(); @@ -37324,24 +39058,24 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 233: + case 234: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); break; - case 232: + case 233: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 199: + case 200: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 229: case 230: + case 231: if (!isStatic) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064); } break; - case 186: + case 187: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -37379,27 +39113,27 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 145: - case 229: + case 146: case 230: case 231: case 232: + case 233: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 143) { + while (node.parent && node.parent.kind === 144) { node = node.parent; } - return node.parent && node.parent.kind === 159; + return node.parent && node.parent.kind === 160; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 179) { + while (node.parent && node.parent.kind === 180) { node = node.parent; } - return node.parent && node.parent.kind === 201; + return node.parent && node.parent.kind === 202; } function forEachEnclosingClass(node, callback) { var result; @@ -37412,17 +39146,28 @@ var ts; } return result; } + function isNodeWithinConstructorOfClass(node, classDeclaration) { + return ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + return true; + } + else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } function isNodeWithinClass(node, classDeclaration) { return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143) { + while (nodeOnRightSide.parent.kind === 144) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 237) { + if (nodeOnRightSide.parent.kind === 238) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 243) { + if (nodeOnRightSide.parent.kind === 244) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -37447,18 +39192,18 @@ var ts; return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 && + entityName.parent.kind === 180 && entityName.parent === entityName.parent.parent.left) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); if (specialPropertyAssignmentSymbol) { return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 244 && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); } - if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 237); + if (entityName.kind !== 180 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 238); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); } @@ -37467,7 +39212,7 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 201) { + if (entityName.parent.kind === 202) { meaning = 793064; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -37482,15 +39227,15 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 279) { + if (entityName.parent.kind === 284) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 145 && entityName.parent.parent.kind === 282) { + if (entityName.parent.kind === 146 && entityName.parent.parent.kind === 287) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } - if (ts.isPartOfExpression(entityName)) { + if (ts.isExpressionNode(entityName)) { if (ts.nodeIsMissing(entityName)) { return undefined; } @@ -37500,12 +39245,12 @@ var ts; } return resolveEntityName(entityName, 107455, false, true); } - else if (entityName.kind === 179 || entityName.kind === 143) { + else if (entityName.kind === 180 || entityName.kind === 144) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 179) { + if (entityName.kind === 180) { checkPropertyAccessExpression(entityName); } else { @@ -37515,22 +39260,22 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 159 ? 793064 : 1920; + var meaning = entityName.parent.kind === 160 ? 793064 : 1920; return resolveEntityName(entityName, meaning, false, true); } - else if (entityName.parent.kind === 253) { + else if (entityName.parent.kind === 257) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 158) { + if (entityName.parent.kind === 159) { return resolveEntityName(entityName, 1); } return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 265) { + if (node.kind === 269) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { @@ -37543,8 +39288,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 176 && - node.parent.parent.kind === 174 && + else if (node.parent.kind === 177 && + node.parent.parent.kind === 175 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); @@ -37555,8 +39300,8 @@ var ts; } switch (node.kind) { case 71: - case 179: - case 143: + case 180: + case 144: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99: var container = ts.getThisContainer(node, false); @@ -37569,19 +39314,19 @@ var ts; if (ts.isInExpressionContext(node)) { return checkExpression(node).symbol; } - case 169: + case 170: return getTypeFromThisTypeNode(node).symbol; case 97: return checkExpression(node).symbol; case 123: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152) { + if (constructorDeclaration && constructorDeclaration.kind === 153) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 239 || node.parent.kind === 245) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } @@ -37593,13 +39338,15 @@ var ts; : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79: + case 89: + case 36: return getSymbolOfNode(node.parent); default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 262) { + if (location && location.kind === 266) { return resolveEntityName(location.name, 107455 | 2097152); } return undefined; @@ -37610,7 +39357,7 @@ var ts; resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 2097152); } function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304) { return unknownType; } if (ts.isPartOfTypeNode(node)) { @@ -37622,7 +39369,7 @@ var ts; } return typeFromTypeNode; } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -37658,20 +39405,20 @@ var ts; return unknownType; } function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 || expr.kind === 177); - if (expr.parent.kind === 216) { + ts.Debug.assert(expr.kind === 179 || expr.kind === 178); + if (expr.parent.kind === 217) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 194) { + if (expr.parent.kind === 195) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 261) { + if (expr.parent.kind === 265) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 177); + ts.Debug.assert(expr.parent.kind === 178); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); @@ -37695,7 +39442,7 @@ var ts; function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { + if (typeHasCallOrConstructSignatures(type)) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); @@ -37704,12 +39451,15 @@ var ts; } return getNamedMembers(propsByName); } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { var symbols_4 = []; - var name_3 = symbol.escapedName; + var name_4 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_3); + var symbol = getPropertyOfType(t, name_4); if (symbol) { symbols_4.push(symbol); } @@ -37739,7 +39489,7 @@ var ts; if (!ts.isGeneratedIdentifier(node)) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 180 && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -37782,7 +39532,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 269) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -37816,7 +39566,7 @@ var ts; else if (nodeLinks_1.flags & 131072) { var isDeclaredInLoop = nodeLinks_1.flags & 262144; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 208 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -37852,16 +39602,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 237: - case 239: + case 238: case 240: - case 242: - case 246: + case 241: + case 243: + case 247: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244: + case 245: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243: + case 244: return node.expression && node.expression.kind === 71 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -37871,7 +39621,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 269 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -37894,6 +39644,10 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } + var target = getSymbolLinks(symbol).target; + if (target && ts.getModifierFlags(node) & 1 && target.flags & 107455) { + return true; + } } if (checkChildren) { return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); @@ -37930,15 +39684,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 264: - case 179: + case 268: case 180: + case 181: return true; } return false; } function getConstantValue(node) { - if (node.kind === 264) { + if (node.kind === 268) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -37950,7 +39704,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 65536 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { typeName = ts.getParseTreeNode(typeName, ts.isEntityName); @@ -37983,7 +39737,7 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 1024 | 6144 | 8192)) { + else if (isTypeAssignableToKind(type, 2048 | 12288 | 16384)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } else if (isTypeAssignableToKind(type, 136)) { @@ -37992,13 +39746,13 @@ var ts; else if (isTypeAssignableToKind(type, 84)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 262178)) { + else if (isTypeAssignableToKind(type, 524322)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 512)) { + else if (isTypeAssignableToKind(type, 1536)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -38016,8 +39770,12 @@ var ts; var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (type.flags & 1024 && + type.symbol === symbol) { + flags |= 131072; + } if (flags & 8192) { - type = getNullableType(type, 2048); + type = getOptionalType(type); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -38061,7 +39819,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 1048576); + return !!(type.flags & 96 && type.flags & 2097152); } return false; } @@ -38124,6 +39882,11 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024); + }, writeLiteralConstValue: writeLiteralConstValue, getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; @@ -38131,7 +39894,7 @@ var ts; if (!fileToDirective) { return undefined; } - var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) + var meaning = (node.kind === 180) || (node.kind === 71 && isInTypeQuery(node)) ? 107455 | 1048576 : 793064 | 1920; var symbol = resolveEntityName(node, meaning, true); @@ -38174,7 +39937,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 269 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -38193,7 +39956,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 265); + return ts.getDeclarationOfKind(moduleSymbol, 269); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -38243,6 +40006,9 @@ var ts; globalRegExpType = getGlobalType("RegExp", 0, true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", 1); @@ -38250,11 +40016,11 @@ var ts; function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 32768; helper <<= 1) { + for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); @@ -38286,6 +40052,7 @@ var ts; case 8192: return "__asyncDelegator"; case 16384: return "__asyncValues"; case 32768: return "__exportStar"; + case 65536: return "__makeTemplateObject"; default: ts.Debug.fail("Unrecognized helper"); } } @@ -38295,19 +40062,22 @@ var ts; } return externalHelpersModule; } + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } function checkGrammarDecorators(node) { if (!node.decorators) { return false; } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 152 && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 153 || node.kind === 154) { + else if (node.kind === 154 || node.kind === 155) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -38325,16 +40095,16 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 131) { - if (node.kind === 148 || node.kind === 150) { + if (node.kind === 149 || node.kind === 151) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 157) { + if (node.kind === 158) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 76: - if (node.kind !== 232 && node.parent.kind === 229) { + if (node.kind !== 233 && node.parent.kind === 230) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); } break; @@ -38354,7 +40124,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 234 || node.parent.kind === 265) { + else if (node.parent.kind === 235 || node.parent.kind === 269) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { @@ -38377,10 +40147,10 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 234 || node.parent.kind === 265) { + else if (node.parent.kind === 235 || node.parent.kind === 269) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { @@ -38393,7 +40163,7 @@ var ts; if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { + else if (node.kind !== 150 && node.kind !== 149 && node.kind !== 158 && node.kind !== 147) { return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64; @@ -38412,17 +40182,17 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; case 79: - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 ? node.parent : node.parent.parent; + if (container.kind === 234 && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512; @@ -38434,13 +40204,13 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { + else if ((node.parent.flags & 2097152) && node.parent.kind === 235) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; @@ -38450,14 +40220,14 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 229) { - if (node.kind !== 151 && - node.kind !== 149 && - node.kind !== 153 && - node.kind !== 154) { + if (node.kind !== 230) { + if (node.kind !== 152 && + node.kind !== 150 && + node.kind !== 154 && + node.kind !== 155) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 && ts.hasModifier(node.parent, 128))) { + if (!(node.parent.kind === 230 && ts.hasModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -38473,10 +40243,10 @@ var ts; if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 || node.parent.flags & 2097152) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 146) { + else if (node.kind === 147) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -38484,7 +40254,7 @@ var ts; break; } } - if (node.kind === 152) { + if (node.kind === 153) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -38499,13 +40269,13 @@ var ts; } return; } - else if ((node.kind === 238 || node.kind === 237) && flags & 2) { + else if ((node.kind === 239 || node.kind === 238) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { + else if (node.kind === 147 && (flags & 92) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { + else if (node.kind === 147 && (flags & 92) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -38521,37 +40291,37 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 153: case 154: - case 152: + case 155: + case 153: + case 150: case 149: - case 148: + case 152: case 151: - case 150: - case 157: - case 233: + case 158: + case 234: + case 239: case 238: - case 237: + case 245: case 244: - case 243: - case 186: case 187: - case 146: + case 188: + case 147: return false; default: - if (node.parent.kind === 234 || node.parent.kind === 265) { + if (node.parent.kind === 235 || node.parent.kind === 269) { return false; } switch (node.kind) { - case 228: - return nodeHasAnyModifiersExcept(node, 120); case 229: - return nodeHasAnyModifiersExcept(node, 117); + return nodeHasAnyModifiersExcept(node, 120); case 230: - case 208: + return nodeHasAnyModifiersExcept(node, 117); case 231: - return true; + case 209: case 232: + return true; + case 233: return nodeHasAnyModifiersExcept(node, 76); default: ts.Debug.fail(); @@ -38564,10 +40334,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 151: - case 228: - case 186: + case 152: + case 229: case 187: + case 188: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -38621,7 +40391,7 @@ var ts; } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarClassLikeDeclaration(node) { @@ -38629,7 +40399,7 @@ var ts; return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 187) { + if (node.kind === 188) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -38672,7 +40442,7 @@ var ts; } } function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -38690,7 +40460,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 200) { + if (arg.kind === 201) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -38716,7 +40486,7 @@ var ts; function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; if (heritageClause.token === 85) { @@ -38763,20 +40533,20 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 144) { + if (node.kind !== 145) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { + if (computedPropertyName.expression.kind === 195 && computedPropertyName.expression.operatorToken.kind === 26) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 || - node.kind === 186 || - node.kind === 151); - if (ts.isInAmbientContext(node)) { + ts.Debug.assert(node.kind === 229 || + node.kind === 187 || + node.kind === 152); + if (node.flags & 2097152) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -38790,50 +40560,53 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); var seen = ts.createUnderscoreEscapedMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263) { + if (prop.kind === 267) { continue; } var name = prop.name; - if (name.kind === 144) { + if (name.kind === 145) { checkGrammarComputedPropertyName(name); } - if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 266 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 151) { + if (mod.kind !== 120 || prop.kind !== 152) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } var currentKind = void 0; - if (prop.kind === 261 || prop.kind === 262) { - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151) { - currentKind = Property; - } - else if (prop.kind === 153) { - currentKind = GetAccessor; - } - else if (prop.kind === 154) { - currentKind = SetAccessor; - } - else { - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + switch (prop.kind) { + case 265: + case 266: + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8) { + checkGrammarNumericLiteral(name); + } + case 152: + currentKind = 1; + break; + case 154: + currentKind = 2; + break; + case 155: + currentKind = 4; + break; + default: + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -38844,11 +40617,11 @@ var ts; seen.set(effectiveName, currentKind); } else { - if (currentKind === Property && existingKind === Property) { + if (currentKind === 1 && existingKind === 1) { grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + else if ((currentKind & 6) && (existingKind & 6)) { + if (existingKind !== 6 && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { @@ -38865,7 +40638,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 255) { + if (attr.kind === 259) { continue; } var jsxAttr = attr; @@ -38877,7 +40650,7 @@ var ts; return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 && !initializer.expression) { + if (initializer && initializer.kind === 260 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -38886,12 +40659,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 217 && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384) === 0) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 227) { + if (forInOrOfStatement.initializer.kind === 228) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -38899,20 +40672,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -38926,7 +40699,7 @@ var ts; if (languageVersion < 1) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (ts.isInAmbientContext(accessor)) { + else if (accessor.flags & 2097152) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { @@ -38939,11 +40712,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 ? + return grammarErrorOnNode(accessor.name, kind === 154 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 154) { + else if (kind === 155) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -38962,15 +40735,50 @@ var ts; } } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 154 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 154 ? 1 : 2)) { return ts.getThisParameter(accessor); } } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 140) { + if (node.type.kind !== 137) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(137)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 227: + var decl = parent; + if (decl.name.kind !== 71) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 150: + if (!ts.hasModifier(parent, 32) || + !ts.hasModifier(parent, 64)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 149: + if (!ts.hasModifier(parent, 64)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -38980,7 +40788,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 178) { + if (node.parent.kind === 179) { if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } @@ -38989,18 +40797,18 @@ var ts; } } if (ts.isClassLike(node.parent)) { - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + if (node.flags & 2097152) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 230) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 231) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 163) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 164) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } function checkGrammarBreakOrContinueStatement(node) { @@ -39010,9 +40818,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 222: + case 223: if (node.label && current.label.escapedText === node.label.escapedText) { - var isMisplacedContinueLabel = node.kind === 217 + var isMisplacedContinueLabel = node.kind === 218 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -39020,8 +40828,8 @@ var ts; return false; } break; - case 221: - if (node.kind === 218 && !node.label) { + case 222: + if (node.kind === 219 && !node.label) { return false; } break; @@ -39034,13 +40842,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 218 + var message = node.kind === 219 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 218 + var message = node.kind === 219 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -39052,7 +40860,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 175 || node.name.kind === 174) { + if (node.name.kind === 176 || node.name.kind === 175) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -39062,12 +40870,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && + expr.kind === 193 && expr.operator === 38 && expr.operand.kind === 8; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { - if (ts.isInAmbientContext(node)) { + if (node.parent.parent.kind !== 216 && node.parent.parent.kind !== 217) { + if (node.flags & 2097152) { if (node.initializer) { if (ts.isConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { @@ -39093,8 +40901,11 @@ var ts; } } } + if (node.exclamationToken && (node.parent.parent.kind !== 209 || !node.type || node.initializer || node.flags & 2097152)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + !(node.parent.parent.flags & 2097152) && ts.hasModifier(node.parent.parent, 1)) { checkESModuleMarker(node.name); } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); @@ -39102,7 +40913,7 @@ var ts; } function checkESModuleMarker(name) { if (name.kind === 71) { - if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } } @@ -39143,15 +40954,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 211: case 212: case 213: - case 220: case 214: + case 221: case 215: case 216: + case 217: return false; - case 222: + case 223: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -39199,49 +41010,56 @@ var ts; } } function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } } function checkGrammarProperty(node) { if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } } - else if (node.parent.kind === 230) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 231) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 163) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 164) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (ts.isInAmbientContext(node) && node.initializer) { + if (node.flags & 2097152 && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } + if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 2097152 || ts.hasModifier(node, 32 | 128))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 230 || - node.kind === 231 || + if (node.kind === 231 || + node.kind === 232 || + node.kind === 239 || node.kind === 238 || - node.kind === 237 || + node.kind === 245 || node.kind === 244 || - node.kind === 243 || - node.kind === 236 || + node.kind === 237 || ts.hasModifier(node, 2 | 1 | 512)) { return false; } @@ -39250,7 +41068,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208) { + if (ts.isDeclaration(decl) || decl.kind === 209) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -39258,10 +41076,10 @@ var ts; } } function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 2097152) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152) { if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; } @@ -39269,7 +41087,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { + if (node.parent.kind === 208 || node.parent.kind === 235 || node.parent.kind === 269) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -39280,15 +41098,15 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 4) { + if (node.numericLiteralFlags & 32) { var diagnosticMessage = void 0; if (languageVersion >= 1) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 173)) { + else if (ts.isChildOfNodeWithKind(node, 174)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 264)) { + else if (ts.isChildOfNodeWithKind(node, 268)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -39307,13 +41125,15 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -39334,8 +41154,8 @@ var ts; ts.createTypeChecker = createTypeChecker; function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 242: - case 246: + case 243: + case 247: return true; default: return ts.isDeclarationName(name); @@ -39343,17 +41163,28 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 239: - case 237: case 240: - case 242: + case 238: + case 241: + case 243: return true; case 71: - return decl.parent.kind === 242; + return decl.parent.kind === 243; default: return false; } } + var JsxNames; + (function (JsxNames) { + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + })(JsxNames || (JsxNames = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -39366,9 +41197,6 @@ var ts; if (updated !== original) { setOriginalNode(updated, original); setTextRange(updated, original); - if (original.startsOnNewLine) { - updated.startsOnNewLine = true; - } ts.aggregateTransformFlags(updated); } return updated; @@ -39391,6 +41219,9 @@ var ts; } ts.createNodeArray = createNodeArray; function getSynthesizedClone(node) { + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -39410,7 +41241,7 @@ var ts; if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } - if (typeof value === "string") { + if (ts.isString(value)) { return createStringLiteral(value); } return createLiteralFromNode(value); @@ -39447,7 +41278,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -39479,11 +41310,12 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - function getGeneratedNameForNode(node) { + function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateKind = 4; name.autoGenerateId = nextAutoGenerateId; name.original = node; + name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; nextAutoGenerateId++; return name; } @@ -39513,7 +41345,7 @@ var ts; } ts.createFalse = createFalse; function createQualifiedName(left, right) { - var node = createSynthesizedNode(143); + var node = createSynthesizedNode(144); node.left = left; node.right = asName(right); return node; @@ -39527,7 +41359,7 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function createComputedPropertyName(expression) { - var node = createSynthesizedNode(144); + var node = createSynthesizedNode(145); node.expression = expression; return node; } @@ -39539,7 +41371,7 @@ var ts; } ts.updateComputedPropertyName = updateComputedPropertyName; function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(145); + var node = createSynthesizedNode(146); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -39555,7 +41387,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(146); + var node = createSynthesizedNode(147); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -39579,7 +41411,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(147); + var node = createSynthesizedNode(148); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -39591,7 +41423,7 @@ var ts; } ts.updateDecorator = updateDecorator; function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148); + var node = createSynthesizedNode(149); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -39611,7 +41443,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149); + var node = createSynthesizedNode(150); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -39633,7 +41465,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(150, typeParameters, parameters, type); + var node = createSignatureDeclaration(151, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -39650,7 +41482,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(151); + var node = createSynthesizedNode(152); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -39678,7 +41510,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(152); + var node = createSynthesizedNode(153); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -39698,7 +41530,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(153); + var node = createSynthesizedNode(154); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -39721,7 +41553,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(154); + var node = createSynthesizedNode(155); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -39742,7 +41574,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); + return createSignatureDeclaration(156, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -39750,7 +41582,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); + return createSignatureDeclaration(157, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -39758,7 +41590,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(157); + var node = createSynthesizedNode(158); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -39795,7 +41627,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(158); + var node = createSynthesizedNode(159); node.parameterName = asName(parameterName); node.type = type; return node; @@ -39809,7 +41641,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(159); + var node = createSynthesizedNode(160); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -39823,7 +41655,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); + return createSignatureDeclaration(161, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -39831,7 +41663,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); + return createSignatureDeclaration(162, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -39839,7 +41671,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(162); + var node = createSynthesizedNode(163); node.exprName = exprName; return node; } @@ -39851,7 +41683,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(163); + var node = createSynthesizedNode(164); node.members = createNodeArray(members); return node; } @@ -39863,7 +41695,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(164); + var node = createSynthesizedNode(165); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -39875,7 +41707,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(165); + var node = createSynthesizedNode(166); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -39887,7 +41719,7 @@ var ts; } ts.updateTypleTypeNode = updateTypleTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(166, types); + return createUnionOrIntersectionTypeNode(167, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -39895,7 +41727,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(167, types); + return createUnionOrIntersectionTypeNode(168, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -39914,7 +41746,7 @@ var ts; : node; } function createParenthesizedType(type) { - var node = createSynthesizedNode(168); + var node = createSynthesizedNode(169); node.type = type; return node; } @@ -39926,22 +41758,22 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(169); + return createSynthesizedNode(170); } ts.createThisTypeNode = createThisTypeNode; - function createTypeOperatorNode(type) { - var node = createSynthesizedNode(170); - node.operator = 127; - node.type = ts.parenthesizeElementTypeMember(type); + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(171); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 127; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } ts.createTypeOperatorNode = createTypeOperatorNode; function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(171); + var node = createSynthesizedNode(172); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -39955,7 +41787,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(172); + var node = createSynthesizedNode(173); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -39973,7 +41805,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(173); + var node = createSynthesizedNode(174); node.literal = literal; return node; } @@ -39985,7 +41817,7 @@ var ts; } ts.updateLiteralTypeNode = updateLiteralTypeNode; function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(174); + var node = createSynthesizedNode(175); node.elements = createNodeArray(elements); return node; } @@ -39997,7 +41829,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(175); + var node = createSynthesizedNode(176); node.elements = createNodeArray(elements); return node; } @@ -40009,7 +41841,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(176); + var node = createSynthesizedNode(177); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -40027,7 +41859,7 @@ var ts; } ts.updateBindingElement = updateBindingElement; function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(177); + var node = createSynthesizedNode(178); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -40041,7 +41873,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(178); + var node = createSynthesizedNode(179); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -40055,7 +41887,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(179); + var node = createSynthesizedNode(180); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); setEmitFlags(node, 131072); @@ -40070,7 +41902,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(180); + var node = createSynthesizedNode(181); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -40084,7 +41916,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(181); + var node = createSynthesizedNode(182); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -40100,7 +41932,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(182); + var node = createSynthesizedNode(183); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -40116,7 +41948,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(183); + var node = createSynthesizedNode(184); node.tag = ts.parenthesizeForAccess(tag); node.template = template; return node; @@ -40130,7 +41962,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(184); + var node = createSynthesizedNode(185); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -40144,7 +41976,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(185); + var node = createSynthesizedNode(186); node.expression = expression; return node; } @@ -40156,7 +41988,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(186); + var node = createSynthesizedNode(187); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -40180,7 +42012,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(187); + var node = createSynthesizedNode(188); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -40214,7 +42046,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(188); + var node = createSynthesizedNode(189); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40226,7 +42058,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(189); + var node = createSynthesizedNode(190); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40238,7 +42070,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(190); + var node = createSynthesizedNode(191); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40250,7 +42082,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(191); + var node = createSynthesizedNode(192); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -40262,7 +42094,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(192); + var node = createSynthesizedNode(193); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -40275,7 +42107,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(193); + var node = createSynthesizedNode(194); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -40288,7 +42120,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(194); + var node = createSynthesizedNode(195); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -40305,7 +42137,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(195); + var node = createSynthesizedNode(196); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -40335,7 +42167,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(196); + var node = createSynthesizedNode(197); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -40373,7 +42205,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(197); + var node = createSynthesizedNode(198); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 ? asteriskTokenOrExpression : expression; return node; @@ -40387,7 +42219,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(198); + var node = createSynthesizedNode(199); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -40399,7 +42231,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(199); + var node = createSynthesizedNode(200); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40420,11 +42252,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(200); + return createSynthesizedNode(201); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(201); + var node = createSynthesizedNode(202); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -40438,7 +42270,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(202); + var node = createSynthesizedNode(203); node.expression = expression; node.type = type; return node; @@ -40452,7 +42284,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(203); + var node = createSynthesizedNode(204); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -40464,7 +42296,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(204); + var node = createSynthesizedNode(205); node.keywordToken = keywordToken; node.name = name; return node; @@ -40477,7 +42309,7 @@ var ts; } ts.updateMetaProperty = updateMetaProperty; function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(205); + var node = createSynthesizedNode(206); node.expression = expression; node.literal = literal; return node; @@ -40491,11 +42323,11 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(206); + return createSynthesizedNode(207); } ts.createSemicolonClassElement = createSemicolonClassElement; function createBlock(statements, multiLine) { - var block = createSynthesizedNode(207); + var block = createSynthesizedNode(208); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -40509,7 +42341,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(208); + var node = createSynthesizedNode(209); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -40524,11 +42356,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(209); + return createSynthesizedNode(210); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(210); + var node = createSynthesizedNode(211); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -40540,7 +42372,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(211); + var node = createSynthesizedNode(212); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -40556,7 +42388,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(212); + var node = createSynthesizedNode(213); node.statement = statement; node.expression = expression; return node; @@ -40570,7 +42402,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(213); + var node = createSynthesizedNode(214); node.expression = expression; node.statement = statement; return node; @@ -40584,7 +42416,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(214); + var node = createSynthesizedNode(215); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -40602,7 +42434,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(215); + var node = createSynthesizedNode(216); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -40618,7 +42450,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(216); + var node = createSynthesizedNode(217); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -40636,7 +42468,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(217); + var node = createSynthesizedNode(218); node.label = asName(label); return node; } @@ -40648,7 +42480,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(218); + var node = createSynthesizedNode(219); node.label = asName(label); return node; } @@ -40660,7 +42492,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(219); + var node = createSynthesizedNode(220); node.expression = expression; return node; } @@ -40672,7 +42504,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(220); + var node = createSynthesizedNode(221); node.expression = expression; node.statement = statement; return node; @@ -40686,7 +42518,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(221); + var node = createSynthesizedNode(222); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -40700,7 +42532,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(222); + var node = createSynthesizedNode(223); node.label = asName(label); node.statement = statement; return node; @@ -40714,7 +42546,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(223); + var node = createSynthesizedNode(224); node.expression = expression; return node; } @@ -40726,7 +42558,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(224); + var node = createSynthesizedNode(225); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -40742,11 +42574,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(225); + return createSynthesizedNode(226); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); + var node = createSynthesizedNode(227); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -40762,7 +42594,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); + var node = createSynthesizedNode(228); node.flags |= flags & 3; node.declarations = createNodeArray(declarations); return node; @@ -40775,7 +42607,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(228); + var node = createSynthesizedNode(229); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -40801,7 +42633,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(229); + var node = createSynthesizedNode(230); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40823,7 +42655,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(230); + var node = createSynthesizedNode(231); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40845,7 +42677,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(231); + var node = createSynthesizedNode(232); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40865,7 +42697,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(232); + var node = createSynthesizedNode(233); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40883,7 +42715,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(233); + var node = createSynthesizedNode(234); node.flags |= flags & (16 | 4 | 512); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -40902,7 +42734,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(234); + var node = createSynthesizedNode(235); node.statements = createNodeArray(statements); return node; } @@ -40914,7 +42746,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(235); + var node = createSynthesizedNode(236); node.clauses = createNodeArray(clauses); return node; } @@ -40926,7 +42758,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(236); + var node = createSynthesizedNode(237); node.name = asName(name); return node; } @@ -40938,7 +42770,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(237); + var node = createSynthesizedNode(238); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -40956,7 +42788,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(238); + var node = createSynthesizedNode(239); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -40974,7 +42806,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(239); + var node = createSynthesizedNode(240); node.name = name; node.namedBindings = namedBindings; return node; @@ -40988,7 +42820,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(240); + var node = createSynthesizedNode(241); node.name = name; return node; } @@ -41000,7 +42832,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(241); + var node = createSynthesizedNode(242); node.elements = createNodeArray(elements); return node; } @@ -41012,7 +42844,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(242); + var node = createSynthesizedNode(243); node.propertyName = propertyName; node.name = name; return node; @@ -41026,11 +42858,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(243); + var node = createSynthesizedNode(244); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = expression; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58, expression, false, undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -41043,7 +42875,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(244); + var node = createSynthesizedNode(245); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -41061,7 +42893,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(245); + var node = createSynthesizedNode(246); node.elements = createNodeArray(elements); return node; } @@ -41073,7 +42905,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246); + var node = createSynthesizedNode(247); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -41087,7 +42919,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createExternalModuleReference(expression) { - var node = createSynthesizedNode(248); + var node = createSynthesizedNode(249); node.expression = expression; return node; } @@ -41099,7 +42931,7 @@ var ts; } ts.updateExternalModuleReference = updateExternalModuleReference; function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(249); + var node = createSynthesizedNode(250); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -41115,7 +42947,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(250); + var node = createSynthesizedNode(251); node.tagName = tagName; node.attributes = attributes; return node; @@ -41129,7 +42961,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(251); + var node = createSynthesizedNode(252); node.tagName = tagName; node.attributes = attributes; return node; @@ -41143,7 +42975,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(252); + var node = createSynthesizedNode(253); node.tagName = tagName; return node; } @@ -41154,8 +42986,24 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(254); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(253); + var node = createSynthesizedNode(257); node.name = name; node.initializer = initializer; return node; @@ -41169,7 +43017,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(254); + var node = createSynthesizedNode(258); node.properties = createNodeArray(properties); return node; } @@ -41181,7 +43029,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(255); + var node = createSynthesizedNode(259); node.expression = expression; return node; } @@ -41193,7 +43041,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(256); + var node = createSynthesizedNode(260); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -41206,7 +43054,7 @@ var ts; } ts.updateJsxExpression = updateJsxExpression; function createCaseClause(expression, statements) { - var node = createSynthesizedNode(257); + var node = createSynthesizedNode(261); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -41220,7 +43068,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(258); + var node = createSynthesizedNode(262); node.statements = createNodeArray(statements); return node; } @@ -41232,7 +43080,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); + var node = createSynthesizedNode(263); node.token = token; node.types = createNodeArray(types); return node; @@ -41245,8 +43093,8 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(260); - node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + var node = createSynthesizedNode(264); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; } @@ -41259,7 +43107,7 @@ var ts; } ts.updateCatchClause = updateCatchClause; function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(261); + var node = createSynthesizedNode(265); node.name = asName(name); node.questionToken = undefined; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -41274,7 +43122,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(262); + var node = createSynthesizedNode(266); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -41288,7 +43136,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(263); + var node = createSynthesizedNode(267); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; return node; } @@ -41300,7 +43148,7 @@ var ts; } ts.updateSpreadAssignment = updateSpreadAssignment; function createEnumMember(name, initializer) { - var node = createSynthesizedNode(264); + var node = createSynthesizedNode(268); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -41315,7 +43163,7 @@ var ts; ts.updateEnumMember = updateEnumMember; function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createSynthesizedNode(265); + var updated = createSynthesizedNode(269); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -41384,28 +43232,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(287); + var node = createSynthesizedNode(291); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(291); + var node = createSynthesizedNode(295); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(290); + var node = createSynthesizedNode(294); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(288); + var node = createSynthesizedNode(292); node.expression = expression; node.original = original; setTextRange(node, original); @@ -41421,7 +43269,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 289) { + if (node.kind === 293) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -41431,7 +43279,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(289); + var node = createSynthesizedNode(293); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -41443,7 +43291,7 @@ var ts; } ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { - var node = ts.createNode(266); + var node = ts.createNode(270); node.sourceFiles = sourceFiles; return node; } @@ -41520,10 +43368,10 @@ var ts; } ts.createExternalModuleExport = createExternalModuleExport; function asName(name) { - return typeof name === "string" ? createIdentifier(name) : name; + return ts.isString(name) ? createIdentifier(name) : name; } function asExpression(value) { - return typeof value === "string" || typeof value === "number" ? createLiteral(value) : value; + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -41546,7 +43394,7 @@ var ts; function getOrCreateEmitNode(node) { if (!node.emitNode) { if (ts.isParseTreeNode(node)) { - if (node.kind === 265) { + if (node.kind === 269) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -41570,6 +43418,12 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; function getSourceMapRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.sourceMapRange) || node; @@ -41598,6 +43452,16 @@ var ts; return node; } ts.setTokenSourceMapRange = setTokenSourceMapRange; + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; function getCommentRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.commentRange) || node; @@ -41725,7 +43589,7 @@ var ts; } ts.setOriginalNode = setOriginalNode; function mergeEmitNode(sourceEmitNode, destEmitNode) { - var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; if (!destEmitNode) destEmitNode = {}; if (leadingComments) @@ -41744,6 +43608,8 @@ var ts; destEmitNode.constantValue = constantValue; if (helpers) destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -41832,12 +43698,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); + return createReactNamespace(ts.idText(jsxFactory), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -41857,7 +43723,7 @@ var ts; if (children.length > 1) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; - child.startsOnNewLine = true; + startOnNewLine(child); argumentsList.push(child); } } @@ -41868,6 +43734,25 @@ var ts; return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); } ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; function getHelperName(name) { return ts.setEmitFlags(ts.createIdentifier(name), 4096 | 2); } @@ -41930,7 +43815,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 222 + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 223 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -41948,13 +43833,13 @@ var ts; case 8: case 9: return false; - case 177: + case 178: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 178: + case 179: return target.properties.length > 0; default: return true; @@ -41980,7 +43865,7 @@ var ts; } else { switch (callee.kind) { - case 179: { + case 180: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = ts.createTempVariable(recordTempVariable); target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); @@ -41992,7 +43877,7 @@ var ts; } break; } - case 180: { + case 181: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = ts.createTempVariable(recordTempVariable); target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); @@ -42045,14 +43930,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 153: case 154: + case 155: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 261: + case 265: return createExpressionForPropertyAssignment(property, receiver); - case 262: + case 266: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 151: + case 152: return createExpressionForMethodDeclaration(property, receiver); } } @@ -42167,8 +44052,8 @@ var ts; var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); - if (node.startsOnNewLine) { - updated.startsOnNewLine = true; + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, true); } ts.aggregateTransformFlags(updated); return updated; @@ -42211,7 +44096,7 @@ var ts; while (statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { break; @@ -42252,7 +44137,7 @@ var ts; ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 185) { + if (skipped.kind === 186) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -42261,15 +44146,15 @@ var ts; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(194, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(194, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(195, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(195, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 197) { + && operand.kind === 198) { return false; } return true; @@ -42308,7 +44193,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 194 && node.operatorToken.kind === 37) { + if (node.kind === 195 && node.operatorToken.kind === 37) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -42323,7 +44208,7 @@ var ts; return 0; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); + var conditionalPrecedence = ts.getOperatorPrecedence(196, 55); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { @@ -42333,20 +44218,30 @@ var ts; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 194 && e.operatorToken.kind === 26 + return e.kind === 195 && e.operatorToken.kind === 26 ? ts.createParen(e) : e; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + return (check.kind === 200 || + check.kind === 187 || + check.kind === 293 || + ts.isBinaryExpression(check) && check.operatorToken.kind === 26) + ? ts.createParen(e) + : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; function parenthesizeForNew(expression) { - var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); - switch (emittedExpression.kind) { - case 181: - return ts.createParen(expression); + var leftmostExpr = getLeftmostExpression(expression, true); + switch (leftmostExpr.kind) { case 182: - return emittedExpression.arguments - ? expression - : ts.createParen(expression); + return ts.createParen(expression); + case 183: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; } return parenthesizeForAccess(expression); } @@ -42354,7 +44249,7 @@ var ts; function parenthesizeForAccess(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 182 || emittedExpression.arguments)) { + && (emittedExpression.kind !== 183 || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -42392,7 +44287,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(194, 26); + var commaPrecedence = ts.getOperatorPrecedence(195, 26); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -42403,14 +44298,14 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 186 || kind === 187) { + if (kind === 187 || kind === 188) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4); } } - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, false).kind; + if (leftmostExpressionKind === 179 || leftmostExpressionKind === 187) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; @@ -42418,10 +44313,10 @@ var ts; ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 166: case 167: - case 160: + case 168: case 161: + case 162: return ts.createParenthesizedType(member); } return member; @@ -42429,8 +44324,8 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 162: - case 170: + case 163: + case 171: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -42453,24 +44348,27 @@ var ts; } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function getLeftmostExpression(node) { + function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 193: + case 194: node = node.operand; continue; - case 194: + case 195: node = node.left; continue; - case 195: + case 196: node = node.condition; continue; + case 182: + if (stopAtCallExpressions) { + return node; + } case 181: case 180: - case 179: node = node.expression; continue; - case 288: + case 292: node = node.expression; continue; } @@ -42478,7 +44376,7 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body).kind === 178) { + if (!ts.isBlock(body) && getLeftmostExpression(body, false).kind === 179) { return ts.setTextRange(ts.createParen(body), body); } return body; @@ -42494,13 +44392,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7; } switch (node.kind) { - case 185: + case 186: return (kinds & 1) !== 0; - case 184: - case 202: + case 185: case 203: + case 204: return (kinds & 2) !== 0; - case 288: + case 292: return (kinds & 4) !== 0; } return false; @@ -42525,14 +44423,14 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 185) { + while (node.kind === 186) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 203) { + while (ts.isAssertionExpression(node) || node.kind === 204) { node = node.expression; } return node; @@ -42540,15 +44438,15 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 185: return ts.updateParen(outerExpression, expression); - case 184: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 202: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 203: return ts.updateNonNullExpression(outerExpression, expression); - case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 186: return ts.updateParen(outerExpression, expression); + case 185: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 203: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 204: return ts.updateNonNullExpression(outerExpression, expression); + case 292: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { - return node.kind === 185 + return node.kind === 186 && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -42564,8 +44462,7 @@ var ts; } ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { - node.startsOnNewLine = true; - return node; + return ts.setStartsOnNewLine(node, true); } ts.startOnNewLine = startOnNewLine; function getExternalHelpersModuleName(node) { @@ -42609,12 +44506,12 @@ var ts; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { var name = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 238 && node.importClause) { + if (node.kind === 239 && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 244 && node.moduleSpecifier) { + if (node.kind === 245 && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -42676,11 +44573,11 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 261: + case 265: return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 262: + case 266: return bindingElement.name; - case 263: + case 267: return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return undefined; @@ -42696,11 +44593,11 @@ var ts; ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 146: - case 176: + case 147: + case 177: return bindingElement.dotDotDotToken; - case 198: - case 263: + case 199: + case 267: return bindingElement; } return undefined; @@ -42708,7 +44605,7 @@ var ts; ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 176: + case 177: if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) @@ -42716,7 +44613,7 @@ var ts; : propertyName; } break; - case 261: + case 265: if (bindingElement.name) { var propertyName = bindingElement.name; return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) @@ -42724,7 +44621,7 @@ var ts; : propertyName; } break; - case 263: + case 267: return bindingElement.name; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); @@ -42738,11 +44635,11 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 174: case 175: - case 177: - return name.elements; + case 176: case 178: + return name.elements; + case 179: return name.properties; } } @@ -42781,11 +44678,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: - return convertToArrayAssignmentPattern(node); - case 174: + case 176: case 178: + return convertToArrayAssignmentPattern(node); + case 175: + case 179: return convertToObjectAssignmentPattern(node); } } @@ -42921,249 +44818,251 @@ var ts; return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 142) || kind === 169) { + if ((kind > 0 && kind <= 143) || kind === 170) { return node; } switch (kind) { case 71: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 143: - return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 144: - return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145: - return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); + return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); case 146: - return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); case 147: - return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 148: - return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); case 149: - return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 150: - return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 151: - return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); case 152: - return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 153: - return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 154: - return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); + return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 155: - return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); case 156: - return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 157: - return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 158: - return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 159: - return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); case 160: - return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 161: - return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 162: - return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 163: - return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); case 164: - return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); + return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 165: - return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 166: - return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); case 167: - return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 168: + return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + case 169: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170: - return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); case 171: - return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); + return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); case 172: - return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 173: - return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); case 174: - return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); + return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); case 175: - return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 176: - return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); + return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); case 177: - return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); case 178: - return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); case 179: - return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); case 180: - return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); + return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); case 181: - return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); case 182: - return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 183: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 184: - return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 185: - return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 186: - return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188: - return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 189: - return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 190: - return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: - return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); case 192: - return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); + return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); case 193: - return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); + return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); case 194: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); case 195: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 196: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 197: - return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 198: - return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); case 199: + return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); + case 200: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 201: - return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202: - return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 203: - return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); case 204: - return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 205: + return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); + case 206: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - case 207: - return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 208: + return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + case 209: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 210: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 211: - return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); case 212: - return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); case 213: - return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); case 214: - return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 215: - return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 216: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217: - return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); + return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218: - return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); + return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219: - return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); case 220: - return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); case 221: - return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); + return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 222: - return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); case 223: - return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 224: + return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); + case 225: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 226: - return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 227: - return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); case 228: - return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 229: - return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 230: - return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 231: - return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); + return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 232: - return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); case 233: - return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); + return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 234: - return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); case 235: - return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 236: - return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 237: - return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); + return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); case 238: - return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); case 239: - return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); + return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 240: - return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); case 241: - return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); + return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); case 242: - return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); case 243: - return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); + return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); case 244: - return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); + return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); case 245: - return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); case 246: + return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); + case 247: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 248: - return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 249: - return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); + return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); case 250: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); case 251: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 252: - return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); case 253: - return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); case 254: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 257: + return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); + case 258: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 255: + case 259: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 256: + case 260: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 257: + case 261: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258: + case 262: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 259: + case 263: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 260: + case 264: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); - case 261: + case 265: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 262: + case 266: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 263: + case 267: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); - case 264: + case 268: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 265: + case 269: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 288: + case 292: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 289: + case 293: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -43189,52 +45088,52 @@ var ts; var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 142)) { + if ((kind > 0 && kind <= 143)) { return initial; } - if ((kind >= 158 && kind <= 173)) { + if ((kind >= 159 && kind <= 174)) { return initial; } var result = initial; switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 287: + case 207: + case 210: + case 201: + case 226: + case 291: break; - case 143: + case 144: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 144: + case 145: result = reduceNode(node.expression, cbNode, result); break; - case 146: + case 147: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 147: + case 148: result = reduceNode(node.expression, cbNode, result); break; - case 148: + case 149: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149: + case 150: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151: + case 152: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43243,12 +45142,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 152: + case 153: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 153: + case 154: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43256,55 +45155,55 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154: + case 155: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 174: case 175: + case 176: result = reduceNodes(node.elements, cbNodes, result); break; - case 176: + case 177: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 177: + case 178: result = reduceNodes(node.elements, cbNodes, result); break; - case 178: + case 179: result = reduceNodes(node.properties, cbNodes, result); break; - case 179: + case 180: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 180: + case 181: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 181: + case 182: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 182: + case 183: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 183: + case 184: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 184: + case 185: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 186: + case 187: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -43312,121 +45211,121 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 187: + case 188: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 185: - case 188: + case 186: case 189: case 190: case 191: - case 197: + case 192: case 198: - case 203: + case 199: + case 204: result = reduceNode(node.expression, cbNode, result); break; - case 192: case 193: + case 194: result = reduceNode(node.operand, cbNode, result); break; - case 194: + case 195: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 195: + case 196: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 196: + case 197: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 199: + case 200: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 201: + case 202: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 202: + case 203: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 205: + case 206: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; - case 207: + case 208: result = reduceNodes(node.statements, cbNodes, result); break; - case 208: + case 209: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 210: + case 211: result = reduceNode(node.expression, cbNode, result); break; - case 211: + case 212: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 212: + case 213: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 213: - case 220: + case 214: + case 221: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 214: + case 215: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 215: case 216: + case 217: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219: - case 223: + case 220: + case 224: result = reduceNode(node.expression, cbNode, result); break; - case 221: + case 222: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 222: + case 223: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224: + case 225: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 226: + case 227: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 227: + case 228: result = reduceNodes(node.declarations, cbNodes, result); break; - case 228: + case 229: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43435,7 +45334,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 229: + case 230: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -43443,126 +45342,131 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 232: + case 233: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 233: + case 234: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 234: + case 235: result = reduceNodes(node.statements, cbNodes, result); break; - case 235: + case 236: result = reduceNodes(node.clauses, cbNodes, result); break; - case 237: + case 238: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 238: + case 239: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 239: - result = reduceNode(node.name, cbNode, result); - result = reduceNode(node.namedBindings, cbNode, result); - break; case 240: result = reduceNode(node.name, cbNode, result); + result = reduceNode(node.namedBindings, cbNode, result); break; case 241: - case 245: - result = reduceNodes(node.elements, cbNodes, result); + result = reduceNode(node.name, cbNode, result); break; case 242: case 246: + result = reduceNodes(node.elements, cbNodes, result); + break; + case 243: + case 247: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 243: + case 244: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 244: + case 245: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248: + case 249: result = reduceNode(node.expression, cbNode, result); break; - case 249: + case 250: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 250: + case 254: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; case 251: + case 252: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 254: + case 258: result = reduceNodes(node.properties, cbNodes, result); break; - case 252: + case 253: result = reduceNode(node.tagName, cbNode, result); break; - case 253: + case 257: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 255: + case 259: result = reduceNode(node.expression, cbNode, result); break; - case 256: + case 260: result = reduceNode(node.expression, cbNode, result); break; - case 257: + case 261: result = reduceNode(node.expression, cbNode, result); - case 258: + case 262: result = reduceNodes(node.statements, cbNodes, result); break; - case 259: + case 263: result = reduceNodes(node.types, cbNodes, result); break; - case 260: + case 264: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; - case 261: + case 265: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262: + case 266: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 263: + case 267: result = reduceNode(node.expression, cbNode, result); break; - case 264: + case 268: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 265: + case 269: result = reduceNodes(node.statements, cbNodes, result); break; - case 288: + case 292: result = reduceNode(node.expression, cbNode, result); break; - case 289: + case 293: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -43615,7 +45519,7 @@ var ts; return subtreeFlags; } function aggregateTransformFlagsForSubtree(node) { - if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 201)) { + if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 202)) { return 0; } return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); @@ -43651,12 +45555,12 @@ var ts; if (isDebugInfoEnabled) return; Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, - "__debugObjectFlags": { get: function () { return this.flags & 32768 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, - "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 65536 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ ts.objectAllocator.getNodeConstructor(), @@ -43668,11 +45572,11 @@ var ts; var ctor = nodeConstructors_1[_i]; if (!ctor.prototype.hasOwnProperty("__debugKind")) { Object.defineProperties(ctor.prototype, { - "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, - "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, - "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, - "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, - "__debugGetText": { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { value: function (includeTrivia) { if (ts.nodeIsSynthesized(this)) return ""; @@ -43708,15 +45612,15 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 238: + case 239: externalImports.push(node); break; - case 237: - if (node.moduleReference.kind === 248) { + case 238: + if (node.moduleReference.kind === 249) { externalImports.push(node); } break; - case 244: + case 245: if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -43729,26 +45633,26 @@ var ts; else { for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + if (!uniqueExports.get(ts.idText(specifier.name))) { var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + exportSpecifiers.add(ts.idText(name), specifier); var decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + uniqueExports.set(ts.idText(specifier.name), true); exportedNames = ts.append(exportedNames, specifier.name); } } } break; - case 243: + case 244: if (node.isExportEquals && !exportEquals) { exportEquals = node; } break; - case 208: + case 209: if (ts.hasModifier(node, 1)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -43756,7 +45660,7 @@ var ts; } } break; - case 228: + case 229: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -43766,15 +45670,15 @@ var ts; } else { var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (!uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } } break; - case 229: + case 230: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -43784,9 +45688,9 @@ var ts; } else { var name = node.name; - if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } @@ -43812,8 +45716,9 @@ var ts; } } else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { - uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); exportedNames = ts.append(exportedNames, decl.name); } } @@ -43829,6 +45734,14 @@ var ts; } return values; } + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 || + expression.kind === 8 || + expression.kind === 13 || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); var ts; (function (ts) { @@ -44086,7 +45999,7 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); + var name = ts.createIdentifier(ts.idText(propertyName)); return ts.createPropertyAccess(value, name); } } @@ -44172,7 +46085,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -44183,14 +46096,15 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179); context.enableSubstitution(180); + context.enableSubstitution(181); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; @@ -44199,6 +46113,7 @@ var ts; var enabledSubstitutions; var classAliases; var applicableSubstitutions; + var pendingExpressions; return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -44223,15 +46138,15 @@ var ts; } function onBeforeVisitNode(node) { switch (node.kind) { - case 265: + case 269: + case 236: case 235: - case 234: - case 207: + case 208: currentScope = node; currentScopeFirstDeclarationsOfName = undefined; break; + case 230: case 229: - case 228: if (ts.hasModifier(node, 2)) { break; } @@ -44239,7 +46154,7 @@ var ts; recordEmittedDeclarationInScope(node); } else { - ts.Debug.assert(node.kind === 229 || ts.hasModifier(node, 512)); + ts.Debug.assert(node.kind === 230 || ts.hasModifier(node, 512)); } break; } @@ -44261,10 +46176,10 @@ var ts; } function sourceElementVisitorWorker(node) { switch (node.kind) { + case 239: case 238: - case 237: - case 243: case 244: + case 245: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -44273,16 +46188,19 @@ var ts; function visitEllidableStatement(node) { var parsed = ts.getParseTreeNode(node); if (parsed !== node) { + if (node.transformFlags & 2) { + return ts.visitEachChild(node, visitor, context); + } return node; } switch (node.kind) { - case 238: + case 239: return visitImportDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); - case 243: - return visitExportAssignment(node); case 244: + return visitExportAssignment(node); + case 245: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -44292,11 +46210,11 @@ var ts; return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 244 || - node.kind === 238 || + if (node.kind === 245 || node.kind === 239 || - (node.kind === 237 && - node.moduleReference.kind === 248)) { + node.kind === 240 || + (node.kind === 238 && + node.moduleReference.kind === 249)) { return undefined; } else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { @@ -44312,15 +46230,15 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 152: - return undefined; - case 149: - case 157: case 153: + return undefined; + case 150: + case 158: case 154: - case 151: + case 155: + case 152: return visitorWorker(node); - case 206: + case 207: return node; default: ts.Debug.failBadSyntaxKind(node); @@ -44351,11 +46269,11 @@ var ts; case 76: case 124: case 131: - case 164: case 165: - case 163: - case 158: - case 145: + case 166: + case 164: + case 159: + case 146: case 119: case 122: case 136: @@ -44363,11 +46281,10 @@ var ts; case 130: case 105: case 137: + case 162: case 161: + case 163: case 160: - case 162: - case 159: - case 166: case 167: case 168: case 169: @@ -44375,58 +46292,61 @@ var ts; case 171: case 172: case 173: - case 157: - case 147: - case 231: - case 149: - case 236: + case 174: + case 158: + case 148: + case 232: return undefined; - case 152: + case 150: + return visitPropertyDeclaration(node); + case 237: + return undefined; + case 153: return visitConstructor(node); - case 230: + case 231: return ts.createNotEmittedStatement(node); - case 229: + case 230: return visitClassDeclaration(node); - case 199: + case 200: return visitClassExpression(node); - case 259: + case 263: return visitHeritageClause(node); - case 201: + case 202: return visitExpressionWithTypeArguments(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 153: - return visitGetAccessor(node); case 154: + return visitGetAccessor(node); + case 155: return visitSetAccessor(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: - return visitFunctionExpression(node); case 187: + return visitFunctionExpression(node); + case 188: return visitArrowFunction(node); - case 146: + case 147: return visitParameter(node); - case 185: + case 186: return visitParenthesizedExpression(node); - case 184: - case 202: + case 185: + case 203: return visitAssertionExpression(node); - case 181: - return visitCallExpression(node); case 182: + return visitCallExpression(node); + case 183: return visitNewExpression(node); - case 203: + case 204: return visitNonNullExpression(node); - case 232: + case 233: return visitEnumDeclaration(node); - case 208: + case 209: return visitVariableStatement(node); - case 226: + case 227: return visitVariableDeclaration(node); - case 233: + case 234: return visitModuleDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); default: ts.Debug.failBadSyntaxKind(node); @@ -44434,7 +46354,7 @@ var ts; } } function visitSourceFile(node) { - var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } @@ -44455,7 +46375,8 @@ var ts; var facts = 0; if (ts.some(staticProperties)) facts |= 1; - if (ts.getClassExtendsHeritageClauseElement(node)) + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95) facts |= 64; if (shouldEmitDecorateCallForClass(node)) facts |= 2; @@ -44472,6 +46393,8 @@ var ts; return facts; } function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); var facts = getClassFacts(node, staticProperties); if (facts & 128) { @@ -44482,6 +46405,10 @@ var ts; ? createClassDeclarationHeadWithDecorators(node, name, facts) : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; + if (ts.some(pendingExpressions)) { + statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; if (facts & 1) { addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); } @@ -44559,13 +46486,15 @@ var ts; return statement; } function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85; })); var classExpression = ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, node); - if (staticProperties.length > 0) { + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; var temp = ts.createTempVariable(hoistVariableDeclaration); if (resolver.getNodeCheckFlags(node) & 8388608) { @@ -44574,22 +46503,25 @@ var ts; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } + pendingExpressions = savedPendingExpressions; return classExpression; } - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(ts.createNodeArray(members), node.members); } - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); @@ -44597,14 +46529,14 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); } function transformConstructorParameters(constructor) { return ts.visitParameterList(constructor && constructor.parameters, visitor, context) || []; } - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -44613,7 +46545,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } var properties = getInitializedProperties(node, false); @@ -44632,7 +46564,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -44666,7 +46598,7 @@ var ts; return isInitializedProperty(member, false); } function isInitializedProperty(member, isStatic) { - return member.kind === 149 + return member.kind === 150 && isStatic === ts.hasModifier(member, 32) && member.initializer !== undefined; } @@ -44684,7 +46616,7 @@ var ts; for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); expressions.push(expression); @@ -44692,22 +46624,24 @@ var ts; return expressions; } function transformInitializedProperty(property, receiver) { - var propertyName = visitPropertyNameOfClassElement(property); + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32))) + : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); return ts.createAssignment(memberAccess, initializer); } function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); } - function isStaticDecoratedClassElement(member) { - return isDecoratedClassElement(member, true); + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, true, parent); } - function isInstanceDecoratedClassElement(member) { - return isDecoratedClassElement(member, false); + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, false, parent); } - function isDecoratedClassElement(member, isStatic) { - return ts.nodeOrChildIsDecorated(member) + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) && isStatic === ts.hasModifier(member, 32); } function getDecoratorsOfParameters(node) { @@ -44739,12 +46673,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 153: case 154: + case 155: return getAllDecoratorsOfAccessors(node, member); - case 151: + case 152: return getAllDecoratorsOfMethod(member); - case 149: + case 150: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -44800,8 +46734,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { - var member = members_3[_i]; + for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { + var member = members_4[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -44823,7 +46757,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 149 + ? member.kind === 150 ? ts.createVoidZero() : ts.createNull() : undefined; @@ -44907,37 +46841,37 @@ var ts; } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 151 - || kind === 153 + return kind === 152 || kind === 154 - || kind === 149; + || kind === 155 + || kind === 150; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 151; + return node.kind === 152; } function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 229: - case 199: + case 230: + case 200: return ts.getFirstConstructorWithBody(node) !== undefined; - case 151: - case 153: + case 152: case 154: + case 155: return true; } return false; } function serializeTypeOfNode(node) { switch (node.kind) { - case 149: - case 146: - case 153: - return serializeTypeNode(node.type); + case 150: + case 147: case 154: + return serializeTypeNode(node.type); + case 155: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 229: - case 199: - case 151: + case 230: + case 200: + case 152: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -44969,7 +46903,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 153) { + if (container && node.kind === 154) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -44996,22 +46930,22 @@ var ts; case 95: case 130: return ts.createVoidZero(); - case 168: + case 169: return serializeTypeNode(node.type); - case 160: case 161: + case 162: return ts.createIdentifier("Function"); - case 164: case 165: + case 166: return ts.createIdentifier("Array"); - case 158: + case 159: case 122: return ts.createIdentifier("Boolean"); case 136: return ts.createIdentifier("String"); case 134: return ts.createIdentifier("Object"); - case 173: + case 174: switch (node.literal.kind) { case 9: return ts.createIdentifier("String"); @@ -45031,18 +46965,18 @@ var ts; return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 159: + case 160: return serializeTypeReferenceNode(node); + case 168: case 167: - case 166: return serializeUnionOrIntersectionType(node); - case 162: - case 170: + case 163: case 171: case 172: - case 163: + case 173: + case 164: case 119: - case 169: + case 170: break; default: ts.Debug.failBadSyntaxKind(node); @@ -45054,6 +46988,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169) { + typeNode = typeNode.type; + } + if (typeNode.kind === 130) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 95 || typeNode.kind === 139)) { + continue; + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; @@ -45069,7 +47012,7 @@ var ts; serializedUnion = serializedIndividual; } } - return serializedUnion; + return serializedUnion || ts.createVoidZero(); } function serializeTypeReferenceNode(node) { switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { @@ -45113,7 +47056,7 @@ var ts; return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } return name; - case 143: + case 144: return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -45134,30 +47077,46 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; if (ts.isComputedPropertyName(name)) { - return generateNameForComputedPropertyName + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? ts.getGeneratedNameForNode(name) : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.getSynthesizedClone(name); } } - function visitPropertyNameOfClassElement(member) { - var name = member.name; + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { if (ts.isComputedPropertyName(name)) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - if (member.decorators) { + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { var generatedName = ts.getGeneratedNameForNode(name); hoistVariableDeclaration(generatedName); - expression = ts.createAssignment(generatedName, expression); + return ts.createAssignment(generatedName, expression); } - return ts.updateComputedPropertyName(name, expression); + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), false); + if (expr) { + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; + } + return ts.updateComputedPropertyName(name, expr); } else { return name; @@ -45176,6 +47135,13 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -45400,11 +47366,11 @@ var ts; function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ], currentScope.kind === 265 ? 0 : 1)); + ], currentScope.kind === 269 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { - if (node.kind === 232) { + if (node.kind === 233) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -45465,7 +47431,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 234) { + if (body.kind === 235) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -45489,13 +47455,13 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true); ts.setTextRange(block, blockLocation); - if (body.kind !== 234) { + if (body.kind !== 235) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 233) { + if (moduleDeclaration.body.kind === 234) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -45515,7 +47481,7 @@ var ts; return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; } function visitNamedImportBindings(node) { - if (node.kind === 240) { + if (node.kind === 241) { return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } else { @@ -45619,7 +47585,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -45650,15 +47616,15 @@ var ts; if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; context.enableSubstitution(71); - context.enableSubstitution(262); - context.enableEmitNotification(233); + context.enableSubstitution(266); + context.enableEmitNotification(234); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 233; + return ts.getOriginalNode(node).kind === 234; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 232; + return ts.getOriginalNode(node).kind === 233; } function onEmitNode(hint, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; @@ -45704,9 +47670,9 @@ var ts; switch (node.kind) { case 71: return substituteExpressionIdentifier(node); - case 179: - return substitutePropertyAccessExpression(node); case 180: + return substitutePropertyAccessExpression(node); + case 181: return substituteElementAccessExpression(node); } return node; @@ -45736,9 +47702,9 @@ var ts; function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container && container.kind !== 265) { - var substitute = (applicableSubstitutions & 2 && container.kind === 233) || - (applicableSubstitutions & 8 && container.kind === 232); + if (container && container.kind !== 269) { + var substitute = (applicableSubstitutions & 2 && container.kind === 234) || + (applicableSubstitutions & 8 && container.kind === 233); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), node); } @@ -45856,15 +47822,15 @@ var ts; switch (node.kind) { case 120: return undefined; - case 191: + case 192: return visitAwaitExpression(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: - return visitFunctionExpression(node); case 187: + return visitFunctionExpression(node); + case 188: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -45898,7 +47864,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 187; + var isArrowFunction = node.kind === 188; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; if (!isArrowFunction) { var statements = []; @@ -45954,14 +47920,14 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(181); - context.enableSubstitution(179); + context.enableSubstitution(182); context.enableSubstitution(180); - context.enableEmitNotification(229); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); + context.enableSubstitution(181); + context.enableEmitNotification(230); context.enableEmitNotification(152); + context.enableEmitNotification(154); + context.enableEmitNotification(155); + context.enableEmitNotification(153); } } function onEmitNode(hint, node, emitCallback) { @@ -45986,18 +47952,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179: - return substitutePropertyAccessExpression(node); case 180: - return substituteElementAccessExpression(node); + return substitutePropertyAccessExpression(node); case 181: + return substituteElementAccessExpression(node); + case 182: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -46021,11 +47987,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 - || kind === 152 - || kind === 151 + return kind === 230 || kind === 153 - || kind === 154; + || kind === 152 + || kind === 154 + || kind === 155; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { @@ -46046,7 +48012,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288; return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ ts.createThis(), hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), @@ -46109,45 +48075,45 @@ var ts; return node; } switch (node.kind) { - case 191: + case 192: return visitAwaitExpression(node); - case 197: + case 198: return visitYieldExpression(node); - case 222: + case 223: return visitLabeledStatement(node); - case 178: + case 179: return visitObjectLiteralExpression(node); - case 194: + case 195: return visitBinaryExpression(node, noDestructuringValue); - case 226: + case 227: return visitVariableDeclaration(node); - case 216: + case 217: return visitForOfStatement(node, undefined); - case 214: + case 215: return visitForStatement(node); - case 190: + case 191: return visitVoidExpression(node); - case 152: + case 153: return visitConstructorDeclaration(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 153: - return visitGetAccessorDeclaration(node); case 154: + return visitGetAccessorDeclaration(node); + case 155: return visitSetAccessorDeclaration(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: - return visitFunctionExpression(node); case 187: + return visitFunctionExpression(node); + case 188: return visitArrowFunction(node); - case 146: + case 147: return visitParameter(node); - case 210: + case 211: return visitExpressionStatement(node); - case 185: + case 186: return visitParenthesizedExpression(node, noDestructuringValue); - case 260: + case 264: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -46169,7 +48135,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 216 && statement.awaitModifier) { + if (statement.kind === 217 && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); @@ -46181,7 +48147,7 @@ var ts; var objects = []; for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { var e = elements_3[_i]; - if (e.kind === 263) { + if (e.kind === 267) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -46193,7 +48159,7 @@ var ts; if (!chunkObject) { chunkObject = []; } - if (e.kind === 261) { + if (e.kind === 265) { var p = e; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } @@ -46210,7 +48176,7 @@ var ts; function visitObjectLiteralExpression(node) { if (node.transformFlags & 1048576) { var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 178) { + if (objects.length && objects[0].kind !== 179) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -46461,14 +48427,14 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(181); - context.enableSubstitution(179); + context.enableSubstitution(182); context.enableSubstitution(180); - context.enableEmitNotification(229); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); + context.enableSubstitution(181); + context.enableEmitNotification(230); context.enableEmitNotification(152); + context.enableEmitNotification(154); + context.enableEmitNotification(155); + context.enableEmitNotification(153); } } function onEmitNode(hint, node, emitCallback) { @@ -46493,18 +48459,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179: - return substitutePropertyAccessExpression(node); case 180: - return substituteElementAccessExpression(node); + return substitutePropertyAccessExpression(node); case 181: + return substituteElementAccessExpression(node); + case 182: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -46528,11 +48494,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 - || kind === 152 - || kind === 151 + return kind === 230 || kind === 153 - || kind === 154; + || kind === 152 + || kind === 154 + || kind === 155; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { @@ -46606,11 +48572,13 @@ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { return node; } + currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; @@ -46625,11 +48593,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 249: - return visitJsxElement(node, false); case 250: + return visitJsxElement(node, false); + case 251: return visitJsxSelfClosingElement(node, false); - case 256: + case 254: + return visitJsxFragment(node, false); + case 260: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -46639,12 +48609,14 @@ var ts; switch (node.kind) { case 10: return visitJsxText(node); - case 256: + case 260: return visitJsxExpression(node); - case 249: - return visitJsxElement(node, true); case 250: + return visitJsxElement(node, true); + case 251: return visitJsxSelfClosingElement(node, true); + case 254: + return visitJsxFragment(node, true); default: ts.Debug.failBadSyntaxKind(node); return undefined; @@ -46656,6 +48628,9 @@ var ts; function visitJsxSelfClosingElement(node, isChild) { return visitJsxOpeningLikeElement(node, undefined, isChild, node); } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, node); + } function visitJsxOpeningLikeElement(node, children, isChild, location) { var tagName = getTagName(node); var objectProperties; @@ -46681,6 +48656,13 @@ var ts; } return element; } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -46694,10 +48676,11 @@ var ts; return ts.createTrue(); } else if (node.kind === 9) { - var decoded = tryDecodeEntities(node.text); - return decoded ? ts.setTextRange(ts.createLiteral(decoded), node) : node; + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); } - else if (node.kind === 256) { + else if (node.kind === 260) { if (node.expression === undefined) { return ts.createTrue(); } @@ -46757,13 +48740,13 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 249) { + if (node.kind === 250) { return getTagName(node.openingElement); } else { var name = node.tagName; if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.createExpressionFromEntityName(name); @@ -46772,11 +48755,12 @@ var ts; } function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { return name; } else { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(text); } } function visitJsxExpression(node) { @@ -46785,259 +48769,259 @@ var ts; } ts.transformJsx = transformJsx; var entities = ts.createMapFromTemplate({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 }); })(ts || (ts = {})); var ts; @@ -47056,7 +49040,7 @@ var ts; return node; } switch (node.kind) { - case 194: + case 195: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -47184,6 +49168,10 @@ var ts; var currentSourceFile; var currentText; var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } var convertedLoopState; var enabledSubstitutions; return transformSourceFile; @@ -47197,6 +49185,7 @@ var ts; ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; currentText = undefined; + taggedTemplateStringDeclarations = undefined; hierarchyFacts = 0; return visited; } @@ -47210,13 +49199,13 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return hierarchyFacts & 4096 - && node.kind === 219 + && node.kind === 220 && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) + || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 208))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432) !== 0; } @@ -47244,63 +49233,63 @@ var ts; switch (node.kind) { case 115: return undefined; - case 229: + case 230: return visitClassDeclaration(node); - case 199: + case 200: return visitClassExpression(node); - case 146: + case 147: return visitParameter(node); - case 228: + case 229: return visitFunctionDeclaration(node); - case 187: + case 188: return visitArrowFunction(node); - case 186: + case 187: return visitFunctionExpression(node); - case 226: + case 227: return visitVariableDeclaration(node); case 71: return visitIdentifier(node); - case 227: + case 228: return visitVariableDeclarationList(node); - case 221: + case 222: return visitSwitchStatement(node); - case 235: + case 236: return visitCaseBlock(node); - case 207: + case 208: return visitBlock(node, false); + case 219: case 218: - case 217: return visitBreakOrContinueStatement(node); - case 222: + case 223: return visitLabeledStatement(node); - case 212: case 213: - return visitDoOrWhileStatement(node, undefined); case 214: - return visitForStatement(node, undefined); + return visitDoOrWhileStatement(node, undefined); case 215: - return visitForInStatement(node, undefined); + return visitForStatement(node, undefined); case 216: + return visitForInStatement(node, undefined); + case 217: return visitForOfStatement(node, undefined); - case 210: + case 211: return visitExpressionStatement(node); - case 178: + case 179: return visitObjectLiteralExpression(node); - case 260: + case 264: return visitCatchClause(node); - case 262: + case 266: return visitShorthandPropertyAssignment(node); - case 144: + case 145: return visitComputedPropertyName(node); - case 177: + case 178: return visitArrayLiteralExpression(node); - case 181: - return visitCallExpression(node); case 182: + return visitCallExpression(node); + case 183: return visitNewExpression(node); - case 185: + case 186: return visitParenthesizedExpression(node, true); - case 194: + case 195: return visitBinaryExpression(node, true); case 13: case 14: @@ -47311,28 +49300,28 @@ var ts; return visitStringLiteral(node); case 8: return visitNumericLiteral(node); - case 183: + case 184: return visitTaggedTemplateExpression(node); - case 196: - return visitTemplateExpression(node); case 197: - return visitYieldExpression(node); + return visitTemplateExpression(node); case 198: + return visitYieldExpression(node); + case 199: return visitSpreadElement(node); case 97: return visitSuperKeyword(false); case 99: return visitThisKeyword(node); - case 204: + case 205: return visitMetaProperty(node); - case 151: + case 152: return visitMethodDeclaration(node); - case 153: case 154: + case 155: return visitAccessorDeclaration(node); - case 208: + case 209: return visitVariableStatement(node); - case 219: + case 220: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -47346,6 +49335,9 @@ var ts; addCaptureThisForNodeIfNeeded(statements, node); statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } ts.addRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); @@ -47410,13 +49402,13 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 218 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || + var jump = node.kind === 219 ? 2 : 4; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 218) { + if (node.kind === 219) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; } @@ -47426,13 +49418,13 @@ var ts; } } else { - if (node.kind === 218) { + if (node.kind === 219) { labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, true, ts.idText(node.label), labelMarker); } else { labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, false, ts.idText(node.label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -47487,9 +49479,7 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (ts.getEmitFlags(node) & 65536) { - ts.setEmitFlags(classFunction, 65536); - } + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536) | 524288); var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; ts.setEmitFlags(inner, 1536); @@ -47592,17 +49582,17 @@ var ts; return block; } function isSufficientlyCoveredByReturnStatements(statement) { - if (statement.kind === 219) { + if (statement.kind === 220) { return true; } - else if (statement.kind === 211) { + else if (statement.kind === 212) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 207) { + else if (statement.kind === 208) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -47631,7 +49621,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 210 && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 211 && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -47639,8 +49629,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 | 32768))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 194 - || superCallExpression.left.kind !== 181) { + if (superCallExpression.kind !== 195 + || superCallExpression.left.kind !== 182) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); @@ -47708,7 +49698,7 @@ var ts; var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer))), parameter)) ]), parameter), 1 | 32 | 384)); - statement.startsOnNewLine = true; + ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 | 32 | 1048576); statements.push(statement); @@ -47741,7 +49731,7 @@ var ts; statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 && node.kind !== 187) { + if (node.transformFlags & 32768 && node.kind !== 188) { captureThisForNode(statements, node, ts.createThis()); } } @@ -47759,18 +49749,18 @@ var ts; if (hierarchyFacts & 16384) { var newTarget = void 0; switch (node.kind) { - case 187: + case 188: return statements; - case 151: - case 153: + case 152: case 154: + case 155: newTarget = ts.createVoidZero(); break; - case 152: + case 153: newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"); break; - case 228: - case 186: + case 229: + case 187: newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4), 93, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"), ts.createVoidZero()); break; default: @@ -47791,20 +49781,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 206: + case 207: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 151: + case 152: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 153: case 154: + case 155: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 152: + case 153: break; default: ts.Debug.failBadSyntaxKind(node); @@ -47869,7 +49859,7 @@ var ts; ts.createObjectLiteral(properties, true) ]); if (startsOnNewLine) { - call.startsOnNewLine = true; + ts.startOnNewLine(call); } exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return call; @@ -47929,7 +49919,7 @@ var ts; : enterSubtree(16286, 65); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 && !name && (node.kind === 228 || node.kind === 186)) { + if (hierarchyFacts & 16384 && !name && (node.kind === 229 || node.kind === 187)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152, 0); @@ -47963,7 +49953,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 187); + ts.Debug.assert(node.kind === 188); statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -48015,9 +50005,9 @@ var ts; } function visitExpressionStatement(node) { switch (node.expression.kind) { - case 185: + case 186: return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); - case 194: + case 195: return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); } return ts.visitEachChild(node, visitor, context); @@ -48025,9 +50015,9 @@ var ts; function visitParenthesizedExpression(node, needsDestructuringValue) { if (!needsDestructuringValue) { switch (node.expression.kind) { - case 185: + case 186: return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); - case 194: + case 195: return ts.updateParen(node, visitBinaryExpression(node.expression, false)); } } @@ -48137,10 +50127,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); + convertedLoopState.labels.set(ts.idText(node.label), true); } function resetLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); + convertedLoopState.labels.set(ts.idText(node.label), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -48153,14 +50143,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 212: case 213: - return visitDoOrWhileStatement(node, outermostLabeledStatement); case 214: - return visitForStatement(node, outermostLabeledStatement); + return visitDoOrWhileStatement(node, outermostLabeledStatement); case 215: - return visitForInStatement(node, outermostLabeledStatement); + return visitForStatement(node, outermostLabeledStatement); case 216: + return visitForInStatement(node, outermostLabeledStatement); + case 217: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -48286,7 +50276,7 @@ var ts; && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 144) { + if (property.name.kind === 145) { numInitialProperties = i; break; } @@ -48299,7 +50289,7 @@ var ts; var expressions = []; var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); if (node.multiLine) { - assignment.startsOnNewLine = true; + ts.startOnNewLine(assignment); } expressions.push(assignment); addObjectLiteralMembers(expressions, node, temp, numInitialProperties); @@ -48348,11 +50338,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 214: case 215: case 216: + case 217: var initializer = node.initializer; - if (initializer && initializer.kind === 227) { + if (initializer && initializer.kind === 228) { loopInitializer = initializer; } break; @@ -48567,7 +50557,7 @@ var ts; else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -48578,20 +50568,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 153: case 154: + case 155: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); } break; - case 151: + case 152: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 261: + case 265: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 262: + case 266: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -48604,7 +50594,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -48612,7 +50602,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -48621,7 +50611,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return expression; @@ -48665,7 +50655,7 @@ var ts; if (node.transformFlags & 32768) { var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 153) { + if (node.kind === 154) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -48793,7 +50783,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 178 ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -48827,15 +50817,14 @@ var ts; return node; } function visitNumericLiteral(node) { - if (node.numericLiteralFlags & 48) { + if (node.numericLiteralFlags & 384) { return ts.setTextRange(ts.createNumericLiteral(node.text), node); } return node; } function visitTaggedTemplateExpression(node) { var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - var temp = ts.createTempVariable(hoistVariableDeclaration); - var templateArguments = [temp]; + var templateArguments = [undefined]; var cookedStrings = []; var rawStrings = []; var template = node.template; @@ -48853,11 +50842,16 @@ var ts; templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); } } - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, undefined, templateArguments) - ])); + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, undefined, templateArguments); } function getRawLiteral(node) { var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); @@ -48935,13 +50929,13 @@ var ts; if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; context.enableSubstitution(99); - context.enableEmitNotification(152); - context.enableEmitNotification(151); context.enableEmitNotification(153); + context.enableEmitNotification(152); context.enableEmitNotification(154); + context.enableEmitNotification(155); + context.enableEmitNotification(188); context.enableEmitNotification(187); - context.enableEmitNotification(186); - context.enableEmitNotification(228); + context.enableEmitNotification(229); } } function onSubstituteNode(hint, node) { @@ -48966,10 +50960,10 @@ var ts; function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 176: - case 229: - case 232: - case 226: + case 177: + case 230: + case 233: + case 227: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -49030,11 +51024,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 210) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 211) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 181) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 182) { return false; } var callTarget = statementExpression.expression; @@ -49042,7 +51036,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 198) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 199) { return false; } var expression = callArgument.expression; @@ -49057,12 +51051,25 @@ var ts; ts.createIdentifier("_super") ]); } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), undefined, [ + cooked, + raw + ]); + } var extendsHelper = { name: "typescript:extends", scoped: false, priority: 0, text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -49181,13 +51188,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 212: - return visitDoStatement(node); case 213: + return visitDoStatement(node); + case 214: return visitWhileStatement(node); - case 221: - return visitSwitchStatement(node); case 222: + return visitSwitchStatement(node); + case 223: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -49195,24 +51202,24 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: + case 187: return visitFunctionExpression(node); - case 153: case 154: + case 155: return visitAccessorDeclaration(node); - case 208: + case 209: return visitVariableStatement(node); - case 214: - return visitForStatement(node); case 215: + return visitForStatement(node); + case 216: return visitForInStatement(node); - case 218: + case 219: return visitBreakStatement(node); - case 217: + case 218: return visitContinueStatement(node); - case 219: + case 220: return visitReturnStatement(node); default: if (node.transformFlags & 16777216) { @@ -49228,21 +51235,21 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 194: - return visitBinaryExpression(node); case 195: + return visitBinaryExpression(node); + case 196: return visitConditionalExpression(node); - case 197: + case 198: return visitYieldExpression(node); - case 177: - return visitArrayLiteralExpression(node); case 178: + return visitArrayLiteralExpression(node); + case 179: return visitObjectLiteralExpression(node); - case 180: - return visitElementAccessExpression(node); case 181: - return visitCallExpression(node); + return visitElementAccessExpression(node); case 182: + return visitCallExpression(node); + case 183: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -49250,9 +51257,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 228: + case 229: return visitFunctionDeclaration(node); - case 186: + case 187: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -49409,10 +51416,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 179: + case 180: target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 180: + case 181: target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -49558,7 +51565,7 @@ var ts; var visited = ts.visitNode(expression, visitor, ts.isExpression); if (visited) { if (multiLine) { - visited.startsOnNewLine = true; + ts.startOnNewLine(visited); } expressions.push(visited); } @@ -49575,7 +51582,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); } @@ -49613,35 +51620,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 207: + case 208: return transformAndEmitBlock(node); - case 210: - return transformAndEmitExpressionStatement(node); case 211: - return transformAndEmitIfStatement(node); + return transformAndEmitExpressionStatement(node); case 212: - return transformAndEmitDoStatement(node); + return transformAndEmitIfStatement(node); case 213: - return transformAndEmitWhileStatement(node); + return transformAndEmitDoStatement(node); case 214: - return transformAndEmitForStatement(node); + return transformAndEmitWhileStatement(node); case 215: + return transformAndEmitForStatement(node); + case 216: return transformAndEmitForInStatement(node); - case 217: - return transformAndEmitContinueStatement(node); case 218: - return transformAndEmitBreakStatement(node); + return transformAndEmitContinueStatement(node); case 219: - return transformAndEmitReturnStatement(node); + return transformAndEmitBreakStatement(node); case 220: - return transformAndEmitWithStatement(node); + return transformAndEmitReturnStatement(node); case 221: - return transformAndEmitSwitchStatement(node); + return transformAndEmitWithStatement(node); case 222: - return transformAndEmitLabeledStatement(node); + return transformAndEmitSwitchStatement(node); case 223: - return transformAndEmitThrowStatement(node); + return transformAndEmitLabeledStatement(node); case 224: + return transformAndEmitThrowStatement(node); + case 225: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -49873,7 +51880,7 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, node); } @@ -49883,7 +51890,7 @@ var ts; } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findContinueTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, node); } @@ -49891,7 +51898,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, node); } @@ -49901,7 +51908,7 @@ var ts; } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findBreakTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, node); } @@ -49935,7 +51942,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 258 && defaultClauseIndex === -1) { + if (clause.kind === 262 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -49945,7 +51952,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 257) { + if (clause.kind === 261) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -49996,7 +52003,7 @@ var ts; } function transformAndEmitLabeledStatement(node) { if (containsYield(node)) { - beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginLabeledBlock(ts.idText(node.label)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -50006,7 +52013,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginScriptLabeledBlock(ts.idText(node.label)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -50061,7 +52068,7 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); @@ -50175,7 +52182,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); + var text = ts.idText(variable.name); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -50480,8 +52487,7 @@ var ts; if (clauses) { var labelExpression = ts.createPropertyAccess(state, "label"); var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); - switchStatement.startsOnNewLine = true; - return [switchStatement]; + return [ts.startOnNewLine(switchStatement)]; } if (statements) { return statements; @@ -50750,24 +52756,24 @@ var ts; if (compilerOptions.jsx === 1 || compilerOptions.jsx === 3) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(251); context.enableEmitNotification(252); - context.enableEmitNotification(250); + context.enableEmitNotification(253); + context.enableEmitNotification(251); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179); - context.enableSubstitution(261); + context.enableSubstitution(180); + context.enableSubstitution(265); return transformSourceFile; function transformSourceFile(node) { return node; } function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 251: case 252: - case 250: + case 253: + case 251: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -50802,7 +52808,7 @@ var ts; return node; } function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); if (token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -50821,7 +52827,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -50832,11 +52838,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); - context.enableSubstitution(194); - context.enableSubstitution(192); + context.enableSubstitution(195); context.enableSubstitution(193); - context.enableSubstitution(262); - context.enableEmitNotification(265); + context.enableSubstitution(194); + context.enableSubstitution(266); + context.enableEmitNotification(269); var moduleInfoMap = []; var deferredExports = []; var currentSourceFile; @@ -50845,7 +52851,7 @@ var ts; var needUMDDynamicImportHelper; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; } currentSourceFile = node; @@ -50867,7 +52873,7 @@ var ts; function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); @@ -51003,23 +53009,23 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 238: + case 239: return visitImportDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); - case 244: + case 245: return visitExportDeclaration(node); - case 243: + case 244: return visitExportAssignment(node); - case 208: + case 209: return visitVariableStatement(node); - case 228: - return visitFunctionDeclaration(node); case 229: + return visitFunctionDeclaration(node); + case 230: return visitClassDeclaration(node); - case 290: + case 294: return visitMergeDeclarationMarker(node); - case 291: + case 295: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, importCallExpressionVisitor, context); @@ -51037,28 +53043,65 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { needUMDDynamicImportHelper = true; - return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536); + return ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(arg, containsLexicalThis), createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(ts.createIdentifier("__syncRequire"), createImportCallExpressionCommonJS(temp, containsLexicalThis), createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), - ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + var parameters = [ + ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, parameters, undefined, undefined, body); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, parameters, undefined, body); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); + var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2) { + func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); + } + else { + func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock([ts.createReturn(requireCall)])); + if (containsLexicalThis) { + ts.setEmitFlags(func, 8); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } function visitImportDeclaration(node) { var statements; @@ -51161,10 +53204,10 @@ var ts; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), node, true); } return ts.singleOrMany(statements); } @@ -51248,7 +53291,7 @@ var ts; } } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -51280,10 +53323,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240: + case 241: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241: + case 242: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -51341,7 +53384,7 @@ var ts; } function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -51391,7 +53434,7 @@ var ts; return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265) { + if (node.kind === 269) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -51433,10 +53476,10 @@ var ts; switch (node.kind) { case 71: return substituteExpressionIdentifier(node); - case 194: + case 195: return substituteBinaryExpression(node); + case 194: case 193: - case 192: return substituteUnaryExpression(node); } return node; @@ -51451,7 +53494,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 265) { + if (exportContainer && exportContainer.kind === 269) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); @@ -51494,7 +53537,7 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 + var expression = node.kind === 194 ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 ? 59 : 60), ts.createLiteral(1)), node) : node; for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { @@ -51548,10 +53591,10 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); - context.enableSubstitution(194); - context.enableSubstitution(192); + context.enableSubstitution(195); context.enableSubstitution(193); - context.enableEmitNotification(265); + context.enableSubstitution(194); + context.enableEmitNotification(269); var moduleInfoMap = []; var deferredExports = []; var exportFunctionsMap = []; @@ -51606,8 +53649,8 @@ var ts; function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); if (externalModuleName) { var text = externalModuleName.text; @@ -51629,7 +53672,7 @@ var ts; function createSystemModuleBody(node, dependencyGroups) { var statements = []; startLexicalEnvironment(); - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) @@ -51655,7 +53698,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 244 && externalImport.exportClause) { + if (externalImport.kind === 245 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -51678,7 +53721,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 244) { + if (externalImport.kind !== 245) { continue; } var exportDecl = externalImport; @@ -51687,7 +53730,7 @@ var ts; } for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -51730,21 +53773,21 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { - case 238: + case 239: if (!entry.importClause) { break; } - case 237: + case 238: ts.Debug.assert(importVariableName !== undefined); statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 244: + case 245: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); } @@ -51760,13 +53803,13 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 238: + case 239: return visitImportDeclaration(node); - case 237: + case 238: return visitImportEqualsDeclaration(node); - case 244: + case 245: return undefined; - case 243: + case 244: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -51887,14 +53930,14 @@ var ts; } function shouldHoistVariableDeclarationList(node) { return (ts.getEmitFlags(node) & 2097152) === 0 - && (enclosingBlockScopedContainer.kind === 265 + && (enclosingBlockScopedContainer.kind === 269 || (ts.getOriginalNode(node).flags & 3) === 0); } function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; } function createExportedVariableAssignment(name, value, location) { return createVariableAssignment(name, value, location, true); @@ -51909,7 +53952,7 @@ var ts; : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -51942,10 +53985,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240: + case 241: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241: + case 242: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -51989,7 +54032,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); + excludeName = ts.idText(decl.name); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -52015,7 +54058,7 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; @@ -52045,43 +54088,43 @@ var ts; } function nestedElementVisitor(node) { switch (node.kind) { - case 208: + case 209: return visitVariableStatement(node); - case 228: - return visitFunctionDeclaration(node); case 229: + return visitFunctionDeclaration(node); + case 230: return visitClassDeclaration(node); - case 214: - return visitForStatement(node); case 215: - return visitForInStatement(node); + return visitForStatement(node); case 216: + return visitForInStatement(node); + case 217: return visitForOfStatement(node); - case 212: - return visitDoStatement(node); case 213: + return visitDoStatement(node); + case 214: return visitWhileStatement(node); - case 222: + case 223: return visitLabeledStatement(node); - case 220: - return visitWithStatement(node); case 221: + return visitWithStatement(node); + case 222: return visitSwitchStatement(node); - case 235: + case 236: return visitCaseBlock(node); - case 257: + case 261: return visitCaseClause(node); - case 258: + case 262: return visitDefaultClause(node); - case 224: + case 225: return visitTryStatement(node); - case 260: + case 264: return visitCatchClause(node); - case 207: + case 208: return visitBlock(node); - case 290: + case 294: return visitMergeDeclarationMarker(node); - case 291: + case 295: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -52121,6 +54164,9 @@ var ts; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } } return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); } @@ -52175,7 +54221,7 @@ var ts; } function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 - && node.kind === 194) { + && node.kind === 195) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -52189,7 +54235,7 @@ var ts; } } function visitImportCallExpression(node) { - return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { @@ -52218,7 +54264,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 265; + return container !== undefined && container.kind === 269; } else { return false; @@ -52233,7 +54279,7 @@ var ts; return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265) { + if (node.kind === 269) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -52266,10 +54312,10 @@ var ts; switch (node.kind) { case 71: return substituteExpressionIdentifier(node); - case 194: + case 195: return substituteBinaryExpression(node); - case 192: case 193: + case 194: return substituteUnaryExpression(node); } return node; @@ -52321,14 +54367,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 + var expression = node.kind === 194 ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 193) { + if (node.kind === 194) { expression = node.operator === 43 ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -52345,7 +54391,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, false); - if (exportContainer && exportContainer.kind === 265) { + if (exportContainer && exportContainer.kind === 269) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -52373,7 +54419,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(265); + context.enableEmitNotification(269); context.enableSubstitution(71); var currentSourceFile; return transformSourceFile; @@ -52398,9 +54444,9 @@ var ts; } function visitor(node) { switch (node.kind) { - case 237: + case 238: return undefined; - case 243: + case 244: return visitExportAssignment(node); } return node; @@ -52472,7 +54518,7 @@ var ts; if (jsx === 2) { transformers.push(ts.transformJsx); } - if (languageVersion < 5) { + if (languageVersion < 6) { transformers.push(ts.transformESNext); } if (languageVersion < 4) { @@ -52494,7 +54540,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(292); + var enabledSyntaxKindFeatures = new Array(296); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -52701,8 +54747,8 @@ var ts; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 266; + var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var isBundledEmit = sourceFileOrBundle.kind === 270; var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52764,7 +54810,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 238); + ts.Debug.assert(aliasEmitInfo.node.kind === 239); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -52799,7 +54845,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -52814,6 +54860,7 @@ var ts; var writer = ts.createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; + writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; @@ -52837,10 +54884,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 226) { + if (declaration.kind === 227) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 241 || declaration.kind === 242 || declaration.kind === 239) { + else if (declaration.kind === 242 || declaration.kind === 243 || declaration.kind === 240) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -52851,7 +54898,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 238) { + if (moduleElementEmitInfo.node.kind === 239) { moduleElementEmitInfo.isVisible = true; } else { @@ -52859,12 +54906,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 233) { + if (nodeToCheck.kind === 234) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 233) { + if (nodeToCheck.kind === 234) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -52917,16 +54964,22 @@ var ts; emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } function reportInaccessibleThisError() { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - var shouldUseResolverType = declaration.kind === 146 && + var shouldUseResolverType = declaration.kind === 147 && (resolver.isRequiredInitializedParameter(declaration) || resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { @@ -52998,41 +55051,41 @@ var ts; case 139: case 95: case 130: - case 169: - case 173: + case 170: + case 174: return writeTextOfNode(currentText, type); - case 201: + case 202: return emitExpressionWithTypeArguments(type); - case 159: + case 160: return emitTypeReference(type); - case 162: + case 163: return emitTypeQuery(type); - case 164: - return emitArrayType(type); case 165: - return emitTupleType(type); + return emitArrayType(type); case 166: - return emitUnionType(type); + return emitTupleType(type); case 167: - return emitIntersectionType(type); + return emitUnionType(type); case 168: + return emitIntersectionType(type); + case 169: return emitParenType(type); - case 170: - return emitTypeOperator(type); case 171: - return emitIndexedAccessType(type); + return emitTypeOperator(type); case 172: + return emitIndexedAccessType(type); + case 173: return emitMappedType(type); - case 160: case 161: + case 162: return emitSignatureDeclarationWithJsDocComments(type); - case 163: + case 164: return emitTypeLiteral(type); case 71: return emitEntityName(type); - case 143: + case 144: return emitEntityName(type); - case 158: + case 159: return emitTypePredicate(type); } function writeEntityName(entityName) { @@ -53040,22 +55093,22 @@ var ts; writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 143 ? entityName.left : entityName.expression; - var right = entityName.kind === 143 ? entityName.right : entityName.name; + var left = entityName.kind === 144 ? entityName.left : entityName.expression; + var right = entityName.kind === 144 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 237 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 238 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 || node.expression.kind === 179); + ts.Debug.assert(node.expression.kind === 71 || node.expression.kind === 180); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -53211,10 +55264,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 237 || - (node.parent.kind === 265 && isCurrentFileExternalModule)) { + else if (node.kind === 238 || + (node.parent.kind === 269 && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 265) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 269) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -53223,7 +55276,7 @@ var ts; }); } else { - if (node.kind === 238) { + if (node.kind === 239) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -53241,30 +55294,30 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 228: + case 229: return writeFunctionDeclaration(node); - case 208: + case 209: return writeVariableStatement(node); - case 230: + case 231: return writeInterfaceDeclaration(node); - case 229: + case 230: return writeClassDeclaration(node); - case 231: - return writeTypeAliasDeclaration(node); case 232: - return writeEnumDeclaration(node); + return writeTypeAliasDeclaration(node); case 233: + return writeEnumDeclaration(node); + case 234: return writeModuleDeclaration(node); - case 237: - return writeImportEqualsDeclaration(node); case 238: + return writeImportEqualsDeclaration(node); + case 239: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 265) { + if (node.parent.kind === 269) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { write("export "); @@ -53272,7 +55325,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && needsDeclare) { + else if (node.kind !== 231 && needsDeclare) { write("declare "); } } @@ -53322,7 +55375,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 240) { + if (namedBindings.kind === 241) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -53345,7 +55398,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 240) { + if (node.importClause.namedBindings.kind === 241) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -53362,13 +55415,13 @@ var ts; writer.writeLine(); } function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 233; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 234; var moduleSpecifier; - if (parent.kind === 237) { + if (parent.kind === 238) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 233) { + else if (parent.kind === 234) { moduleSpecifier = parent.name; } else { @@ -53436,7 +55489,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 234) { + while (node.body && node.body.kind !== 235) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -53506,7 +55559,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 151 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 152 && ts.hasModifier(node.parent, 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -53516,15 +55569,15 @@ var ts; writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - (node.parent.parent && node.parent.parent.kind === 163)) { - ts.Debug.assert(node.parent.kind === 151 || - node.parent.kind === 150 || - node.parent.kind === 160 || + if (node.parent.kind === 161 || + node.parent.kind === 162 || + (node.parent.parent && node.parent.parent.kind === 164)) { + ts.Debug.assert(node.parent.kind === 152 || + node.parent.kind === 151 || node.parent.kind === 161 || - node.parent.kind === 155 || - node.parent.kind === 156); + node.parent.kind === 162 || + node.parent.kind === 156 || + node.parent.kind === 157); emitType(node.constraint); } else { @@ -53533,15 +55586,15 @@ var ts; } if (node.default && !isPrivateMethodTypeParameter(node)) { write(" = "); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - (node.parent.parent && node.parent.parent.kind === 163)) { - ts.Debug.assert(node.parent.kind === 151 || - node.parent.kind === 150 || - node.parent.kind === 160 || + if (node.parent.kind === 161 || + node.parent.kind === 162 || + (node.parent.parent && node.parent.parent.kind === 164)) { + ts.Debug.assert(node.parent.kind === 152 || + node.parent.kind === 151 || node.parent.kind === 161 || - node.parent.kind === 155 || - node.parent.kind === 156); + node.parent.kind === 162 || + node.parent.kind === 156 || + node.parent.kind === 157); emitType(node.default); } else { @@ -53551,34 +55604,34 @@ var ts; function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 229: + case 230: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 230: + case 231: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 156: + case 157: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 155: + case 156: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; + case 152: case 151: - case 150: if (ts.hasModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229) { + else if (node.parent.parent.kind === 230) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 228: + case 229: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 231: + case 232: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -53611,7 +55664,7 @@ var ts; } function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 229) { + if (node.parent.parent.kind === 230) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -53648,7 +55701,7 @@ var ts; diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + }, !ts.findAncestor(node, function (n) { return n.kind === 234; })); } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -53705,7 +55758,7 @@ var ts; enclosingDeclaration = prevEnclosingDeclaration; } function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } emitJsDocComments(node); @@ -53714,18 +55767,24 @@ var ts; write(";"); writeLine(); } + function bindingNameContainsVisibleBindingElement(node) { + return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); + } + function isVariableDeclarationVisible(node) { + return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); + } function emitVariableDeclaration(node) { - if (node.kind !== 226 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 227 || isVariableDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - writeTextOfNode(currentText, node.name); - if ((node.kind === 149 || node.kind === 148 || - (node.kind === 146 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); + if ((node.kind === 150 || node.kind === 149 || + (node.kind === 147 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 149 || node.kind === 148) && node.parent.kind === 163) { + if ((node.kind === 150 || node.kind === 149) && node.parent.kind === 164) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -53738,15 +55797,15 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 226) { + if (node.kind === 227) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148 || - (node.kind === 146 && ts.hasModifier(node.parent, 8))) { + else if (node.kind === 150 || node.kind === 149 || + (node.kind === 147 && ts.hasModifier(node.parent, 8))) { if (ts.hasModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -53754,7 +55813,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 || node.kind === 146) { + else if (node.parent.kind === 230 || node.kind === 147) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -53780,7 +55839,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 200) { + if (element.kind !== 201 && isVariableDeclarationVisible(element)) { elements.push(element); } } @@ -53813,7 +55872,7 @@ var ts; } } function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { @@ -53830,12 +55889,12 @@ var ts; else { write("var "); } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, resolver.isDeclarationVisible); + emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); write(";"); writeLine(); } function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -53844,12 +55903,12 @@ var ts; emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getAccessorNameVisibilityError); if (!ts.hasModifier(node, 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 153 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 154 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -53862,82 +55921,152 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 153 + return accessor.kind === 154 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : undefined; } } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 154) { - if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { + if (accessorWithTypeAnnotation.kind === 155) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - typeName: accessorWithTypeAnnotation.name - }; } else { if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: accessorWithTypeAnnotation.name + }; } } function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 228) { + if (node.kind === 229) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 151 || node.kind === 152) { + else if (node.kind === 152 || node.kind === 153) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 228) { + if (node.kind === 229) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 152) { + else if (node.kind === 153) { write("constructor"); } else { - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getMethodNameVisibilityError); if (ts.hasQuestionToken(node)) { write("?"); } } emitSignatureDeclaration(node); } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + if (ts.hasDynamicName(node)) { + ts.Debug.assert(resolver.isLateBound(node)); + writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); + } + else { + writeTextOfNode(currentText, node.name); + } + } + function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + var entityName = node.name.expression; + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + writeTextOfNode(currentText, node.name); } function emitSignatureDeclarationWithJsDocComments(node) { emitJsDocComments(node); @@ -53947,20 +56076,20 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 157) { + if (node.kind === 158) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 && ts.hasModifier(node, 8)) { + if (node.kind === 153 && ts.hasModifier(node, 8)) { write("();"); writeLine(); return; } - if (node.kind === 156 || node.kind === 161) { + if (node.kind === 157 || node.kind === 162) { write("new "); } - else if (node.kind === 160) { + else if (node.kind === 161) { var currentOutput = writer.getText(); if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { closeParenthesizedFunctionType = true; @@ -53971,20 +56100,20 @@ var ts; write("("); } emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 157) { + if (node.kind === 158) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 160 || node.kind === 161; - if (isFunctionTypeOrConstructorType || node.parent.kind === 163) { + var isFunctionTypeOrConstructorType = node.kind === 161 || node.kind === 162; + if (isFunctionTypeOrConstructorType || node.parent.kind === 164) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 152 && !ts.hasModifier(node, 8)) { + else if (node.kind !== 153 && !ts.hasModifier(node, 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -53998,23 +56127,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 156: + case 157: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 155: + case 156: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 157: + case 158: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; + case 152: case 151: - case 150: if (ts.hasModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -54022,7 +56151,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54035,7 +56164,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 228: + case 229: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -54067,9 +56196,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - node.parent.parent.kind === 163) { + if (node.parent.kind === 161 || + node.parent.kind === 162 || + node.parent.parent.kind === 164) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8)) { @@ -54085,26 +56214,26 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 152: + case 153: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 156: + case 157: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 155: + case 156: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157: + case 158: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 152: case 151: - case 150: if (ts.hasModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -54112,7 +56241,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229) { + else if (node.parent.parent.kind === 230) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54124,7 +56253,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 228: + case 229: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -54135,12 +56264,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 174) { + if (bindingPattern.kind === 175) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 175) { + else if (bindingPattern.kind === 176) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -54151,10 +56280,10 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 200) { + if (bindingElement.kind === 201) { write(" "); } - else if (bindingElement.kind === 176) { + else if (bindingElement.kind === 177) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -54176,39 +56305,39 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 228: - case 233: - case 237: - case 230: case 229: + case 234: + case 238: case 231: + case 230: case 232: + case 233: return emitModuleElement(node, isModuleElementVisible(node)); - case 208: + case 209: return emitModuleElement(node, isVariableStatementVisible(node)); - case 238: + case 239: return emitModuleElement(node, !node.importClause); - case 244: + case 245: return emitExportDeclaration(node); + case 153: case 152: case 151: - case 150: return writeFunctionDeclaration(node); - case 156: - case 155: case 157: + case 156: + case 158: return emitSignatureDeclarationWithJsDocComments(node); - case 153: case 154: + case 155: return emitAccessorDeclaration(node); + case 150: case 149: - case 148: return emitPropertyDeclaration(node); - case 264: + case 268: return emitEnumMemberDeclaration(node); - case 243: + case 244: return emitExportAssignment(node); - case 265: + case 269: return emitSourceFile(node); } } @@ -54227,7 +56356,7 @@ var ts; } return addedBundledEmitReference; function getDeclFileName(emitFileNames, sourceFileOrBundle) { - var isBundledEmit = sourceFileOrBundle.kind === 266; + var isBundledEmit = sourceFileOrBundle.kind === 270; if (isBundledEmit && !addBundledFileReference) { return; } @@ -54241,7 +56370,7 @@ var ts; var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { - var sourceFiles = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); @@ -54329,7 +56458,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 265) { + if (sourceFileOrBundle.kind === 269) { sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { @@ -54436,7 +56565,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 287 + if (node.kind !== 291 && (emitFlags & 16) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -54453,7 +56582,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 287 + if (node.kind !== 291 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); @@ -54595,7 +56724,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287; + var isEmittedNode = node.kind !== 291; var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { @@ -54609,7 +56738,7 @@ var ts; } if (!skipTrailingComments) { containerEnd = end; - if (node.kind === 227) { + if (node.kind === 228) { declarationListContainerEnd = end; } } @@ -54745,7 +56874,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -54758,7 +56887,7 @@ var ts; if (hasTrailingNewLine) { writer.writeLine(); } - else { + else if (kind === 3) { writer.write(" "); } } @@ -54919,7 +57048,7 @@ var ts; return ".js"; } function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266) { + if (sourceFileOrBundle.kind === 270) { return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); } return ts.getOriginalSourceFile(sourceFileOrBundle); @@ -54985,8 +57114,8 @@ var ts; } } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 265 ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 269 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); if (bundle) { @@ -55022,7 +57151,7 @@ var ts; } function emitHelpers(node, writeLines) { var helpersEmitted = false; - var bundle = node.kind === 266 ? node : undefined; + var bundle = node.kind === 270 ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -55095,8 +57224,8 @@ var ts; break; } switch (node.kind) { - case 265: return printFile(node); - case 266: return printBundle(node); + case 269: return printFile(node); + case 270: return printBundle(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -55246,192 +57375,210 @@ var ts; return emitLiteral(node); case 71: return emitIdentifier(node); - case 143: - return emitQualifiedName(node); case 144: - return emitComputedPropertyName(node); + return emitQualifiedName(node); case 145: - return emitTypeParameter(node); + return emitComputedPropertyName(node); case 146: - return emitParameter(node); + return emitTypeParameter(node); case 147: - return emitDecorator(node); + return emitParameter(node); case 148: - return emitPropertySignature(node); + return emitDecorator(node); case 149: - return emitPropertyDeclaration(node); + return emitPropertySignature(node); case 150: - return emitMethodSignature(node); + return emitPropertyDeclaration(node); case 151: - return emitMethodDeclaration(node); + return emitMethodSignature(node); case 152: - return emitConstructor(node); + return emitMethodDeclaration(node); case 153: + return emitConstructor(node); case 154: - return emitAccessorDeclaration(node); case 155: - return emitCallSignature(node); + return emitAccessorDeclaration(node); case 156: - return emitConstructSignature(node); + return emitCallSignature(node); case 157: - return emitIndexSignature(node); + return emitConstructSignature(node); case 158: - return emitTypePredicate(node); + return emitIndexSignature(node); case 159: - return emitTypeReference(node); + return emitTypePredicate(node); case 160: - return emitFunctionType(node); + return emitTypeReference(node); case 161: - return emitConstructorType(node); + return emitFunctionType(node); + case 277: + return emitJSDocFunctionType(node); case 162: - return emitTypeQuery(node); + return emitConstructorType(node); case 163: - return emitTypeLiteral(node); + return emitTypeQuery(node); case 164: - return emitArrayType(node); + return emitTypeLiteral(node); case 165: - return emitTupleType(node); + return emitArrayType(node); case 166: - return emitUnionType(node); + return emitTupleType(node); case 167: - return emitIntersectionType(node); + return emitUnionType(node); case 168: + return emitIntersectionType(node); + case 169: return emitParenthesizedType(node); - case 201: + case 202: return emitExpressionWithTypeArguments(node); - case 169: - return emitThisType(); case 170: - return emitTypeOperator(node); + return emitThisType(); case 171: - return emitIndexedAccessType(node); + return emitTypeOperator(node); case 172: - return emitMappedType(node); + return emitIndexedAccessType(node); case 173: - return emitLiteralType(node); + return emitMappedType(node); case 174: - return emitObjectBindingPattern(node); + return emitLiteralType(node); + case 272: + write("*"); + return; + case 273: + write("?"); + return; + case 274: + return emitJSDocNullableType(node); + case 275: + return emitJSDocNonNullableType(node); + case 276: + return emitJSDocOptionalType(node); + case 278: + return emitJSDocVariadicType(node); case 175: - return emitArrayBindingPattern(node); + return emitObjectBindingPattern(node); case 176: + return emitArrayBindingPattern(node); + case 177: return emitBindingElement(node); - case 205: - return emitTemplateSpan(node); case 206: - return emitSemicolonClassElement(); + return emitTemplateSpan(node); case 207: - return emitBlock(node); + return emitSemicolonClassElement(); case 208: - return emitVariableStatement(node); + return emitBlock(node); case 209: - return emitEmptyStatement(); + return emitVariableStatement(node); case 210: - return emitExpressionStatement(node); + return emitEmptyStatement(); case 211: - return emitIfStatement(node); + return emitExpressionStatement(node); case 212: - return emitDoStatement(node); + return emitIfStatement(node); case 213: - return emitWhileStatement(node); + return emitDoStatement(node); case 214: - return emitForStatement(node); + return emitWhileStatement(node); case 215: - return emitForInStatement(node); + return emitForStatement(node); case 216: - return emitForOfStatement(node); + return emitForInStatement(node); case 217: - return emitContinueStatement(node); + return emitForOfStatement(node); case 218: - return emitBreakStatement(node); + return emitContinueStatement(node); case 219: - return emitReturnStatement(node); + return emitBreakStatement(node); case 220: - return emitWithStatement(node); + return emitReturnStatement(node); case 221: - return emitSwitchStatement(node); + return emitWithStatement(node); case 222: - return emitLabeledStatement(node); + return emitSwitchStatement(node); case 223: - return emitThrowStatement(node); + return emitLabeledStatement(node); case 224: - return emitTryStatement(node); + return emitThrowStatement(node); case 225: - return emitDebuggerStatement(node); + return emitTryStatement(node); case 226: - return emitVariableDeclaration(node); + return emitDebuggerStatement(node); case 227: - return emitVariableDeclarationList(node); + return emitVariableDeclaration(node); case 228: - return emitFunctionDeclaration(node); + return emitVariableDeclarationList(node); case 229: - return emitClassDeclaration(node); + return emitFunctionDeclaration(node); case 230: - return emitInterfaceDeclaration(node); + return emitClassDeclaration(node); case 231: - return emitTypeAliasDeclaration(node); + return emitInterfaceDeclaration(node); case 232: - return emitEnumDeclaration(node); + return emitTypeAliasDeclaration(node); case 233: - return emitModuleDeclaration(node); + return emitEnumDeclaration(node); case 234: - return emitModuleBlock(node); + return emitModuleDeclaration(node); case 235: - return emitCaseBlock(node); + return emitModuleBlock(node); case 236: - return emitNamespaceExportDeclaration(node); + return emitCaseBlock(node); case 237: - return emitImportEqualsDeclaration(node); + return emitNamespaceExportDeclaration(node); case 238: - return emitImportDeclaration(node); + return emitImportEqualsDeclaration(node); case 239: - return emitImportClause(node); + return emitImportDeclaration(node); case 240: - return emitNamespaceImport(node); + return emitImportClause(node); case 241: - return emitNamedImports(node); + return emitNamespaceImport(node); case 242: - return emitImportSpecifier(node); + return emitNamedImports(node); case 243: - return emitExportAssignment(node); + return emitImportSpecifier(node); case 244: - return emitExportDeclaration(node); + return emitExportAssignment(node); case 245: - return emitNamedExports(node); + return emitExportDeclaration(node); case 246: - return emitExportSpecifier(node); + return emitNamedExports(node); case 247: - return; + return emitExportSpecifier(node); case 248: + return; + case 249: return emitExternalModuleReference(node); case 10: return emitJsxText(node); - case 251: - return emitJsxOpeningElement(node); case 252: - return emitJsxClosingElement(node); + case 255: + return emitJsxOpeningElementOrFragment(node); case 253: + case 256: + return emitJsxClosingElementOrFragment(node); + case 257: return emitJsxAttribute(node); - case 254: + case 258: return emitJsxAttributes(node); - case 255: + case 259: return emitJsxSpreadAttribute(node); - case 256: + case 260: return emitJsxExpression(node); - case 257: + case 261: return emitCaseClause(node); - case 258: + case 262: return emitDefaultClause(node); - case 259: + case 263: return emitHeritageClause(node); - case 260: + case 264: return emitCatchClause(node); - case 261: + case 265: return emitPropertyAssignment(node); - case 262: + case 266: return emitShorthandPropertyAssignment(node); - case 263: + case 267: return emitSpreadAssignment(node); - case 264: + case 268: return emitEnumMember(node); } if (ts.isExpression(node)) { @@ -55461,67 +57608,69 @@ var ts; case 91: writeTokenNode(node); return; - case 177: - return emitArrayLiteralExpression(node); case 178: - return emitObjectLiteralExpression(node); + return emitArrayLiteralExpression(node); case 179: - return emitPropertyAccessExpression(node); + return emitObjectLiteralExpression(node); case 180: - return emitElementAccessExpression(node); + return emitPropertyAccessExpression(node); case 181: - return emitCallExpression(node); + return emitElementAccessExpression(node); case 182: - return emitNewExpression(node); + return emitCallExpression(node); case 183: - return emitTaggedTemplateExpression(node); + return emitNewExpression(node); case 184: - return emitTypeAssertionExpression(node); + return emitTaggedTemplateExpression(node); case 185: - return emitParenthesizedExpression(node); + return emitTypeAssertionExpression(node); case 186: - return emitFunctionExpression(node); + return emitParenthesizedExpression(node); case 187: - return emitArrowFunction(node); + return emitFunctionExpression(node); case 188: - return emitDeleteExpression(node); + return emitArrowFunction(node); case 189: - return emitTypeOfExpression(node); + return emitDeleteExpression(node); case 190: - return emitVoidExpression(node); + return emitTypeOfExpression(node); case 191: - return emitAwaitExpression(node); + return emitVoidExpression(node); case 192: - return emitPrefixUnaryExpression(node); + return emitAwaitExpression(node); case 193: - return emitPostfixUnaryExpression(node); + return emitPrefixUnaryExpression(node); case 194: - return emitBinaryExpression(node); + return emitPostfixUnaryExpression(node); case 195: - return emitConditionalExpression(node); + return emitBinaryExpression(node); case 196: - return emitTemplateExpression(node); + return emitConditionalExpression(node); case 197: - return emitYieldExpression(node); + return emitTemplateExpression(node); case 198: - return emitSpreadExpression(node); + return emitYieldExpression(node); case 199: - return emitClassExpression(node); + return emitSpreadExpression(node); case 200: + return emitClassExpression(node); + case 201: return; - case 202: - return emitAsExpression(node); case 203: - return emitNonNullExpression(node); + return emitAsExpression(node); case 204: + return emitNonNullExpression(node); + case 205: return emitMetaProperty(node); - case 249: - return emitJsxElement(node); case 250: + return emitJsxElement(node); + case 251: return emitJsxSelfClosingElement(node); - case 288: + case 254: + return emitJsxFragment(node); + case 292: return emitPartiallyEmittedExpression(node); - case 289: + case 293: return emitCommaList(node); } } @@ -55577,9 +57726,16 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); - emit(node.name); + if (node.name) { + emit(node.name); + } emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); + if (node.parent && node.parent.kind === 277 && !node.name) { + emit(node.type); + } + else { + emitWithPrefix(": ", node.type); + } emitExpressionWithPrefix(" = ", node.initializer); } function emitDecorator(decorator) { @@ -55629,7 +57785,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 153 ? "get " : "set "); + write(node.kind === 154 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -55675,6 +57831,24 @@ var ts; write(" => "); emit(node.type); } + function emitJSDocFunctionType(node) { + write("function"); + emitParameters(node, node.parameters); + write(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + write("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + write("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + write("="); + } function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); @@ -55696,6 +57870,10 @@ var ts; emit(node.elementType); write("[]"); } + function emitJSDocVariadicType(node) { + write("..."); + emit(node.type); + } function emitTupleType(node) { write("["); emitList(node, node.elementTypes, 336); @@ -55829,7 +58007,7 @@ var ts; if (ts.isNumericLiteral(expression)) { var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23)) < 0; + && !ts.stringContains(text, ts.tokenToString(23)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); @@ -55911,7 +58089,7 @@ var ts; } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 192 + return operand.kind === 193 && ((node.operator === 37 && (operand.operator === 37 || operand.operator === 43)) || (node.operator === 38 && (operand.operator === 38 || operand.operator === 44))); } @@ -56023,7 +58201,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); writeToken(82, node.thenStatement.end, node); - if (node.elseStatement.kind === 211) { + if (node.elseStatement.kind === 212) { write(" "); emit(node.elseStatement); } @@ -56086,7 +58264,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 227) { + if (node.kind === 228) { emit(node); } else { @@ -56194,26 +58372,15 @@ var ts; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 524288) { - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + pushNameGenerationScope(node); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4, body, emitBlockCallback); } else { - pushNameGenerationScope(); - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } - popNameGenerationScope(); + emitBlockFunctionBody(body); } + popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); } @@ -56303,11 +58470,9 @@ var ts; } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 65); write("}"); - popNameGenerationScope(); if (indentedFlag) { decreaseIndent(); } @@ -56337,11 +58502,9 @@ var ts; emitModifiers(node, node.modifiers); write("enum "); emit(node.name); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 81); write("}"); - popNameGenerationScope(); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); @@ -56350,7 +58513,7 @@ var ts; } emit(node.name); var body = node.body; - while (body.kind === 233) { + while (body.kind === 234) { write("."); emit(body.name); body = body.body; @@ -56359,11 +58522,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - pushNameGenerationScope(); + pushNameGenerationScope(node); write("{"); emitBlockStatements(node, isEmptyBlock(node)); write("}"); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitCaseBlock(node) { writeToken(17, node.pos); @@ -56474,21 +58637,30 @@ var ts; } write("/>"); } - function emitJsxOpeningElement(node) { + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 131072); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { write("<"); - emitJsxTagName(node.tagName); - writeIfAny(node.attributes.properties, " "); - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + if (node.attributes.properties && node.attributes.properties.length > 0) { + write(" "); + emit(node.attributes); + } } write(">"); } function emitJsxText(node) { writer.writeLiteral(getTextOfNode(node, true)); } - function emitJsxClosingElement(node) { + function emitJsxClosingElementOrFragment(node) { write(""); } function emitJsxAttributes(node) { @@ -56604,11 +58776,11 @@ var ts; } function emitSourceFileWorker(node) { var statements = node.statements; - pushNameGenerationScope(); + pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitList(node, statements, 1, index === -1 ? statements.length : index); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); @@ -56868,11 +59040,6 @@ var ts; function decreaseIndent() { writer.decreaseIndent(); } - function writeIfAny(nodes, text) { - if (ts.some(nodes)) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -56903,8 +59070,9 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = guessIndentation(lines); - for (var i = 0; i < lines.length; i++) { - var line = indentation ? lines[i].slice(indentation) : lines[i]; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var lineText = lines_1[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); @@ -56914,8 +59082,8 @@ var ts; } function guessIndentation(lines) { var indentation; - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var line = lines_1[_a]; + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { if (indentation === undefined || i < indentation) { @@ -56983,7 +59151,7 @@ var ts; } } else { - return nextNode.startsOnNewLine; + return ts.getStartsOnNewLine(nextNode); } } function shouldWriteClosingLineTerminator(parentNode, children, format) { @@ -57011,7 +59179,7 @@ var ts; } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { - var startsOnNewLine = node.startsOnNewLine; + var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { return (format & 32768) !== 0; } @@ -57023,7 +59191,7 @@ var ts; parent = skipSynthesizedParentheses(parent); node1 = skipSynthesizedParentheses(node1); node2 = skipSynthesizedParentheses(node2); - if (node2.startsOnNewLine) { + if (ts.getStartsOnNewLine(node2)) { return true; } return !ts.nodeIsSynthesized(parent) @@ -57036,7 +59204,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 185 && ts.nodeIsSynthesized(node)) { + while (node.kind === 186 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -57046,7 +59214,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } else if (node.kind === 9 && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -57070,17 +59238,32 @@ var ts; } return ts.getLiteralText(node, currentSourceFile); } - function pushNameGenerationScope() { + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288) { + return; + } tempFlagsStack.push(tempFlags); tempFlags = 0; } - function popNameGenerationScope() { + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288) { + return; + } tempFlags = tempFlagsStack.pop(); } function generateName(name) { if (name.autoGenerateKind === 4) { - var node = getNodeForGeneratedName(name); - return generateNameCached(node); + if (name.skipNameGenerationScope) { + var savedTempFlags = tempFlags; + popNameGenerationScope(undefined); + var result = generateNameCached(getNodeForGeneratedName(name)); + pushNameGenerationScope(undefined); + tempFlags = savedTempFlags; + return result; + } + else { + return generateNameCached(getNodeForGeneratedName(name)); + } } else { var autoGenerateId = name.autoGenerateId; @@ -57168,21 +59351,21 @@ var ts; switch (node.kind) { case 71: return makeUniqueName(getTextOfNode(node)); + case 234: case 233: - case 232: return generateNameForModuleOrEnum(node); - case 238: - case 244: + case 239: + case 245: return generateNameForImportOrExportDeclaration(node); - case 228: case 229: - case 243: + case 230: + case 244: return generateNameForExportDefault(); - case 199: + case 200: return generateNameForClassExpression(); - case 151: - case 153: + case 152: case 154: + case 155: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0); @@ -57195,7 +59378,7 @@ var ts; case 2: return makeTempVariableName(268435456); case 3: - return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); + return makeUniqueName(ts.idText(name)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -57302,7 +59485,7 @@ var ts; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; @@ -57316,21 +59499,353 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } - while (true) { - var fileName = ts.combinePaths(searchPath, configName); - if (fileExists(fileName)) { - return fileName; + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; + function createBuilder(options) { + var isModuleEmit; + var fileInfos = ts.createMap(); + var semanticDiagnosticsPerFile = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; + var emitHandler; + return { + updateProgram: updateProgram, + getFilesAffectedBy: getFilesAffectedBy, + emitChangedFiles: emitChangedFiles, + getSemanticDiagnostics: getSemanticDiagnostics, + clear: clear + }; + function createProgramGraph(program) { + var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; + if (isModuleEmit !== currentIsModuleEmit) { + isModuleEmit = currentIsModuleEmit; + emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; + ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { + createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, + onDeleteValue: removeExistingFileInfo, + onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } + }); + } + function registerChangedFile(path) { + changedFilesSet.set(path, true); + semanticDiagnosticsPerFile.delete(path); + } + function addNewFileInfo(program, sourceFile) { + registerChangedFile(sourceFile.path); + emitHandler.onAddSourceFile(program, sourceFile); + return { version: sourceFile.version, signature: undefined }; + } + function removeExistingFileInfo(_existingFileInfo, path) { + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); + emitHandler.onRemoveSourceFile(path); + } + function updateExistingFileInfo(program, existingInfo, sourceFile) { + if (existingInfo.version !== sourceFile.version) { + registerChangedFile(sourceFile.path); + existingInfo.version = sourceFile.version; + emitHandler.onUpdateSourceFile(program, sourceFile); } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + registerChangedFile(sourceFile.path); } - searchPath = parentPath; } - return undefined; + function ensureProgramGraph(program) { + if (!emitHandler) { + createProgramGraph(program); + } + } + function updateProgram(newProgram) { + if (emitHandler) { + createProgramGraph(newProgram); + } + } + function getFilesAffectedBy(program, path) { + ensureProgramGraph(program); + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); + } + function emitChangedFiles(program, writeFileCallback) { + ensureProgramGraph(program); + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(undefined, writeFileCallback)]; + } + var seenFiles = ts.createMap(); + var result; + changedFilesSet.forEach(function (_true, path) { + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); + } + }); + }); + changedFilesSet.clear(); + return result || ts.emptyArray; + } + function getSemanticDiagnostics(program, cancellationToken) { + ensureProgramGraph(program); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + return program.getSemanticDiagnostics(undefined, cancellationToken); + } + var diagnostics; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + function clear() { + isModuleEmit = undefined; + emitHandler = undefined; + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + info.signature = latestSignature; + } + else { + var emitOutput = getFileEmitOutput(program, sourceFile, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = options.computeHash(emitOutput.outputFiles[0].text); + info.signature = latestSignature; + } + else { + latestSignature = prevSignature; + } + } + return !prevSignature || latestSignature !== prevSignature; + } + function getReferencedFiles(program, sourceFile) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getNonModuleEmitHandler() { + return { + onAddSourceFile: ts.noop, + onRemoveSourceFile: ts.noop, + onUpdateSourceFile: ts.noop, + onUpdateSourceFileWithSameVersion: ts.returnFalse, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function getFilesAffectedByUpdatedShape(program, sourceFile) { + var options = program.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return [sourceFile]; + } + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + } + function getModuleEmitHandler() { + var references = ts.createMap(); + return { + onAddSourceFile: setReferences, + onRemoveSourceFile: onRemoveSourceFile, + onUpdateSourceFile: updateReferences, + onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function setReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + } + function updateReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + else { + references.delete(sourceFile.path); + } + } + function updateReferencesTrackingChangedReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (!newReferences) { + return references.delete(sourceFile.path); + } + var oldReferences = references.get(sourceFile.path); + references.set(sourceFile.path, newReferences); + if (!oldReferences || oldReferences.size !== newReferences.size) { + return true; + } + return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || + !!oldReferences.size; + } + function onRemoveSourceFile(removedFilePath) { + references.forEach(function (referencesInFile, filePath) { + if (referencesInFile.has(removedFilePath)) { + var referencedByInfo = fileInfos.get(filePath); + if (referencedByInfo) { + registerChangedFile(filePath); + } + } + }); + references.delete(removedFilePath); + } + function getReferencedByPaths(referencedFilePath) { + return ts.mapDefinedIter(references.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + }); + } + function getFilesAffectedByUpdatedShape(program, sourceFile) { + if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFile]; + } + var seenFileNamesMap = ts.createMap(); + var path = sourceFile.path; + seenFileNamesMap.set(path, sourceFile); + var queue = getReferencedByPaths(path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = program.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { + queue.push.apply(queue, getReferencedByPaths(currentPath)); + } + } + } + return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); + } + } + } + ts.createBuilder = createBuilder; +})(ts || (ts = {})); +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); } ts.findConfigFile = findConfigFile; function resolveTripleslashReference(moduleName, containingFile) { @@ -57488,18 +60003,23 @@ var ts; var output = ""; for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { var diagnostic = diagnostics_1[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + output += formatDiagnostic(diagnostic, host); } return output; } ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; @@ -57527,6 +60047,7 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; + var context = ""; if (diagnostic.file) { var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; @@ -57538,10 +60059,10 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += host.getNewLine(); + context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -57549,23 +60070,22 @@ var ts; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + host.getNewLine(); - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; + context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += redForegroundEscapeSequence; if (i === firstLine) { var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { - output += lineContent.replace(/./g, "~"); + context += lineContent.replace(/./g, "~"); } - output += resetEscapeSequence; - output += host.getNewLine(); + context += resetEscapeSequence; } output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; @@ -57573,13 +60093,17 @@ var ts; var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += context; + } output += host.getNewLine(); } return output; } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { - if (typeof messageText === "string") { + if (ts.isString(messageText)) { return messageText; } else { @@ -57620,6 +60144,45 @@ var ts; } return resolutions; } + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function shouldProgramCreateNewSourceFiles(program, newOptions) { + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57648,8 +60211,9 @@ var ts; var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -57675,7 +60239,9 @@ var ts; var sourceFileToPackageName = ts.createMap(); var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); + var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); @@ -57698,9 +60264,19 @@ var ts; }); } } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); } - var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + ts.Debug.assert(!!missingFilePaths); moduleResolutionCache = undefined; + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } oldProgram = undefined; program = { getRootFileNames: function () { return rootNames; }, @@ -57731,7 +60307,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57759,8 +60335,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var sourceFile = files_2[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var sourceFile = files_1[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -57772,26 +60348,28 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + var result_3 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_3.push(resolvedModule); } - return result_4; + return result_3; } var unknownModuleNames; var result; + var reusedNames; var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - if (file === oldSourceFile) { + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); if (oldResolvedModule) { if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); } (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); continue; } } @@ -57813,7 +60391,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) : ts.emptyArray; if (!result) { ts.Debug.assert(resolutions.length === moduleNames.length); @@ -57875,6 +60453,9 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2; + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0; + } var oldSourceFiles = oldProgram.getSourceFiles(); var SeenPackageName; (function (SeenPackageName) { @@ -57882,11 +60463,11 @@ var ts; SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; })(SeenPackageName || (SeenPackageName = {})); var seenPackageNames = ts.createMap(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) - : host.getSourceFile(oldSourceFile.fileName, options.target); + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0; } @@ -57941,6 +60522,10 @@ var ts; } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + oldProgram.structureIsReused = 1; + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } newSourceFiles.push(newSourceFile); } if (oldProgram.structureIsReused !== 2) { @@ -57979,20 +60564,20 @@ var ts; if (oldProgram.structureIsReused !== 2) { return oldProgram.structureIsReused; } - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + if (host.hasChangedAutomaticTypeDirectiveNames) { return oldProgram.structureIsReused = 1; } - for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { - var p = _d[_c]; - filesByName.set(p, undefined); - } + missingFilePaths = oldProgram.getMissingFilePaths(); for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { - var modifiedFile = modifiedSourceFiles_2[_e]; + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -58022,10 +60607,16 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); @@ -58105,9 +60696,6 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - if (ts.isCheckJsEnabledForFile(sourceFile, options)) { - sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); - } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -58135,12 +60723,17 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || + sourceFile.scriptKind === 5 || isCheckJs; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); + if (isCheckJs) { + diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + } return ts.filter(diagnostics, shouldReportDiagnostic); }); } @@ -58171,62 +60764,62 @@ var ts; return diagnostics; function walk(node) { switch (parent.kind) { - case 146: - case 149: + case 147: + case 150: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: - case 226: + case 229: + case 188: + case 227: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); return; } } switch (node.kind) { - case 237: + case 238: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 243: + case 244: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 259: + case 263: var heritageClause = node; if (heritageClause.token === 108) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 230: + case 231: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 233: + case 234: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 231: + case 232: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 232: + case 233: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 203: + case 204: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 202: + case 203: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 184: + case 185: ts.Debug.fail(); } var prevParent = parent; @@ -58239,25 +60832,25 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } switch (parent.kind) { - case 229: - case 151: - case 150: + case 230: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: + case 229: + case 188: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } - case 208: + case 209: if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 208); + return checkModifiers(nodes, parent.kind === 209); } break; - case 149: + case 150: if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -58268,15 +60861,15 @@ var ts; return; } break; - case 146: + case 147: if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 181: case 182: - case 201: + case 183: + case 202: if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return; @@ -58398,9 +60991,9 @@ var ts; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { + case 239: case 238: - case 237: - case 244: + case 245: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; @@ -58412,7 +61005,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 233: + case 234: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); @@ -58462,7 +61055,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } return sourceFile; @@ -58546,7 +61139,7 @@ var ts; else { fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } - }); + }, shouldCreateNewSourceFile); if (packageId) { var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); @@ -58809,7 +61402,7 @@ var ts; if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } - if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0; @@ -58997,7 +61590,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -59085,31 +61678,32 @@ var ts; name: "target", shortName: "t", type: ts.createMapFromTemplate({ - "es3": 0, - "es5": 1, - "es6": 2, - "es2015": 2, - "es2016": 3, - "es2017": 4, - "esnext": 5, + es3: 0, + es5: 1, + es6: 2, + es2015: 2, + es2016: 3, + es2017: 4, + es2018: 5, + esnext: 6, }), paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", shortName: "m", type: ts.createMapFromTemplate({ - "none": ts.ModuleKind.None, - "commonjs": ts.ModuleKind.CommonJS, - "amd": ts.ModuleKind.AMD, - "system": ts.ModuleKind.System, - "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES2015, - "es2015": ts.ModuleKind.ES2015, - "esnext": ts.ModuleKind.ESNext + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -59128,6 +61722,7 @@ var ts; "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", "dom": "lib.dom.d.ts", "dom.iterable": "lib.dom.iterable.d.ts", @@ -59147,6 +61742,7 @@ var ts; "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", + "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -59273,6 +61869,20 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, { name: "noImplicitThis", type: "boolean", @@ -59318,8 +61928,8 @@ var ts; { name: "moduleResolution", type: ts.createMapFromTemplate({ - "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic, + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, }), paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, @@ -59502,8 +62112,8 @@ var ts; { name: "newLine", type: ts.createMapFromTemplate({ - "crlf": 0, - "lf": 1 + crlf: 0, + lf: 1 }), paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Advanced_Options, @@ -59838,7 +62448,7 @@ var ts; } function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; function parseConfigFileTextToJson(fileName, jsonText) { @@ -59851,7 +62461,7 @@ var ts; ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function readJsonConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; function tryReadFile(fileName, readFile) { @@ -59935,7 +62545,7 @@ var ts; var result = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 261) { + if (element.kind !== 265) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -59992,9 +62602,9 @@ var ts; if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); var text = valueExpression.text; - if (option && typeof option.type !== "string") { + if (option && !ts.isString(option.type)) { var customOption = option; if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); @@ -60004,7 +62614,13 @@ var ts; case 8: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 178: + case 193: + if (valueExpression.operator !== 38 || valueExpression.operand.kind !== 8) { + break; + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 179: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; if (option) { @@ -60014,7 +62630,7 @@ var ts; else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); } - case 177: + case 178: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -60032,13 +62648,13 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : - typeof option.type === "string" ? option.type : "string"; + ts.isString(option.type) ? option.type : "string"; } function isCompilerOptionsValue(option, value) { if (option) { @@ -60047,7 +62663,7 @@ var ts; if (option.type === "list") { return ts.isArray(value); } - var expectedType = typeof option.type === "string" ? option.type : "string"; + var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } } @@ -60208,12 +62824,13 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -60221,14 +62838,15 @@ var ts; raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec }; function getFileNames() { - var fileNames; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - fileNames = raw["files"]; - if (fileNames.length === 0) { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -60237,35 +62855,35 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } } - if (fileNames === undefined && includeSpecs === undefined) { + if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } return result; } @@ -60275,12 +62893,20 @@ var ts; } } } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); @@ -60317,11 +62943,11 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { - if (typeof json.extends !== "string") { + if (!ts.isString(json.extends)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { @@ -60409,7 +63035,7 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } @@ -60433,7 +63059,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -60493,7 +63119,7 @@ var ts; if (optType === "list" && ts.isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors); } - else if (typeof optType !== "string") { + else if (!ts.isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); } return normalizeNonListOptionValue(opt, basePath, value); @@ -60507,13 +63133,13 @@ var ts; return undefined; if (option.type === "list") { var listOption_1 = option; - if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else if (typeof option.type !== "string") { - return option.type.get(typeof value === "string" ? value.toLowerCase() : value); + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -60549,28 +63175,36 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); + } + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); - if (include) { - include = validateSpecs(include, errors, false, jsonSourceFile, "include"); - } - if (exclude) { - exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); - } - var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); - if (fileNames) { - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } - if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -60586,9 +63220,11 @@ var ts; var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); return { fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + spec: spec }; } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter(function (spec) { var diag = specToDiagnostic(spec, allowTrailingRecursion); @@ -60938,7 +63574,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.scanner = ts.createScanner(5, true); + ts.scanner = ts.createScanner(6, true); var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -60949,35 +63585,35 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 146: - case 226: - case 176: - case 149: - case 148: - case 261: - case 262: - case 151: + case 147: + case 227: + case 177: case 150: + case 149: + case 265: + case 266: case 152: + case 151: case 153: case 154: - case 228: - case 186: + case 155: + case 229: case 187: - case 260: - case 253: + case 188: + case 264: + case 257: return 1; - case 145: - case 230: + case 146: case 231: - case 163: + case 232: + case 164: return 2; - case 283: + case 288: return node.name === undefined ? 1 | 2 : 2; - case 264: - case 229: + case 268: + case 230: return 1 | 2; - case 233: + case 234: if (ts.isAmbientModule(node)) { return 4 | 1; } @@ -60987,25 +63623,25 @@ var ts; else { return 4; } - case 232: - case 241: + case 233: case 242: - case 237: - case 238: case 243: + case 238: + case 239: case 244: + case 245: return 7; - case 265: + case 269: return 4 | 1; } return 7; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 265) { + if (node.kind === 269) { return 1; } - else if (node.parent.kind === 243) { + else if (node.parent.kind === 244) { return 7; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -61031,15 +63667,15 @@ var ts; ts.getMeaningFromLocation = getMeaningFromLocation; function getMeaningFromRightHandSideOfImportEquals(node) { ts.Debug.assert(node.kind === 71); - if (node.parent.kind === 143 && + if (node.parent.kind === 144 && node.parent.right === node && - node.parent.parent.kind === 237) { + node.parent.parent.kind === 238) { return 1 | 2 | 4; } return 4; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 143) { + while (node.parent.kind === 144) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -61051,27 +63687,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 143) { - while (root.parent && root.parent.kind === 143) { + if (root.parent.kind === 144) { + while (root.parent && root.parent.kind === 144) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 159 && !isLastClause; + return root.parent.kind === 160 && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 179) { - while (root.parent && root.parent.kind === 179) { + if (root.parent.kind === 180) { + while (root.parent && root.parent.kind === 180) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 201 && root.parent.parent.kind === 259) { + if (!isLastClause && root.parent.kind === 202 && root.parent.parent.kind === 263) { var decl = root.parent.parent.parent; - return (decl.kind === 229 && root.parent.parent.token === 108) || - (decl.kind === 230 && root.parent.parent.token === 85); + return (decl.kind === 230 && root.parent.parent.token === 108) || + (decl.kind === 231 && root.parent.parent.token === 85); } return false; } @@ -61081,24 +63717,24 @@ var ts; } switch (node.kind) { case 99: - return !ts.isPartOfExpression(node); - case 169: + return !ts.isExpressionNode(node); + case 170: return true; } switch (node.parent.kind) { - case 159: + case 160: return true; - case 201: + case 202: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 181); + return isCallOrNewExpressionTarget(node, 182); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 182); + return isCallOrNewExpressionTarget(node, 183); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -61111,7 +63747,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 223 && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -61121,13 +63757,13 @@ var ts; ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { return node.kind === 71 && - (node.parent.kind === 218 || node.parent.kind === 217) && + (node.parent.kind === 219 || node.parent.kind === 218) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { return node.kind === 71 && - node.parent.kind === 222 && + node.parent.kind === 223 && node.parent.label === node; } function isLabelName(node) { @@ -61135,15 +63771,15 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 143 && node.parent.right === node; + return node.parent.kind === 144 && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 179 && node.parent.name === node; + return node && node.parent && node.parent.kind === 180 && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 233 && node.parent.name === node; + return node.parent.kind === 234 && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { @@ -61153,22 +63789,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { + case 150: case 149: - case 148: - case 261: - case 264: + case 265: + case 268: + case 152: case 151: - case 150: - case 153: case 154: - case 233: + case 155: + case 234: return ts.getNameOfDeclaration(node.parent) === node; - case 180: + case 181: return node.parent.argumentExpression === node; - case 144: + case 145: return true; - case 173: - return node.parent.parent.kind === 171; + case 174: + return node.parent.parent.kind === 172; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -61178,7 +63814,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 283) { + if (node.kind === 288) { node = node.parent.parent; } while (true) { @@ -61187,17 +63823,17 @@ var ts; return undefined; } switch (node.kind) { - case 265: + case 269: + case 152: case 151: - case 150: - case 228: - case 186: - case 153: - case 154: case 229: + case 187: + case 154: + case 155: case 230: - case 232: + case 231: case 233: + case 234: return node; } } @@ -61205,48 +63841,48 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 265: + case 269: return ts.isExternalModule(node) ? "module" : "script"; - case 233: + case 234: return "module"; - case 229: - case 199: + case 230: + case 200: return "class"; - case 230: return "interface"; - case 231: return "type"; - case 232: return "enum"; - case 226: + case 231: return "interface"; + case 232: return "type"; + case 233: return "enum"; + case 227: return getKindOfVariableDeclaration(node); - case 176: + case 177: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 188: + case 229: case 187: - case 228: - case 186: return "function"; - case 153: return "getter"; - case 154: return "setter"; + case 154: return "getter"; + case 155: return "setter"; + case 152: case 151: - case 150: return "method"; + case 150: case 149: - case 148: return "property"; - case 157: return "index"; - case 156: return "construct"; - case 155: return "call"; - case 152: return "constructor"; - case 145: return "type parameter"; - case 264: return "enum member"; - case 146: return ts.hasModifier(node, 92) ? "property" : "parameter"; - case 237: - case 242: - case 239: - case 246: + case 158: return "index"; + case 157: return "construct"; + case 156: return "call"; + case 153: return "constructor"; + case 146: return "type parameter"; + case 268: return "enum member"; + case 147: return ts.hasModifier(node, 92) ? "property" : "parameter"; + case 238: + case 243: case 240: + case 247: + case 241: return "alias"; - case 283: + case 288: return "type"; - case 194: + case 195: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { @@ -61257,7 +63893,7 @@ var ts; var rightKind = getNodeKind(right); return rightKind === "" ? "const" : rightKind; case 3: - return "method"; + return ts.isFunctionExpression(right) ? "method" : "property"; case 4: return "property"; case 5: @@ -61284,7 +63920,7 @@ var ts; case 99: return true; case 71: - return ts.identifierIsThisKeyword(node) && node.parent.kind === 146; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 147; default: return false; } @@ -61320,7 +63956,8 @@ var ts; } ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { @@ -61328,41 +63965,41 @@ var ts; return false; } switch (n.kind) { - case 229: case 230: - case 232: - case 178: - case 174: - case 163: - case 207: - case 234: + case 231: + case 233: + case 179: + case 175: + case 164: + case 208: case 235: - case 241: - case 245: + case 236: + case 242: + case 246: return nodeEndsWith(n, 18, sourceFile); - case 260: + case 264: return isCompletedNode(n.block, sourceFile); - case 182: + case 183: if (!n.arguments) { return true; } - case 181: - case 185: - case 168: + case 182: + case 186: + case 169: return nodeEndsWith(n, 20, sourceFile); - case 160: case 161: + case 162: return isCompletedNode(n.type, sourceFile); - case 152: case 153: case 154: - case 228: - case 186: - case 151: - case 150: - case 156: case 155: + case 229: case 187: + case 152: + case 151: + case 157: + case 156: + case 188: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -61370,65 +64007,65 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20, sourceFile); - case 233: + case 234: return n.body && isCompletedNode(n.body, sourceFile); - case 211: + case 212: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 210: + case 211: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 25); - case 177: - case 175: - case 180: - case 144: - case 165: + case 178: + case 176: + case 181: + case 145: + case 166: return nodeEndsWith(n, 22, sourceFile); - case 157: + case 158: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 22, sourceFile); - case 257: - case 258: + case 261: + case 262: return false; - case 214: case 215: case 216: - case 213: + case 217: + case 214: return isCompletedNode(n.statement, sourceFile); - case 212: + case 213: var hasWhileKeyword = findChildOfKind(n, 106, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 20, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 162: + case 163: return isCompletedNode(n.exprName, sourceFile); - case 189: - case 188: case 190: - case 197: + case 189: + case 191: case 198: + case 199: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 183: + case 184: return isCompletedNode(n.template, sourceFile); - case 196: + case 197: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 205: + case 206: return ts.nodeIsPresent(n.literal); - case 244: - case 238: + case 245: + case 239: return ts.nodeIsPresent(n.moduleSpecifier); - case 192: + case 193: return isCompletedNode(n.operand, sourceFile); - case 194: - return isCompletedNode(n.right, sourceFile); case 195: + return isCompletedNode(n.right, sourceFile); + case 196: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -61438,11 +64075,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { + var last_2 = ts.lastOrUndefined(children); + if (last_2.kind === expectedLastToken) { return true; } - else if (last.kind === 25 && children.length !== 1) { + else if (last_2.kind === 25 && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -61540,8 +64177,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { - var child = children_2[_i]; + for (var _i = 0, children_3 = children; _i < children_3.length; _i++) { + var child = children_3[_i]; var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || (child.pos === previousToken.end); if (shouldDiveInChildNode && nodeHasTokens(child)) { @@ -61585,7 +64222,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265 || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 269 || ts.isJSDocCommentContainingNode(n)); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -61630,13 +64267,13 @@ var ts; if (token.kind === 27 && token.parent.kind === 10) { return true; } - if (token.kind === 27 && token.parent.kind === 256) { + if (token.kind === 27 && token.parent.kind === 260) { return true; } - if (token && token.kind === 18 && token.parent.kind === 256) { + if (token && token.kind === 18 && token.parent.kind === 260) { return true; } - if (token.kind === 27 && token.parent.kind === 252) { + if (token.kind === 27 && token.parent.kind === 253) { return true; } return false; @@ -61683,16 +64320,16 @@ var ts; result.push("abstract"); if (flags & 1) result.push("export"); - if (ts.isInAmbientContext(node)) + if (node.flags & 2097152) result.push("declare"); return result.length > 0 ? result.join(",") : ""; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 159 || node.kind === 181) { + if (node.kind === 160 || node.kind === 182) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 229 || node.kind === 230) { + if (ts.isFunctionLike(node) || node.kind === 230 || node.kind === 231) { return node.typeParameters; } return undefined; @@ -61743,38 +64380,19 @@ var ts; return result; } ts.cloneCompilerOptions = cloneCompilerOptions; - function compareDataObjects(dst, src) { - if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { - return false; - } - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { - return false; - } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; - } - } - } - return true; - } - ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 177 || - node.kind === 178) { - if (node.parent.kind === 194 && + if (node.kind === 178 || + node.kind === 179) { + if (node.parent.kind === 195 && node.parent.left === node && node.parent.operatorToken.kind === 58) { return true; } - if (node.parent.kind === 216 && + if (node.parent.kind === 217 && node.parent.initializer === node) { return true; } - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 261 ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 265 ? node.parent.parent : node.parent)) { return true; } } @@ -61808,20 +64426,18 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + ts.typeKeywords = [ + 119, + 122, + 130, + 133, + 134, + 136, + 137, + 105, + ]; function isTypeKeyword(kind) { - switch (kind) { - case 119: - case 122: - case 130: - case 133: - case 134: - case 136: - case 137: - case 105: - return true; - default: - return false; - } + return ts.contains(ts.typeKeywords, kind); } ts.isTypeKeyword = isTypeKeyword; function isExternalModuleSymbol(moduleSymbol) { @@ -61840,7 +64456,7 @@ var ts; })(ts || (ts = {})); (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 146; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 147; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -61865,6 +64481,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { @@ -62014,7 +64631,7 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function getDeclaredName(typeChecker, symbol, location) { - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144) { + if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145) { return ts.getTextOfIdentifierOrLiteral(location); } var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); @@ -62023,15 +64640,13 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 242 || location.parent.kind === 246) && + (location.parent.kind === 243 || location.parent.kind === 247) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -62050,6 +64665,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -62065,6 +64684,92 @@ var ts; return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; + function getSourceFileImportLocation(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 && text.charCodeAt(position) === 10) { + position++; + } + } + } + } + } + ts.getSourceFileImportLocation = getSourceFileImportLocation; + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + var clone_7 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_7)) { + clone_7.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; + } + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + if (firstChild) { + suppressLeading(firstChild); + } + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + if (lastChild) { + suppressTrailing(lastChild); + } + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; })(ts || (ts = {})); var ts; (function (ts) { @@ -62082,7 +64787,7 @@ var ts; return undefined; } } - if (ts.isInAmbientContext(tokenAtLocation)) { + if (tokenAtLocation.flags & 2097152) { return undefined; } return spanInNode(tokenAtLocation); @@ -62113,89 +64818,89 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 208: + case 209: return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 226: + case 227: + case 150: case 149: - case 148: return spanInVariableDeclaration(node); - case 146: + case 147: return spanInParameterDeclaration(node); - case 228: + case 229: + case 152: case 151: - case 150: - case 153: case 154: - case 152: - case 186: + case 155: + case 153: case 187: + case 188: return spanInFunctionDeclaration(node); - case 207: + case 208: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 234: + case 235: return spanInBlock(node); - case 260: + case 264: return spanInBlock(node.block); - case 210: + case 211: return textSpan(node.expression); - case 219: + case 220: return textSpan(node.getChildAt(0), node.expression); - case 213: + case 214: return textSpanEndingAtNextToken(node, node.expression); - case 212: + case 213: return spanInNode(node.statement); - case 225: + case 226: return textSpan(node.getChildAt(0)); - case 211: + case 212: return textSpanEndingAtNextToken(node, node.expression); - case 222: + case 223: return spanInNode(node.statement); + case 219: case 218: - case 217: return textSpan(node.getChildAt(0), node.label); - case 214: - return spanInForStatement(node); case 215: - return textSpanEndingAtNextToken(node, node.expression); + return spanInForStatement(node); case 216: + return textSpanEndingAtNextToken(node, node.expression); + case 217: return spanInInitializerOfForLike(node); - case 221: + case 222: return textSpanEndingAtNextToken(node, node.expression); - case 257: - case 258: + case 261: + case 262: return spanInNode(node.statements[0]); - case 224: + case 225: return spanInBlock(node.tryBlock); - case 223: + case 224: return textSpan(node, node.expression); - case 243: + case 244: return textSpan(node, node.expression); - case 237: - return textSpan(node, node.moduleReference); case 238: + return textSpan(node, node.moduleReference); + case 239: return textSpan(node, node.moduleSpecifier); - case 244: + case 245: return textSpan(node, node.moduleSpecifier); - case 233: + case 234: if (ts.getModuleInstanceState(node) !== 1) { return undefined; } - case 229: - case 232: - case 264: - case 176: + case 230: + case 233: + case 268: + case 177: return textSpan(node); - case 220: + case 221: return spanInNode(node.statement); - case 147: + case 148: return spanInNodeArray(node.parent.decorators); - case 174: case 175: + case 176: return spanInBindingPattern(node); - case 230: case 231: + case 232: return undefined; case 25: case 1: @@ -62223,20 +64928,20 @@ var ts; case 74: case 87: return spanInNextNode(node); - case 142: + case 143: return spanInOfKeyword(node); default: if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } if ((node.kind === 71 || - node.kind === 198 || - node.kind === 261 || - node.kind === 262) && + node.kind === 199 || + node.kind === 265 || + node.kind === 266) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 194) { + if (node.kind === 195) { var binaryExpression = node; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); @@ -62249,40 +64954,40 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { switch (node.parent.kind) { - case 212: + case 213: return spanInPreviousNode(node); - case 147: + case 148: return spanInNode(node.parent); - case 214: - case 216: + case 215: + case 217: return textSpan(node); - case 194: + case 195: if (node.parent.operatorToken.kind === 26) { return textSpan(node); } break; - case 187: + case 188: if (node.parent.body === node) { return textSpan(node); } break; } } - if (node.parent.kind === 261 && + if (node.parent.kind === 265 && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 184 && node.parent.type === node) { + if (node.parent.kind === 185 && node.parent.type === node) { return spanInNextNode(node.parent.type); } if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } - if ((node.parent.kind === 226 || - node.parent.kind === 146)) { + if ((node.parent.kind === 227 || + node.parent.kind === 147)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -62290,7 +64995,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 194) { + if (node.parent.kind === 195) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -62302,7 +65007,7 @@ var ts; } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 227 && + if (variableDeclaration.parent.kind === 228 && variableDeclaration.parent.declarations[0] === variableDeclaration) { return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } @@ -62311,7 +65016,7 @@ var ts; } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 215) { + if (variableDeclaration.parent.parent.kind === 216) { return spanInNode(variableDeclaration.parent.parent); } if (ts.isBindingPattern(variableDeclaration.name)) { @@ -62319,10 +65024,10 @@ var ts; } if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1) || - variableDeclaration.parent.parent.kind === 216) { + variableDeclaration.parent.parent.kind === 217) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 227 && + if (variableDeclaration.parent.kind === 228 && variableDeclaration.parent.declarations[0] !== variableDeclaration) { return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } @@ -62351,7 +65056,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1) || - (functionDeclaration.parent.kind === 229 && functionDeclaration.kind !== 152); + (functionDeclaration.parent.kind === 230 && functionDeclaration.kind !== 153); } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -62371,22 +65076,22 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 233: + case 234: if (ts.getModuleInstanceState(block.parent) !== 1) { return undefined; } - case 213: - case 211: - case 215: - return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); case 214: + case 212: case 216: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + case 215: + case 217: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 227) { + if (forLikeStatement.initializer.kind === 228) { var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -62408,62 +65113,62 @@ var ts; } } function spanInBindingPattern(bindingPattern) { - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 200 ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 201 ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - if (bindingPattern.parent.kind === 176) { + if (bindingPattern.parent.kind === 177) { return textSpan(bindingPattern.parent); } return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 175 && node.kind !== 174); - var elements = node.kind === 177 ? + ts.Debug.assert(node.kind !== 176 && node.kind !== 175); + var elements = node.kind === 178 ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 200 ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 201 ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - return textSpan(node.parent.kind === 194 ? node.parent : node); + return textSpan(node.parent.kind === 195 ? node.parent : node); } function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 232: + case 233: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 229: + case 230: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 235: + case 236: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 234: + case 235: if (ts.getModuleInstanceState(node.parent.parent) !== 1) { return undefined; } - case 232: - case 229: + case 233: + case 230: return textSpan(node); - case 207: + case 208: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 260: + case 264: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 235: + case 236: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 174: + case 175: var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: @@ -62476,7 +65181,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 175: + case 176: var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: @@ -62488,33 +65193,33 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 212 || - node.parent.kind === 181 || - node.parent.kind === 182) { + if (node.parent.kind === 213 || + node.parent.kind === 182 || + node.parent.kind === 183) { return spanInPreviousNode(node); } - if (node.parent.kind === 185) { + if (node.parent.kind === 186) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInCloseParenToken(node) { switch (node.parent.kind) { - case 186: - case 228: case 187: + case 229: + case 188: + case 152: case 151: - case 150: - case 153: case 154: - case 152: - case 213: - case 212: + case 155: + case 153: case 214: - case 216: - case 181: + case 213: + case 215: + case 217: case 182: - case 185: + case 183: + case 186: return spanInPreviousNode(node); default: return spanInNode(node.parent); @@ -62522,26 +65227,26 @@ var ts; } function spanInColonToken(node) { if (ts.isFunctionLike(node.parent) || - node.parent.kind === 261 || - node.parent.kind === 146) { + node.parent.kind === 265 || + node.parent.kind === 147) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 184) { + if (node.parent.kind === 185) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 212) { + if (node.parent.kind === 213) { return textSpanEndingAtNextToken(node, node.parent.expression); } return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 216) { + if (node.parent.kind === 217) { return spanInNextNode(node); } return spanInNode(node.parent); @@ -62554,157 +65259,75 @@ var ts; var ts; (function (ts) { function createClassifier() { - var scanner = ts.createScanner(5, false); - var noRegexTable = []; - noRegexTable[71] = true; - noRegexTable[9] = true; - noRegexTable[8] = true; - noRegexTable[12] = true; - noRegexTable[99] = true; - noRegexTable[43] = true; - noRegexTable[44] = true; - noRegexTable[20] = true; - noRegexTable[22] = true; - noRegexTable[18] = true; - noRegexTable[101] = true; - noRegexTable[86] = true; - var templateStack = []; - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 125 || - keyword2 === 135 || - keyword2 === 123 || - keyword2 === 115) { - return true; - } - return false; - } - return true; - } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0; i < dense.length; i += 3) { - var start = dense[i]; - var length_6 = dense[i + 1]; - var type = dense[i + 2]; - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); - } - } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1: return ts.TokenClass.Comment; - case 3: return ts.TokenClass.Keyword; - case 4: return ts.TokenClass.NumberLiteral; - case 5: return ts.TokenClass.Operator; - case 6: return ts.TokenClass.StringLiteral; - case 8: return ts.TokenClass.Whitespace; - case 10: return ts.TokenClass.Punctuation; - case 2: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 9: - case 17: - default: - return ts.TokenClass.Identifier; - } - } + var scanner = ts.createScanner(6, false); function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); } function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; var token = 0; var lastNonTriviaToken = 0; - while (templateStack.length > 0) { - templateStack.pop(); - } - switch (lexState) { - case 3: - text = "\"\\\n" + text; - offset = 3; - break; - case 2: - text = "'\\\n" + text; - offset = 3; - break; - case 1: - text = "/*\n" + text; - offset = 3; - break; - case 4: - text = "`\n" + text; - offset = 2; - break; - case 5: - text = "}\n" + text; - offset = 2; - case 6: - templateStack.push(14); - break; + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(14); } scanner.setText(text); - var result = { - endOfLineState: 0, - spans: [] - }; + var endOfLineState = 0; + var spans = []; var angleBracketStack = 0; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 41 || token === 63) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 12) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1); + function handleToken() { + switch (token) { + case 41: + case 63: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12) { token = 12; } - } - else if (lastNonTriviaToken === 23 && isKeyword(token)) { - token = 71; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - token = 71; - } - else if (lastNonTriviaToken === 71 && - token === 27) { - angleBracketStack++; - } - else if (token === 29 && angleBracketStack > 0) { - angleBracketStack--; - } - else if (token === 119 || - token === 136 || - token === 133 || - token === 122 || - token === 137) { + break; + case 27: + if (lastNonTriviaToken === 71) { + angleBracketStack++; + } + break; + case 29: + if (angleBracketStack > 0) { + angleBracketStack--; + } + break; + case 119: + case 136: + case 133: + case 122: + case 137: if (angleBracketStack > 0 && !syntacticClassifierAbsent) { token = 71; } - } - else if (token === 14) { + break; + case 14: templateStack.push(token); - } - else if (token === 17) { + break; + case 17: if (templateStack.length > 0) { templateStack.push(token); } - } - else if (token === 18) { + break; + case 18: if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); if (lastTemplateStackToken === 14) { @@ -62721,250 +65344,320 @@ var ts; templateStack.pop(); } } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9) { - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { - numBackslashes++; - } - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 - ? 3 - : 2; - } + break; + default: + if (!ts.isKeyword(token)) { + break; } - } - else if (token === 3) { - if (scanner.isUnterminated()) { - result.endOfLineState = 1; + if (lastNonTriviaToken === 23) { + token = 71; } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 16) { - result.endOfLineState = 5; - } - else if (token === 13) { - result.endOfLineState = 4; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + token = 71; } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 14) { - result.endOfLineState = 6; - } } } - function addResult(start, end, classification) { - if (classification === 8) { - return; + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + var noRegexTable = ts.arrayToNumericMap([ + 71, + 9, + 8, + 12, + 99, + 43, + 44, + 20, + 22, + 18, + 101, + 86, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 9: { + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { + numBackslashes++; } - if (start === 0 && offset > 0) { - start += offset; + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 ? 3 : 2; + } + case 3: + return scanner.isUnterminated() ? 1 : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 16: + return 5; + case 13: + return 4; + default: + throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } } - start -= offset; - end -= offset; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); + return lastOnTemplateStack === 14 ? 6 : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8) { + return; + } + if (start === 0 && offset > 0) { + start += offset; + } + var length = end - start; + if (length > 0) { + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_6 = dense[i + 1]; + var type = dense[i + 2]; + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 39: - case 41: - case 42: - case 37: - case 38: - case 45: - case 46: - case 47: - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - case 32: - case 33: - case 34: - case 35: - case 48: - case 50: - case 49: - case 53: - case 54: - case 69: - case 68: - case 70: - case 65: - case 66: - case 67: - case 59: - case 60: - case 61: - case 63: - case 64: - case 58: - case 26: - return true; - default: - return false; - } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 37: - case 38: - case 52: - case 51: - case 43: - case 44: - return true; - default: - return false; - } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1: return ts.TokenClass.Comment; + case 3: return ts.TokenClass.Keyword; + case 4: return ts.TokenClass.NumberLiteral; + case 5: return ts.TokenClass.Operator; + case 6: return ts.TokenClass.StringLiteral; + case 8: return ts.TokenClass.Whitespace; + case 10: return ts.TokenClass.Punctuation; + case 2: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 9: + case 17: + return ts.TokenClass.Identifier; } - function isKeyword(token) { - return token >= 72 && token <= 142; + } + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + return true; } - function classFromKind(token) { - if (isKeyword(token)) { - return 3; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5; - } - else if (token >= 17 && token <= 70) { - return 10; - } - switch (token) { - case 8: - return 4; - case 9: + switch (keyword2) { + case 125: + case 135: + case 123: + case 115: + return true; + default: + return false; + } + } + function getPrefixFromLexState(lexState) { + switch (lexState) { + case 3: + return { prefix: "\"\\\n" }; + case 2: + return { prefix: "'\\\n" }; + case 1: + return { prefix: "/*\n" }; + case 4: + return { prefix: "`\n" }; + case 5: + return { prefix: "}\n", pushTemplate: true }; + case 6: + return { prefix: "", pushTemplate: true }; + case 0: + return { prefix: "" }; + default: + throw ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 39: + case 41: + case 42: + case 37: + case 38: + case 45: + case 46: + case 47: + case 27: + case 29: + case 30: + case 31: + case 93: + case 92: + case 118: + case 32: + case 33: + case 34: + case 35: + case 48: + case 50: + case 49: + case 53: + case 54: + case 69: + case 68: + case 70: + case 65: + case 66: + case 67: + case 59: + case 60: + case 61: + case 63: + case 64: + case 58: + case 26: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 37: + case 38: + case 52: + case 51: + case 43: + case 44: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5; + } + else if (token >= 17 && token <= 70) { + return 10; + } + switch (token) { + case 8: + return 4; + case 9: + return 6; + case 12: + return 7; + case 7: + case 3: + case 2: + return 1; + case 5: + case 4: + return 8; + case 71: + default: + if (ts.isTemplateLiteralKind(token)) { return 6; - case 12: - return 7; - case 7: - case 3: - case 2: - return 1; - case 5: - case 4: - return 8; - case 71: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6; - } - return 2; - } + } + return 2; } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; } - ts.createClassifier = createClassifier; function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); } ts.getSemanticClassifications = getSemanticClassifications; function checkForClassificationCancellation(cancellationToken, kind) { switch (kind) { - case 233: - case 229: + case 234: case 230: - case 228: + case 231: + case 229: cancellationToken.throwIfCancellationRequested(); } } function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - var result = []; - processNode(sourceFile); - return { spans: result, endOfLineState: 0 }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448) === 0) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (flags & 32) { - return 11; - } - else if (flags & 384) { - return 12; - } - else if (flags & 524288) { - return 16; - } - else if (meaningAtPosition & 2) { - if (flags & 64) { - return 13; - } - else if (flags & 262144) { - return 15; - } - } - else if (flags & 1536) { - if (meaningAtPosition & 4 || - (meaningAtPosition & 1 && hasValueSideModule(symbol))) { - return 14; + checkForClassificationCancellation(cancellationToken, node.kind); + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); } } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600) === 0) { return undefined; - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 233 && - ts.getModuleInstanceState(declaration) === 1; - }); - } } - function processNode(node) { - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(cancellationToken, kind); - if (kind === 71 && !ts.nodeIsMissing(node)) { - var identifier = node; - if (classifiableNames.has(identifier.escapedText)) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } + else if (flags & 32) { + return 11; + } + else if (flags & 384) { + return 12; + } + else if (flags & 524288) { + return 16; + } + else if (flags & 1536) { + return meaningAtPosition & 4 || meaningAtPosition & 1 && hasValueSideModule(symbol) ? 14 : undefined; + } + else if (flags & 2097152) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2) { + return flags & 64 ? 13 : flags & 262144 ? 15 : undefined; + } + else { + return undefined; } } - ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1; + }); + } function getClassificationTypeName(type) { switch (type) { case 1: return "comment"; @@ -62992,7 +65685,7 @@ var ts; case 24: return "jsx attribute string literal value"; } } - function convertClassifications(classifications) { + function convertClassificationsToSpans(classifications) { ts.Debug.assert(classifications.spans.length % 3 === 0); var dense = classifications.spans; var result = []; @@ -63005,14 +65698,14 @@ var ts; return result; } function getSyntacticClassifications(cancellationToken, sourceFile, span) { - return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); } ts.getSyntacticClassifications = getSyntacticClassifications; function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { var spanStart = span.start; var spanLength = span.length; - var triviaScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(6, false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6, false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 }; @@ -63080,16 +65773,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 279: + case 284: processJSDocParameterTag(tag); break; - case 282: + case 287: processJSDocTemplateTag(tag); break; - case 281: + case 286: processElement(tag.typeExpression); break; - case 280: + case 285: processElement(tag.typeExpression); break; } @@ -63170,22 +65863,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 251: + case 252: if (token.parent.tagName === token) { return 19; } break; - case 252: + case 253: if (token.parent.tagName === token) { return 20; } break; - case 250: + case 251: if (token.parent.tagName === token) { return 21; } break; - case 253: + case 257: if (token.parent.name === token) { return 22; } @@ -63205,17 +65898,17 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 58) { - if (token.parent.kind === 226 || - token.parent.kind === 149 || - token.parent.kind === 146 || - token.parent.kind === 253) { + if (token.parent.kind === 227 || + token.parent.kind === 150 || + token.parent.kind === 147 || + token.parent.kind === 257) { return 5; } } - if (token.parent.kind === 194 || - token.parent.kind === 192 || + if (token.parent.kind === 195 || token.parent.kind === 193 || - token.parent.kind === 195) { + token.parent.kind === 194 || + token.parent.kind === 196) { return 5; } } @@ -63225,7 +65918,7 @@ var ts; return 4; } else if (tokenKind === 9) { - return token.parent.kind === 253 ? 24 : 6; + return token.parent.kind === 257 ? 24 : 6; } else if (tokenKind === 12) { return 6; @@ -63239,32 +65932,32 @@ var ts; else if (tokenKind === 71) { if (token) { switch (token.parent.kind) { - case 229: + case 230: if (token.parent.name === token) { return 11; } return; - case 145: + case 146: if (token.parent.name === token) { return 15; } return; - case 230: + case 231: if (token.parent.name === token) { return 13; } return; - case 232: + case 233: if (token.parent.name === token) { return 12; } return; - case 233: + case 234: if (token.parent.name === token) { return 14; } return; - case 146: + case 147: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 : 17; } @@ -63297,38 +65990,31 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); - var entries; if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, false, span, compilerOptions, host, scriptPath); } else { - entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, false, span, host, scriptPath); } } else { - entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); } - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries - }; } - PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames; + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { - rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); - var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; }); - return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); @@ -63359,8 +66045,8 @@ var ts; var files = tryReadDirectory(host, baseDirectory, extensions, undefined, ["./*"]); if (files) { var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var filePath = files_2[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0) { continue; @@ -63376,8 +66062,8 @@ var ts; } var directories = tryGetDirectories(host, baseDirectory); if (directories) { - for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { - var directory = directories_2[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var directory = directories_1[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); result.push(createCompletionEntryForModule(directoryName, "directory", span)); } @@ -63387,42 +66073,55 @@ var ts; } function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result; + var result = []; + var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { - var fileExtensions = ts.getSupportedExtensions(compilerOptions); var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span, host); - if (paths) { - for (var path in paths) { - if (paths.hasOwnProperty(path)) { - if (path === "*") { - if (paths[path]) { - for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { - var pattern = _a[_i]; - for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { - var match = _c[_b]; - result.push(createCompletionEntryForModule(match, "external module name", span)); - } - } - } - } - else if (ts.startsWith(path, fragment)) { - var entry = paths[path] && paths[path].length === 1 && paths[path][0]; - if (entry) { - result.push(createCompletionEntryForModule(path, "external module name", span)); - } + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span, host, undefined, result); + var _loop_6 = function (path) { + if (!paths.hasOwnProperty(path)) + return "continue"; + var patterns = paths[path]; + if (!patterns) + return "continue"; + if (path === "*") { + for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { + var pattern = patterns_1[_i]; + var _loop_7 = function (match) { + if (result.some(function (entry) { return entry.name === match; })) + return "continue"; + result.push(createCompletionEntryForModule(match, "external module name", span)); + }; + for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { + var match = _b[_a]; + _loop_7(match); } } } + else if (ts.startsWith(path, fragment)) { + if (patterns.length === 1) { + if (result.some(function (entry) { return entry.name === path; })) + return "continue"; + result.push(createCompletionEntryForModule(path, "external module name", span)); + } + } + }; + for (var path in paths) { + _loop_6(path); } } - else { - result = []; + if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (host.directoryExists(nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, false, span, host, undefined, result); + } + }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { - var moduleName = _e[_d]; + for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { + var moduleName = _a[_i]; result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } return result; @@ -63434,7 +66133,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); @@ -63460,7 +66159,7 @@ var ts; return undefined; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); @@ -63489,44 +66188,34 @@ var ts; } } } - return ts.deduplicate(nonRelativeModuleNames); + return ts.deduplicate(nonRelativeModuleNames, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { var token = ts.getTokenAtPosition(sourceFile, position, false); - if (!token) { - return undefined; - } var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - if (!commentRanges || !commentRanges.length) { - return undefined; - } - var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { return undefined; } - var completionInfo = { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: [] - }; - var text = sourceFile.text.substr(range.pos, position - range.pos); + var text = sourceFile.text.slice(range.pos, position); var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - if (kind === "path") { + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + switch (kind) { + case "path": { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, host, sourceFile.path); + return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, host, sourceFile.path); } - else { - var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + case "types": { + var span_11 = ts.createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); + return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } + default: + return undefined; } - return completionInfo; } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { @@ -63542,17 +66231,17 @@ var ts; try { typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (e) { } + catch (_b) { } if (typeRoots) { - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; + for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { + var root = typeRoots_2[_c]; getCompletionEntriesFromDirectories(host, root, span, result); } } } if (host.getDirectories) { - for (var _c = 0, _d = findPackageJsons(scriptPath, host); _c < _d.length; _c++) { - var packageJson = _d[_c]; + for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { + var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); getCompletionEntriesFromDirectories(host, typesDir, span, result); } @@ -63563,32 +66252,23 @@ var ts; if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name", span)); } } } } - function findPackageJsons(currentDir, host) { + function findPackageJsons(directory, host) { var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent = ts.getDirectoryPath(currentDir); - if (currentDir === parent) { - break; - } - currentDir = parent; - } - else { - break; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; } - } + paths.push(currentConfigPath); + }); return paths; } function enumerateNodeModulesVisibleToScript(host, scriptPath) { @@ -63673,7 +66353,7 @@ var ts; try { return ts.directoryProbablyExists(path, host); } - catch (e) { } + catch (_a) { } return undefined; } function tryIOAndConsumeErrors(host, toApply) { @@ -63684,7 +66364,7 @@ var ts; try { return toApply && toApply.apply(host, args); } - catch (e) { } + catch (_a) { } return undefined; } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); @@ -63700,20 +66380,21 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries_2 && pathCompletionsInfo(entries_2); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; if (sourceFile.languageVariant === 1 && - location && location.parent && location.parent.kind === 252) { + location && location.parent && location.parent.kind === 253) { var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -63724,23 +66405,23 @@ var ts; }] }; } if (request) { - var entries_2 = request.kind === "JsDocTagName" + var entries_3 = request.kind === "JsDocTagName" ? ts.JsDoc.getJSDocTagNameCompletions() : request.kind === "JsDocTag" ? ts.JsDoc.getJSDocTagCompletions() : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); } if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); @@ -63754,7 +66435,7 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName)) { + if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { return; } uniqueNames.set(realName, true); @@ -63769,8 +66450,8 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); if (!displayName) { return undefined; } @@ -63779,42 +66460,63 @@ var ts; kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(origin !== undefined), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && ts.stripQuotes(origin.moduleSymbol.name); + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); - var uniqueNames = ts.createMap(); + var uniques = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); - if (entry) { - var id = entry.name; - if (!uniqueNames.has(id)) { - entries.push(entry); - uniqueNames.set(id, true); - } + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + if (!entry) { + continue; } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); + } + entries.push(entry); } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniqueNames; + return uniques; } function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { var node = ts.findPrecedingToken(position, sourceFile); if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 261 && - node.parent.parent.kind === 178 && + if (node.parent.kind === 265 && + node.parent.parent.kind === 179 && node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); } - else if (node.parent.kind === 238 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { - return Completions.PathCompletions.getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker); + else if (node.parent.kind === 239 || node.parent.kind === 245 + || ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent) + || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + return pathCompletionsInfo(entries); } else if (isEqualityExpression(node.parent)) { return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); @@ -63830,6 +66532,14 @@ var ts; return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); } } + function pathCompletionsInfo(entries) { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: entries, + }; + } function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; @@ -63877,13 +66587,13 @@ var ts; } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } - if (type && type.flags & 16384) { + if (type && type.flags & 32768) { type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; } - if (type.flags & 65536) { + if (type.flags & 131072) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); @@ -63902,48 +66612,126 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral_1) === entryName ? s : undefined; }); - if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; - } + function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { + var name = _a.name, source = _a.source; + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + if (!completionData) { + return { type: "none" }; } - var keywordCompletion = ts.forEach(getKeywordCompletions(0), function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: "keyword", - kindModifiers: "", - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined - }; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; + if (request) { + return { type: "request", request: request }; + } + var symbol = ts.find(symbols, function (s) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; + return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral, origin) === name + && getSourceFromOrigin(origin) === source; + }); + return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + } + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var name = entryId.name; + var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case "JsDocTagName": + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case "JsDocTag": + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case "JsDocParameterName": + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); + var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; + } + case "none": { + if (ts.some(getKeywordCompletions(0), function (c) { return c.name === name; })) { + return { + name: name, + kind: "keyword", + kindModifiers: "", + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined, + tags: undefined, + codeActions: undefined, + source: undefined, + }; + } + return undefined; + } } - return undefined; } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (!completionData) { - return undefined; - } - var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral) === entryName ? s : undefined; }); + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); + ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + formatContext: formatContext, + symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), + getCanonicalFileName: getCanonicalFileName, + symbolToken: undefined, + kind: isDefaultExport ? 1 : 0, + }); + return { sourceDisplay: sourceDisplay, codeActions: codeActions }; + } + function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { + var result = []; + ts.codefix.forEachExternalModule(checker, allSourceFiles, function (module) { + for (var _i = 0, _a = checker.getExportsOfModule(module); _i < _a.length; _i++) { + var exported = _a[_i]; + if (ts.skipAlias(exported, checker) === exportedSymbol) { + result.push(module); + } + } + }); + return result; + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { + var completion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + function getRecommendedCompletion(currentToken, checker) { + var ty = checker.getContextualType(currentToken); + var symbol = ty && ty.symbol; + return symbol && (symbol.flags & 384 || symbol.flags & 32 && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, 67108863, false); + if (chain) + return ts.first(chain); + return isModuleSymbol(symbol.parent) ? symbol : symbol.parent && getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 269; }); + } + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, false); @@ -63969,11 +66757,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271) { currentToken = ts.getTokenAtPosition(sourceFile, position, true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 284 || + (currentToken.parent.kind !== 289 || currentToken.parent.name !== currentToken))) { insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); } @@ -63983,7 +66771,19 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; + return { + symbols: ts.emptyArray, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0, + symbolToOriginInfoMap: undefined, + recommendedCompletion: undefined, + }; } if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -64011,11 +66811,11 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23) { - if (parent.kind === 179) { + if (parent.kind === 180) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent.kind === 143) { + else if (parent.kind === 144) { node = contextToken.parent.left; isRightOfDot = true; } @@ -64024,24 +66824,24 @@ var ts; } } else if (sourceFile.languageVariant === 1) { - if (parent && parent.kind === 179) { + if (parent && parent.kind === 180) { contextToken = parent; parent = parent.parent; } switch (parent.kind) { - case 252: + case 253: if (contextToken.kind === 41) { isStartingCloseTag = true; location = contextToken; } break; - case 194: + case 195: if (!(parent.left.flags & 32768)) { break; } - case 250: - case 249: case 251: + case 250: + case 252: if (contextToken.kind === 27) { isRightOfOpenTag = true; location = contextToken; @@ -64057,6 +66857,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -64086,15 +66887,15 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 277: - case 279: case 284: - case 280: - case 281: - case 283: + case 289: + case 285: + case 286: + case 288: return true; } } @@ -64121,7 +66922,7 @@ var ts; symbols.push(symbol_2); } } - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 && d.kind !== 233 && d.kind !== 232; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 269 && d.kind !== 234 && d.kind !== 233; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -64133,17 +66934,15 @@ var ts; } } function addTypeProperties(type) { - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } + if (ts.isSourceFileJavaScript(sourceFile)) { + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, true)); } - if (isJavaScriptFile && type.flags & 65536) { - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); + else { + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } } } } @@ -64170,7 +66969,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { + if ((jsxContainer.kind === 251) || (jsxContainer.kind === 252)) { attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); @@ -64191,17 +66990,22 @@ var ts; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; if (scopeNode) { isGlobalCompletion = - scopeNode.kind === 265 || - scopeNode.kind === 196 || - scopeNode.kind === 256 || + scopeNode.kind === 269 || + scopeNode.kind === 197 || + scopeNode.kind === 260 || + scopeNode.kind === 208 || ts.isStatement(scopeNode); } var symbolMeanings = 793064 | 107455 | 1920 | 2097152; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + if (options.includeExternalModuleExports) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); + } + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { if (ts.isExportAssignment(location.parent)) { return true; @@ -64224,22 +67028,22 @@ var ts; function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 && - contextToken.parent.kind === 162; + contextToken.parent.kind === 163; } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 56: - return parentKind === 149 || - parentKind === 148 || - parentKind === 146 || - parentKind === 226 || + return parentKind === 150 || + parentKind === 149 || + parentKind === 147 || + parentKind === 227 || ts.isFunctionLikeKind(parentKind); case 58: - return parentKind === 231; + return parentKind === 232; case 118: - return parentKind === 202; + return parentKind === 203; } } } @@ -64254,6 +67058,48 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + continue; + } + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + else { + name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); + } + } + if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + return false; + } function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -64275,11 +67121,11 @@ var ts; return true; } if (contextToken.kind === 29 && contextToken.parent) { - if (contextToken.parent.kind === 251) { + if (contextToken.parent.kind === 252) { return true; } - if (contextToken.parent.kind === 252 || contextToken.parent.kind === 250) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 249; + if (contextToken.parent.kind === 253 || contextToken.parent.kind === 251) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 250; } } return false; @@ -64289,40 +67135,40 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 26: - return containingNodeKind === 181 - || containingNodeKind === 152 - || containingNodeKind === 182 - || containingNodeKind === 177 - || containingNodeKind === 194 - || containingNodeKind === 160; + return containingNodeKind === 182 + || containingNodeKind === 153 + || containingNodeKind === 183 + || containingNodeKind === 178 + || containingNodeKind === 195 + || containingNodeKind === 161; case 19: - return containingNodeKind === 181 - || containingNodeKind === 152 - || containingNodeKind === 182 - || containingNodeKind === 185 - || containingNodeKind === 168; + return containingNodeKind === 182 + || containingNodeKind === 153 + || containingNodeKind === 183 + || containingNodeKind === 186 + || containingNodeKind === 169; case 21: - return containingNodeKind === 177 - || containingNodeKind === 157 - || containingNodeKind === 144; + return containingNodeKind === 178 + || containingNodeKind === 158 + || containingNodeKind === 145; case 128: case 129: return true; case 23: - return containingNodeKind === 233; + return containingNodeKind === 234; case 17: - return containingNodeKind === 229; + return containingNodeKind === 230; case 58: - return containingNodeKind === 226 - || containingNodeKind === 194; + return containingNodeKind === 227 + || containingNodeKind === 195; case 14: - return containingNodeKind === 196; + return containingNodeKind === 197; case 15: - return containingNodeKind === 205; + return containingNodeKind === 206; case 114: case 112: case 113: - return containingNodeKind === 149; + return containingNodeKind === 150; } switch (previousToken.getText()) { case "public": @@ -64354,26 +67200,26 @@ var ts; allowStringLiteral = true; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 178) { + if (objectLikeContainer.kind === 179) { isNewIdentifierLocation = true; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, false); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 174); + ts.Debug.assert(objectLikeContainer.kind === 175); isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) throw ts.Debug.fail("Root declaration is not variable-like."); - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216; - if (!canGetType && rootDeclaration.kind === 146) { + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217; + if (!canGetType && rootDeclaration.kind === 147) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 151 || rootDeclaration.parent.kind === 154) { + else if (rootDeclaration.parent.kind === 152 || rootDeclaration.parent.kind === 155) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -64391,9 +67237,9 @@ var ts; return true; } function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 241 ? - 238 : - 244; + var declarationKind = namedImportsOrExports.kind === 242 ? + 239 : + 245; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -64466,8 +67312,8 @@ var ts; case 17: case 26: switch (contextToken.parent.kind) { - case 241: - case 245: + case 242: + case 246: return contextToken.parent; } } @@ -64503,6 +67349,10 @@ var ts; if (ts.isClassLike(location)) { return location; } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -64512,7 +67362,7 @@ var ts; } } } - if (location && location.kind === 286 && ts.isClassLike(location.parent)) { + if (location && location.kind === 290 && ts.isClassLike(location.parent)) { return location.parent; } return undefined; @@ -64538,29 +67388,29 @@ var ts; case 28: case 41: case 71: - case 179: - case 254: - case 253: - case 255: - if (parent && (parent.kind === 250 || parent.kind === 251)) { + case 180: + case 258: + case 257: + case 259: + if (parent && (parent.kind === 251 || parent.kind === 252)) { return parent; } - else if (parent.kind === 253) { + else if (parent.kind === 257) { return parent.parent.parent; } break; case 9: - if (parent && ((parent.kind === 253) || (parent.kind === 255))) { + if (parent && ((parent.kind === 257) || (parent.kind === 259))) { return parent.parent.parent; } break; case 18: if (parent && - parent.kind === 256 && - parent.parent && parent.parent.kind === 253) { + parent.kind === 260 && + parent.parent && parent.parent.kind === 257) { return parent.parent.parent.parent; } - if (parent && parent.kind === 255) { + if (parent && parent.kind === 259) { return parent.parent.parent; } break; @@ -64572,55 +67422,55 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 26: - return containingNodeKind === 226 || - containingNodeKind === 227 || - containingNodeKind === 208 || - containingNodeKind === 232 || + return containingNodeKind === 227 || + containingNodeKind === 228 || + containingNodeKind === 209 || + containingNodeKind === 233 || isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 230 || - containingNodeKind === 175 || containingNodeKind === 231 || + containingNodeKind === 176 || + containingNodeKind === 232 || (ts.isClassLike(contextToken.parent) && contextToken.parent.typeParameters && contextToken.parent.typeParameters.end >= contextToken.pos); case 23: - return containingNodeKind === 175; - case 56: return containingNodeKind === 176; + case 56: + return containingNodeKind === 177; case 21: - return containingNodeKind === 175; + return containingNodeKind === 176; case 19: - return containingNodeKind === 260 || + return containingNodeKind === 264 || isFunctionLikeButNotConstructor(containingNodeKind); case 17: - return containingNodeKind === 232 || - containingNodeKind === 230 || - containingNodeKind === 163; + return containingNodeKind === 233 || + containingNodeKind === 231 || + containingNodeKind === 164; case 25: - return containingNodeKind === 148 && + return containingNodeKind === 149 && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 230 || - contextToken.parent.parent.kind === 163); + (contextToken.parent.parent.kind === 231 || + contextToken.parent.parent.kind === 164); case 27: - return containingNodeKind === 229 || - containingNodeKind === 199 || - containingNodeKind === 230 || + return containingNodeKind === 230 || + containingNodeKind === 200 || containingNodeKind === 231 || + containingNodeKind === 232 || ts.isFunctionLikeKind(containingNodeKind); case 115: - return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 150 && !ts.isClassLike(contextToken.parent.parent); case 24: - return containingNodeKind === 146 || + return containingNodeKind === 147 || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 175); + contextToken.parent.parent.kind === 176); case 114: case 112: case 113: - return containingNodeKind === 146 && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 147 && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118: - return containingNodeKind === 242 || - containingNodeKind === 246 || - containingNodeKind === 240; + return containingNodeKind === 243 || + containingNodeKind === 247 || + containingNodeKind === 241; case 125: case 135: if (isFromClassElementDeclaration(contextToken)) { @@ -64670,7 +67520,7 @@ var ts; return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 152; + return ts.isFunctionLikeKind(kind) && kind !== 153; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8) { @@ -64701,19 +67551,19 @@ var ts; var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; - if (m.kind !== 261 && - m.kind !== 262 && - m.kind !== 176 && - m.kind !== 151 && - m.kind !== 153 && - m.kind !== 154) { + if (m.kind !== 265 && + m.kind !== 266 && + m.kind !== 177 && + m.kind !== 152 && + m.kind !== 154 && + m.kind !== 155) { continue; } if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; - if (m.kind === 176 && m.propertyName) { + if (m.kind === 177 && m.propertyName) { if (m.propertyName.kind === 71) { existingName = m.propertyName.escapedText; } @@ -64730,10 +67580,10 @@ var ts; var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; - if (m.kind !== 149 && - m.kind !== 151 && - m.kind !== 153 && - m.kind !== 154) { + if (m.kind !== 150 && + m.kind !== 152 && + m.kind !== 154 && + m.kind !== 155) { continue; } if (isCurrentlyEditingNode(m)) { @@ -64778,7 +67628,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 253) { + if (attr.kind === 257) { seenNames.set(attr.name.escapedText, true); } } @@ -64788,13 +67638,22 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { - var name = symbol.name; + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + var name = getSymbolName(symbol, origin, target); if (!name) return undefined; if (symbol.flags & 1920) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 || firstCharCode === 34) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { + return undefined; + } + } + if (symbol.flags & 106500) { + var escapedName = symbol.escapedName; + if (escapedName.length >= 3 && + escapedName.charCodeAt(0) === 95 && + escapedName.charCodeAt(1) === 95 && + escapedName.charCodeAt(2) === 64) { return undefined; } } @@ -64825,7 +67684,9 @@ var ts; } function getAllKeywordCompletions() { var allKeywordsCompletions = []; - for (var i = 72; i <= 142; i++) { + for (var i = 72; i <= 143; i++) { + if (i === 139) + continue; allKeywordsCompletions.push({ name: ts.tokenToString(i), kind: "keyword", @@ -64906,12 +67767,14 @@ var ts; return node.parent; } } - function getPropertiesForCompletion(type, checker) { - if (!(type.flags & 65536)) { - return checker.getPropertiesOfType(type); + function getPropertiesForCompletion(type, checker, isForAccess) { + if (!(type.flags & 131072)) { + return type.getApparentProperties(); } var types = type.types; - var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 || checker.isArrayLikeType(memberType)); }); + var filteredTypes = isForAccess ? types : types.filter(function (memberType) { + return !(memberType.flags & 16382 || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); + }); return checker.getAllPossiblePropertiesOfTypes(filteredTypes); } })(Completions = ts.Completions || (ts.Completions = {})); @@ -64970,87 +67833,44 @@ var ts; } return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - function parent(node) { - return node && node.parent; - } function getHighlightSpans(node, sourceFile) { - if (!node) { - return undefined; - } switch (node.kind) { case 90: case 82: - if (hasKind(node.parent, 211)) { - return getIfElseOccurrences(node.parent, sourceFile); - } - break; + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; case 96: - if (hasKind(node.parent, 219)) { - return highlightSpans(getReturnOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); case 100: - if (hasKind(node.parent, 223)) { - return highlightSpans(getThrowOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); case 102: case 74: case 87: - var tryStatement = node.kind === 74 ? parent(parent(node)) : parent(node); - if (hasKind(tryStatement, 224)) { - return highlightSpans(getTryCatchFinallyOccurrences(tryStatement, sourceFile)); - } - break; + var tryStatement = node.kind === 74 ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); case 98: - if (hasKind(node.parent, 221)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 73: case 79: - if (hasKind(parent(parent(parent(node))), 221)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent.parent.parent)); - } - break; + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 72: case 77: - if (hasKind(node.parent, 218) || hasKind(node.parent, 217)) { - return highlightSpans(getBreakOrContinueStatementOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); case 88: - if (hasKind(node.parent, 214) || - hasKind(node.parent, 215) || - hasKind(node.parent, 216)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; case 106: case 81: - if (hasKind(node.parent, 213) || hasKind(node.parent, 212)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, true); }, getLoopBreakContinueOccurrences); case 123: - if (hasKind(node.parent, 152)) { - return highlightSpans(getConstructorOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isConstructorDeclaration, getConstructorOccurrences); case 125: case 135: - if (hasKind(node.parent, 153) || hasKind(node.parent, 154)) { - return highlightSpans(getGetAndSetOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isAccessor, getGetAndSetOccurrences); default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 208)) { - return highlightSpans(getModifierOccurrences(node.kind, node.parent)); - } + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; } function highlightSpans(nodes) { return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); @@ -65061,19 +67881,18 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 223) { + if (ts.isThrowStatement(node)) { statementAccumulator.push(node); } - else if (node.kind === 224) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); + else if (ts.isTryStatement(node)) { + if (node.catchClause) { + aggregate(node.catchClause); } else { - aggregate(tryStatement.tryBlock); + aggregate(node.tryBlock); } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); + if (node.finallyBlock) { + aggregate(node.finallyBlock); } } else if (!ts.isFunctionLike(node)) { @@ -65084,17 +67903,17 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_2 = child.parent; - if (ts.isFunctionBlock(parent_2) || parent_2.kind === 265) { - return parent_2; + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 269) { + return parent; } - if (parent_2.kind === 224) { - var tryStatement = parent_2; + if (parent.kind === 225) { + var tryStatement = parent; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_2; + child = parent; } return undefined; } @@ -65103,7 +67922,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 218 || node.kind === 217) { + if (node.kind === 219 || node.kind === 218) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -65116,116 +67935,93 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node = statement.parent; node; node = node.parent) { + return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 221: - if (statement.kind === 217) { - continue; + case 222: + if (statement.kind === 218) { + return false; } - case 214: case 215: case 216: + case 217: + case 214: case 213: - case 212: - if (!statement.label || isLabeledBy(node, statement.label.text)) { - return node; - } - break; + return !statement.label || isLabeledBy(node, statement.label.text); default: - if (ts.isFunctionLike(node)) { - return undefined; - } - break; + return (ts.isFunctionLike(node) && "quit"); } - } - return undefined; + }); } function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 229 || - container.kind === 199 || - (declaration.kind === 146 && hasKind(container, 152)))) { - return undefined; - } - } - else if (modifier === 115) { - if (!(container.kind === 229 || container.kind === 199)) { - return undefined; - } - } - else if (modifier === 84 || modifier === 124) { - if (!(container.kind === 234 || container.kind === 265)) { - return undefined; - } - } - else if (modifier === 117) { - if (!(container.kind === 229 || declaration.kind === 229)) { - return undefined; - } - } - else { + if (!isLegalModifier(modifier, declaration)) { return undefined; } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; + var modifierFlag = ts.modifierToFlag(modifier); + return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { + if (ts.getModifierFlags(node) & modifierFlag) { + var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); + ts.Debug.assert(!!mod); + return mod; + } + }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + var container = declaration.parent; switch (container.kind) { - case 234: - case 265: + case 235: + case 269: + case 208: + case 261: + case 262: if (modifierFlag & 128) { - nodes = declaration.members.concat([declaration]); + return declaration.members.concat([declaration]); } else { - nodes = container.statements; + return container.statements; } - break; - case 152: - nodes = container.parameters.concat(container.parent.members); - break; - case 229: - case 199: - nodes = container.members; + case 153: + return container.parameters.concat(container.parent.members); + case 230: + case 200: + var nodes = container.members; if (modifierFlag & 28) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 152 && member; - }); + var constructor = ts.find(container.members, ts.isConstructorDeclaration); if (constructor) { - nodes = nodes.concat(constructor.parameters); + return nodes.concat(constructor.parameters); } } else if (modifierFlag & 128) { - nodes = nodes.concat([container]); + return nodes.concat([container]); } - break; + return nodes; default: ts.Debug.fail("Invalid container kind."); } - ts.forEach(nodes, function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return keywords; - function getFlagFromModifier(modifier) { - switch (modifier) { - case 114: - return 4; - case 112: - return 8; - case 113: - return 16; - case 115: - return 32; - case 84: - return 1; - case 124: - return 2; - case 117: - return 128; - default: - ts.Debug.fail(); - } + } + function isLegalModifier(modifier, declaration) { + var container = declaration.parent; + switch (modifier) { + case 112: + case 113: + case 114: + switch (container.kind) { + case 230: + case 200: + return true; + case 153: + return declaration.kind === 147; + default: + return false; + } + case 115: + return container.kind === 230 || container.kind === 200; + case 84: + case 124: + return container.kind === 235 || container.kind === 269; + case 117: + return container.kind === 230 || declaration.kind === 230; + default: + return false; } } function pushKeywordIf(keywordList, token) { @@ -65241,8 +68037,8 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 153); tryPushAccessorKeyword(accessorDeclaration.symbol, 154); + tryPushAccessorKeyword(accessorDeclaration.symbol, 155); return keywords; function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); @@ -65264,7 +68060,7 @@ var ts; function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88, 106, 81)) { - if (loopNode.kind === 212) { + if (loopNode.kind === 213) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 106)) { @@ -65285,13 +68081,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 214: case 215: case 216: - case 212: + case 217: case 213: + case 214: return getLoopBreakContinueOccurrences(owner); - case 221: + case 222: return getSwitchCaseDefaultOccurrences(owner); } } @@ -65341,11 +68137,11 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 207))) { + if (!func) { return undefined; } var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { pushKeywordIf(keywords, returnStatement.getFirstToken(), 96); }); ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { @@ -65354,36 +68150,20 @@ var ts; return keywords; } function getIfElseOccurrences(ifStatement, sourceFile) { - var keywords = []; - while (hasKind(ifStatement.parent, 211) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 90); - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 211)) { - break; - } - ifStatement = ifStatement.elseStatement; - } + var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; for (var i = 0; i < keywords.length; i++) { if (keywords[i].kind === 82 && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; - var shouldCombindElseAndIf = true; - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + var shouldCombineElseAndIf = true; + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; + shouldCombineElseAndIf = false; break; } } - if (shouldCombindElseAndIf) { + if (shouldCombineElseAndIf) { result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), @@ -65397,8 +68177,28 @@ var ts; } return result; } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 90); + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 82)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 222; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 223; owner = owner.parent) { if (owner.label.escapedText === labelName) { return true; } @@ -65562,10 +68362,10 @@ var ts; } cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 181: + case 182: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 && parent.kind === 226) { + if (exportKind === 2 && parent.kind === 227) { var name = parent.name; if (name.kind === 71) { directImports.push(name); @@ -65575,19 +68375,19 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 237: + case 238: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1)); break; - case 238: + case 239: var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { + if (namedBindings && namedBindings.kind === 241) { handleNamespaceImport(direct, namedBindings.name); } else { directImports.push(direct); } break; - case 244: + case 245: if (!direct.exportClause) { handleDirectImports(getContainingModuleSymbol(direct, checker)); } @@ -65605,7 +68405,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 265 || sourceFileLike.kind === 233); + ts.Debug.assert(sourceFileLike.kind === 269 || sourceFileLike.kind === 234); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -65654,7 +68454,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 237) { + if (decl.kind === 238) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -65667,7 +68467,7 @@ var ts; if (decl.moduleSpecifier.kind !== 9) { return; } - if (decl.kind === 244) { + if (decl.kind === 245) { searchForNamedImport(decl.exportClause); return; } @@ -65676,7 +68476,7 @@ var ts; return; } var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { + if (namedBindings && namedBindings.kind === 241) { handleNamespaceImportLike(namedBindings.name); return; } @@ -65716,7 +68516,7 @@ var ts; } } else { - var localSymbol = element.kind === 246 && element.propertyName + var localSymbol = element.kind === 247 && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -65730,7 +68530,7 @@ var ts; function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 244) + if (statement.kind !== 245) return; var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; if (moduleSpecifier || !exportClause) @@ -65749,7 +68549,7 @@ var ts; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 265) { + if (searchSourceFile.kind === 269) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -65794,7 +68594,7 @@ var ts; return map; } function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 265 ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 269 ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -65808,18 +68608,18 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 244: - case 238: { + case 245: + case 239: { var decl = statement; if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9) { action(decl, decl.moduleSpecifier); } break; } - case 237: { + case 238: { var decl = statement; var moduleReference = decl.moduleReference; - if (moduleReference.kind === 248 && + if (moduleReference.kind === 249 && moduleReference.expression.kind === 9) { action(decl, moduleReference.expression); } @@ -65832,11 +68632,11 @@ var ts; function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; switch (decl.kind) { - case 181: - case 238: - case 244: + case 182: + case 239: + case 245: return decl; - case 248: + case 249: return decl.parent; default: ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); @@ -65847,7 +68647,7 @@ var ts; function getExport() { var parent = node.parent; if (symbol.exportSymbol) { - if (parent.kind === 179) { + if (parent.kind === 180) { return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) ? getSpecialPropertyExport(parent.parent, false) : undefined; @@ -65944,10 +68744,10 @@ var ts; ts.Debug.fail(); } function getExportNode(parent, node) { - if (parent.kind === 226) { + if (parent.kind === 227) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 260 ? undefined : p.parent.parent.kind === 208 ? p.parent.parent : undefined; + p.parent.kind === 264 ? undefined : p.parent.parent.kind === 209 ? p.parent.parent : undefined; } else { return parent; @@ -65956,14 +68756,14 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 237: + case 238: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 242: + case 243: return parent.propertyName ? undefined : { isNamedImport: true }; - case 239: case 240: + case 241: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -65980,9 +68780,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.escapedText; }); @@ -66002,22 +68799,22 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 181) { + if (node.kind === 182) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 265) { + if (parent.kind === 269) { return parent; } - ts.Debug.assert(parent.kind === 234 && isAmbientModuleDeclaration(parent.parent)); + ts.Debug.assert(parent.kind === 235 && isAmbientModuleDeclaration(parent.parent)); return parent.parent; } function isAmbientModuleDeclaration(node) { - return node.kind === 233 && node.name.kind === 9; + return node.kind === 234 && node.name.kind === 9; } function isExternalModuleImportEquals(_a) { var moduleReference = _a.moduleReference; - return moduleReference.kind === 248 && moduleReference.expression.kind === 9; + return moduleReference.kind === 249 && moduleReference.expression.kind === 9; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -66053,14 +68850,14 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { - if (node.kind === 265) { + if (node.kind === 269) { return undefined; } var checker = program.getTypeChecker(); - if (node.parent.kind === 262) { - var result_5 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); - return result_5; + if (node.parent.kind === 266) { + var result_4 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); + return result_4; } else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { var symbol = checker.getSymbolAtLocation(node); @@ -66091,29 +68888,29 @@ var ts; var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_2 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var symbol = def.symbol, node_3 = def.node; + var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: "label", displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + var node_4 = def.node; + return { node: node_4, name: node_4.text, kind: "label", displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { - var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword", displayParts: [{ text: name_5, kind: "keyword" }] }; + var node_5 = def.node; + var name_6 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_6, kind: "keyword", displayParts: [{ text: name_6, kind: "keyword" }] }; } case "this": { - var node_5 = def.node; - var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: "var", displayParts: displayParts_2 }; + var node_6 = def.node; + var symbol = checker.getSymbolAtLocation(node_6); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts; + return { node: node_6, name: "this", kind: "var", displayParts: displayParts_2 }; } case "string": { - var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + var node_7 = def.node; + return { node: node_7, name: node_7.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -66166,13 +68963,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, node, checker); } - else if (node.kind === 178) { + else if (node.kind === 179) { return { kind: "interface", displayParts: [ts.punctuationPart(19), ts.textPart("object literal"), ts.punctuationPart(20)] }; } - else if (node.kind === 199) { + else if (node.kind === 200) { return { kind: "local class", displayParts: [ts.punctuationPart(19), ts.textPart("anonymous local class"), ts.punctuationPart(20)] @@ -66219,7 +69016,7 @@ var ts; (function (Core) { function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 265) { + if (node.kind === 269) { return undefined; } if (!options.implementations) { @@ -66247,12 +69044,12 @@ var ts; return false; } switch (node.parent.kind) { - case 233: - case 248: - case 238: - case 244: + case 234: + case 249: + case 239: + case 245: return true; - case 181: + case 182: return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); default: return false; @@ -66275,9 +69072,9 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 265: + case 269: break; - case 233: + case 234: references.push({ type: "node", node: decl.name }); break; default: @@ -66315,16 +69112,22 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, node.kind === 123, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 }, state); } else { - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -66361,7 +69164,7 @@ var ts; }; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -66441,9 +69244,9 @@ var ts; checker.getPropertySymbolOfDestructuringAssignment(location); } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176); + var bindingElement = ts.getDeclarationOfKind(symbol, 177); if (bindingElement && - bindingElement.parent.kind === 174 && + bindingElement.parent.kind === 175 && !bindingElement.propertyName) { return bindingElement; } @@ -66462,7 +69265,7 @@ var ts; } function getSymbolScope(symbol) { var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 186 || valueDeclaration.kind === 199)) { + if (valueDeclaration && (valueDeclaration.kind === 187 || valueDeclaration.kind === 200)) { return valueDeclaration; } if (!declarations) { @@ -66471,7 +69274,7 @@ var ts; if (flags & (4 | 8192)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 229); + return ts.getAncestor(privateDeclaration, 230); } return undefined; } @@ -66489,7 +69292,7 @@ var ts; if (scope && scope !== container) { return undefined; } - if (!container || container.kind === 265 && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 269 && !ts.isExternalOrCommonJsModule(container)) { return undefined; } scope = container; @@ -66510,8 +69313,8 @@ var ts; if (position > container.end) break; var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6))) { positions.push(position); } position = text.indexOf(symbolName, position + symbolNameLength + 1); @@ -66718,12 +69521,12 @@ var ts; for (var _i = 0, _a = classSymbol.members.get("__constructor").declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123, sourceFile); - ts.Debug.assert(decl.kind === 152 && !!ctrKeyword); + ts.Debug.assert(decl.kind === 153 && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 151) { + if (decl && decl.kind === 152) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 99, function (thisKeyword) { @@ -66743,7 +69546,7 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 152); + ts.Debug.assert(decl.kind === 153); var body = decl.body; if (body) { forEachDescendantOfKind(body, 97, function (node) { @@ -66762,7 +69565,7 @@ var ts; if (refNode.kind !== 71) { return; } - if (refNode.parent.kind === 262) { + if (refNode.parent.kind === 266) { getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } var containingClass = getContainingClassIfInHeritageClause(refNode); @@ -66778,7 +69581,7 @@ var ts; } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { var body = parent.body; - if (body.kind === 207) { + if (body.kind === 208) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); @@ -66801,7 +69604,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 | 64)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 196608) { + if (componentType.getFlags() & 393216) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -66819,12 +69622,12 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 201 - && node.parent.kind === 259 + if (node.kind === 202 + && node.parent.kind === 263 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 71 || node.kind === 179) { + else if (node.kind === 71 || node.kind === 180) { return getContainingClassIfInHeritageClause(node.parent); } } @@ -66832,13 +69635,13 @@ var ts; } function isImplementationExpression(node) { switch (node.kind) { - case 185: + case 186: return isImplementationExpression(node.expression); + case 188: case 187: - case 186: + case 179: + case 200: case 178: - case 199: - case 177: return true; default: return false; @@ -66872,7 +69675,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 230) { + else if (declaration.kind === 231) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -66899,13 +69702,13 @@ var ts; } var staticFlag = 32; switch (searchSpaceNode.kind) { - case 149: - case 148: - case 151: case 150: + case 149: case 152: + case 151: case 153: case 154: + case 155: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; break; @@ -66932,32 +69735,32 @@ var ts; var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); var staticFlag = 32; switch (searchSpaceNode.kind) { + case 152: case 151: - case 150: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } + case 150: case 149: - case 148: - case 152: case 153: case 154: + case 155: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; break; - case 265: + case 269: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 228: - case 186: + case 229: + case 187: break; default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 265) { + if (searchSpaceNode.kind === 269) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); @@ -66981,26 +69784,26 @@ var ts; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 186: - case 228: + case 187: + case 229: if (searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; + case 152: case 151: - case 150: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 199: - case 229: + case 200: + case 230: if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32) === staticFlag) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 265: - if (container.kind === 265 && !ts.isExternalModule(container)) { + case 269: + if (container.kind === 269 && !ts.isExternalModule(container)) { result.push(FindAllReferences.nodeEntry(node)); } break; @@ -67023,9 +69826,9 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position, false); - if (node_7 && node_7.kind === 9 && node_7.text === searchText) { - references.push(FindAllReferences.nodeEntry(node_7, true)); + var node_8 = ts.getTouchingWord(sourceFile, position, false); + if (node_8 && node_8.kind === 9 && node_8.text === searchText) { + references.push(FindAllReferences.nodeEntry(node_8, true)); } } } @@ -67034,7 +69837,7 @@ var ts; var result = [symbol]; var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - if (containingObjectLiteralElement.kind !== 262) { + if (containingObjectLiteralElement.kind !== 266) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); if (propertySymbol) { result.push(propertySymbol); @@ -67048,10 +69851,7 @@ var ts; result.push(shorthandValueSymbol); } } - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 146 && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - ts.addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } + ts.addRange(result, getParameterPropertySymbols(symbol, checker)); var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); if (bindingElementPropertySymbol) { result.push(bindingElementPropertySymbol); @@ -67071,6 +69871,11 @@ var ts; } } } + function getParameterPropertySymbols(symbol, checker) { + return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isParameterPropertyDeclaration(symbol.valueDeclaration) + ? checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name) + : undefined; + } function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { if (!symbol) { return; @@ -67084,7 +69889,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 230) { + else if (declaration.kind === 231) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -67105,23 +69910,31 @@ var ts; } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; if (search.includes(referenceSymbol)) { return referenceSymbol; } + if (referenceSymbol.flags & 1) { + ts.Debug.assert(!(referenceSymbol.flags & 4)); + var paramProps = getParameterPropertySymbols(referenceSymbol, checker); + if (paramProps) { + return getRelatedSymbol(search, ts.find(paramProps, function (x) { return !!(x.flags & 4); }), referenceLocation, state); + } + } var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, state.checker), function (contextualSymbol) { - return ts.find(state.checker.getRootSymbols(contextualSymbol), search.includes); + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { + return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); }); if (contextualSymbol) { return contextualSymbol; } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, state.checker); + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, checker); if (propertySymbol && search.includes(propertySymbol)) { return propertySymbol; } } - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, checker); if (bindingElementPropertySymbol) { var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); if (fromBindingElement) @@ -67146,7 +69959,7 @@ var ts; } } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 144) { + if (node.name.kind === 145) { var nameExpression = node.name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -67160,20 +69973,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; + var result_5 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } - if (contextualType.flags & 65536) { + if (contextualType.flags & 131072) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -67201,7 +70014,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 226) { + else if (node.kind === 227) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2); } @@ -67211,18 +70024,18 @@ var ts; } else { switch (node.kind) { - case 229: - case 199: - case 232: + case 230: + case 200: case 233: + case 234: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 208) { - ts.Debug.assert(node.parent.kind === 227); + if (node.parent && node.parent.parent && node.parent.parent.kind === 209) { + ts.Debug.assert(node.parent.kind === 228); return node.parent.parent; } } @@ -67268,7 +70081,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 | 64) && localParentType.symbol !== symbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 196608) { + else if (localParentType.flags & 393216) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -67317,7 +70130,7 @@ var ts; symbol = aliased; } } - if (node.parent.kind === 262) { + if (node.parent.kind === 266) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -67360,14 +70173,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 65536 && !(type.flags & 16)) { - var result_7 = []; + if (type.flags & 131072 && !(type.flags & 16)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_7; + return result_6; } if (!type.symbol) { return undefined; @@ -67375,6 +70188,23 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (comment) { + return { + definitions: definitions, + textSpan: ts.createTextSpanFromBounds(comment.pos, comment.end) + }; + } + var node = ts.getTouchingPropertyName(sourceFile, position, true); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; function shouldSkipAlias(node, declaration) { if (node.kind !== 71) { return false; @@ -67383,11 +70213,11 @@ var ts; return true; } switch (declaration.kind) { - case 239: - case 237: + case 240: + case 238: return true; - case 242: - return declaration.parent.kind === 241; + case 243: + return declaration.parent.kind === 242; default: return false; } @@ -67431,7 +70261,7 @@ var ts; var definition; for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 152 : isSignatureDeclaration(d)) { + if (selectConstructors ? d.kind === 153 : isSignatureDeclaration(d)) { declarations.push(d); if (d.body) definition = d; @@ -67446,10 +70276,10 @@ var ts; } function isSignatureDeclaration(node) { switch (node.kind) { + case 153: + case 229: case 152: - case 228: case 151: - case 150: return true; default: return false; @@ -67524,6 +70354,7 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { + var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -67543,6 +70374,7 @@ var ts; "fileOverview", "function", "ignore", + "inheritDoc", "inner", "lends", "link", @@ -67587,14 +70419,36 @@ var ts; forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - if (tag.kind === 276) { - tags.push({ name: tag.tagName.text, text: tag.comment }); - } + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 282: + return withNode(tag.class); + case 287: + return withList(tag.typeParameters); + case 286: + return withNode(tag.typeExpression); + case 288: + case 289: + case 284: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return node.getText() + " " + comment; + } + function withList(list) { + return list.map(function (x) { return x.getText(); }) + " " + comment; + } + } function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -67619,6 +70473,7 @@ var ts; })); } JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; function getJSDocTagCompletions() { return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -67630,6 +70485,18 @@ var ts; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "", + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; function getJSDocParameterNameCompletions(tag) { if (!ts.isIdentifier(tag.name)) { return ts.emptyArray; @@ -67651,6 +70518,18 @@ var ts; }); } JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter", + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; @@ -67662,31 +70541,25 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - return undefined; + return singleLineTemplate; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.getStart() < position) { + if (commentOwner.kind === 10) { return undefined; } + if (commentOwner.getStart() < position || parameters.length === 0) { + return singleLineTemplate; + } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = ""; - if (parameters) { - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; - } - } - } + var docParams = parameters.map(function (_a, i) { + var name = _a.name; + var nameText = ts.isIdentifier(name) ? name.text : "param" + i; + var type = isJavaScriptFile ? "{any} " : ""; + return indentationStr + " * @param " + type + nameText + newLine; + }).join(""); var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + @@ -67699,26 +70572,23 @@ var ts; function getCommentOwnerInfo(tokenAtPos) { for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 228: - case 151: + case 229: case 152: + case 153: + case 151: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 229: - return { commentOwner: commentOwner }; - case 208: { + case 209: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return { commentOwner: commentOwner, parameters: parameters_1 }; + return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; } - case 265: + case 269: return undefined; - case 233: - return commentOwner.parent.kind === 233 ? undefined : { commentOwner: commentOwner }; - case 194: { + case 195: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0) { return undefined; @@ -67726,21 +70596,25 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } + case 10: { + var parameters_3 = ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_3 }; + } } } } function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 185) { + while (rightHandSide.kind === 186) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 186: case 187: + case 188: return rightHandSide.parameters; - case 199: + case 200: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152) { + if (member.kind === 153) { return member.parameters; } } @@ -67805,7 +70679,7 @@ var ts; }); getTypingNamesFromSourceFileNames(fileNames); if (unresolvedImports) { - var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); addInferredTypings(module_1, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typingLocation, name) { @@ -67857,7 +70731,7 @@ var ts; if (!ts.hasJavaScriptFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); }); if (fromFileNames.length) { @@ -67879,15 +70753,15 @@ var ts; if (log) log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); var packageNames = []; - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; var normalizedFileName = ts.normalizePath(fileName); var baseFileName = ts.getBaseFileName(normalizedFileName); if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_8.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -67910,6 +70784,60 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + function validatePackageName(packageName) { + if (!packageName) { + return 2; + } + if (packageName.length > maxPackageNameLength) { + return 3; + } + if (packageName.charCodeAt(0) === 46) { + return 4; + } + if (packageName.charCodeAt(0) === 95) { + return 5; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6; + } + return 0; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2: + return "Package name '" + typing + "' cannot be empty"; + case 3: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4: + return "Package name '" + typing + "' cannot start with '.'"; + case 5: + return "Package name '" + typing + "' cannot start with '_'"; + case 1: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0: + throw ts.Debug.fail(); + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; @@ -67919,7 +70847,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_8 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; @@ -67930,7 +70858,7 @@ var ts; }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_6(sourceFile); + _loop_8(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -67963,9 +70891,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 239: - case 242: - case 237: + case 240: + case 243: + case 238: var importer = checker.getSymbolAtLocation(declaration.name); var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -67991,7 +70919,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (name.kind === 144) { + else if (name.kind === 145) { return tryAddComputedPropertyName(name.expression, containers, true); } else { @@ -68009,7 +70937,7 @@ var ts; } return true; } - if (expression.kind === 179) { + if (expression.kind === 180) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -68021,7 +70949,7 @@ var ts; function getContainers(declaration) { var containers = []; var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144) { + if (name.kind === 145) { if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } @@ -68048,9 +70976,8 @@ var ts; return bestMatchKind; } function compareNavigateToItems(i1, i2) { - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -68171,7 +71098,7 @@ var ts; return; } switch (node.kind) { - case 152: + case 153: var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { @@ -68181,28 +71108,28 @@ var ts; } } break; - case 151: - case 153: + case 152: case 154: - case 150: + case 155: + case 151: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; + case 150: case 149: - case 148: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 239: + case 240: var importClause = node; if (importClause.name) { addLeafNode(importClause); } var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 240) { + if (namedBindings.kind === 241) { addLeafNode(namedBindings); } else { @@ -68213,8 +71140,8 @@ var ts; } } break; - case 176: - case 226: + case 177: + case 227: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -68233,12 +71160,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; + case 188: + case 229: case 187: - case 228: - case 186: addNodeWithRecursiveChild(node, node.body); break; - case 232: + case 233: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -68248,9 +71175,9 @@ var ts; } endNode(); break; - case 229: - case 199: case 230: + case 200: + case 231: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -68258,22 +71185,38 @@ var ts; } endNode(); break; - case 233: + case 234: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 246: - case 237: - case 157: - case 155: + case 247: + case 238: + case 158: case 156: - case 231: + case 157: + case 232: addLeafNode(node); break; + case 195: { + var special = ts.getSpecialPropertyAssignmentKind(node); + switch (special) { + case 1: + case 2: + case 3: + addNodeWithRecursiveChild(node, node.right); + break; + case 4: + case 5: + case 0: + break; + default: + ts.Debug.assertNever(special); + } + } default: if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283) { + if (tag.kind === 288) { addLeafNode(tag); } }); @@ -68313,55 +71256,56 @@ var ts; nameToItems.set(name, [itemWithSameName, child]); return true; } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { - merge(a, b); - return true; - } - return false; - } }); - function shouldReallyMerge(a, b) { - return a.kind === b.kind && (a.kind !== 233 || areSameModule(a, b)); - function areSameModule(a, b) { - if (a.body.kind !== b.body.kind) { - return false; - } - if (a.body.kind !== 233) { - return true; - } - return areSameModule(a.body, b.body); - } + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); + return true; } - function merge(target, source) { - target.additionalNodes = target.additionalNodes || []; - target.additionalNodes.push(source.node); - if (source.additionalNodes) { - (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); - } - target.children = ts.concatenate(target.children, source.children); - if (target.children) { - mergeChildren(target.children); - sortChildren(target.children); - } - var _a; + return false; + } + function shouldReallyMerge(a, b) { + if (a.kind !== b.kind) { + return false; + } + switch (a.kind) { + case 150: + case 152: + case 154: + case 155: + return ts.hasModifier(a, 32) === ts.hasModifier(b, 32); + case 234: + return areSameModule(a, b); + default: + return true; } } + function areSameModule(a, b) { + return a.body.kind === b.body.kind && (a.body.kind !== 234 || areSameModule(a.body, b.body)); + } + function merge(target, source) { + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } function sortChildren(children) { children.sort(compareChildren); } function compareChildren(child1, child2) { - var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); - if (name1 && name2) { - var cmp = ts.compareStringsCaseInsensitive(name1, name2); - return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); - } - else { - return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); - } + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } function tryGetName(node) { - if (node.kind === 233) { + if (node.kind === 234) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -68369,18 +71313,18 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { - case 186: case 187: - case 199: + case 188: + case 200: return getFunctionOrClassName(node); - case 283: + case 288: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 233) { + if (node.kind === 234) { return getModuleName(node); } var name = ts.getNameOfDeclaration(node); @@ -68391,29 +71335,29 @@ var ts; } } switch (node.kind) { - case 265: + case 269: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 187: - case 228: - case 186: + case 188: case 229: - case 199: + case 187: + case 230: + case 200: if (ts.getModifierFlags(node) & 512) { return "default"; } return getFunctionOrClassName(node); - case 152: + case 153: return "constructor"; - case 156: + case 157: return "new()"; - case 155: + case 156: return "()"; - case 157: + case 158: return "[]"; - case 283: + case 288: return getJSDocTypedefTagName(node); default: return ""; @@ -68425,7 +71369,7 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 208) { + if (parentNode && parentNode.kind === 209) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; if (nameIdentifier.kind === 71) { @@ -68453,24 +71397,24 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 229: - case 199: - case 232: case 230: + case 200: case 233: - case 265: case 231: - case 283: + case 234: + case 269: + case 232: + case 288: return true; - case 152: - case 151: case 153: + case 152: case 154: - case 226: + case 155: + case 227: return hasSomeImportantChild(item); + case 188: + case 229: case 187: - case 228: - case 186: return isTopLevelFunctionDeclaration(item); default: return false; @@ -68480,10 +71424,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 234: - case 265: - case 151: + case 235: + case 269: case 152: + case 153: return true; default: return hasSomeImportantChild(item); @@ -68492,7 +71436,7 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 226 && childKind !== 176; + return childKind !== 227 && childKind !== 177; }); } } @@ -68546,25 +71490,25 @@ var ts; } var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 233) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 234) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } return result.join("."); } function getInteriorModule(decl) { - return decl.body.kind === 233 ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 234 ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 144; + return !member.name || member.name.kind === 145; } function getNodeSpan(node) { - return node.kind === 265 + return node.kind === 269 ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 226) { + if (node.parent && node.parent.kind === 227) { node = node.parent; } return ts.getNodeModifiers(node); @@ -68573,14 +71517,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 226) { + else if (node.parent.kind === 227) { return ts.declarationNameToString(node.parent.name); } - else if (node.parent.kind === 194 && + else if (node.parent.kind === 195 && node.parent.operatorToken.kind === 58) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 261 && node.parent.name) { + else if (node.parent.kind === 265 && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512) { @@ -68592,9 +71536,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { + case 188: case 187: - case 186: - case 199: + case 200: return true; default: return false; @@ -68606,191 +71550,155 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { - var collapseText = "..."; - var maxDepth = 20; - var defaultLabel = "#region"; - var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { - var elements = []; - var depth = 0; + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + sourceFile.forEachChild(function walk(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + n.forEachChild(walk); + depthRemaining++; + }); + } + function addRegionOutliningSpans(sourceFile, out) { var regions = []; - walk(sourceFile); - gatherRegions(); - return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { - if (hintSpanNode && startElement && endElement) { - var span_13 = { - textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), - hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_13); + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?$/); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; } - } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span_14 = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_14); - } - } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var currentComment = comments_3[_i]; - cancellationToken.throwIfCancellationRequested(); - if (currentComment.kind === 2) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; - } - else if (currentComment.kind === 3) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; - } - } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + if (!result[1]) { + var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span_13, span_13, false, result[2] || "#region")); } - } - function combineAndAddMultipleSingleLineComments(count, start, end) { - if (count > 1) { - var multipleSingleLineComments = { - kind: 2, - pos: start, - end: end, - }; - addOutliningSpanComments(multipleSingleLineComments, false); - } - } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 187; - } - function gatherRegions() { - var lineStarts = sourceFile.getLineStarts(); - for (var i = 0; i < lineStarts.length; i++) { - var currentLineStart = lineStarts[i]; - var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); - var comment = sourceFile.text.substring(currentLineStart, lineEnd); - var result = comment.match(regionMatch); - if (result && !ts.isInComment(sourceFile, currentLineStart)) { - if (!result[1]) { - var start = sourceFile.getFullText().indexOf("//", currentLineStart); - var textSpan = ts.createTextSpanFromBounds(start, lineEnd); - var region = { - textSpan: textSpan, - hintSpan: textSpan, - bannerText: result[2] || defaultLabel, - autoCollapse: false - }; - regions.push(region); - } - else { - var region = regions.pop(); - if (region) { - region.textSpan.length = lineEnd - region.textSpan.start; - region.hintSpan.length = lineEnd - region.textSpan.start; - elements.push(region); - } - } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); } } } - function walk(n) { + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var _a = comments_3[_i], kind = _a.kind, pos = _a.pos, end = _a.end; cancellationToken.throwIfCancellationRequested(); - if (depth > maxDepth) { - return; + switch (kind) { + case 2: + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; + } + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); + } + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); } - switch (n.kind) { - case 207: - if (!ts.isFunctionBlock(n)) { - var parent = n.parent; - var openBrace_1 = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace_1 = ts.findChildOfKind(n, 18, sourceFile); - if (parent.kind === 212 || - parent.kind === 215 || - parent.kind === 216 || - parent.kind === 214 || - parent.kind === 211 || - parent.kind === 213 || - parent.kind === 220 || - parent.kind === 260) { - addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), true); - break; + } + } + function createOutliningSpanFromBounds(pos, end) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 208: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, n.parent.kind !== 188); + } + switch (n.parent.kind) { + case 213: + case 216: + case 217: + case 215: + case 212: + case 214: + case 221: + case 264: + return spanForNode(n.parent); + case 225: + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); } - if (parent.kind === 224) { - var tryStatement = parent; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), true); - break; - } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), true); - break; - } - } + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 87, sourceFile)); } - var span_15 = ts.createTextSpanFromNode(n); - elements.push({ - textSpan: span_15, - hintSpan: span_15, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); - break; - } - case 234: { - var openBrace_2 = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace_2 = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), true); - break; - } - case 229: - case 230: - case 232: - case 235: { - var openBrace_3 = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace_3 = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), true); - break; + default: + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); } - case 178: - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); - break; - case 177: - var openBracket = ts.findChildOfKind(n, 21, sourceFile); - var closeBracket = ts.findChildOfKind(n, 22, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); - break; + case 235: + return spanForNode(n.parent); + case 230: + case 231: + case 233: + case 236: + return spanForNode(n); + case 179: + return spanForObjectOrArrayLiteral(n); + case 178: + return spanForObjectOrArrayLiteral(n, 21); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 17; } + return spanForNode(node, false, !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 17; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 17 ? 18 : 22; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; } - depth++; - ts.forEachChild(n, walk); - depth--; + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - OutliningElementsCollector.collectElements = collectElements; + function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); var ts; @@ -68875,9 +71783,9 @@ var ts; if (index > 0) { var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span_16 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_16, chunk.text, true)) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_16, chunk.text, false)); + var span_14 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_14, chunk.text, true)) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_14, chunk.text, false)); } } } @@ -69023,7 +71931,7 @@ var ts; if (ch >= 65 && ch <= 90) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { + if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 6)) { return false; } var str = String.fromCharCode(ch); @@ -69033,24 +71941,24 @@ var ts; if (ch >= 97 && ch <= 122) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { + if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 6)) { return false; } var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function indexOfIgnoringCase(string, value) { - var n = string.length - value.length; + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; for (var i = 0; i <= n; i++) { - if (startsWithIgnoringCase(string, value, i)) { + if (startsWithIgnoringCase(str, value, i)) { return i; } } return -1; } - function startsWithIgnoringCase(string, value, start) { + function startsWithIgnoringCase(str, value, start) { for (var i = 0; i < value.length; i++) { - var ch1 = toLowerCase(string.charCodeAt(i + start)); + var ch1 = toLowerCase(str.charCodeAt(i + start)); var ch2 = value.charCodeAt(i); if (ch1 !== ch2) { return false; @@ -69294,7 +72202,7 @@ var ts; else { if (token === 71 || ts.isKeyword(token)) { token = nextToken(); - if (token === 140) { + if (token === 141) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -69320,7 +72228,7 @@ var ts; } if (token === 18) { token = nextToken(); - if (token === 140) { + if (token === 141) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -69334,7 +72242,7 @@ var ts; token = nextToken(); if (token === 71 || ts.isKeyword(token)) { token = nextToken(); - if (token === 140) { + if (token === 141) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -69360,7 +72268,7 @@ var ts; } if (token === 18) { token = nextToken(); - if (token === 140) { + if (token === 141) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -69370,7 +72278,7 @@ var ts; } else if (token === 39) { token = nextToken(); - if (token === 140) { + if (token === 141) { token = nextToken(); if (token === 9) { recordModuleName(); @@ -69617,14 +72525,14 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 181) { + if (argumentInfo.invocation.kind !== 182) { return undefined; } var callExpression = argumentInfo.invocation; var expression = callExpression.expression; var name = expression.kind === 71 ? expression - : expression.kind === 179 + : expression.kind === 180 ? expression.name : undefined; if (!name || !name.escapedText) { @@ -69676,23 +72584,23 @@ var ts; var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 && node.parent.kind === 183) { + else if (node.kind === 13 && node.parent.kind === 184) { if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0, sourceFile); } } - else if (node.kind === 14 && node.parent.parent.kind === 183) { + else if (node.kind === 14 && node.parent.parent.kind === 184) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196); + ts.Debug.assert(templateExpression.kind === 197); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 205 && node.parent.parent.parent.kind === 183) { + else if (node.parent.kind === 206 && node.parent.parent.parent.kind === 184) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196); + ts.Debug.assert(templateExpression.kind === 197); if (node.kind === 16 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } @@ -69770,7 +72678,7 @@ var ts; var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 196) { + if (template.kind === 197) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -69779,7 +72687,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 265; n = n.parent) { + for (var n = node; n.kind !== 269; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -69845,7 +72753,7 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(26), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(), + documentation: candidateSignature.getDocumentationComment(typeChecker), tags: candidateSignature.getJsDocTags() }; }); @@ -69861,7 +72769,7 @@ var ts; }); return { name: parameter.name, - documentation: parameter.getDocumentationComment(), + documentation: parameter.getDocumentationComment(typeChecker), displayParts: displayParts, isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) }; @@ -69887,7 +72795,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32) { - return ts.getDeclarationOfKind(symbol, 199) ? + return ts.getDeclarationOfKind(symbol, 200) ? "local class" : "class"; } if (flags & 384) @@ -69963,10 +72871,14 @@ var ts; } return unionPropertyKind; } - if (location.parent && ts.isJsxAttribute(location.parent)) { - return "JSX attribute"; + switch (location.parent && location.parent.kind) { + case 252: + return location.kind === 71 ? "property" : "JSX attribute"; + case 257: + return "JSX attribute"; + default: + return "property"; } - return "property"; } return ""; } @@ -69992,7 +72904,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 179) { + if (location.parent && location.parent.kind === 180) { var right = location.parent.name; if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; @@ -70011,10 +72923,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); + var useConstructSignatures = callExpressionLike.kind === 183 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { signature = allSignatures.length ? allSignatures[0] : undefined; @@ -70047,13 +72956,14 @@ var ts; case "local var": displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); + if (!(type.flags & 65536 && type.objectFlags & 16) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + displayParts.push(ts.lineBreakPart()); + } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); - } addSignatureDisplayParts(signature, allSignatures, 16); break; default: @@ -70063,25 +72973,25 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || - (location.kind === 123 && location.parent.kind === 152)) { + (location.kind === 123 && location.parent.kind === 153)) { var functionDeclaration_1 = location.parent; var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 153 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 152) { + if (functionDeclaration_1.kind === 153) { symbolKind = "constructor"; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 156 && !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -70090,7 +73000,7 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 199)) { + if (ts.getDeclarationOfKind(symbol, 200)) { pushTypePart("local class"); } else { @@ -70130,7 +73040,7 @@ var ts; } if (symbolFlags & 1536) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 233); + var declaration = ts.getDeclarationOfKind(symbol, 234); var isNamespace = declaration && declaration.name && declaration.name.kind === 71; displayParts.push(ts.keywordPart(isNamespace ? 129 : 128)); displayParts.push(ts.spacePart()); @@ -70149,23 +73059,23 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var decl = ts.getDeclarationOfKind(symbol, 145); + var decl = ts.getDeclarationOfKind(symbol, 146); ts.Debug.assert(decl !== undefined); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 156) { + if (declaration.kind === 157) { displayParts.push(ts.keywordPart(94)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 155 && declaration.name) { + else if (declaration.kind !== 156 && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64)); } - else if (declaration.kind === 231) { + else if (declaration.kind === 232) { addInPrefix(); displayParts.push(ts.keywordPart(138)); displayParts.push(ts.spacePart()); @@ -70179,7 +73089,7 @@ var ts; symbolKind = "enum member"; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 264) { + if (declaration.kind === 268) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -70191,18 +73101,24 @@ var ts; } if (symbolFlags & 2097152) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236) { - displayParts.push(ts.keywordPart(84)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - } - else { - displayParts.push(ts.keywordPart(91)); + switch (symbol.declarations[0].kind) { + case 237: + displayParts.push(ts.keywordPart(84)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129)); + break; + case 244: + displayParts.push(ts.keywordPart(84)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 : 79)); + break; + default: + displayParts.push(ts.keywordPart(91)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 237) { + if (declaration.kind === 238) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -70271,20 +73187,20 @@ var ts; } } if (!documentation) { - documentation = symbol.getDocumentationComment(); + documentation = symbol.getDocumentationComment(typeChecker); tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbolFlags & 4) { - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 265; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 269; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 194) { + if (!declaration.parent || declaration.parent.kind !== 195) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); if (!rhsSymbol) { continue; } - documentation = rhsSymbol.getDocumentationComment(); + documentation = rhsSymbol.getDocumentationComment(typeChecker); tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; @@ -70312,8 +73228,10 @@ var ts; addNewLineIfDisplayPartsExist(); if (symbolKind) { pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); + if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } } } function pushTypePart(symbolKind) { @@ -70343,7 +73261,7 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20)); } - documentation = signature.getDocumentationComment(); + documentation = signature.getDocumentationComment(typeChecker); tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -70359,14 +73277,14 @@ var ts; return false; } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 186) { + if (declaration.kind === 187) { return true; } - if (declaration.kind !== 226 && declaration.kind !== 228) { + if (declaration.kind !== 227 && declaration.kind !== 229) { return false; } for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { - if (parent.kind === 265 || parent.kind === 234) { + if (parent.kind === 269 || parent.kind === 235) { return false; } } @@ -70450,12 +73368,12 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_7 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } var value = options[opt.name]; - if (typeof value === "string") { + if (ts.isString(value)) { options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } else { @@ -70466,7 +73384,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_7(opt); + _loop_9(opt); } return options; } @@ -70476,8 +73394,96 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(5, false, 0); - var jsxScanner = ts.createScanner(5, false, 1); + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); + ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); + ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); + ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); + ts.Debug.assert(commonParent !== undefined, "commonParent is null"); + this.currentTokenSpan = currentRange; + this.currentTokenParent = currentTokenParent; + this.nextTokenSpan = nextRange; + this.nextTokenParent = nextTokenParent; + this.contextNode = commonParent; + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 17, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 18, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var standardScanner = ts.createScanner(6, false, 0); + var jsxScanner = ts.createScanner(6, false, 1); var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -70550,10 +73556,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { + case 257: + case 252: case 253: case 251: - case 252: - case 250: return ts.isKeyword(node.kind) || node.kind === 71; } } @@ -70691,116 +73697,7 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var FormattingContext = (function () { - function FormattingContext(sourceFile, formattingRequestKind, options) { - this.sourceFile = sourceFile; - this.formattingRequestKind = formattingRequestKind; - this.options = options; - } - FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; - this.contextNodeAllOnSameLine = undefined; - this.nextNodeAllOnSameLine = undefined; - this.tokensAreOnSameLine = undefined; - this.contextNodeBlockIsOnOneLine = undefined; - this.nextNodeBlockIsOnOneLine = undefined; - }; - FormattingContext.prototype.ContextNodeAllOnSameLine = function () { - if (this.contextNodeAllOnSameLine === undefined) { - this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); - } - return this.contextNodeAllOnSameLine; - }; - FormattingContext.prototype.NextNodeAllOnSameLine = function () { - if (this.nextNodeAllOnSameLine === undefined) { - this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); - } - return this.nextNodeAllOnSameLine; - }; - FormattingContext.prototype.TokensAreOnSameLine = function () { - if (this.tokensAreOnSameLine === undefined) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine === endLine); - } - return this.tokensAreOnSameLine; - }; - FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { - if (this.contextNodeBlockIsOnOneLine === undefined) { - this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); - } - return this.contextNodeBlockIsOnOneLine; - }; - FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { - if (this.nextNodeBlockIsOnOneLine === undefined) { - this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); - } - return this.nextNodeBlockIsOnOneLine; - }; - FormattingContext.prototype.NodeIsOnOneLine = function (node) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine === endLine; - }; - FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18, this.sourceFile); - if (openBrace && closeBrace) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; - return startLine === endLine; - } - return false; - }; - return FormattingContext; - }()); - formatting.FormattingContext = FormattingContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var FormattingRequestKind; - (function (FormattingRequestKind) { - FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; - FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; - FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; - FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; - })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rule = (function () { - function Rule(Descriptor, Operation, Flag) { - if (Flag === void 0) { Flag = 0; } - this.Descriptor = Descriptor; - this.Operation = Operation; - this.Flag = Flag; - } - return Rule; - }()); - formatting.Rule = Rule; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { + formatting.anyContext = ts.emptyArray; var RuleAction; (function (RuleAction) { RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; @@ -70808,42 +73705,6 @@ var ts; RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; RuleAction[RuleAction["Delete"] = 8] = "Delete"; })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleDescriptor = (function () { - function RuleDescriptor(LeftTokenRange, RightTokenRange) { - this.LeftTokenRange = LeftTokenRange; - this.RightTokenRange = RightTokenRange; - } - RuleDescriptor.prototype.toString = function () { - return "[leftRange=" + this.LeftTokenRange + "," + - "rightRange=" + this.RightTokenRange + "]"; - }; - RuleDescriptor.create1 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create2 = function (left, right) { - return RuleDescriptor.create4(left, formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create3 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), right); - }; - RuleDescriptor.create4 = function (left, right) { - return new RuleDescriptor(left, right); - }; - return RuleDescriptor; - }()); - formatting.RuleDescriptor = RuleDescriptor; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { var RuleFlags; (function (RuleFlags) { RuleFlags[RuleFlags["None"] = 0] = "None"; @@ -70855,836 +73716,579 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperation = (function () { - function RuleOperation(Context, Action) { - this.Context = Context; - this.Action = Action; + function getAllRules() { + var allTokens = []; + for (var token = 0; token <= 143; token++) { + allTokens.push(token); } - RuleOperation.prototype.toString = function () { - return "[context=" + this.Context + "," + - "action=" + this.Action + "]"; - }; - RuleOperation.create1 = function (action) { - return RuleOperation.create2(formatting.RuleOperationContext.Any, action); - }; - RuleOperation.create2 = function (context, action) { - return new RuleOperation(context, action); - }; - return RuleOperation; - }()); - formatting.RuleOperation = RuleOperation; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleOperationContext = (function () { - function RuleOperationContext() { - var funcs = []; - for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i] = arguments[_i]; + function anyTokenExcept(token) { + return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3])); + var keywords = tokenRangeFromRange(72, 143); + var binaryOperators = tokenRangeFromRange(27, 70); + var binaryKeywordOperators = [92, 93, 143, 118, 126]; + var unaryPrefixOperators = [43, 44, 52, 51]; + var unaryPrefixExpressions = [ + 8, 71, 19, 21, + 17, 99, 94 + ]; + var unaryPreincrementExpressions = [71, 19, 99, 94]; + var unaryPostincrementExpressions = [71, 20, 22, 94]; + var unaryPredecrementExpressions = [71, 19, 99, 94]; + var unaryPostdecrementExpressions = [71, 20, 22, 94]; + var comments = [2, 3]; + var typeNames = [71].concat(ts.typeKeywords); + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71, 3, 75, 84, 91]); + var controlOpenBraceLeftTokenRange = tokenRangeFrom([20, 3, 81, 102, 87, 82]); + var highPriorityCommonRules = [ + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1), + rule("IgnoreAfterLineComment", 2, anyToken, formatting.anyContext, 1), + rule("NoSpaceBeforeColon", anyToken, 56, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), + rule("SpaceAfterColon", 56, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2), + rule("NoSpaceBeforeQuestionMark", anyToken, 55, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), + rule("SpaceAfterQuestionMarkInConditionalOperator", 55, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2), + rule("NoSpaceAfterQuestionMark", 55, anyToken, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeDot", anyToken, 23, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterDot", 23, anyToken, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), + rule("NoSpaceAfterUnaryPreincrementOperator", 43, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterUnaryPredecrementOperator", 44, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44, [isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterPostincrementWhenFollowedByAdd", 43, 37, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37, 37, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterAddWhenFollowedByPreincrement", 37, 43, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44, 38, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38, 38, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38, 44, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("NoSpaceAfterCloseBrace", 18, [22, 26, 25], [isNonJsxSameLineTokenContext], 8), + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18, [isMultilineBlockContext], 4), + rule("SpaceAfterCloseBrace", 18, anyTokenExcept(20), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2), + rule("SpaceBetweenCloseBraceAndElse", 18, 82, [isNonJsxSameLineTokenContext], 2), + rule("SpaceBetweenCloseBraceAndWhile", 18, 106, [isNonJsxSameLineTokenContext], 2), + rule("NoSpaceBetweenEmptyBraceBrackets", 17, 18, [isNonJsxSameLineTokenContext, isObjectContext], 8), + rule("NoSpaceBetweenFunctionKeywordAndStar", 89, 39, [isFunctionDeclarationOrFunctionExpressionContext], 8), + rule("SpaceAfterStarInGeneratorDeclaration", 39, [71, 19], [isFunctionDeclarationOrFunctionExpressionContext], 2), + rule("SpaceAfterFunctionInFuncDecl", 89, anyToken, [isFunctionDeclContext], 2), + rule("NewLineAfterOpenBraceInBlockContext", 17, anyToken, [isMultilineBlockContext], 4), + rule("SpaceAfterGetSetInMember", [125, 135], 71, [isFunctionDeclContext], 2), + rule("NoSpaceBetweenYieldKeywordAndStar", 116, 39, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [116, 39], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2), + rule("NoSpaceBetweenReturnAndSemicolon", 96, 25, [isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterCertainKeywords", [104, 100, 94, 80, 96, 103, 121], anyToken, [isNonJsxSameLineTokenContext], 2), + rule("SpaceAfterLetConstInVariableDeclaration", [110, 76], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8), + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterVoidOperator", 105, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2), + rule("SpaceBetweenAsyncAndOpenParen", 120, 19, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2), + rule("SpaceBetweenAsyncAndFunctionKeyword", 120, 89, [isNonJsxSameLineTokenContext], 2), + rule("NoSpaceBetweenTagAndTemplateString", 71, [13, 14], [isNonJsxSameLineTokenContext], 8), + rule("SpaceBeforeJsxAttribute", anyToken, 71, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41, 29, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterEqualInJsxAttribute", 58, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterModuleImport", [128, 132], 19, [isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterCertainTypeScriptKeywords", [ + 117, + 75, + 124, + 79, + 83, + 84, + 85, + 125, + 108, + 91, + 109, + 128, + 129, + 112, + 114, + 113, + 131, + 135, + 115, + 138, + 141, + 127, + ], anyToken, [isNonJsxSameLineTokenContext], 2), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85, 108, 141], [isNonJsxSameLineTokenContext], 2), + rule("SpaceAfterModuleName", 9, 17, [isModuleDeclContext], 2), + rule("SpaceBeforeArrow", anyToken, 36, [isNonJsxSameLineTokenContext], 2), + rule("SpaceAfterArrow", 36, anyToken, [isNonJsxSameLineTokenContext], 2), + rule("NoSpaceAfterEllipsis", 24, 71, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterOptionalParameters", 55, [20, 26], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17, 18, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8), + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 20, 27, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), + rule("NoSpaceAfterOpenAngularBracket", 27, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), + rule("NoSpaceAfterCloseAngularBracket", 29, [19, 21, 29, 26], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), + rule("SpaceBeforeAt", anyToken, 57, [isNonJsxSameLineTokenContext], 2), + rule("NoSpaceAfterAt", 57, anyToken, [isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterDecorator", anyToken, [ + 117, + 71, + 84, + 79, + 75, + 115, + 114, + 112, + 113, + 125, + 135, + 21, + 39, + ], [isEndOfDecoratorContextOnSameLine], 2), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94, 19, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8), + ]; + var userConfigurableRules = [ + rule("SpaceAfterConstructor", 123, 19, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2), + rule("NoSpaceAfterConstructor", 123, 19, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterComma", 26, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2), + rule("NoSpaceAfterComma", 26, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8), + rule("SpaceAfterAnonymousFunctionKeyword", 89, 19, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2), + rule("NoSpaceAfterAnonymousFunctionKeyword", 89, 19, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8), + rule("SpaceAfterKeywordInControl", keywords, 19, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2), + rule("NoSpaceAfterKeywordInControl", keywords, 19, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8), + rule("SpaceAfterOpenParen", 19, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2), + rule("SpaceBeforeCloseParen", anyToken, 20, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2), + rule("SpaceBetweenOpenParens", 19, 19, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2), + rule("NoSpaceBetweenParens", 19, 20, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterOpenParen", 19, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeCloseParen", anyToken, 20, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterOpenBracket", 21, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2), + rule("SpaceBeforeCloseBracket", anyToken, 22, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2), + rule("NoSpaceBetweenBrackets", 21, 22, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterOpenBracket", 21, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeCloseBracket", anyToken, 22, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterOpenBrace", 17, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2), + rule("SpaceBeforeCloseBrace", anyToken, 18, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2), + rule("NoSpaceBetweenEmptyBraceBrackets", 17, 18, [isNonJsxSameLineTokenContext, isObjectContext], 8), + rule("NoSpaceAfterOpenBrace", 17, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeCloseBrace", anyToken, 18, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterTemplateHeadAndMiddle", [14, 15], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15, 16], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2), + rule("NoSpaceAfterTemplateHeadAndMiddle", [14, 15], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15, 16], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8), + rule("SpaceAfterOpenBraceInJsxExpression", 17, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2), + rule("NoSpaceAfterOpenBraceInJsxExpression", 17, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8), + rule("SpaceAfterSemicolonInFor", 25, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2), + rule("NoSpaceAfterSemicolonInFor", 25, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8), + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8), + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4, 1), + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4, 1), + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4, 1), + rule("SpaceAfterTypeAssertion", 29, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2), + rule("NoSpaceAfterTypeAssertion", 29, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8), + ]; + var lowPriorityCommonRules = [ + rule("NoSpaceBeforeSemicolon", anyToken, 25, [isNonJsxSameLineTokenContext], 8), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), + rule("NoSpaceBeforeComma", anyToken, 26, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120), 21, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterCloseBracket", 22, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8), + rule("SpaceAfterSemicolon", 25, anyToken, [isNonJsxSameLineTokenContext], 2), + rule("SpaceBetweenStatements", [20, 81, 82, 73], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2), + rule("SpaceAfterTryFinally", [102, 87], 17, [isNonJsxSameLineTokenContext], 2), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); } - this.customContextChecks = funcs; } - RuleOperationContext.prototype.IsAny = function () { - return this === RuleOperationContext.Any; - }; - RuleOperationContext.prototype.InContext = function (context) { - if (this.IsAny()) { + return tokenRangeFrom(tokens); + } + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 215; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 195: + case 196: + case 203: + case 247: + case 243: + case 159: + case 167: + case 168: return true; - } - for (var _i = 0, _a = this.customContextChecks; _i < _a.length; _i++) { - var check = _a[_i]; - if (!check(context)) { - return false; - } - } + case 177: + case 232: + case 238: + case 227: + case 147: + case 268: + case 150: + case 149: + return context.currentTokenSpan.kind === 58 || context.nextTokenSpan.kind === 58; + case 216: + case 146: + return context.currentTokenSpan.kind === 92 || context.nextTokenSpan.kind === 92; + case 217: + return context.currentTokenSpan.kind === 143 || context.nextTokenSpan.kind === 143; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 196; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 175 || isSingleLineBlockContext(context); + } + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { return true; - }; - RuleOperationContext.Any = new RuleOperationContext(); - return RuleOperationContext; - }()); - formatting.RuleOperationContext = RuleOperationContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rules = (function () { - function Rules() { - this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1)); - this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1)); - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromRange(0, 142, [20])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(18, 82), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(18, 106), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); - this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71, 3, 75, 84, 91]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(44, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(43, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(37, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(37, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(44, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(38, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([102, 87]), 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(36, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(24, 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.FromTokens([20, 26])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(20, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 29), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.FromTokens([19, 21, 29, 26])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(57, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([117, 71, 84, 79, 75, 115, 114, 112, 113, 125, 135, 21, 39])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(89, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(39, formatting.Shared.TokenRange.FromTokens([71, 19])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(116, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116, 39]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(120, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(120, 89), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(71, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(41, 29), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); - this.HighPriorityCommonRules = [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, - this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceBeforeArrow, this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator, - this.NoSpaceAfterNewKeywordOnConstructorSignature - ]; - this.UserConfigurableRules = [ - this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, - this.SpaceAfterComma, this.NoSpaceAfterComma, - this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, - this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, - this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, - this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, - this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, - this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, - this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, - this.NewLineBeforeOpenBraceInControl, - this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, - this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion - ]; - this.LowPriorityCommonRules = [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; - if (ts.Debug.isDebugging) { - var o = this; - for (var name in o) { - var rule = o[name]; - if (rule instanceof formatting.Rule) { - rule.debugName = name; - } - } - } } - Rules.IsOptionEnabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; - }; - Rules.IsOptionDisabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; - }; - Rules.IsOptionDisabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; - }; - Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; - }; - Rules.IsOptionEnabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; - }; - Rules.IsForContext = function (context) { - return context.contextNode.kind === 214; - }; - Rules.IsNotForContext = function (context) { - return !Rules.IsForContext(context); - }; - Rules.IsBinaryOpContext = function (context) { - switch (context.contextNode.kind) { - case 194: - case 195: - case 202: - case 246: - case 242: - case 158: - case 166: - case 167: - return true; - case 176: - case 231: - case 237: - case 226: - case 146: - case 264: - case 149: - case 148: - return context.currentTokenSpan.kind === 58 || context.nextTokenSpan.kind === 58; - case 215: - case 145: - return context.currentTokenSpan.kind === 92 || context.nextTokenSpan.kind === 92; - case 216: - return context.currentTokenSpan.kind === 142 || context.nextTokenSpan.kind === 142; - } - return false; - }; - Rules.IsNotBinaryOpContext = function (context) { - return !Rules.IsBinaryOpContext(context); - }; - Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 195; - }; - Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { - return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); - }; - Rules.IsBraceWrappedContext = function (context) { - return context.contextNode.kind === 174 || Rules.IsSingleLineBlockContext(context); - }; - Rules.IsBeforeMultilineBlockContext = function (context) { - return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); - }; - Rules.IsMultilineBlockContext = function (context) { - return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsSingleLineBlockContext = function (context) { - return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.contextNode); - }; - Rules.IsBeforeBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.nextTokenParent); - }; - Rules.NodeIsBlockContext = function (node) { - if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) { + switch (node.kind) { + case 208: + case 236: + case 179: + case 235: return true; - } - switch (node.kind) { - case 207: - case 235: - case 178: - case 234: - return true; - } - return false; - }; - Rules.IsFunctionDeclContext = function (context) { - switch (context.contextNode.kind) { - case 228: - case 151: - case 150: - case 153: - case 154: - case 155: - case 186: - case 152: - case 187: - case 230: - return true; - } - return false; - }; - Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 228 || context.contextNode.kind === 186; - }; - Rules.IsTypeScriptDeclWithBlockContext = function (context) { - return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); - }; - Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { - switch (node.kind) { - case 229: - case 199: - case 230: - case 232: - case 163: - case 233: - case 244: - case 245: - case 238: - case 241: - return true; - } - return false; - }; - Rules.IsAfterCodeBlockContext = function (context) { - switch (context.currentTokenParent.kind) { - case 229: - case 233: - case 232: - case 260: - case 234: - case 221: + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 229: + case 152: + case 151: + case 154: + case 155: + case 156: + case 187: + case 153: + case 188: + case 231: + return true; + } + return false; + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 229 || context.contextNode.kind === 187; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 230: + case 200: + case 231: + case 233: + case 164: + case 234: + case 245: + case 246: + case 239: + case 242: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 230: + case 234: + case 233: + case 264: + case 235: + case 222: + return true; + case 208: { + var blockParent = context.currentTokenParent.parent; + if (!blockParent || blockParent.kind !== 188 && blockParent.kind !== 187) { return true; - case 207: { - var blockParent = context.currentTokenParent.parent; - if (!blockParent || blockParent.kind !== 187 && blockParent.kind !== 186) { - return true; - } } } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 212: + case 222: + case 215: + case 216: + case 217: + case 214: + case 225: + case 213: + case 221: + case 264: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 179; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 182; + } + function isNewContext(context) { + return context.contextNode.kind === 183; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 26; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 22; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 188; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; + } + function isNonJsxElementContext(context) { + return context.contextNode.kind !== 250; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 260; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 257; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 257; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 251; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 148; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 228 && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 234; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 164; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 157; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 27 && token.kind !== 29) { return false; - }; - Rules.IsControlDeclContext = function (context) { - switch (context.contextNode.kind) { - case 211: - case 221: - case 214: - case 215: - case 216: - case 213: - case 224: - case 212: - case 220: - case 260: - return true; - default: - return false; - } - }; - Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 178; - }; - Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 181; - }; - Rules.IsNewContext = function (context) { - return context.contextNode.kind === 182; - }; - Rules.IsFunctionCallOrNewContext = function (context) { - return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); - }; - Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 26; - }; - Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 22; - }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 187; - }; - Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; - }; - Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 249; - }; - Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 256; - }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 253; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 253; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 250; - }; - Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { - return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); - }; - Rules.IsEndOfDecoratorContextOnSameLine = function (context) { - return context.TokensAreOnSameLine() && - context.contextNode.decorators && - Rules.NodeIsInDecoratorContext(context.currentTokenParent) && - !Rules.NodeIsInDecoratorContext(context.nextTokenParent); - }; - Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isPartOfExpression(node)) { - node = node.parent; - } - return node.kind === 147; - }; - Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 227 && - context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; - }; - Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind !== 2; - }; - Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 233; - }; - Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 163; - }; - Rules.IsConstructorSignatureContext = function (context) { - return context.contextNode.kind === 156; - }; - Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 27 && token.kind !== 29) { + } + switch (parent.kind) { + case 160: + case 185: + case 232: + case 230: + case 200: + case 231: + case 229: + case 187: + case 188: + case 152: + case 151: + case 156: + case 157: + case 182: + case 183: + case 202: + return true; + default: return false; - } - switch (parent.kind) { - case 159: - case 184: - case 231: - case 229: - case 199: - case 230: - case 228: - case 186: - case 187: - case 151: - case 150: - case 155: - case 156: - case 181: - case 182: - case 201: - return true; - default: - return false; - } - }; - Rules.IsTypeArgumentOrParameterOrAssertionContext = function (context) { - return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || - Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); - }; - Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 184; - }; - Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 105 && context.currentTokenParent.kind === 190; - }; - Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 197 && context.contextNode.expression !== undefined; - }; - Rules.IsNonNullAssertionContext = function (context) { - return context.contextNode.kind === 203; - }; - return Rules; - }()); - formatting.Rules = Rules; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 185; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 105 && context.currentTokenParent.kind === 191; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 198 && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 204; + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; (function (ts) { var formatting; (function (formatting) { - var RulesMap = (function () { - function RulesMap() { - this.map = []; - this.mapRowLength = 0; - } - RulesMap.create = function (rules) { - var result = new RulesMap(); - result.Initialize(rules); - return result; - }; - RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 142 + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength); - var rulesBucketConstructionStateList = new Array(this.map.length); - this.FillRules(rules, rulesBucketConstructionStateList); - return this.map; - }; - RulesMap.prototype.FillRules = function (rules, rulesBucketConstructionStateList) { - var _this = this; - rules.forEach(function (rule) { - _this.FillRule(rule, rulesBucketConstructionStateList); - }); - }; - RulesMap.prototype.GetRuleBucketIndex = function (row, column) { - ts.Debug.assert(row <= 142 && column <= 142, "Must compute formatting context from tokens"); - var rulesBucketIndex = (row * this.mapRowLength) + column; - return rulesBucketIndex; - }; - RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { - var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); - rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { - rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { - var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); - var rulesBucket = _this.map[rulesBucketIndex]; + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); + }; + } + function buildMap(rules) { + var map = new Array(mapRowLength * mapRowLength); + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; if (rulesBucket === undefined) { - rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); - } - rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); - }); - }); - }; - RulesMap.prototype.GetRule = function (context) { - var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); - var bucket = this.map[bucketIndex]; - if (bucket) { - for (var _i = 0, _a = bucket.Rules(); _i < _a.length; _i++) { - var rule = _a[_i]; - if (rule.Operation.Context.InContext(context)) { - return rule; + rulesBucket = map[index] = []; } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); } } - return undefined; - }; - return RulesMap; - }()); - formatting.RulesMap = RulesMap; - var MaskBitSize = 5; - var Mask = 0x1f; + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 143 && column <= 143, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; + var mapRowLength = 143 + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; - RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; - RulesPosition[RulesPosition["ContextRulesSpecific"] = MaskBitSize * 2] = "ContextRulesSpecific"; - RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; - RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; - RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesBucketConstructionState = (function () { - function RulesBucketConstructionState() { - this.rulesInsertionIndexBitmap = 0; - } - RulesBucketConstructionState.prototype.GetInsertionIndex = function (maskPosition) { - var index = 0; - var pos = 0; - var indexBitmap = this.rulesInsertionIndexBitmap; - while (pos <= maskPosition) { - index += (indexBitmap & Mask); - indexBitmap >>= MaskBitSize; - pos += MaskBitSize; - } - return index; - }; - RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { - var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; - value++; - ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); - var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); - temp |= value << maskPosition; - this.rulesInsertionIndexBitmap = temp; - }; - return RulesBucketConstructionState; - }()); - formatting.RulesBucketConstructionState = RulesBucketConstructionState; - var RulesBucket = (function () { - function RulesBucket() { - this.rules = []; - } - RulesBucket.prototype.Rules = function () { - return this.rules; - }; - RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { - var position; - if (rule.Operation.Action === 1) { - position = specificTokens ? - RulesPosition.IgnoreRulesSpecific : - RulesPosition.IgnoreRulesAny; - } - else if (!rule.Operation.Context.IsAny()) { - position = specificTokens ? - RulesPosition.ContextRulesSpecific : - RulesPosition.ContextRulesAny; - } - else { - position = specificTokens ? - RulesPosition.NoContextRulesSpecific : - RulesPosition.NoContextRulesAny; - } - var state = constructionState[rulesBucketIndex]; - if (state === undefined) { - state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); - } - var index = state.GetInsertionIndex(position); - this.rules.splice(index, 0, rule); - state.IncreaseInsertionIndex(position); - }; - return RulesBucket; - }()); - formatting.RulesBucket = RulesBucket; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Shared; - (function (Shared) { - var allTokens = []; - for (var token = 0; token <= 142; token++) { - allTokens.push(token); - } - var TokenValuesAccess = (function () { - function TokenValuesAccess(tokens) { - if (tokens === void 0) { tokens = []; } - this.tokens = tokens; - } - TokenValuesAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenValuesAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - TokenValuesAccess.prototype.isSpecific = function () { return true; }; - return TokenValuesAccess; - }()); - var TokenSingleValueAccess = (function () { - function TokenSingleValueAccess(token) { - this.token = token; - } - TokenSingleValueAccess.prototype.GetTokens = function () { - return [this.token]; - }; - TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue === this.token; - }; - TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; - return TokenSingleValueAccess; - }()); - var TokenAllAccess = (function () { - function TokenAllAccess() { - } - TokenAllAccess.prototype.GetTokens = function () { - return allTokens; - }; - TokenAllAccess.prototype.Contains = function () { - return true; - }; - TokenAllAccess.prototype.toString = function () { - return "[allTokens]"; - }; - TokenAllAccess.prototype.isSpecific = function () { return false; }; - return TokenAllAccess; - }()); - var TokenAllExceptAccess = (function () { - function TokenAllExceptAccess(except) { - this.except = except; - } - TokenAllExceptAccess.prototype.GetTokens = function () { - var _this = this; - return allTokens.filter(function (t) { return t !== _this.except; }); - }; - TokenAllExceptAccess.prototype.Contains = function (token) { - return token !== this.except; - }; - TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; - return TokenAllExceptAccess; - }()); - var TokenRange; - (function (TokenRange) { - function FromToken(token) { - return new TokenSingleValueAccess(token); - } - TokenRange.FromToken = FromToken; - function FromTokens(tokens) { - return new TokenValuesAccess(tokens); - } - TokenRange.FromTokens = FromTokens; - function FromRange(from, to, except) { - if (except === void 0) { except = []; } - var tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - tokens.push(token); - } - } - return new TokenValuesAccess(tokens); - } - TokenRange.FromRange = FromRange; - function AnyExcept(token) { - return new TokenAllExceptAccess(token); - } - TokenRange.AnyExcept = AnyExcept; - TokenRange.Any = new TokenAllAccess(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ - 92, 93, 142, 118, 126 - ]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ - 43, 44, 52, 51 - ]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ - 8, 71, 19, 21, - 17, 99, 94 - ]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ - 71, 19, 99, 94 - ]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ - 71, 20, 22, 94 - ]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ - 71, 19, 99, 94 - ]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ - 71, 20, 22, 94 - ]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([ - 71, 133, 136, 122, - 137, 105, 119 - ]); - })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); - })(Shared = formatting.Shared || (formatting.Shared = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RulesProvider = (function () { - function RulesProvider() { - this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); - this.rulesMap = formatting.RulesMap.create(activeRules); + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; } - RulesProvider.prototype.getRulesMap = function () { - return this.rulesMap; - }; - RulesProvider.prototype.getFormatOptions = function () { - return this.options; - }; - RulesProvider.prototype.ensureUpToDate = function (options) { - if (!this.options || !ts.compareDataObjects(this.options, options)) { - this.options = ts.clone(options); - } - }; - return RulesProvider; - }()); - formatting.RulesProvider = RulesProvider; + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; @@ -71695,7 +74299,7 @@ var ts; (function (Constants) { Constants[Constants["Unknown"] = -1] = "Unknown"; })(Constants || (Constants = {})); - function formatOnEnter(position, sourceFile, rulesProvider, options) { + function formatOnEnter(position, sourceFile, formatContext) { var line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { return []; @@ -71711,15 +74315,15 @@ var ts; pos: ts.getStartPositionOfLine(line - 1, sourceFile), end: endOfFormatSpan + 1 }; - return formatSpan(span, sourceFile, options, rulesProvider, 2); + return formatSpan(span, sourceFile, formatContext, 2); } formatting.formatOnEnter = formatOnEnter; - function formatOnSemicolon(position, sourceFile, rulesProvider, options) { + function formatOnSemicolon(position, sourceFile, formatContext) { var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3); } formatting.formatOnSemicolon = formatOnSemicolon; - function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + function formatOnOpeningCurly(position, sourceFile, formatContext) { var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17, sourceFile); if (!openingCurly) { return []; @@ -71730,28 +74334,28 @@ var ts; pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), end: position }; - return formatSpan(textRange, sourceFile, options, rulesProvider, 4); + return formatSpan(textRange, sourceFile, formatContext, 4); } formatting.formatOnOpeningCurly = formatOnOpeningCurly; - function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { + function formatOnClosingCurly(position, sourceFile, formatContext) { var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5); } formatting.formatOnClosingCurly = formatOnClosingCurly; - function formatDocument(sourceFile, rulesProvider, options) { + function formatDocument(sourceFile, formatContext) { var span = { pos: 0, end: sourceFile.text.length }; - return formatSpan(span, sourceFile, options, rulesProvider, 0); + return formatSpan(span, sourceFile, formatContext, 0); } formatting.formatDocument = formatDocument; - function formatSelection(start, end, sourceFile, rulesProvider, options) { + function formatSelection(start, end, sourceFile, formatContext) { var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), end: end, }; - return formatSpan(span, sourceFile, options, rulesProvider, 1); + return formatSpan(span, sourceFile, formatContext, 1); } formatting.formatSelection = formatSelection; function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { @@ -71772,17 +74376,17 @@ var ts; } function isListElement(parent, node) { switch (parent.kind) { - case 229: case 230: + case 231: return ts.rangeContainsRange(parent.members, node); - case 233: - var body = parent.body; - return body && body.kind === 234 && ts.rangeContainsRange(body.statements, node); - case 265: - case 207: case 234: + var body = parent.body; + return body && body.kind === 235 && ts.rangeContainsRange(body.statements, node); + case 269: + case 208: + case 235: return ts.rangeContainsRange(parent.statements, node); - case 260: + case 264: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -71861,12 +74465,12 @@ var ts; } return 0; } - function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); }); + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1, function (_) { return false; }, sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; - function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + function formatNodeLines(node, sourceFile, formatContext, requestKind) { if (!node) { return []; } @@ -71874,13 +74478,14 @@ var ts; pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), end: node.end }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + return formatSpan(span, sourceFile, formatContext, requestKind); } - function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } - function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRange; var previousParent; @@ -71950,18 +74555,18 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 229: return 75; - case 230: return 109; - case 228: return 89; - case 232: return 232; - case 153: return 125; - case 154: return 135; - case 151: + case 230: return 75; + case 231: return 109; + case 229: return 89; + case 233: return 233; + case 154: return 125; + case 155: return 135; + case 152: if (node.asteriskToken) { return 39; } - case 149: - case 146: + case 150: + case 147: return ts.getNameOfDeclaration(node).kind; } } @@ -71993,16 +74598,16 @@ var ts; return indentation; case 41: case 29: { - if (container.kind === 251 || - container.kind === 252 || - container.kind === 250) { + if (container.kind === 252 || + container.kind === 253 || + container.kind === 251) { return indentation; } break; } case 21: case 22: { - if (container.kind !== 172) { + if (container.kind !== 173) { return indentation; } break; @@ -72059,7 +74664,7 @@ var ts; undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } var childIndentationAmount = -1; - if (isListItem) { + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); if (childIndentationAmount !== -1) { inheritedIndentation = childIndentationAmount; @@ -72090,11 +74695,15 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 147 ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 148 ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 10) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, true, false); + } childContextNode = node; - if (isFirstListItem && parent.kind === 177 && inheritedIndentation === -1) { + if (isFirstListItem && parent.kind === 178 && inheritedIndentation === -1) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -72143,24 +74752,21 @@ var ts; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } - var lineAdded; + var lineAction = 0; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); var savePreviousRange = previousRange; - lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); - if (rangeHasError) { - indentToken = false; - } - else { - if (lineAdded !== undefined) { - indentToken = lineAdded; - } - else { + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + if (!rangeHasError) { + if (lineAction === 0) { var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } + else { + indentToken = lineAction === 1; + } } } if (currentTokenInfo.trailingTrivia) { @@ -72179,7 +74785,7 @@ var ts; switch (triviaItem.kind) { case 3: if (triviaInRange) { - indentMultilineComment(triviaItem, commentIndentation, !indentNextTokenOrTrivia); + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -72196,7 +74802,7 @@ var ts; } } if (tokenIndentation !== -1 && indentNextTokenOrTrivia) { - insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } @@ -72216,42 +74822,42 @@ var ts; } function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); - var lineAdded; + var lineAction = 0; if (!rangeHasError) { if (!previousRange) { var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { - lineAdded = + lineAction = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - return lineAdded; + return lineAction; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); - var rule = rulesProvider.getRulesMap().GetRule(formattingContext); + var rule = getRule(formattingContext); var trimTrailingWhitespaces; - var lineAdded; + var lineAction = 0; if (rule) { applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.Operation.Action & (2 | 8) && currentStartLine !== previousStartLine) { - lineAdded = false; + if (rule.action & (2 | 8) && currentStartLine !== previousStartLine) { + lineAction = 2; if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(false); } } - else if (rule.Operation.Action & 4 && currentStartLine === previousStartLine) { - lineAdded = true; + else if (rule.action & 4 && currentStartLine === previousStartLine) { + lineAction = 1; if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(true); } } - trimTrailingWhitespaces = !(rule.Operation.Action & 8) && rule.Flag !== 1; + trimTrailingWhitespaces = !(rule.action & 8) && rule.flags !== 1; } else { trimTrailingWhitespaces = true; @@ -72259,7 +74865,7 @@ var ts; if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } - return lineAdded; + return lineAction; } function insertIndentation(pos, indentation, lineAdded) { var indentationString = getIndentationString(indentation, options); @@ -72289,7 +74895,8 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; var parts; @@ -72307,7 +74914,9 @@ var ts; parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } - parts.push({ pos: startPos, end: commentRange.end }); + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } } var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); @@ -72379,7 +74988,7 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - switch (rule.Operation.Action) { + switch (rule.action) { case 1: return; case 8: @@ -72388,7 +74997,7 @@ var ts; } break; case 4: - if (rule.Flag !== 1 && previousStartLine !== currentStartLine) { + if (rule.flags !== 1 && previousStartLine !== currentStartLine) { return; } var lineDelta = currentStartLine - previousStartLine; @@ -72397,7 +75006,7 @@ var ts; } break; case 2: - if (rule.Flag !== 1 && previousStartLine !== currentStartLine) { + if (rule.flags !== 1 && previousStartLine !== currentStartLine) { return; } var posDelta = currentRange.pos - previousRange.end; @@ -72408,6 +75017,12 @@ var ts; } } } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, false); } var tokenStart = tokenAtPosition.getStart(sourceFile); @@ -72436,12 +75051,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { + case 153: + case 229: + case 187: case 152: - case 228: - case 186: case 151: - case 150: - case 187: + case 188: if (node.typeParameters === list) { return 27; } @@ -72449,8 +75064,8 @@ var ts; return 19; } break; - case 181: case 182: + case 183: if (node.typeArguments === list) { return 27; } @@ -72458,7 +75073,7 @@ var ts; return 19; } break; - case 159: + case 160: if (node.typeArguments === list) { return 27; } @@ -72546,19 +75161,7 @@ var ts; var precedingToken = ts.findPrecedingToken(position, sourceFile); var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, true, precedingToken || null); if (enclosingCommentRange) { - var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; - var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; - ts.Debug.assert(commentStartLine >= 0); - if (previousLine <= commentStartLine) { - return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); - } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; - if (column === 0) { - return column; - } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); - return firstNonWhitespaceCharacterCode === 42 ? column - 1 : column; + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { return getBaseIndentation(options); @@ -72569,38 +75172,55 @@ var ts; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (options.indentStyle === ts.IndentStyle.Block) { - var current_1 = position; - while (current_1 > 0) { - var char = sourceFile.text.charCodeAt(current_1); - if (!ts.isWhiteSpaceLike(char)) { - break; - } - current_1--; - } - var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); - return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); + return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 && precedingToken.parent.kind !== 194) { + if (precedingToken.kind === 26 && precedingToken.parent.kind !== 195) { var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1) { return actualIndentation; } } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { var previous; var current = precedingToken; - var currentStart; - var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { - currentStart = getStartLineAndCharacterForNode(current, sourceFile); + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous, true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); - if (nextTokenKind !== 0) { - indentationDelta = assumeNewLineBeforeCloseBrace && nextTokenKind === 2 ? options.indentSize : 0; - } - else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; - } - break; + var indentationDelta = nextTokenKind !== 0 + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, true, options); } var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); if (actualIndentation !== -1) { @@ -72613,24 +75233,19 @@ var ts; previous = current; current = current.parent; } - if (!current) { - return getBaseIndentation(options); - } - return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); + return getBaseIndentation(options); } - SmartIndenter.getIndentation = getIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); - return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, false, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; function getBaseIndentation(options) { return options.baseIndentSize || 0; } SmartIndenter.getBaseIndentation = getBaseIndentation; - function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { var parent = current.parent; - var parentStart; while (parent) { var useActualIndentation = true; if (ignoreActualIndentationRange) { @@ -72643,8 +75258,8 @@ var ts; return actualIndentation + indentationDelta; } } - parentStart = getParentStart(parent, current, sourceFile); - var parentAndChildShareLine = parentStart.line === currentStart.line || + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); @@ -72656,21 +75271,20 @@ var ts; return actualIndentation + indentationDelta; } } - if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current, isNextChild) && !parentAndChildShareLine) { indentationDelta += options.indentSize; } + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); current = parent; - currentStart = parentStart; parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; } return indentationDelta + getBaseIndentation(options); } - function getParentStart(parent, child, sourceFile) { + function getContainingListOrParentStart(parent, child, sourceFile) { var containingList = getContainingList(child, sourceFile); - if (containingList) { - return sourceFile.getLineAndCharacterOfPosition(containingList.pos); - } - return sourceFile.getLineAndCharacterOfPosition(parent.getStart(sourceFile)); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); } function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { var commaItemInfo = ts.findListItemInfo(commaToken); @@ -72683,7 +75297,7 @@ var ts; } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 265 || !parentAndChildShareLine); + (parent.kind === 269 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; } @@ -72712,8 +75326,17 @@ var ts; function getStartLineAndCharacterForNode(n, sourceFile) { return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 211 && parent.elseStatement === child) { + if (parent.kind === 212 && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 82, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -72728,37 +75351,37 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 159: + case 160: return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); - case 178: + case 179: return node.parent.properties; - case 177: + case 178: return node.parent.elements; - case 228: - case 186: + case 229: case 187: - case 151: - case 150: - case 155: + case 188: case 152: - case 161: - case 156: { + case 151: + case 156: + case 153: + case 162: + case 157: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); } - case 229: + case 230: return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); - case 182: - case 181: { + case 183: + case 182: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); } - case 227: + case 228: return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); - case 241: - case 245: + case 242: + case 246: return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); } } @@ -72794,10 +75417,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 181: case 182: - case 179: + case 183: case 180: + case 181: node = node.expression; break; default: @@ -72851,51 +75474,51 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 210: - case 229: - case 199: + case 211: case 230: - case 232: + case 200: case 231: - case 177: - case 207: - case 234: + case 233: + case 232: case 178: - case 163: - case 172: - case 165: + case 208: case 235: - case 258: - case 257: - case 185: case 179: - case 181: + case 164: + case 173: + case 166: + case 236: + case 262: + case 261: + case 186: + case 180: case 182: - case 208: - case 226: - case 243: - case 219: - case 195: + case 183: + case 209: + case 227: + case 244: + case 220: + case 196: + case 176: case 175: - case 174: + case 252: case 251: - case 250: - case 256: - case 150: - case 155: + case 260: + case 151: case 156: - case 146: - case 160: + case 157: + case 147: case 161: - case 168: - case 183: - case 191: - case 245: - case 241: + case 162: + case 169: + case 184: + case 192: case 246: case 242: - case 261: - case 149: + case 247: + case 243: + case 265: + case 150: return true; } return false; @@ -72903,33 +75526,64 @@ var ts; function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0; switch (parent.kind) { - case 212: case 213: - case 215: - case 216: case 214: - case 211: - case 228: - case 186: - case 151: + case 216: + case 217: + case 215: + case 212: + case 229: case 187: case 152: + case 188: case 153: case 154: - return childKind !== 207; - case 244: - return childKind !== 245; - case 238: - return childKind !== 239 || - (child.namedBindings && child.namedBindings.kind !== 241); - case 249: - return childKind !== 252; + case 155: + return childKind !== 208; + case 245: + return childKind !== 246; + case 239: + return childKind !== 240 || + (!!child.namedBindings && child.namedBindings.kind !== 242); + case 250: + return childKind !== 253; } return indentByDefault; } SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; - function shouldIndentChildNode(parent, child) { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 220: + case 224: + switch (parent.kind) { + case 208: + var grandParent = parent.parent; + switch (grandParent && grandParent.kind) { + case 229: + case 187: + return false; + default: + return true; + } + case 261: + case 262: + case 269: + case 235: + return true; + default: + throw ts.Debug.fail(); + } + case 218: + case 219: + return true; + default: + return false; + } + } + function shouldIndentChildNode(parent, child, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false)) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -72940,22 +75594,22 @@ var ts; var textChanges; (function (textChanges) { function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -73019,7 +75673,7 @@ var ts; } textChanges.getAdjustedEndPosition = getAdjustedEndPosition; function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 || (candidate.kind === 25 && node.parent.kind === 178)); + return candidate && node.parent && (candidate.kind === 26 || (candidate.kind === 25 && node.parent.kind === 179)); } function spaces(count) { var s = ""; @@ -73029,15 +75683,20 @@ var ts; return s; } var ChangeTracker = (function () { - function ChangeTracker(newLine, rulesProvider, validator) { + function ChangeTracker(newLine, formatContext, validator) { this.newLine = newLine; - this.rulesProvider = rulesProvider; + this.formatContext = formatContext; this.validator = validator; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -73156,9 +75815,9 @@ var ts; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } if ((ts.isStatementButNotDeclaration(after)) || + after.kind === 150 || after.kind === 149 || - after.kind === 148 || - after.kind === 150) { + after.kind === 151) { if (sourceFile.text.charCodeAt(after.end - 1) !== 59) { this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, @@ -73234,7 +75893,7 @@ var ts; node: ts.createToken(separator), options: {} }); - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.rulesProvider.getFormatOptions()); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); var insertPos = ts.skipTrivia(sourceFile.text, end, true, false); if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; @@ -73313,7 +75972,7 @@ var ts; if (this.validator) { this.validator(nonformattedText); } - var formatOptions = this.rulesProvider.getFormatOptions(); + var formatOptions = this.formatContext.options; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; var initialIndentation = options.indentation !== undefined ? options.indentation @@ -73325,7 +75984,7 @@ var ts; : ts.formatting.SmartIndenter.shouldIndentChildNode(node) ? (formatOptions.indentSize || 0) : 0; - return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext); }; ChangeTracker.normalize = function (changes) { var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; }); @@ -73344,14 +76003,14 @@ var ts; printer.writeNode(4, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { + function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { text: nonFormattedText.text, lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(nonFormattedText.text, changes); } function applyChanges(text, changes) { @@ -73530,7 +76189,7 @@ var ts; refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { return ts.flatMapIter(refactors.values(), function (refactor) { - return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); }); } refactor_1.getApplicableRefactors = getApplicableRefactors; @@ -73546,6 +76205,28 @@ var ts; ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var decorator = ts.getAncestor(token, 148); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, undefined, undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -73554,7 +76235,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var qualifiedName = ts.getAncestor(token, 143); + var qualifiedName = ts.getAncestor(token, 144); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); if (!ts.isIdentifier(qualifiedName.left)) { return undefined; @@ -73661,7 +76342,7 @@ var ts; var checker = context.program.getTypeChecker(); var leftExpression = token.parent.expression; var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 32768) { + if (leftExpressionType.flags & 65536) { var symbol = leftExpressionType.symbol; if (symbol.flags & 32) { classDeclaration = symbol.declarations && symbol.declarations[0]; @@ -73686,13 +76367,13 @@ var ts; actions = [methodCodeAction]; } if (makeStatic) { - if (classDeclaration.kind === 199) { + if (classDeclaration.kind === 200) { return actions; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -73707,7 +76388,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -73723,7 +76404,7 @@ var ts; actions = [methodCodeAction]; } var typeNode; - if (token.parent.parent.kind === 194) { + if (token.parent.parent.kind === 195) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); @@ -73734,8 +76415,9 @@ var ts; var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - (actions || (actions = [])).push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; + actions = ts.append(actions, { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: propertyChangeTracker.getChanges() }); if (!makeStatic) { @@ -73752,15 +76434,14 @@ var ts; return actions; } function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 181) { + if (token.parent.parent.kind === 182) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? - ts.Diagnostics.Declare_method_0 : - ts.Diagnostics.Declare_static_method_0), [tokenName]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: methodDeclarationChangeTracker.getChanges() }; } @@ -73789,7 +76470,9 @@ var ts; } else { var meaning = ts.getMeaningFromLocation(node); - suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } if (suggestion) { return [{ @@ -73820,6 +76503,39 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, sourceFile.fileName, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + changes: [], + commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -73878,10 +76594,11 @@ var ts; if (!superCall) { return undefined; } - if (superCall.expression && superCall.expression.kind === 181) { + if (superCall.expression && superCall.expression.kind === 182) { var expressionArguments = superCall.expression.arguments; - for (var i = 0; i < expressionArguments.length; i++) { - if (expressionArguments[i].expression === token) { + for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { + var arg = expressionArguments_1[_i]; + if (arg.expression === token) { return undefined; } } @@ -73894,7 +76611,7 @@ var ts; changes: changeTracker.getChanges() }]; function findSuperCall(n) { - if (n.kind === 210 && ts.isSuperCall(n.expression)) { + if (n.kind === 211 && ts.isSuperCall(n.expression)) { return n; } if (ts.isFunctionLike(n)) { @@ -74008,9 +76725,9 @@ var ts; } switch (token.kind) { case 71: - return deleteIdentifierOrPrefixWithUnderscore(token); - case 149: - case 240: + return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); + case 150: + case 241: return [deleteNode(token.parent)]; default: return deleteDefault(); @@ -74039,12 +76756,12 @@ var ts; }] }; } - function deleteIdentifierOrPrefixWithUnderscore(identifier) { + function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { var parent = identifier.parent; switch (parent.kind) { - case 226: + case 227: return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 145: + case 146: var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); @@ -74056,14 +76773,16 @@ var ts; else { return [deleteNodeInList(parent)]; } - case 146: + case 147: var functionDeclaration = parent.parent; - return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), - prefixIdentifierWithUnderscore(identifier)]; - case 237: - var importEquals = ts.getAncestor(identifier, 237); + var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); + return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code + ? [deleteAction] + : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; + case 238: + var importEquals = ts.getAncestor(identifier, 238); return [deleteNode(importEquals)]; - case 242: + case 243: var namedImports = parent.parent; if (namedImports.elements.length === 1) { return deleteNamedImportBinding(namedImports); @@ -74071,10 +76790,10 @@ var ts; else { return [deleteNodeInList(parent)]; } - case 239: + case 240: var importClause = parent; if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); + var importDecl = ts.getAncestor(importClause, 239); return [deleteNode(importDecl)]; } else { @@ -74087,7 +76806,7 @@ var ts; return [deleteNode(importClause.name)]; } } - case 240: + case 241: return deleteNamedImportBinding(parent); default: return deleteDefault(); @@ -74102,25 +76821,25 @@ var ts; return undefined; } else { - var importDecl = ts.getAncestor(namedBindings, 238); + var importDecl = ts.getAncestor(namedBindings, 239); return [deleteNode(importDecl)]; } } function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { - case 214: + case 215: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 216: + case 217: var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 227); + ts.Debug.assert(forOfStatement.initializer.kind === 228); var forOfInitializer = forOfStatement.initializer; return [ replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), prefixIdentifierWithUnderscore(identifier) ]; - case 215: + case 216: return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; @@ -74169,22 +76888,22 @@ var ts; var sourceFile = context.sourceFile; var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); var decl = ts.findAncestor(node, function (n) { - return n.kind === 202 || - n.kind === 155 || + return n.kind === 203 || n.kind === 156 || - n.kind === 228 || - n.kind === 153 || n.kind === 157 || - n.kind === 172 || + n.kind === 229 || + n.kind === 154 || + n.kind === 158 || + n.kind === 173 || + n.kind === 152 || n.kind === 151 || + n.kind === 147 || n.kind === 150 || - n.kind === 146 || n.kind === 149 || - n.kind === 148 || - n.kind === 154 || - n.kind === 231 || - n.kind === 184 || - n.kind === 226; + n.kind === 155 || + n.kind === 232 || + n.kind === 185 || + n.kind === 227; }); if (!decl) return; @@ -74195,8 +76914,8 @@ var ts; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; - if (jsdocType.kind === 270) { - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048), undefined, 8); + if (jsdocType.kind === 274) { + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096), undefined, 8); actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); } return actions; @@ -74219,6 +76938,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -74239,9 +76959,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -74259,14 +76976,14 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0: if (newAction.kind === "NewImport") { return; } - case ModuleSpecifierComparison.Equal: + case 1: updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2: continue; } } @@ -74288,454 +77005,530 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1; } if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2; } if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { var regex = new RegExp(ts.directorySeparator, "g"); var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 + : 2; } - return ModuleSpecifierComparison.Equal; + return 1; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName = void 0; - if (umdSymbol.flags & 2097152) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455)); - symbolName = symbol.name; - } - else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + formatContext: context.formatContext, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbols, context) { + moduleSymbols = ts.toArray(moduleSymbols); + var declarations = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + }); + var actions = []; + if (context.symbolToken) { + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } - return getCodeActionForImport(symbol, symbolName, false, true); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); - } + return actions.concat(getCodeActionsForAddImport(moduleSymbols, context, declarations)); + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 239) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 241 ? namedBindings.name : undefined; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, true)); - } - } - ts.Debug.assert(name !== "default"); - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } + else { + return declaration.name; } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + } + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238: - return parent; - case 248: - return parent.parent; - default: - return undefined; - } - } - } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 239: + return parent; + case 249: + return parent.parent; + case 245: + case 182: + return undefined; + default: + ts.Debug.fail(); } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var importDecl = kind !== 3 + ? ts.createImportDeclaration(undefined, undefined, createImportClauseOfKind(kind, symbolName), quotedModuleSpecifier) + : ts.createImportEqualsDeclaration(undefined, undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - return [getCodeActionForNewImport()]; - } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } - } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); - } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); - } - else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); - } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); - } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); - } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); - } + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } - } - } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); + }); + return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + var id = ts.createIdentifier(symbolName); + switch (kind) { + case 1: + return ts.createImportClause(id, undefined); + case 2: + return ts.createImportClause(undefined, ts.createNamespaceImport(id)); + case 0: + return ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, id)])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + } + codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + function getRelativePathNParents(relativePath) { + var count = 0; + for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { + count++; + } + return count; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSourceFileImportLocation(node) { - var text = node.text; - var ranges = ts.getLeadingCommentRanges(text, 0); - if (!ranges) - return 0; - var position = 0; - if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end + 1; - ranges = ranges.slice(1); - } - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { - position = range.end + 1; - continue; - } - break; + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } - return position; } - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } - }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } - return undefined; - } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } - } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } - } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } - function getNodeModulePathParts(fullPath) { - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1; - } - break; - case 1: - case 2: - if (state === 1 && fullPath.charAt(partStart + 1) === "@") { - state = 2; - } - else { - packageRootIndex = partEnd; - state = 3; - } - break; - case 3: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1; - } - else { - state = 3; - } - break; + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } - fileNameIndex = partStart; - return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } + } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); + break; + case 1: + case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; + } + else { + packageRootIndex = partEnd; + state = 3; + } + break; + case 3: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1; } - return fileName; + else { + state = 3; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName, options) { + var noExtension = ts.removeFileExtension(fileName); + return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionsForAddImport(moduleSymbols, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 239 && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + }); + if (fromExistingImport) { + return [fromExistingImport]; + } + var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 239 + ? node.moduleSpecifier + : node.moduleReference.kind === 249 + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile, kind = context.kind; + var name = importClause.name; + var namedBindings = (importClause.kind !== 238 && importClause).namedBindings; + switch (kind) { + case 1: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0: { + var newImportSpecifier_1 = ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 242 && namedBindings.elements.length !== 0) { + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 242 && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); + }); } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + return undefined; + } + case 2: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + case 3: + return undefined; + default: + ts.Debug.assertNever(kind); + } + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken, compilerOptions = context.compilerOptions; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; + } + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455)); + symbolName = symbol.name; + } + else { + throw ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: getUmdImportKind(compilerOptions) })); + } + function getUmdImportKind(compilerOptions) { + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1; + } + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + return 2; + default: + throw ts.Debug.assertNever(moduleKind); + } + } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) + && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 }))); } } + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, undefined); } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol, sourceFile); + } } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + } + codefix.forEachExternalModule = forEachExternalModule; + function isImportablePath(fromPath, toPath) { + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var res = ""; + var lastCharWasValid = true; + var firstCharCode = moduleSpecifier.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); } + else { + lastCharWasValid = false; + } + for (var i = 1; i < moduleSpecifier.length; i++) { + var ch = moduleSpecifier.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -74857,15 +77650,15 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216); switch (declaration.kind) { - case 153: case 154: - case 148: + case 155: case 149: + case 150: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); var property = ts.createProperty(undefined, modifiers, name, optional ? ts.createToken(55) : undefined, typeNode, undefined); return property; - case 150: case 151: + case 152: var signatures = checker.getSignaturesOfType(type, 0); if (!ts.some(signatures)) { return undefined; @@ -74876,8 +77669,8 @@ var ts; return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); } var signatureDeclarations = []; - for (var i = 0; i < signatures.length; i++) { - var signature = signatures[i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); if (methodDeclaration) { signatureDeclarations.push(methodDeclaration); @@ -74900,7 +77693,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -74938,8 +77731,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var i = 0; i < signatures.length; i++) { - var sig = signatures[i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -74977,6 +77770,773 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71: + case 24: + case 114: + case 112: + case 113: + case 131: + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229: + case 152: + case 153: + return true; + case 187: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 153: + case 187: + case 229: + case 152: + var isConstructor = containingFunction.kind === 153; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, false).accessibility !== 0) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 153; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 194: + usageContext.isNumber = true; + break; + case 193: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 195: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 261: + case 262: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 182: + case 183: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 180: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 181: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43: + case 44: + case 38: + case 52: + usageContext.isNumber = true; + break; + case 37: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + case 40: + case 39: + case 41: + case 42: + case 45: + case 46: + case 47: + case 48: + case 49: + case 50: + case 60: + case 62: + case 61: + case 63: + case 64: + case 68: + case 69: + case 70: + case 65: + case 67: + case 66: + case 38: + case 27: + case 30: + case 29: + case 31: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59: + case 37: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 524322) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + case 58: + case 32: + case 34: + case 35: + case 33: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92: + if (node === parent.left) { + usageContext.isString = true; + } + break; + case 54: + if (node === parent.left && + (node.parent.parent.kind === 227 || ts.isAssignmentExpression(node.parent.parent, true))) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53: + case 26: + case 93: + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 182) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, true) : checker.getAnyType()); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, false, checker)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + var members_5 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + var numberIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4, name); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + members_5.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), false); + } + return checker.createAnonymousType(undefined, members_5, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + return checker.createSignature(undefined, undefined, undefined, parameters, returnType, undefined, callContext.argumentTypes.length, false, false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1) && !(type.flags & 16384)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var annotateWithTypeFromJSDoc; + (function (annotateWithTypeFromJSDoc) { + var actionName = "annotate"; + var annotateTypeFromJSDoc = { + name: "Annotate with type from JSDoc", + description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(annotateTypeFromJSDoc); + function getAvailableActions(context) { + if (ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, false); + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { + return [{ + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, + actions: [ + { + description: annotateTypeFromJSDoc.description, + name: actionName + } + ] + }]; + } + } + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { + if (actionName !== action) { + return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 147) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, false); + var decl = ts.findAncestor(token, isDeclarationWithType); + var jsdocType = ts.getJSDocType(decl); + if (!decl || !jsdocType || decl.type) { + return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var declarationWithType = addType(decl, transformJSDocType(jsdocType)); + ts.suppressLeadingAndTrailingTrivia(declarationWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, declarationWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function getEditsForFunctionAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, false); + var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var functionWithType = addTypesToFunctionLike(decl); + ts.suppressLeadingAndTrailingTrivia(functionWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, functionWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 227 || + node.kind === 147 || + node.kind === 149 || + node.kind === 150; + } + function addTypesToFunctionLike(decl) { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, true); + var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, true)), p.initializer); }); + var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, true)); + switch (decl.kind) { + case 229: + return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 153: + return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); + case 187: + return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 188: + return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); + case 152: + return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); + case 154: + return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); + case 155: + return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body); + default: + return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind); + } + } + function addType(decl, jsdocType) { + switch (decl.kind) { + case 227: + return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); + case 149: + return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + case 150: + return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + default: + return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind); + } + } + function transformJSDocType(node) { + if (node === undefined) { + return undefined; + } + switch (node.kind) { + case 272: + case 273: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 276: + return transformJSDocOptionalType(node); + case 275: + return transformJSDocType(node.type); + case 274: + return transformJSDocNullableType(node); + case 278: + return transformJSDocVariadicType(node); + case 277: + return transformJSDocFunctionType(node); + case 147: + return transformJSDocParameter(node); + case 160: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, undefined); + ts.setEmitFlags(visited, 1); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + var parameters = node.parameters && node.parameters.map(transformJSDocType); + return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 278 && index === node.parent.parameters.length - 1; + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(24) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter(undefined, undefined, undefined, node.typeArguments[0].kind === 133 ? "n" : "s", undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 ? "number" : "string", []), undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { @@ -74994,14 +78554,14 @@ var ts; if (!ts.isInJavaScriptFile(context.file)) { return undefined; } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + var symbol = getConstructorSymbol(context); + if (!symbol) { + return undefined; + } + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { symbol = symbol.valueDeclaration.initializer.symbol; } - if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { + if ((symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { return [ { name: convertFunctionToES6Class.name, @@ -75020,12 +78580,9 @@ var ts; if (actionName !== action) { return undefined; } - var start = context.startPosition; var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var ctorSymbol = getConstructorSymbol(context); + var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 | 3))) { @@ -75036,12 +78593,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 228: + case 229: precedingNode = ctorDeclaration; deleteNode(ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 226: + case 227: precedingNode = ctorDeclaration.parent.parent; if (ctorDeclaration.parent.declarations.length === 1) { deleteNode(precedingNode); @@ -75109,31 +78666,33 @@ var ts; if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { return; } - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 211 ? assignmentBinaryExpression.parent : assignmentBinaryExpression; deleteNode(nodeToDelete); if (!assignmentBinaryExpression.right) { return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186: { + case 187: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120)); + var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; } - case 187: { + case 188: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; - if (arrowFunctionBody.kind === 207) { + if (arrowFunctionBody.kind === 208) { bodyBlock = arrowFunctionBody; } else { var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120)); + var method = ts.createMethod(undefined, fullModifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; } @@ -75162,7 +78721,7 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 186) { + if (!initializer || initializer.kind !== 187) { return undefined; } if (node.name.kind !== 71) { @@ -75172,7 +78731,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var modifiers = getModifierKindFromSource(precedingNode, 84); + var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); return cls; } function createClassFromFunctionDeclaration(node) { @@ -75180,9 +78740,19 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var modifiers = getModifierKindFromSource(node, 84); + var cls = ts.createClassDeclaration(undefined, modifiers, node.name, undefined, undefined, memberElements); return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + } + function getConstructorSymbol(_a) { + var startPosition = _a.startPosition, file = _a.file, program = _a.program; + var checker = program.getTypeChecker(); + var token = ts.getTokenAtPosition(file, startPosition, false); + return checker.getSymbolAtLocation(token); } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -75191,15 +78761,15 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var extractMethod; - (function (extractMethod_1) { - var extractMethod = { - name: "Extract Method", - description: ts.Diagnostics.Extract_function.message, + var extractSymbol; + (function (extractSymbol_1) { + var extractSymbol = { + name: "Extract Symbol", + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction, }; - refactor.registerRefactor(extractMethod); + refactor.registerRefactor(extractSymbol); function getAvailableActions(context) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -75210,62 +78780,99 @@ var ts; if (extractions === undefined) { return undefined; } - var actions = []; - var usedNames = ts.createMap(); + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; - if (errors.length) { - continue; + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; + if (functionExtraction.errors.length === 0) { + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } } - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); - if (!usedNames.has(description)) { - usedNames.set(description, true); - actions.push({ - description: description, - name: "scope_" + i - }); + if (constantExtraction.errors.length === 0) { + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } } i++; } - if (actions.length === 0) { - return undefined; + var infos = []; + if (functionActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); } - return [{ - name: extractMethod.name, - description: extractMethod.description, - inlineable: true, - actions: actions - }]; + if (constantActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : undefined; } + extractSymbol_1.getAvailableActions = getAvailableActions; function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; - var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); - ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); - var index = +parsedIndexMatch[1]; - ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - return getExtractionAtIndex(targetRange, context, index); + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); } + extractSymbol_1.getEditsForAction = getEditsForAction; var Messages; (function (Messages) { function createMessage(message) { return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; } - Messages.CannotExtractFunction = createMessage("Cannot extract function."); - Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages.InsufficientSelection = createMessage("Select more than a single identifier."); - Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); - Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - })(Messages || (Messages = {})); + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -75278,36 +78885,29 @@ var ts; function getRangeToExtract(sourceFile, span) { var length = span.length; if (length === 0) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, false), sourceFile, span); var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); var declarations = []; var rangeFacts = RangeFacts.None; if (!start || !end) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start.parent !== end.parent) { - var startParent = ts.skipParentheses(start.parent); - var endParent = ts.skipParentheses(end.parent); - if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { - start = end = endParent; - } - else { - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); - } + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start !== end) { if (!isBlockLike(start.parent)) { - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { - var errors = checkNode(statement); - if (errors) { - return { errors: errors }; + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; } statements.push(statement); } @@ -75317,39 +78917,65 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - else { - var errors = checkRootNode(start) || checkNode(start); - if (errors) { - return { errors: errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; + if (ts.isReturnStatement(start) && !start.expression) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - function createErrorResult(sourceFile, start, length, message) { - return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = undefined; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; } function checkRootNode(node) { if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { - return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; } return undefined; } function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 149) { + if (current.kind === 150) { if (ts.hasModifier(current, 32)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 146) { + else if (current.kind === 147) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 152) { + if (ctorOrMethod.kind === 153) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 151) { + else if (current.kind === 152) { if (ts.hasModifier(current, 32)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -75365,11 +78991,11 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; } - if (ts.isInAmbientContext(nodeToCheck)) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + if (nodeToCheck.flags & 2097152) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; } var containingClass = ts.getContainingClass(nodeToCheck); if (containingClass) { @@ -75385,22 +79011,22 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 226) ? node.parent.parent : node; + var declaringNode = (node.kind === 227) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } declarations.push(node.symbol); } switch (node.kind) { - case 238: - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + case 239: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; case 97: - if (node.parent.kind === 181) { + if (node.parent.kind === 182) { var containingClass_1 = ts.getContainingClass(node); if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; } } @@ -75409,12 +79035,12 @@ var ts; } break; } - if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 228: case 229: - if (node.parent.kind === 265 && node.parent.externalModuleIndicator === undefined) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + case 230: + if (node.parent.kind === 269 && node.parent.externalModuleIndicator === undefined) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } break; } @@ -75422,18 +79048,18 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 211: + case 212: permittedJumps = 0; break; - case 224: + case 225: permittedJumps = 0; break; - case 207: - if (node.parent && node.parent.kind === 224 && node.finallyBlock === node) { + case 208: + if (node.parent && node.parent.kind === 225 && node.parent.finallyBlock === node) { permittedJumps = 4; } break; - case 257: + case 261: permittedJumps |= 1; break; default: @@ -75443,11 +79069,11 @@ var ts; break; } switch (node.kind) { - case 169: + case 170: case 99: rangeFacts |= RangeFacts.UsesThis; break; - case 222: + case 223: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -75455,34 +79081,34 @@ var ts; seenLabels.pop(); break; } + case 219: case 218: - case 217: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } } else { - if (!(permittedJumps & (node.kind === 218 ? 1 : 2))) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + if (!(permittedJumps & (node.kind === 219 ? 1 : 2))) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 191: + case 192: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 197: + case 198: rangeFacts |= RangeFacts.IsGenerator; break; - case 219: + case 220: if (permittedJumps & 4) { rangeFacts |= RangeFacts.HasReturn; } else { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); } break; default: @@ -75493,120 +79119,168 @@ var ts; } } } - extractMethod_1.getRangeToExtract = getRangeToExtract; + extractSymbol_1.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; } - else if (ts.isPartOfExpression(node)) { + else if (ts.isExpressionNode(node)) { return ts.isExpressionStatement(node.parent) ? [node.parent] : node; } return undefined; } - function isValidExtractionTarget(node) { - return (node.kind === 228) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); } function collectEnclosingScopes(range) { - var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; if (range.facts & RangeFacts.UsesThis) { var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { - if (current !== start && isValidExtractionTarget(current)) { - (scopes = scopes || []).push(current); - } - if (current && current.parent && current.parent.kind === 146) { - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; + var scopes = []; + while (true) { + current = current.parent; + if (current.kind === 147) { + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 269) { + return scopes; + } } } - return scopes; } - function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; - ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); } - extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; function getPossibleExtractions(targetRange, context) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; - return scopes.map(function (scope, i) { - return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; }); + return extractions; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; } - function getDescriptionForScope(scope) { + function getDescriptionForFunctionInScope(scope) { return ts.isFunctionLikeDeclaration(scope) - ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + ? "inner function" : ts.isClassLike(scope) - ? "method in " + getDescriptionForClassLikeDeclaration(scope) - : "function in " + getDescriptionForModuleLikeDeclaration(scope); + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 152: + case 153: return "constructor"; - case 186: + case 187: return scope.name ? "function expression '" + scope.name.text + "'" : "anonymous function expression"; - case 228: + case 229: return "function '" + scope.name.text + "'"; - case 187: + case 188: return "arrow function"; - case 151: + case 152: return "method '" + scope.name.getText(); - case 153: - return "'get " + scope.name.getText() + "'"; case 154: + return "'get " + scope.name.getText() + "'"; + case 155: return "'set " + scope.name.getText() + "'"; default: ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 229 + return scope.kind === 230 ? "class '" + scope.name.text + "'" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 234 + return scope.kind === 235 ? "namespace '" + scope.parent.name.getText() + "'" - : scope.externalModuleIndicator ? "module scope" : "global scope"; + : scope.externalModuleIndicator ? 0 : 1; } - function getUniqueName(fileText) { - var functionNameText = "newFunction"; - for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { - functionNameText = "newFunction_" + i; + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + function getUniqueName(baseName, fileText) { + var nameText = baseName; + for (var i = 1; ts.stringContains(fileText, nameText); i++) { + nameText = baseName + "_" + i; } - return functionNameText; + return nameText; } - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); var file = scope.getSourceFile(); - var functionNameText = getUniqueName(file.text); + var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType = undefined; @@ -75618,7 +79292,7 @@ var ts; if (!isJS) { var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); } var paramDecl = ts.createParameter(undefined, undefined, undefined, name, undefined, typeNode); parameters.push(paramDecl); @@ -75637,9 +79311,10 @@ var ts; : undefined; if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { var modifiers = isJS ? [] : [ts.createToken(112)]; @@ -75655,13 +79330,16 @@ var ts; newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; - var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; var called = getCalledExpression(scope, range, functionNameText); @@ -75672,27 +79350,60 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), ts.getSynthesizedDeepClone(variableDeclaration.type), call)], variableDeclaration.parent.flags))); + } + else { + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement(undefined, undefined, ts.getSynthesizedDeepClone(variableDeclaration.name))); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature(undefined, variableDeclaration.symbol.name, undefined, variableType, undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1); + } + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), typeLiteral, call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2) { + flags = (flags & ~2) | 1; + } + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { - newNodes.push(ts.createVariableStatement(undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119))])); + newNodes.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -75709,37 +79420,132 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter - }); + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139)]); + } + } + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + var file = scope.getSourceFile(); + var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var isJS = ts.isInJavaScriptFile(scope); + var variableType = isJS + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); + var modifiers = []; + modifiers.push(ts.createToken(112)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115)); + } + modifiers.push(ts.createToken(131)); + var newVariable = ts.createProperty(undefined, modifiers, localNameText, undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) + : ts.createThis(), ts.createIdentifier(localNameText)); + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + else if (node.parent.kind === 211 && scope === ts.findAncestor(node, isScope)) { + var newVariableStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2)); + changeTracker.replaceRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2)); + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + var insertionPos = ts.getSourceFileImportLocation(file); + changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { + prefix: insertionPos === 0 ? undefined : context.newLineCharacter, + suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter + }); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + if (node.parent.kind === 211) { + changeTracker.deleteRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + } } var edits = changeTracker.getChanges(); - var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; - var renameFilename = renameRange.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, localNameText, true); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function getRenameLocation(edits, renameFilename, functionNameText) { + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode = undefined; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getRenameLocation(edits, renameFilename, functionNameText, isDeclaredBeforeUse) { var delta = 0; + var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { var change = textChanges_2[_b]; - var span_17 = change.span, newText = change.newText; + var span_15 = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - return span_17.start + delta + index; + lastPos = span_15.start + delta + index; + if (!isDeclaredBeforeUse) { + return lastPos; + } } - delta += newText.length - span_17.length; + delta += newText.length - span_15.length; } } - throw new Error(); + ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(lastPos >= 0); + return lastPos; } function getFirstDeclaration(type) { var firstDeclaration = undefined; @@ -75757,27 +79563,9 @@ var ts; function compareTypesByDeclarationOrder(_a, _b) { var type1 = _a.type, declaration1 = _a.declaration; var type2 = _b.type, declaration2 = _b.declaration; - if (declaration1) { - if (declaration2) { - var positionDiff = declaration1.pos - declaration2.pos; - if (positionDiff !== 0) { - return positionDiff; - } - } - else { - return 1; - } - } - else if (declaration2) { - return -1; - } - var name1 = type1.symbol ? type1.symbol.getName() : ""; - var name2 = type2.symbol ? type2.symbol.getName() : ""; - var nameDiff = ts.compareStrings(name1, name2); - if (nameDiff !== 0) { - return nameDiff; - } - return type1.id - type2.id; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); } function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); @@ -75789,17 +79577,18 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -75813,8 +79602,8 @@ var ts; return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 220 && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -75830,16 +79619,25 @@ var ts; } else { var oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } } } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } function getStatementsOrClassElements(scope) { - if (ts.isFunctionLike(scope)) { + if (ts.isFunctionLikeDeclaration(scope)) { var body = scope.body; if (ts.isBlock(body)) { return body.statements; @@ -75856,20 +79654,74 @@ var ts; } return ts.emptyArray; } - function getNodeToInsertBefore(minPos, scope) { + function getNodeToInsertFunctionBefore(minPos, scope) { return ts.find(getStatementsOrClassElements(scope), function (child) { - return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); }); } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); + var prevMember = undefined; + var allProperties = true; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + ts.Debug.assert(prevMember !== undefined); + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope = undefined; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = undefined; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + ts.Debug.assert(prevStatement !== undefined); + return prevStatement; + } + if (curr === scope) { + ts.Debug.fail("Didn't encounter a block-like before encountering scope"); + break; + } + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); } function getEnclosingTextRange(targetRange, sourceFile) { return isReadonlyArray(targetRange.range) - ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } : targetRange.range; } var Usage; @@ -75881,18 +79733,49 @@ var ts; var allTypeParameterUsages = ts.createMap(); var usagesPerScope = []; var substitutionsPerScope = []; - var errorsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic = undefined; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (2048 | 16384)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { - var _ = scopes_1[_i]; + var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - errorsPerScope.push([]); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 229 + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); - var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); if (inGenericContext && !isReadonlyArray(targetRange.range)) { @@ -75921,7 +79804,18 @@ var ts; } ts.Debug.assert(i_1 === scopes.length); } - var _loop_8 = function (i) { + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_10 = function (i) { + var scopeUsages = usagesPerScope[i]; + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } var hasWrite = false; var readonlyClassPropertyWrite = undefined; usagesPerScope[i].usages.forEach(function (value) { @@ -75934,20 +79828,27 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } }; for (var i = 0; i < scopes.length; i++) { - _loop_8(i); - } - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + _loop_10(i); } - return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -75966,7 +79867,7 @@ var ts; var visitedTypes = symbolWalker.walkType(type).visitedTypes; for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { var visitedType = visitedTypes_1[_i]; - if (visitedType.flags & 16384) { + if (visitedType.flags & 32768) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); } } @@ -75978,7 +79879,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { collectUsages(node.left, 2); @@ -76010,17 +79911,15 @@ var ts; var symbolId = recordUsagebySymbol(n, usage, isTypeNode); if (symbolId) { for (var i = 0; i < scopes.length; i++) { - var substitition = substitutionsPerScope[i].get(symbolId); - if (substitition) { - usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); } } } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { return undefined; } @@ -76048,9 +79947,14 @@ var ts; return undefined; } if (targetRange.facts & RangeFacts.IsGenerator && usage === 2) { - for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { - var errors = errorsPerScope_1[_a]; - errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); } } for (var i = 0; i < scopes.length; i++) { @@ -76066,7 +79970,9 @@ var ts; } else if (isTypeName) { if (!(symbol.flags & 262144)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } } else { @@ -76080,17 +79986,30 @@ var ts; if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { return; } - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { - var scope = errorsPerScope_2[_i]; - scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + function getSymbolReferencedByIdentifier(identifier) { + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { @@ -76103,7 +80022,9 @@ var ts; if (prefix === undefined) { return undefined; } - return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -76122,47 +80043,202 @@ var ts; } function isExtractableExpression(node) { switch (node.parent.kind) { - case 264: + case 268: return false; } switch (node.kind) { case 9: - return node.parent.kind !== 238 && - node.parent.kind !== 242; - case 198: - case 174: - case 176: + return node.parent.kind !== 239 && + node.parent.kind !== 243; + case 199: + case 175: + case 177: return false; case 71: - return node.parent.kind !== 176 && - node.parent.kind !== 242 && - node.parent.kind !== 246; + return node.parent.kind !== 177 && + node.parent.kind !== 243 && + node.parent.kind !== 247; } return true; } function isBlockLike(node) { switch (node.kind) { - case 207: - case 265: - case 234: - case 257: + case 208: + case 269: + case 235: + case 261: return true; default: return false; } } - })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; (function (ts) { - ts.servicesVersion = "0.5"; - var ruleProvider; + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, false); + if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) { + return undefined; + } + var resolvedTo = ts.getResolvedModule(file, node.text); + if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) { + return undefined; + } + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text); + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 239: + case 249: + return true; + default: + return false; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage) { + var actionName = "Convert to default import"; + var useDefaultImport = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(useDefaultImport); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition, program = context.program; + if (!program.getCompilerOptions().allowSyntheticDefaultImports) { + return undefined; + } + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); + var resolvedFile = program.getSourceFile(module.resolvedFileName); + if (!(resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { + return undefined; + } + return [ + { + name: useDefaultImport.name, + description: useDefaultImport.description, + actions: [ + { + description: useDefaultImport.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + var file = context.file, startPosition = context.startPosition; + ts.Debug.assertEqual(actionName, _actionName); + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier; + var newImportClause = ts.createImportClause(name, undefined); + var newImportStatement = ts.createImportDeclaration(undefined, undefined, newImportClause, moduleSpecifier); + return { + edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }), + renameFilename: undefined, + renameLocation: undefined, + }; + } + function getConvertibleImportAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition, false); + while (true) { + switch (node.kind) { + case 238: + var eq = node; + var moduleReference = eq.moduleReference; + return moduleReference.kind === 249 && ts.isStringLiteral(moduleReference.expression) + ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } + : undefined; + case 239: + var d = node; + var importClause = d.importClause; + return !importClause.name && importClause.namedBindings.kind === 241 && ts.isStringLiteral(d.moduleSpecifier) + ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier } + : undefined; + case 241: + case 249: + case 91: + case 71: + case 9: + case 39: + break; + default: + return undefined; + } + node = node.parent; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.servicesVersion = "0.7"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; + node.flags = parent.flags & 6387712; return node; } var NodeObject = (function () { @@ -76174,31 +80250,42 @@ var ts; this.parent = undefined; this.kind = kind; } + NodeObject.prototype.assertHasRealPosition = function (message) { + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); }; NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); }; NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); return this.pos; }; NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); return this.end; }; NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getStart(sourceFile) - this.pos; }; NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); if (!sourceFile) { sourceFile = this.getSourceFile(); } @@ -76220,7 +80307,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286, nodes.pos, nodes.end, this); + var list = createNode(290, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -76243,9 +80330,9 @@ var ts; return; } if (ts.isJSDocCommentContainingNode(this)) { - var children_3 = []; - this.forEachChild(function (child) { children_3.push(child); }); - this._children = children_3; + var children_4 = []; + this.forEachChild(function (child) { children_4.push(child); }); + this._children = children_4; return; } var children = []; @@ -76278,37 +80365,42 @@ var ts; this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children.length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children[index]; }; NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); if (!this._children) this.createChildren(sourceFile); return this._children; }; NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 || kid.kind > 285; }); - return child.kind < 143 ? + var child = ts.find(children, function (kid) { return kid.kind < 271 || kid.kind > 289; }); + return child.kind < 144 ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); var child = ts.lastOrUndefined(children); if (!child) { return undefined; } - return child.kind < 143 ? child : child.getLastToken(sourceFile); + return child.kind < 144 ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -76347,7 +80439,10 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; @@ -76379,7 +80474,7 @@ var ts; }; Object.defineProperty(SymbolObject.prototype, "name", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedName); + return ts.symbolName(this); }, enumerable: true, configurable: true @@ -76393,9 +80488,29 @@ var ts; SymbolObject.prototype.getDeclarations = function () { return this.declarations; }; - SymbolObject.prototype.getDocumentationComment = function () { + SymbolObject.prototype.getDocumentationComment = function (checker) { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.declarations) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.documentationComment.length === 0 || this.declarations.some(hasJSDocInheritDocTag)) { + if (checker) { + for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); + if (inheritedDocs.length > 0) { + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + break; + } + } + } + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -76423,7 +80538,7 @@ var ts; } Object.defineProperty(IdentifierObject.prototype, "text", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedText); + return ts.idText(this); }, enumerable: true, configurable: true @@ -76464,13 +80579,19 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & 32768 && this.objectFlags & (1 | 2) + return this.flags & 65536 && this.objectFlags & (1 | 2) ? this.checker.getBaseTypes(this) : undefined; }; TypeObject.prototype.getNonNullableType = function () { return this.checker.getNonNullableType(this); }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; return TypeObject; }()); var SignatureObject = (function () { @@ -76491,7 +80612,19 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; + if (this.declaration) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]); + if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { + var inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -76503,6 +80636,37 @@ var ts; }; return SignatureObject; }()); + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + var foundDocs = false; + return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + if (foundDocs) { + return ts.emptyArray; + } + var superType = typeChecker.getTypeAtLocation(superTypeNode); + if (!superType) { + return ts.emptyArray; + } + var baseProperty = typeChecker.getPropertyOfType(superType, propertyName); + if (!baseProperty) { + return ts.emptyArray; + } + var inheritedDocs = baseProperty.getDocumentationComment(typeChecker); + foundDocs = inheritedDocs.length > 0; + return inheritedDocs; + }); + } + function getAllSuperTypeNodes(declaration) { + var container = declaration.parent; + if (!container || (!ts.isClassDeclaration(container) && !ts.isInterfaceDeclaration(container))) { + return ts.emptyArray; + } + var extended = ts.getClassExtendsHeritageClauseElement(container); + var types = extended ? [extended] : ts.emptyArray; + return ts.isClassLike(container) ? ts.concatenate(types, ts.getClassImplementsHeritageClauseElements(container)) : types; + } var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -76559,13 +80723,13 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_9 = ts.getTextOfIdentifierOrLiteral(name); - if (result_9 !== undefined) { - return result_9; + var result_8 = ts.getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (name.kind === 144) { + if (name.kind === 145) { var expr = name.expression; - if (expr.kind === 179) { + if (expr.kind === 180) { return expr.name.text; } return ts.getTextOfIdentifierOrLiteral(expr); @@ -76575,10 +80739,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 228: - case 186: + case 229: + case 187: + case 152: case 151: - case 150: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -76595,29 +80759,29 @@ var ts; } ts.forEachChild(node, visit); break; - case 229: - case 199: case 230: + case 200: case 231: case 232: case 233: - case 237: - case 246: - case 242: - case 239: + case 234: + case 238: + case 247: + case 243: case 240: - case 153: + case 241: case 154: - case 163: + case 155: + case 164: addDeclaration(node); ts.forEachChild(node, visit); break; - case 146: + case 147: if (!ts.hasModifier(node, 92)) { break; } - case 226: - case 176: { + case 227: + case 177: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -76627,24 +80791,24 @@ var ts; visit(decl.initializer); } } - case 264: + case 268: + case 150: case 149: - case 148: addDeclaration(node); break; - case 244: + case 245: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 238: + case 239: var importClause = node.importClause; if (importClause) { if (importClause.name) { addDeclaration(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { + if (importClause.namedBindings.kind === 241) { addDeclaration(importClause.namedBindings); } else { @@ -76653,7 +80817,7 @@ var ts; } } break; - case 194: + case 195: if (ts.getSpecialPropertyAssignmentKind(node) !== 0) { addDeclaration(node); } @@ -76755,35 +80919,34 @@ var ts; scriptKind: ts.getScriptKind(fileName, this.host) }; } + else { + entry = fileName; + } this.fileNameToEntry.set(path, entry); return entry; }; HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.containsEntryByPath = function (path) { - return this.fileNameToEntry.has(path); + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.containsEntryByPath(path) - ? this.getEntryByPath(path) - : this.createEntry(fileName, path); + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - var fileNames = []; - this.fileNameToEntry.forEach(function (value) { - if (value) { - fileNames.push(value.hostFileName); - } + return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { + return ts.isString(entry) ? entry : entry.hostFileName; }); - return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.scriptSnapshot; }; return HostCache; @@ -76801,7 +80964,7 @@ var ts; var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5, version, true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6, version, true, scriptKind); } else if (this.currentFileVersion !== version) { var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); @@ -76908,7 +81071,6 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -76931,15 +81093,11 @@ var ts; } return sourceFile; } - function getRuleProvider(options) { - ruleProvider.ensureUpToDate(options); - return ruleProvider; - } function synchronizeHostData() { if (host.getProjectVersion) { var hostProjectVersion = host.getProjectVersion(); if (hostProjectVersion) { - if (lastProjectVersion === hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { return; } lastProjectVersion = hostProjectVersion; @@ -76952,42 +81110,28 @@ var ts; lastTypesRootVersion = typeRootsVersion; } var hostCache = new HostCache(host, getCanonicalFileName); - if (programUpToDate()) { + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { return; } - var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var shouldCreateNewSourceFiles = oldSettings && - (oldSettings.target !== newSettings.target || - oldSettings.module !== newSettings.module || - oldSettings.moduleResolution !== newSettings.moduleResolution || - oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || - oldSettings.baseUrl !== newSettings.baseUrl || - !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: function (fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - return hostCache.containsEntryByPath(path) ? - !!hostCache.getEntryByPath(path) : - (host.fileExists && host.fileExists(fileName)); - }, + fileExists: fileExists, readFile: function (fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - if (hostCache.containsEntryByPath(path)) { - var entry = hostCache.getEntryByPath(path); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var entry = hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); } return host.readFile && host.readFile(fileName); }, @@ -76996,13 +81140,16 @@ var ts; }, getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; - } + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames }; if (host.trace) { compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; } if (host.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { @@ -77010,31 +81157,31 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - var newProgram = ts.createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program); - if (program) { - var oldSourceFiles = program.getSourceFiles(); - var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { - var oldSourceFile = oldSourceFiles_2[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); - } - } - } + program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); hostCache = undefined; - program = newProgram; program.getTypeChecker(); return; - function getOrCreateSourceFile(fileName) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (host.fileExists && host.fileExists(fileName)); + } + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path) { + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { ts.Debug.assert(hostCache !== undefined); var hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path); if (!hostFileInformation) { return undefined; } - if (!shouldCreateNewSourceFiles) { + if (!shouldCreateNewSourceFile) { var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); @@ -77043,37 +81190,6 @@ var ts; } return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } - function sourceFileUpToDate(sourceFile) { - if (!sourceFile) { - return false; - } - var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile.version === hostCache.getVersion(path); - } - function programUpToDate() { - if (!program) { - return false; - } - var rootFileNames = hostCache.getRootFileNames(); - if (program.getSourceFiles().length !== rootFileNames.length) { - return false; - } - for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { - var fileName = rootFileNames_2[_i]; - if (!sourceFileUpToDate(program.getSourceFile(fileName))) { - return false; - } - } - var currentOptions = program.getCompilerOptions(); - var newOptions = hostCache.compilationSettings(); - if (!ts.compareDataObjects(currentOptions, newOptions)) { - return false; - } - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } - return true; - } } function getProgram() { synchronizeHostData(); @@ -77109,17 +81225,18 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - function getCompletionsAtPosition(fileName, position) { + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = { includeExternalModuleExports: false }; } synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } - function getCompletionEntrySymbol(fileName, position, entryName) { + function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -77136,10 +81253,10 @@ var ts; if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { case 71: - case 179: - case 143: + case 180: + case 144: case 99: - case 169: + case 170: case 97: var type = typeChecker.getTypeAtLocation(node); if (type) { @@ -77148,7 +81265,7 @@ var ts; kindModifiers: "", textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } @@ -77183,6 +81300,10 @@ var ts; synchronizeHostData(); return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); @@ -77262,16 +81383,8 @@ var ts; function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var outputFiles = []; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { - outputFiles: outputFiles, - emitSkipped: emitOutput.emitSkipped - }; + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } function getSignatureHelpItems(fileName, position) { synchronizeHostData(); @@ -77291,15 +81404,15 @@ var ts; return; } switch (node.kind) { - case 179: - case 143: + case 180: + case 144: case 9: case 86: case 101: case 95: case 97: case 99: - case 169: + case 170: case 71: break; default: @@ -77311,7 +81424,7 @@ var ts; nodeForStartPos = nodeForStartPos.parent; } else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 233 && + if (nodeForStartPos.parent.parent.kind === 234 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; } @@ -77415,29 +81528,24 @@ var ts; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsForDocument(fileName, options) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); if (!ts.isInComment(sourceFile, position)) { - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); } } return []; @@ -77447,12 +81555,26 @@ var ts; var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); - var rulesProvider = getRuleProvider(formatOptions); - return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function applyCodeActionCommand(fileName, actionOrUndefined) { + var action = typeof fileName === "string" ? actionOrUndefined : fileName; + return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + } + function applySingleCodeActionCommand(action) { + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -77537,8 +81659,7 @@ var ts; (char >= 48 && char <= 57); } function isNodeModulesFile(path) { - var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, "/node_modules/"); } } function getRenameInfo(fileName, position) { @@ -77554,8 +81675,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), - rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -77584,6 +81706,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, @@ -77608,6 +81731,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -77642,19 +81766,19 @@ var ts; } function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 248 || + node.parent.kind === 249 || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { - case 253: - case 255: - case 261: - case 262: - case 151: - case 153: + case 257: + case 259: + case 265: + case 266: + case 152: case 154: + case 155: return true; } return false; @@ -77663,12 +81787,12 @@ var ts; switch (node.kind) { case 9: case 8: - if (node.parent.kind === 144) { + if (node.parent.kind === 145) { return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } case 71: return isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 178 || node.parent.parent.kind === 254) && + (node.parent.parent.kind === 179 || node.parent.parent.kind === 258) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -77683,20 +81807,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_10 = []; + var result_9 = []; var symbol = type.getProperty(name); - if (type.flags & 65536) { + if (type.flags & 131072) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_10.push(symbol); + result_9.push(symbol); } }); - return result_10; + return result_9; } if (symbol) { - result_10.push(symbol); - return result_10; + result_9.push(symbol); + return result_9; } } return undefined; @@ -77705,7 +81829,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 180 && + node.parent.kind === 181 && node.parent.argumentExpression === node; } function getDefaultLibFilePath(options) { @@ -77909,7 +82033,7 @@ var ts; if (logPerformance) { var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof result === "string") { + if (ts.isString(result)) { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -78054,6 +82178,10 @@ var ts; var _this = this; return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); @@ -78109,13 +82237,16 @@ var ts; return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); }); }; - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options) { var _this = this; @@ -78377,13 +82508,15 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.6"; +var toolsVersion = ts.versionMajorMinor; var ts; (function (ts) { var server; (function (server) { server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; server.EventInitializationFailed = "event::initializationFailed"; @@ -78423,9 +82556,9 @@ var ts; server.emptyArray = createSortedArray(); var Msg; (function (Msg) { - Msg.Err = "Err"; - Msg.Info = "Info"; - Msg.Perf = "Perf"; + Msg["Err"] = "Err"; + Msg["Info"] = "Info"; + Msg["Perf"] = "Perf"; })(Msg = server.Msg || (server.Msg = {})); function getProjectRootPath(project) { switch (project.projectKind) { @@ -78435,14 +82568,14 @@ var ts; return ""; case server.ProjectKind.External: var projectName = ts.normalizeSlashes(project.getProjectName()); - return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + return ts.getDirectoryPath(projectName); } } function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()), - compilerOptions: project.getCompilerOptions(), + compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, projectRootPath: getProjectRootPath(project), @@ -78541,10 +82674,16 @@ var ts; return []; } server.createSortedArray = createSortedArray; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +(function (ts) { + var server; + (function (server) { var ThrottledOperations = (function () { - function ThrottledOperations(host) { + function ThrottledOperations(host, logger) { this.host = host; this.pendingTimeouts = ts.createMap(); + this.logger = logger.hasLevel(server.LogLevel.verbose) && logger; } ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { var pendingTimeout = this.pendingTimeouts.get(operationId); @@ -78552,9 +82691,15 @@ var ts; this.host.clearTimeout(pendingTimeout); } this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); + if (this.logger) { + this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : "")); + } }; ThrottledOperations.run = function (self, operationId, cb) { self.pendingTimeouts.delete(operationId); + if (self.logger) { + self.logger.info("Running: " + operationId); + } cb(); }; return ThrottledOperations; @@ -78574,7 +82719,7 @@ var ts; }; GcTimer.run = function (self) { self.timerId = undefined; - var log = self.logger.hasLevel(LogLevel.requestTime); + var log = self.logger.hasLevel(server.LogLevel.requestTime); var before = log && self.host.getMemoryUsage(); self.host.gc(); if (log) { @@ -78585,17 +82730,17 @@ var ts; return GcTimer; }()); server.GcTimer = GcTimer; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -(function (ts) { - var server; - (function (server) { + function getBaseConfigFileName(configFilePath) { + var base = ts.getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : undefined; + } + server.getBaseConfigFileName = getBaseConfigFileName; function insertSorted(array, insert, compare) { if (array.length === 0) { array.push(insert); return; } - var insertIndex = ts.binarySearch(array, insert, compare); + var insertIndex = ts.binarySearch(array, insert, ts.identity, compare); if (insertIndex < 0) { array.splice(~insertIndex, 0, insert); } @@ -78609,7 +82754,7 @@ var ts; array.splice(0, 1); return; } - var removeIndex = ts.binarySearch(array, remove, compare); + var removeIndex = ts.binarySearch(array, remove, ts.identity, compare); if (removeIndex >= 0) { array.splice(removeIndex, 1); } @@ -78629,8 +82774,7 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } - function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { - compare = compare || ts.compareValues; + function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, comparer) { var newIndex = 0; var oldIndex = 0; var newLen = newItems.length; @@ -78638,7 +82782,7 @@ var ts; while (newIndex < newLen && oldIndex < oldLen) { var newItem = newItems[newIndex]; var oldItem = oldItems[oldIndex]; - var compareResult = compare(newItem, oldItem); + var compareResult = comparer(newItem, oldItem); if (compareResult === -1) { inserted(newItem); newIndex++; @@ -78660,6 +82804,14 @@ var ts; } } server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function indent(str) { + return "\n " + str; + } + server.indent = indent; + function stringifyIndented(json) { + return "\n " + JSON.stringify(json); + } + server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -78679,11 +82831,14 @@ var ts; CommandTypes["Completions"] = "completions"; CommandTypes["CompletionsFull"] = "completions-full"; CommandTypes["CompletionDetails"] = "completionEntryDetails"; + CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full"; CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; CommandTypes["Configure"] = "configure"; CommandTypes["Definition"] = "definition"; CommandTypes["DefinitionFull"] = "definition-full"; + CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; + CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; CommandTypes["Implementation"] = "implementation"; CommandTypes["ImplementationFull"] = "implementation-full"; CommandTypes["Exit"] = "exit"; @@ -78737,6 +82892,7 @@ var ts; CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; @@ -78806,37 +82962,49 @@ var ts; ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshotVersion() : "Text-" + this.textVersion; }; - TextStorage.prototype.hasScriptVersionCache = function () { + TextStorage.prototype.hasScriptVersionCache_TestOnly = function () { return this.svc !== undefined; }; - TextStorage.prototype.useScriptVersionCache = function (newText) { - this.switchToScriptVersionCache(newText); + TextStorage.prototype.useScriptVersionCache_TestOnly = function () { + this.switchToScriptVersionCache(); }; TextStorage.prototype.useText = function (newText) { this.svc = undefined; - this.setText(newText); + this.text = newText; + this.lineMap = undefined; + this.textVersion++; }; TextStorage.prototype.edit = function (start, end, newText) { this.switchToScriptVersionCache().edit(start, end - start, newText); - }; - TextStorage.prototype.reload = function (text) { - if (this.svc) { - this.svc.reload(text); - } - else { - this.setText(text); + this.ownFileText = false; + this.text = undefined; + this.lineMap = undefined; + }; + TextStorage.prototype.reload = function (newText) { + ts.Debug.assert(newText !== undefined); + this.pendingReloadFromDisk = false; + if (this.text !== newText) { + this.useText(newText); + this.ownFileText = false; + return true; } }; - TextStorage.prototype.reloadFromFile = function (tempFileName) { - if (this.svc || (tempFileName !== this.fileName)) { - this.reload(this.getFileText(tempFileName)); - } - else { - this.setText(undefined); + TextStorage.prototype.reloadWithFileText = function (tempFileName) { + var reloaded = this.reload(this.getFileText(tempFileName)); + this.ownFileText = !tempFileName || tempFileName === this.fileName; + return reloaded; + }; + TextStorage.prototype.reloadFromDisk = function () { + if (!this.pendingReloadFromDisk && !this.ownFileText) { + return this.reloadWithFileText(); } + return false; + }; + TextStorage.prototype.delayReloadFromFileIntoText = function () { + this.pendingReloadFromDisk = true; }; TextStorage.prototype.getSnapshot = function () { - return this.svc + return this.useScriptVersionCacheIfValidOrOpen() ? this.svc.getSnapshot() : ts.ScriptSnapshot.fromString(this.getOrLoadText()); }; @@ -78844,7 +83012,7 @@ var ts; return this.switchToScriptVersionCache().getLineInfo(line); }; TextStorage.prototype.lineToTextSpan = function (line) { - if (!this.svc) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { var lineMap = this.getLineMap(); var start = lineMap[line]; var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; @@ -78853,13 +83021,13 @@ var ts; return this.svc.lineToTextSpan(line); }; TextStorage.prototype.lineOffsetToPosition = function (line, offset) { - if (!this.svc) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } return this.svc.lineOffsetToPosition(line, offset); }; TextStorage.prototype.positionToLineOffset = function (position) { - if (!this.svc) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; return { line: line + 1, offset: character + 1 }; } @@ -78868,70 +83036,78 @@ var ts; TextStorage.prototype.getFileText = function (tempFileName) { return this.host.readFile(tempFileName || this.fileName) || ""; }; - TextStorage.prototype.ensureNoScriptVersionCache = function () { - ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); - }; - TextStorage.prototype.switchToScriptVersionCache = function (newText) { - if (!this.svc) { - this.svc = server.ScriptVersionCache.fromString(newText !== undefined ? newText : this.getOrLoadText()); + TextStorage.prototype.switchToScriptVersionCache = function () { + if (!this.svc || this.pendingReloadFromDisk) { + this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText()); this.svcVersion++; - this.text = undefined; } return this.svc; }; + TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () { + if (this.isOpen) { + return this.switchToScriptVersionCache(); + } + return !this.pendingReloadFromDisk && this.svc; + }; TextStorage.prototype.getOrLoadText = function () { - this.ensureNoScriptVersionCache(); - if (this.text === undefined) { - this.setText(this.getFileText()); + if (this.text === undefined || this.pendingReloadFromDisk) { + ts.Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk"); + this.reloadWithFileText(); } return this.text; }; TextStorage.prototype.getLineMap = function () { - this.ensureNoScriptVersionCache(); + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); }; - TextStorage.prototype.setText = function (newText) { - this.ensureNoScriptVersionCache(); - if (newText === undefined || this.text !== newText) { - this.text = newText; - this.lineMap = undefined; - this.textVersion++; - } - }; return TextStorage; }()); server.TextStorage = TextStorage; + function isDynamicFileName(fileName) { + return ts.getBaseFileName(fileName)[0] === "^"; + } + server.isDynamicFileName = isDynamicFileName; var ScriptInfo = (function () { - function ScriptInfo(host, fileName, scriptKind, hasMixedContent, isDynamic) { - if (hasMixedContent === void 0) { hasMixedContent = false; } - if (isDynamic === void 0) { isDynamic = false; } + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path) { this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; this.hasMixedContent = hasMixedContent; - this.isDynamic = isDynamic; + this.path = path; this.containingProjects = []; - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.isDynamic = isDynamicFileName(fileName); this.textStorage = new TextStorage(host, fileName); - if (hasMixedContent || isDynamic) { + if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); } this.scriptKind = scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName); } + ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { + return this.hasMixedContent || this.isDynamic; + }; ScriptInfo.prototype.isScriptOpen = function () { - return this.isOpen; + return this.textStorage.isOpen; }; ScriptInfo.prototype.open = function (newText) { - this.isOpen = true; - this.textStorage.useScriptVersionCache(newText); - this.markContainingProjectsAsDirty(); + this.textStorage.isOpen = true; + if (newText !== undefined && + this.textStorage.reload(newText)) { + this.markContainingProjectsAsDirty(); + } }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - this.textStorage.useText(this.hasMixedContent || this.isDynamic ? "" : undefined); - this.markContainingProjectsAsDirty(); + ScriptInfo.prototype.close = function (fileExists) { + if (fileExists === void 0) { fileExists = true; } + this.textStorage.isOpen = false; + if (this.isDynamicOrHasMixedContent() || !fileExists) { + if (this.textStorage.reload("")) { + this.markContainingProjectsAsDirty(); + } + } + else if (this.textStorage.reloadFromDisk()) { + this.markContainingProjectsAsDirty(); + } }; ScriptInfo.prototype.getSnapshot = function () { return this.textStorage.getSnapshot(); @@ -78979,7 +83155,14 @@ var ts; ScriptInfo.prototype.detachAllProjects = function () { for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; - p.removeFile(this, false); + if (p.projectKind === server.ProjectKind.Configured) { + p.directoryStructureHost.addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + } + var isInfoRoot = p.isRoot(this); + p.removeFile(this, false, false); + if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) { + p.addMissingFileRoot(this.fileName); + } } ts.clear(this.containingProjects); }; @@ -79017,34 +83200,27 @@ var ts; server.mergeMapLikes(this.formatCodeSettings, formatSettings); } }; - ScriptInfo.prototype.setWatcher = function (watcher) { - this.stopWatcher(); - this.fileWatcher = watcher; - }; - ScriptInfo.prototype.stopWatcher = function () { - if (this.fileWatcher) { - this.fileWatcher.close(); - this.fileWatcher = undefined; - } - }; ScriptInfo.prototype.getLatestVersion = function () { return this.textStorage.getVersion(); }; - ScriptInfo.prototype.reload = function (script) { - this.textStorage.reload(script); - this.markContainingProjectsAsDirty(); - }; ScriptInfo.prototype.saveTo = function (fileName) { var snap = this.textStorage.getSnapshot(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; + ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { + ts.Debug.assert(!this.isDynamicOrHasMixedContent()); + this.textStorage.delayReloadFromFileIntoText(); + this.markContainingProjectsAsDirty(); + }; ScriptInfo.prototype.reloadFromFile = function (tempFileName) { - if (this.hasMixedContent || this.isDynamic) { - this.reload(""); + if (this.isDynamicOrHasMixedContent()) { + this.textStorage.reload(""); + this.markContainingProjectsAsDirty(); } else { - this.textStorage.reloadFromFile(tempFileName); - this.markContainingProjectsAsDirty(); + if (this.textStorage.reloadWithFileText(tempFileName)) { + this.markContainingProjectsAsDirty(); + } } }; ScriptInfo.prototype.getLineInfo = function (line) { @@ -79060,6 +83236,9 @@ var ts; p.markAsDirty(); } }; + ScriptInfo.prototype.isOrphan = function () { + return this.containingProjects.length === 0; + }; ScriptInfo.prototype.lineToTextSpan = function (line) { return this.textStorage.lineToTextSpan(line); }; @@ -79079,195 +83258,542 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var server; - (function (server) { - var LSHost = (function () { - function LSHost(host, project, cancellationToken) { - var _this = this; - this.host = host; - this.project = project; - this.cancellationToken = cancellationToken; - this.resolvedModuleNames = ts.createMap(); - this.resolvedTypeReferenceDirectives = ts.createMap(); - this.cancellationToken = new ts.ThrottledCancellationToken(cancellationToken, project.projectService.throttleWaitMilliseconds); - this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - if (host.trace) { - this.trace = function (s) { return host.trace(s); }; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + createNewValue: createMissingFileWatch, + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + createNewValue: createWildcardDirectoryWatcher, + onDeleteValue: closeFileWatcherOf, + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); } - this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { - var globalCache = _this.project.getTypeAcquisition().enable - ? _this.project.projectService.typingsInstaller.globalTypingsCacheLocation - : undefined; - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (!ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { - var _a = ts.loadModuleFromGlobalCache(moduleName, _this.project.getProjectName(), compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; - if (resolvedModule) { - return { resolvedModule: resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; - } + watcher.close(); + } + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution() { + if (allFilesHaveInvalidatedResolution) { + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; } - return primaryResult; - }; - if (this.host.realpath) { - this.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.dispose = function () { - this.project = undefined; - this.resolveModuleName = undefined; - }; - LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { - this.filesWithChangedSetOfUnresolvedImports = []; - }; - LSHost.prototype.finishRecordingFilesWithChangedResolutions = function () { - var collected = this.filesWithChangedSetOfUnresolvedImports; - this.filesWithChangedSetOfUnresolvedImports = undefined; - return collected; - }; - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult, getResultFileName, logChanges) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name = names_2[_i]; - var resolution = newResolutions.get(name); - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile.get(name); - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); } else { - resolution = loader(name, containingFile, compilerOptions, this); - newResolutions.set(name, resolution); - } - if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { - this.filesWithChangedSetOfUnresolvedImports.push(path); - logChanges = false; + watchFailedLookupLocationOfResolution(resolution, 0); } } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + logChanges = false; + } } - cache.set(path, newResolutions); - return resolvedModules; - function resolutionIsEqualTo(oldResolution, newResolution) { - if (oldResolution === newResolution) { - return true; + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, dirPath.charCodeAt(0) === 47 ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + return { dir: rootDir, dirPath: rootPath }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; } - if (!oldResolution || !newResolution) { - return false; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; } - var oldResult = getResult(oldResolution); - var newResult = getResult(newResolution); - if (oldResult === newResult) { - return true; + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); } - if (!oldResult || !newResult) { - return false; + } + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); } - return getResultFileName(oldResult) === getResultFileName(newResult); } - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; + } + } + } + function createDirectoryWatcher(directory, dirPath) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (resolutionHost.getCachedDirectoryStructureHost) { + resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + if (!allFilesHaveInvalidatedResolution && + dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); } - var result = getResult(resolution); - if (result) { - return getResultFileName(result) !== lastDeletedFileName; + } + }, 1); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; } - return resolution.failedLookupLocations.length === 0; + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions(function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; } - }; - LSHost.prototype.getNewLine = function () { - return this.host.newLine; - }; - LSHost.prototype.getProjectVersion = function () { - return this.project.getProjectVersion(); - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.useCaseSensitiveFileNames = function () { - return this.host.useCaseSensitiveFileNames; - }; - LSHost.prototype.getCancellationToken = function () { - return this.cancellationToken; - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }, function (r) { return r.resolvedFileName; }, false); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }, function (r) { return r.resolvedFileName; }, true); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.project.getScriptInfoLSHost(filename); - if (scriptInfo) { - return scriptInfo.getSnapshot(); + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } - }; - LSHost.prototype.getScriptFileNames = function () { - return this.project.getRootFilesLSHost(); - }; - LSHost.prototype.getTypeRootsVersion = function () { - return this.project.typesVersion; - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.project.getScriptInfoLSHost(fileName); - return info && info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - var info = this.project.getScriptInfoLSHost(filename); - return info && info.getLatestVersion(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return this.host.getCurrentDirectory(); - }; - LSHost.prototype.resolvePath = function (path) { - return this.host.resolvePath(path); - }; - LSHost.prototype.fileExists = function (file) { - var path = ts.toPath(file, this.host.getCurrentDirectory(), this.getCanonicalFileName); - return !this.project.isWatchedMissingFile(path) && this.host.fileExists(file); - }; - LSHost.prototype.readFile = function (fileName) { - return this.host.readFile(fileName); - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - return this.host.readDirectory(path, extensions, exclude, include, depth); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.notifyFileRemoved = function (info) { - this.resolvedModuleNames.delete(info.path); - this.resolvedTypeReferenceDirectives.delete(info.path); - }; - LSHost.prototype.setCompilationSettings = function (opt) { - if (ts.changesAffectModuleResolution(this.compilationSettings, opt)) { - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions(hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (resolutionHost.getCachedDirectoryStructureHost) { + resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } - this.compilationSettings = opt; - }; - return LSHost; - }()); - server.LSHost = LSHost; - })(server = ts.server || (ts.server = {})); + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1); + } + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + closeTypeRootsWatch(); + return; + } + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); var ts; (function (ts) { var server; (function (server) { server.nullTypingsInstaller = { + isKnownTypesPackageName: ts.returnFalse, + installPackage: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -79326,6 +83852,12 @@ var ts; this.installer = installer; this.perProjectCache = ts.createMap(); } + TypingsCache.prototype.isKnownTypesPackageName = function (name) { + return this.installer.isKnownTypesPackageName(name); + }; + TypingsCache.prototype.installPackage = function (options) { + return this.installer.installPackage(options); + }; TypingsCache.prototype.getTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -79336,10 +83868,10 @@ var ts; if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || - compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) || + compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { this.perProjectCache.set(project.getProjectName(), { - compilerOptions: project.getCompilerOptions(), + compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, typings: result, unresolvedImports: unresolvedImports, @@ -79371,285 +83903,6 @@ var ts; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; -(function (ts) { - var server; - (function (server) { - function shouldEmitFile(scriptInfo) { - return !scriptInfo.hasMixedContent && !scriptInfo.isDynamic; - } - server.shouldEmitFile = shouldEmitFile; - var BuilderFileInfo = (function () { - function BuilderFileInfo(scriptInfo, project) { - this.scriptInfo = scriptInfo; - this.project = project; - } - BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { - var sourceFile = this.getSourceFile(); - return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); - }; - BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (statement.kind !== 233 || statement.name.kind !== 9) { - return false; - } - } - return true; - }; - BuilderFileInfo.prototype.computeHash = function (text) { - return this.project.projectService.host.createHash(text); - }; - BuilderFileInfo.prototype.getSourceFile = function () { - return this.project.getSourceFile(this.scriptInfo.path); - }; - BuilderFileInfo.prototype.updateShapeSignature = function () { - var sourceFile = this.getSourceFile(); - if (!sourceFile) { - return true; - } - var lastSignature = this.lastCheckedShapeSignature; - if (sourceFile.isDeclarationFile) { - this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); - } - else { - var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); - } - } - return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; - }; - return BuilderFileInfo; - }()); - server.BuilderFileInfo = BuilderFileInfo; - var AbstractBuilder = (function () { - function AbstractBuilder(project, ctor) { - this.project = project; - this.ctor = ctor; - } - AbstractBuilder.prototype.getFileInfos = function () { - return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createMap()); - }; - AbstractBuilder.prototype.hasFileInfos = function () { - return !!this.fileInfos_doNotAccessDirectly; - }; - AbstractBuilder.prototype.clear = function () { - this.fileInfos_doNotAccessDirectly = undefined; - }; - AbstractBuilder.prototype.getFileInfo = function (path) { - return this.getFileInfos().get(path); - }; - AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { - var fileInfo = this.getFileInfo(path); - if (!fileInfo) { - var scriptInfo = this.project.getScriptInfo(path); - fileInfo = new this.ctor(scriptInfo, this.project); - this.setFileInfo(path, fileInfo); - } - return fileInfo; - }; - AbstractBuilder.prototype.getFileInfoPaths = function () { - return ts.arrayFrom(this.getFileInfos().keys()); - }; - AbstractBuilder.prototype.setFileInfo = function (path, info) { - this.getFileInfos().set(path, info); - }; - AbstractBuilder.prototype.removeFileInfo = function (path) { - this.getFileInfos().delete(path); - }; - AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.getFileInfos().forEach(action); - }; - AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { - this.ensureFileInfoIfInProject(scriptInfo); - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo) { - return false; - } - var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; - if (!emitSkipped) { - var projectRootPath = this.project.getProjectRootPath(); - for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { - var outputFile = outputFiles_1[_i]; - var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); - writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); - } - } - return !emitSkipped; - }; - return AbstractBuilder; - }()); - var NonModuleBuilder = (function (_super) { - __extends(NonModuleBuilder, _super); - function NonModuleBuilder(project) { - var _this = _super.call(this, project, BuilderFileInfo) || this; - _this.project = project; - return _this; - } - NonModuleBuilder.prototype.ensureFileInfoIfInProject = function (scriptInfo) { - if (this.project.containsScriptInfo(scriptInfo)) { - this.getOrCreateFileInfo(scriptInfo.path); - } - }; - NonModuleBuilder.prototype.onProjectUpdateGraph = function () { - var _this = this; - if (this.hasFileInfos()) { - this.forEachFileInfo(function (fileInfo) { - if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { - _this.removeFileInfo(fileInfo.scriptInfo.path); - } - }); - } - }; - NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - var info = this.getOrCreateFileInfo(scriptInfo.path); - var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; - if (info.updateShapeSignature()) { - var options = this.project.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return singleFileResult; - } - return this.project.getAllEmittableFiles(); - } - return singleFileResult; - }; - return NonModuleBuilder; - }(AbstractBuilder)); - var ModuleBuilderFileInfo = (function (_super) { - __extends(ModuleBuilderFileInfo, _super); - function ModuleBuilderFileInfo() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.references = server.createSortedArray(); - _this.referencedBy = server.createSortedArray(); - return _this; - } - ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { - return ts.compareStrings(lf.scriptInfo.fileName, rf.scriptInfo.fileName); - }; - ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { - server.insertSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - }; - ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { - server.removeSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - }; - ModuleBuilderFileInfo.prototype.removeFileReferences = function () { - for (var _i = 0, _a = this.references; _i < _a.length; _i++) { - var reference = _a[_i]; - reference.removeReferencedBy(this); - } - ts.clear(this.references); - }; - return ModuleBuilderFileInfo; - }(BuilderFileInfo)); - var ModuleBuilder = (function (_super) { - __extends(ModuleBuilder, _super); - function ModuleBuilder(project) { - var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; - _this.project = project; - return _this; - } - ModuleBuilder.prototype.clear = function () { - this.projectVersionForDependencyGraph = undefined; - _super.prototype.clear.call(this); - }; - ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { - var _this = this; - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return server.createSortedArray(); - } - var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); - return server.toSortedArray(referencedFilePaths.map(function (f) { return _this.getOrCreateFileInfo(f); }), ModuleBuilderFileInfo.compareFileInfos); - }; - ModuleBuilder.prototype.ensureFileInfoIfInProject = function (_scriptInfo) { - this.ensureProjectDependencyGraphUpToDate(); - }; - ModuleBuilder.prototype.onProjectUpdateGraph = function () { - if (this.hasFileInfos()) { - this.ensureProjectDependencyGraphUpToDate(); - } - }; - ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { - var _this = this; - if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { - var currentScriptInfos = this.project.getScriptInfos(); - for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { - var scriptInfo = currentScriptInfos_1[_i]; - var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); - this.updateFileReferences(fileInfo); - } - this.forEachFileInfo(function (fileInfo) { - if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { - fileInfo.removeFileReferences(); - _this.removeFileInfo(fileInfo.scriptInfo.path); - } - }); - this.projectVersionForDependencyGraph = this.project.getProjectVersion(); - } - }; - ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { - if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { - return; - } - var newReferences = this.getReferencedFileInfos(fileInfo); - var oldReferences = fileInfo.references; - server.enumerateInsertsAndDeletes(newReferences, oldReferences, function (newReference) { return newReference.addReferencedBy(fileInfo); }, function (oldReference) { - oldReference.removeReferencedBy(fileInfo); - }, ModuleBuilderFileInfo.compareFileInfos); - fileInfo.references = newReferences; - fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); - }; - ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - this.ensureProjectDependencyGraphUpToDate(); - var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo || !fileInfo.updateShapeSignature()) { - return singleFileResult; - } - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return this.project.getAllEmittableFiles(); - } - var options = this.project.getCompilerOptions(); - if (options && (options.isolatedModules || options.out || options.outFile)) { - return singleFileResult; - } - var queue = fileInfo.referencedBy.slice(0); - var fileNameSet = ts.createMap(); - fileNameSet.set(scriptInfo.fileName, scriptInfo); - while (queue.length > 0) { - var processingFileInfo = queue.pop(); - if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { - for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { - var potentialFileInfo = _a[_i]; - if (!fileNameSet.has(potentialFileInfo.scriptInfo.fileName)) { - queue.push(potentialFileInfo); - } - } - } - fileNameSet.set(processingFileInfo.scriptInfo.fileName, processingFileInfo.scriptInfo); - } - var result = []; - fileNameSet.forEach(function (scriptInfo, fileName) { - if (shouldEmitFile(scriptInfo)) { - result.push(fileName); - } - }); - return result; - }; - return ModuleBuilder; - }(AbstractBuilder)); - function createBuilder(project) { - var moduleKind = project.getCompilerOptions().module; - switch (moduleKind) { - case ts.ModuleKind.None: - return new NonModuleBuilder(project); - default: - return new ModuleBuilder(project); - } - } - server.createBuilder = createBuilder; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; (function (ts) { var server; (function (server) { @@ -79697,6 +83950,10 @@ var ts; return counts.ts === 0 && counts.tsx === 0; } server.allFilesAreJsOrDts = allFilesAreJsOrDts; + function hasNoTypeScriptSource(fileNames) { + return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts") && !ts.fileExtensionIs(fileName, ".d.ts")) || ts.fileExtensionIs(fileName, ".tsx"); }); + } + server.hasNoTypeScriptSource = hasNoTypeScriptSource; var UnresolvedImportsMap = (function () { function UnresolvedImportsMap() { this.perFileMap = ts.createMap(); @@ -79723,23 +83980,29 @@ var ts; return UnresolvedImportsMap; }()); server.UnresolvedImportsMap = UnresolvedImportsMap; + function isScriptInfo(value) { + return value instanceof server.ScriptInfo; + } + server.isScriptInfo = isScriptInfo; var Project = (function () { - function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; + this.directoryStructureHost = directoryStructureHost; this.rootFiles = []; this.rootFilesMap = ts.createMap(); - this.missingFilesMap = ts.createMap(); this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); this.languageServiceEnabled = true; this.lastReportedVersion = 0; this.projectStructureVersion = 0; this.projectStateVersion = 0; - this.typesVersion = 0; + this.hasChangedAutomaticTypeDirectiveNames = false; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); + this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { this.compilerOptions = ts.getDefaultCompilerOptions(); this.compilerOptions.allowNonTsExtensions = true; @@ -79749,13 +84012,18 @@ var ts; this.compilerOptions.allowNonTsExtensions = true; } this.setInternalCompilerOptionsForEmittingJsFiles(); - this.lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); - this.lsHost.setCompilationSettings(this.compilerOptions); - this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); + var host = this.projectService.host; + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + if (host.realpath) { + this.realpath = function (path) { return host.realpath(path); }; + } + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); + this.languageService = ts.createLanguageService(this, this.documentRegistry); if (!languageServiceEnabled) { this.disableLanguageService(); } - this.builder = server.createBuilder(this); this.markAsDirty(); } Project.prototype.isNonTsProject = function () { @@ -79780,16 +84048,137 @@ var ts; } return result.module; }; + Project.prototype.isKnownTypesPackageName = function (name) { + return this.typingsCache.isKnownTypesPackageName(name); + }; + Project.prototype.installPackage = function (options) { + return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); + }; + Object.defineProperty(Project.prototype, "typingsCache", { + get: function () { + return this.projectService.typingsCache; + }, + enumerable: true, + configurable: true + }); + Project.prototype.getCompilationSettings = function () { + return this.compilerOptions; + }; + Project.prototype.getCompilerOptions = function () { + return this.getCompilationSettings(); + }; + Project.prototype.getNewLine = function () { + return this.directoryStructureHost.newLine; + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.getScriptFileNames = function () { + var _this = this; + if (!this.rootFiles) { + return ts.emptyArray; + } + var result; + this.rootFilesMap.forEach(function (value) { + if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) { + (result || (result = [])).push(isScriptInfo(value) ? value.fileName : value); + } + }); + return ts.addRange(result, this.typingFiles) || ts.emptyArray; + }; + Project.prototype.getOrCreateScriptInfoAndAttachToProject = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost); + if (scriptInfo) { + var existingValue = this.rootFilesMap.get(scriptInfo.path); + if (existingValue !== scriptInfo && existingValue !== undefined) { + this.rootFiles.push(scriptInfo); + this.rootFilesMap.set(scriptInfo.path, scriptInfo); + } + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptKind = function (fileName) { + var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); + return info && info.scriptKind; + }; + Project.prototype.getScriptVersion = function (filename) { + var info = this.getOrCreateScriptInfoAndAttachToProject(filename); + return info && info.getLatestVersion(); + }; + Project.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + }; + Project.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + Project.prototype.getCurrentDirectory = function () { + return this.currentDirectory; + }; + Project.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); + }; + Project.prototype.useCaseSensitiveFileNames = function () { + return this.directoryStructureHost.useCaseSensitiveFileNames; + }; + Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); + }; + Project.prototype.readFile = function (fileName) { + return this.directoryStructureHost.readFile(fileName); + }; + Project.prototype.fileExists = function (file) { + var path = this.toPath(file); + return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); + }; + Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, true); + }; + Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); + }; + Project.prototype.directoryExists = function (path) { + return this.directoryStructureHost.directoryExists(path); + }; + Project.prototype.getDirectories = function (path) { + return this.directoryStructureHost.getDirectories(path); + }; + Project.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); + }; + Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { + return this.projectService.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution", this); + }; + Project.prototype.onInvalidatedResolution = function () { + this.projectService.delayUpdateProjectGraphAndInferredProjectsRefresh(this); + }; + Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { + return this.projectService.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory", this); + }; + Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { + this.hasChangedAutomaticTypeDirectiveNames = true; + this.projectService.delayUpdateProjectGraphAndInferredProjectsRefresh(this); + }; + Project.prototype.getGlobalCache = function () { + return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; + }; + Project.prototype.writeLog = function (s) { + this.projectService.logger.info(s); + }; Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () { if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { this.compilerOptions.noEmitForJsFiles = true; } }; Project.prototype.getGlobalProjectErrors = function () { - return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }); + return server.emptyArray; }; Project.prototype.getAllProjectErrors = function () { - return this.projectErrors; + return server.emptyArray; }; Project.prototype.getLanguageService = function (ensureSynchronized) { if (ensureSynchronized === void 0) { ensureSynchronized = true; } @@ -79798,15 +84187,40 @@ var ts; } return this.languageService; }; + Project.prototype.ensureBuilder = function () { + var _this = this; + if (!this.builder) { + this.builder = ts.createBuilder({ + getCanonicalFileName: this.projectService.toCanonicalFileName, + computeHash: function (data) { return _this.projectService.host.createHash(data); } + }); + } + }; + Project.prototype.shouldEmitFile = function (scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); + }; Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + var _this = this; if (!this.languageServiceEnabled) { return []; } this.updateGraph(); - return this.builder.getFilesAffectedBy(scriptInfo); + this.ensureBuilder(); + return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; - Project.prototype.getProjectVersion = function () { - return this.projectStateVersion.toString(); + Project.prototype.emitFile = function (scriptInfo, writeFile) { + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return false; + } + var _a = this.getLanguageService(false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; }; Project.prototype.enableLanguageService = function () { if (this.languageServiceEnabled) { @@ -79821,6 +84235,7 @@ var ts; } this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; + this.resolutionCache.closeTypeRootsWatch(); this.projectService.onUpdateLanguageServiceStateForProject(this, false); }; Project.prototype.getProjectName = function () { @@ -79835,40 +84250,43 @@ var ts; } return this.program.getSourceFileByPath(path); }; - Project.prototype.updateTypes = function () { - this.typesVersion++; - this.markAsDirty(); - this.updateGraph(); - }; Project.prototype.close = function () { + var _this = this; if (this.program) { for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; - var info = this.projectService.getScriptInfo(f.fileName); - info.detachFromProject(this); + this.detachScriptInfoIfNotRoot(f.fileName); } } - if (!this.program || !this.languageServiceEnabled) { - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; - root.detachFromProject(this); - } + ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); } this.rootFiles = undefined; this.rootFilesMap = undefined; + this.externalFiles = undefined; this.program = undefined; this.builder = undefined; + this.resolutionCache.clear(); + this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; - this.projectErrors = undefined; - this.lsHost.dispose(); - this.lsHost = undefined; - this.missingFilesMap.forEach(function (fileWatcher) { return fileWatcher.close(); }); - this.missingFilesMap = undefined; + this.directoryStructureHost = undefined; + if (this.missingFilesMap) { + ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); + this.missingFilesMap = undefined; + } this.languageService.dispose(); this.languageService = undefined; }; - Project.prototype.getCompilerOptions = function () { - return this.compilerOptions; + Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { + var info = this.projectService.getScriptInfo(uncheckedFilename); + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + }; + Project.prototype.isClosed = function () { + return this.rootFiles === undefined; }; Project.prototype.hasRoots = function () { return this.rootFiles && this.rootFiles.length > 0; @@ -79876,23 +84294,8 @@ var ts; Project.prototype.getRootFiles = function () { return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); }; - Project.prototype.getRootFilesLSHost = function () { - var result = []; - if (this.rootFiles) { - for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { - var f = _a[_i]; - if (this.languageServiceEnabled || f.isScriptOpen()) { - result.push(f.fileName); - } - } - if (this.typingFiles) { - for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { - var f = _c[_b]; - result.push(f); - } - } - } - return result; + Project.prototype.getRootFilesMap = function () { + return this.rootFilesMap; }; Project.prototype.getRootScriptInfos = function () { return this.rootFiles; @@ -79905,17 +84308,11 @@ var ts; return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { - ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."); } return scriptInfo; }); }; - Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { - if (!this.languageServiceEnabled) { - return undefined; - } - return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); - }; Project.prototype.getExcludedFiles = function () { return server.emptyArray; }; @@ -79974,47 +84371,40 @@ var ts; } return false; }; - Project.prototype.getAllEmittableFiles = function () { - if (!this.languageServiceEnabled) { - return []; - } - var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); - var infos = this.getScriptInfos(); - var result = []; - for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { - var info = infos_2[_i]; - if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { - result.push(info.fileName); - } - } - return result; - }; Project.prototype.containsScriptInfo = function (info) { return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); }; Project.prototype.containsFile = function (filename, requireOpen) { - var info = this.projectService.getScriptInfoForNormalizedPath(filename); + var info = this.projectService.getScriptInfoForPath(this.toPath(filename)); if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } }; Project.prototype.isRoot = function (info) { - return this.rootFilesMap && this.rootFilesMap.has(info.path); + return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; }; Project.prototype.addRoot = function (info) { - if (!this.isRoot(info)) { - this.rootFiles.push(info); - this.rootFilesMap.set(info.path, info); - info.attachToProject(this); - this.markAsDirty(); - } + ts.Debug.assert(!this.isRoot(info)); + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); }; - Project.prototype.removeFile = function (info, detachFromProject) { - if (detachFromProject === void 0) { detachFromProject = true; } + Project.prototype.addMissingFileRoot = function (fileName) { + var path = this.projectService.toPath(fileName); + this.rootFilesMap.set(path, fileName); + this.markAsDirty(); + }; + Project.prototype.removeFile = function (info, fileExists, detachFromProject) { if (this.isRoot(info)) { this.removeRoot(info); } - this.lsHost.notifyFileRemoved(info); + if (fileExists) { + this.resolutionCache.removeResolutionsOfFile(info.path); + } + else { + this.resolutionCache.invalidateResolutionOfFile(info.path); + } this.cachedUnresolvedImportsPerFile.remove(info.path); if (detachFromProject) { info.detachFromProject(this); @@ -80056,9 +84446,9 @@ var ts; this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); }; Project.prototype.updateGraph = function () { - this.lsHost.startRecordingFilesWithChangedResolutions(); + this.resolutionCache.startRecordingFilesWithChangedResolutions(); var hasChanges = this.updateGraphWorker(); - var changedFiles = this.lsHost.finishRecordingFilesWithChangedResolutions() || server.emptyArray; + var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { var file = changedFiles_1[_i]; this.cachedUnresolvedImportsPerFile.remove(file); @@ -80076,11 +84466,15 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } - this.builder.onProjectUpdateGraph(); + if (this.builder) { + this.builder.updateProgram(this.program); + } } else { this.lastCachedUnresolvedImportsList = undefined; - this.builder.clear(); + if (this.builder) { + this.builder.clear(); + } } if (hasChanges) { this.projectStructureVersion++; @@ -80098,8 +84492,15 @@ var ts; Project.prototype.updateGraphWorker = function () { var _this = this; var oldProgram = this.program; + ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); + this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); + var start = ts.timestamp(); + this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); + this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); + this.resolutionCache.finishCachingPerDirectoryResolution(); var hasChanges = !oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2)); + this.hasChangedAutomaticTypeDirectiveNames = false; if (hasChanges) { if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -80107,80 +84508,69 @@ var ts; if (this.program.getSourceFileByPath(f.path)) { continue; } - var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(this); - } + this.detachScriptInfoFromProject(f.fileName); } } - var missingFilePaths = this.program.getMissingFilePaths(); - var missingFilePathsSet_1 = ts.arrayToSet(missingFilePaths); - this.missingFilesMap.forEach(function (fileWatcher, missingFilePath) { - if (!missingFilePathsSet_1.has(missingFilePath)) { - _this.missingFilesMap.delete(missingFilePath); - fileWatcher.close(); - } - }); - var _loop_9 = function (missingFilePath) { - if (!this_1.missingFilesMap.has(missingFilePath)) { - var fileWatcher_1 = this_1.projectService.host.watchFile(missingFilePath, function (_filename, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { - fileWatcher_1.close(); - _this.missingFilesMap.delete(missingFilePath); - _this.markAsDirty(); - _this.updateGraph(); - } - }); - this_1.missingFilesMap.set(missingFilePath, fileWatcher_1); - } - }; - var this_1 = this; - for (var _b = 0, missingFilePaths_1 = missingFilePaths; _b < missingFilePaths_1.length; _b++) { - var missingFilePath = missingFilePaths_1[_b]; - _loop_9(missingFilePath); + ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); + if (this.languageServiceEnabled) { + this.resolutionCache.updateTypeRootsWatch(); } } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, function (inserted) { - var scriptInfo = _this.projectService.getOrCreateScriptInfo(inserted, false); + var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost); scriptInfo.attachToProject(_this); - }, function (removed) { - var scriptInfoToDetach = _this.projectService.getScriptInfo(removed); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(_this); - } - }); + }, function (removed) { return _this.detachScriptInfoFromProject(removed); }, ts.compareStringsCaseSensitive); + var elapsed = ts.timestamp() - start; + this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " structureChanged: " + hasChanges + " Elapsed: " + elapsed + "ms"); return hasChanges; }; - Project.prototype.isWatchedMissingFile = function (path) { - return this.missingFilesMap.has(path); - }; - Project.prototype.getScriptInfoLSHost = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); - if (scriptInfo) { - scriptInfo.attachToProject(this); + Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName) { + var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); } - return scriptInfo; + }; + Project.prototype.addMissingFileWatcher = function (missingFilePath) { + var _this = this; + var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { + if (_this.projectKind === ProjectKind.Configured) { + _this.directoryStructureHost.addOrDeleteFile(fileName, missingFilePath, eventKind); + } + if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { + _this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + _this.projectService.delayUpdateProjectGraphAndInferredProjectsRefresh(_this); + } + }, "Missing file from program", this); + return fileWatcher; + }; + Project.prototype.isWatchedMissingFile = function (path) { + return this.missingFilesMap && this.missingFilesMap.has(path); }; Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); if (scriptInfo && !scriptInfo.isAttached(this)) { return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); } return scriptInfo; }; Project.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + return this.projectService.getScriptInfo(uncheckedFileName); }; - Project.prototype.filesToString = function () { + Project.prototype.filesToString = function (writeProjectFileNames) { if (!this.program) { - return ""; + return "\tFiles (0)\n"; } - var strBuilder = ""; - for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - strBuilder += "\t" + file.fileName + "\n"; + var sourceFiles = this.program.getSourceFiles(); + var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; + if (writeProjectFileNames) { + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var file = sourceFiles_9[_i]; + strBuilder += "\t" + file.fileName + "\n"; + } } return strBuilder; }; @@ -80191,28 +84581,22 @@ var ts; this.cachedUnresolvedImportsPerFile.clear(); this.lastCachedUnresolvedImportsList = undefined; } + var oldOptions = this.compilerOptions; this.compilerOptions = compilerOptions; this.setInternalCompilerOptionsForEmittingJsFiles(); - this.lsHost.setCompilationSettings(compilerOptions); + if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) { + this.resolutionCache.clear(); + } this.markAsDirty(); } }; - Project.prototype.reloadScript = function (filename, tempFileName) { - var script = this.projectService.getScriptInfoForNormalizedPath(filename); - if (script) { - ts.Debug.assert(script.isAttached(this)); - script.reloadFromFile(tempFileName); - return true; - } - return false; - }; Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { this.updateGraph(); var info = { projectName: this.getProjectName(), version: this.projectStructureVersion, isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions(), + options: this.getCompilationSettings(), languageServiceDisabled: !this.languageServiceEnabled }; var updatedFileNames = this.updatedFileNames; @@ -80244,55 +84628,11 @@ var ts; else { var projectFileNames = this.getFileNames(); var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); - this.lastReportedFileNames = ts.arrayToSet(projectFileNames.concat(externalFiles)); + var allFiles = projectFileNames.concat(externalFiles); + this.lastReportedFileNames = ts.arrayToSet(allFiles); this.lastReportedVersion = this.projectStructureVersion; - return { info: info, files: projectFileNames, projectErrors: this.getGlobalProjectErrors() }; - } - }; - Project.prototype.getReferencedFiles = function (path) { - var _this = this; - if (!this.languageServiceEnabled) { - return []; - } - var sourceFile = this.getSourceFile(path); - if (!sourceFile) { - return []; - } - var referencedFiles = ts.createMap(); - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = this.program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = symbol.declarations[0].getSourceFile(); - if (declarationSourceFile) { - referencedFiles.set(declarationSourceFile.path, true); - } - } - } - } - var currentDirectory = ts.getDirectoryPath(path); - var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); - referencedFiles.set(referencedPath, true); - } + return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() }; } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - referencedFiles.set(typeFilePath, true); - }); - } - var allFileNames = ts.arrayFrom(referencedFiles.keys()); - return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); }; Project.prototype.removeRoot = function (info) { ts.orderedRemoveItem(this.rootFiles, info); @@ -80303,11 +84643,10 @@ var ts; server.Project = Project; var InferredProject = (function (_super) { __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath) { - var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false) || this; + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; - _this.directoriesWatchedForTsconfig = []; - _this.projectRootPath = projectRootPath; + _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -80317,7 +84656,7 @@ var ts; } }; InferredProject.prototype.setCompilerOptions = function (options) { - var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilerOptions(); + var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilationSettings(); if (!newOptions) { return; } @@ -80331,32 +84670,30 @@ var ts; _super.prototype.setCompilerOptions.call(this, newOptions); }; InferredProject.prototype.addRoot = function (info) { + ts.Debug.assert(info.isScriptOpen()); + this.projectService.startWatchingConfigFilesForInferredProjectRoot(info, this.projectService.openFiles.get(info.path)); if (!this._isJsInferredProject && info.isJavaScript()) { this.toggleJsInferredProject(true); } _super.prototype.addRoot.call(this, info); }; InferredProject.prototype.removeRoot = function (info) { + this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); + _super.prototype.removeRoot.call(this, info); if (this._isJsInferredProject && info.isJavaScript()) { - if (ts.filter(this.getRootScriptInfos(), function (info) { return info.isJavaScript(); }).length === 0) { + if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) { this.toggleJsInferredProject(false); } } - _super.prototype.removeRoot.call(this, info); }; - InferredProject.prototype.getProjectRootPath = function () { - if (this.projectService.useSingleInferredProject) { - return undefined; - } - var rootFiles = this.getRootFiles(); - return ts.getDirectoryPath(rootFiles[0]); + InferredProject.prototype.isProjectWithSingleRoot = function () { + return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || + this.getRootScriptInfos().length === 1; }; InferredProject.prototype.close = function () { + var _this = this; + ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); }); _super.prototype.close.call(this); - for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - this.projectService.stopWatchingDirectory(directory); - } }; InferredProject.prototype.getTypeAcquisition = function () { return { @@ -80378,27 +84715,42 @@ var ts; server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; - _this.wildcardDirectories = wildcardDirectories; + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.plugins = []; - _this.openRefCount = 0; + _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); return _this; } + ConfiguredProject.prototype.updateGraph = function () { + var reloadLevel = this.pendingReload; + this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return this.projectService.reloadFileNamesOfConfiguredProject(this); + case ts.ConfigFileProgramReloadLevel.Full: + this.projectService.reloadConfiguredProject(this); + return true; + default: + return _super.prototype.updateGraph.call(this); + } + }; + ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { + return this.directoryStructureHost; + }; ConfiguredProject.prototype.getConfigFilePath = function () { - return this.getProjectName(); + return server.asNormalizedPath(this.getProjectName()); }; ConfiguredProject.prototype.enablePlugins = function () { var host = this.projectService.host; - var options = this.getCompilerOptions(); + var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); @@ -80411,18 +84763,18 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_10 = function (globalPluginName) { + var _loop_11 = function (globalPluginName) { if (!globalPluginName) return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; - this_2.projectService.logger.info("Loading global plugin " + globalPluginName); - this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + this_1.projectService.logger.info("Loading global plugin " + globalPluginName); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; - var this_2 = this; + var this_1 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_10(globalPluginName); + _loop_11(globalPluginName); } } }; @@ -80452,7 +84804,7 @@ var ts; config: configEntry, project: this, languageService: this.languageService, - languageServiceHost: this.lsHost, + languageServiceHost: this, serverHost: this.projectService.host }; var pluginModule = pluginModuleFactory({ typescript: ts }); @@ -80472,8 +84824,11 @@ var ts; this.projectService.logger.info("Plugin activation failed: " + e); } }; - ConfiguredProject.prototype.getProjectRootPath = function () { - return ts.getDirectoryPath(this.getConfigFilePath()); + ConfiguredProject.prototype.getGlobalProjectErrors = function () { + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; + }; + ConfiguredProject.prototype.getAllProjectErrors = function () { + return this.projectErrors || server.emptyArray; }; ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { this.projectErrors = projectErrors; @@ -80500,81 +84855,56 @@ var ts; } })); }; - ConfiguredProject.prototype.watchConfigFile = function (callback) { + ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { var _this = this; - this.projectFileWatcher = this.projectService.host.watchFile(this.getConfigFilePath(), function (_) { return callback(_this); }); + ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); }; - ConfiguredProject.prototype.watchTypeRoots = function (callback) { - var _this = this; - var roots = this.getEffectiveTypeRoots(); - var watchers = []; - for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { - var root = roots_1[_i]; - this.projectService.logger.info("Add type root watcher for: " + root); - watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + ConfiguredProject.prototype.stopWatchingWildCards = function () { + if (this.directoriesWatchedForWildcards) { + ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); + this.directoriesWatchedForWildcards = undefined; } - this.typeRootsWatchers = watchers; }; - ConfiguredProject.prototype.watchConfigDirectory = function (callback) { - var _this = this; - if (this.directoryWatcher) { - return; + ConfiguredProject.prototype.close = function () { + if (this.configFileWatcher) { + this.configFileWatcher.close(); + this.configFileWatcher = undefined; } - var directoryToWatch = ts.getDirectoryPath(this.getConfigFilePath()); - this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); - this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + this.stopWatchingWildCards(); + this.projectErrors = undefined; + this.configFileSpecs = undefined; + _super.prototype.close.call(this); }; - ConfiguredProject.prototype.watchWildcards = function (callback) { - var _this = this; - if (!this.wildcardDirectories) { - return; - } - var configDirectoryPath = ts.getDirectoryPath(this.getConfigFilePath()); - this.directoriesWatchedForWildcards = ts.createMap(); - this.wildcardDirectories.forEach(function (flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - _this.directoriesWatchedForWildcards.set(directory, _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive)); - } - }); + ConfiguredProject.prototype.addExternalProjectReference = function () { + this.externalProjectRefCount++; }; - ConfiguredProject.prototype.stopWatchingDirectory = function () { - if (this.directoryWatcher) { - this.directoryWatcher.close(); - this.directoryWatcher = undefined; - } + ConfiguredProject.prototype.deleteExternalProjectReference = function () { + this.externalProjectRefCount--; }; - ConfiguredProject.prototype.close = function () { - _super.prototype.close.call(this); - if (this.projectFileWatcher) { - this.projectFileWatcher.close(); - this.projectFileWatcher = undefined; + ConfiguredProject.prototype.hasOpenRef = function () { + var _this = this; + if (!!this.externalProjectRefCount) { + return true; } - if (this.typeRootsWatchers) { - for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { - var watcher = _a[_i]; - watcher.close(); - } - this.typeRootsWatchers = undefined; + if (this.isClosed()) { + return false; } - if (this.directoriesWatchedForWildcards) { - this.directoriesWatchedForWildcards.forEach(function (watcher) { - watcher.close(); - }); - this.directoriesWatchedForWildcards = undefined; + var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + if (this.projectService.hasPendingProjectUpdate(this)) { + return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; } - this.stopWatchingDirectory(); - }; - ConfiguredProject.prototype.addOpenRef = function () { - this.openRefCount++; - }; - ConfiguredProject.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { - return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; + }; + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { + if (hasFileNames) { + ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { + this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); + } }; return ConfiguredProject; }(Project)); @@ -80582,47 +84912,23 @@ var ts; var ExternalProject = (function (_super) { __extends(ExternalProject, _super); function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { - var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectFilePath = projectFilePath; _this.excludedFiles = []; return _this; } ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; - ExternalProject.prototype.getProjectRootPath = function () { - if (this.projectFilePath) { - return ts.getDirectoryPath(this.projectFilePath); - } - return ts.getDirectoryPath(ts.normalizeSlashes(this.getProjectName())); - }; ExternalProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; - ExternalProject.prototype.setProjectErrors = function (projectErrors) { - this.projectErrors = projectErrors; - }; ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { - if (!newTypeAcquisition) { - newTypeAcquisition = { - enable: allRootFilesAreJsOrDts(this), - include: [], - exclude: [] - }; - } - else { - if (newTypeAcquisition.enable === undefined) { - newTypeAcquisition.enable = allRootFilesAreJsOrDts(this); - } - if (!newTypeAcquisition.include) { - newTypeAcquisition.include = []; - } - if (!newTypeAcquisition.exclude) { - newTypeAcquisition.exclude = []; - } - } + ts.Debug.assert(!!newTypeAcquisition, "newTypeAcquisition may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); + ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); this.typeAcquisition = newTypeAcquisition; }; return ExternalProject; @@ -80635,7 +84941,7 @@ var ts; var server; (function (server) { server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - server.ContextEvent = "context"; + server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; server.ProjectInfoTelemetryEvent = "projectInfo"; @@ -80655,37 +84961,37 @@ var ts; } var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); var indentStyle = ts.createMapFromTemplate({ - "none": ts.IndentStyle.None, - "block": ts.IndentStyle.Block, - "smart": ts.IndentStyle.Smart + none: ts.IndentStyle.None, + block: ts.IndentStyle.Block, + smart: ts.IndentStyle.Smart }); var defaultTypeSafeList = { "jquery": { - "match": /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, - "types": ["jquery"] + match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + types: ["jquery"] }, "WinJS": { - "match": /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, - "exclude": [["^", 1, "/.*"]], - "types": ["winjs"] + match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["winjs"] }, "Kendo": { - "match": /^(.*\/kendo)\/kendo\.all\.min\.js$/i, - "exclude": [["^", 1, "/.*"]], - "types": ["kendo-ui"] + match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["kendo-ui"] }, "Office Nuget": { - "match": /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, - "exclude": [["^", 1, "/.*"]], - "types": ["office"] + match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["office"] }, - "Minified files": { - "match": /^(.+\.min\.js)$/i, - "exclude": [["^", 1, "$"]] + "References": { + match: /^(.*\/_references\.js)$/i, + exclude: [["^", 1, "$"]] } }; function convertFormatOptions(protocolOptions) { - if (typeof protocolOptions.indentStyle === "string") { + if (ts.isString(protocolOptions.indentStyle)) { protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase()); ts.Debug.assert(protocolOptions.indentStyle !== undefined); } @@ -80695,7 +85001,7 @@ var ts; function convertCompilerOptions(protocolOptions) { compilerOptionConverters.forEach(function (mappedValues, id) { var propertyValue = protocolOptions[id]; - if (typeof propertyValue === "string") { + if (ts.isString(propertyValue)) { protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase()); } }); @@ -80703,9 +85009,7 @@ var ts; } server.convertCompilerOptions = convertCompilerOptions; function tryConvertScriptKindName(scriptKindName) { - return typeof scriptKindName === "string" - ? convertScriptKindName(scriptKindName) - : scriptKindName; + return ts.isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; } server.tryConvertScriptKindName = tryConvertScriptKindName; function convertScriptKindName(scriptKindName) { @@ -80724,21 +85028,36 @@ var ts; } server.convertScriptKindName = convertScriptKindName; function combineProjectOutput(projects, action, comparer, areEqual) { - var result = ts.flatMap(projects, action).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + var outputs = ts.flatMap(projects, action); + return comparer + ? ts.sortAndDeduplicate(outputs, comparer, areEqual) + : ts.deduplicate(outputs, areEqual); } server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, - getScriptKind: function (_) { return undefined; }, + getScriptKind: function (fileName, extraFileExtensions) { + var result; + if (extraFileExtensions) { + var fileExtension_1 = ts.getAnyExtensionFromPath(fileName); + if (fileExtension_1) { + ts.some(extraFileExtensions, function (info) { + if (info.extension === fileExtension_1) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; + }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, - isDynamicFile: function (x) { return x[0] === "^"; }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, hasMixedContent: function (x) { return x.hasMixedContent; }, - isDynamicFile: function (x) { return x.fileName[0] === "^"; }, }; function findProjectByName(projectName, projects) { for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { @@ -80748,60 +85067,42 @@ var ts; } } } - function createFileNotFoundDiagnostic(fileName) { - return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); - } - function isRootFileInInferredProject(info) { - if (info.containingProjects.length === 0) { - return false; - } - return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); - } - var DirectoryWatchers = (function () { - function DirectoryWatchers(projectService) { - this.projectService = projectService; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - } - DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { - var refCount = this.directoryWatchersRefCount.get(directory) - 1; - this.directoryWatchersRefCount.set(directory, refCount); - if (refCount === 0) { - this.projectService.logger.info("Close directory watcher for: " + directory); - this.directoryWatchersForTsconfig.get(directory).close(); - this.directoryWatchersForTsconfig.delete(directory); - } - }; - DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { - var currentPath = ts.getDirectoryPath(fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath !== parentPath) { - if (!this.directoryWatchersForTsconfig.has(currentPath)) { - this.projectService.logger.info("Add watcher for: " + currentPath); - this.directoryWatchersForTsconfig.set(currentPath, this.projectService.host.watchDirectory(currentPath, callback)); - this.directoryWatchersRefCount.set(currentPath, 1); - } - else { - this.directoryWatchersRefCount.set(currentPath, this.directoryWatchersRefCount.get(currentPath) + 1); - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - }; - return DirectoryWatchers; - }()); + var WatchType; + (function (WatchType) { + WatchType["ConfigFilePath"] = "Config file for the program"; + WatchType["MissingFilePath"] = "Missing file from program"; + WatchType["WildcardDirectories"] = "Wild card directory"; + WatchType["ClosedScriptInfo"] = "Closed Script info"; + WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; + WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; + WatchType["TypeRoots"] = "Type root directory"; + })(WatchType = server.WatchType || (server.WatchType = {})); + var ConfigFileWatcherStatus; + (function (ConfigFileWatcherStatus) { + ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; + ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files"; + ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file"; + ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; + ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; + })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); var ProjectService = (function () { function ProjectService(opts) { + var _this = this; this.filenameToScriptInfo = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); this.externalProjects = []; this.inferredProjects = []; - this.configuredProjects = []; - this.openFiles = []; + this.configuredProjects = ts.createMap(); + this.openFiles = ts.createMap(); + this.openFilesWithNonRootedDiskPath = ts.createMap(); this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); this.projectToSizeMap = ts.createMap(); + this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; + this.legacySafelist = {}; + this.pendingProjectUpdates = ts.createMap(); this.seenProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; @@ -80814,14 +85115,17 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.host.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.directoryWatchers = new DirectoryWatchers(this); - this.throttledOperations = new server.ThrottledOperations(this.host); - if (opts.typesMapLocation) { + this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); + if (this.typesMapLocation) { this.loadTypesMap(); } + else { + this.logger.info("No types map provided; using the default"); + } this.typingsInstaller.attach(this); this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { @@ -80829,13 +85133,42 @@ var ts; hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.host.getCurrentDirectory()); + this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.watchFile = function (host, file, cb, watchType, project) { return ts.addFileWatcherWithLogging(host, file, cb, _this.createWatcherLog(watchType, project)); }; + this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; + this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; + } + else if (this.logger.loggingEnabled()) { + this.watchFile = function (host, file, cb, watchType, project) { return ts.addFileWatcherWithOnlyTriggerLogging(host, file, cb, _this.createWatcherLog(watchType, project)); }; + this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; + this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithOnlyTriggerLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; + } + else { + this.watchFile = ts.addFileWatcher; + this.watchFilePath = ts.addFilePathWatcher; + this.watchDirectory = ts.addDirectoryWatcher; + } } + ProjectService.prototype.createWatcherLog = function (watchType, project) { + var _this = this; + var detailedInfo = " Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + return function (s) { return _this.logger.info(s + detailedInfo); }; + }; + ProjectService.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); + }; + ProjectService.prototype.getExecutingFilePath = function () { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + }; + ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { + return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + }; ProjectService.prototype.getChangedFiles_TestOnly = function () { return this.changedFiles; }; ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { - this.ensureInferredProjectsUpToDate(); + this.ensureProjectStructuresUptoDate(); }; ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { return this.compilerOptionsForInferredProjects; @@ -80863,10 +85196,16 @@ var ts; raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); } this.safelist = raw.typesMap; + for (var key in raw.simpleMap) { + if (raw.simpleMap.hasOwnProperty(key)) { + this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + } + } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; + this.legacySafelist = {}; } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -80882,52 +85221,114 @@ var ts; this.typingsCache.deleteTypingsForProject(response.projectName); break; } - project.updateGraph(); + this.delayUpdateProjectGraphAndInferredProjectsRefresh(project); + }; + ProjectService.prototype.delayInferredProjectsRefresh = function () { + var _this = this; + this.pendingInferredProjectUpdate = true; + this.throttledOperations.schedule("*refreshInferredProjects*", 250, function () { + if (_this.pendingProjectUpdates.size !== 0) { + _this.delayInferredProjectsRefresh(); + } + else { + if (_this.pendingInferredProjectUpdate) { + _this.pendingInferredProjectUpdate = false; + _this.refreshInferredProjects(); + } + _this.sendProjectsUpdatedInBackgroundEvent(); + } + }); + }; + ProjectService.prototype.delayUpdateProjectGraph = function (project) { + var _this = this; + var projectName = project.getProjectName(); + this.pendingProjectUpdates.set(projectName, project); + this.throttledOperations.schedule(projectName, 250, function () { + if (_this.pendingProjectUpdates.delete(projectName)) { + project.updateGraph(); + } + }); + }; + ProjectService.prototype.hasPendingProjectUpdate = function (project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + }; + ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { + var _this = this; + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles: ts.arrayFrom(this.openFiles.keys(), function (path) { return _this.getScriptInfoForPath(path).fileName; }) + } + }; + this.eventHandler(event); + }; + ProjectService.prototype.delayUpdateProjectGraphAndInferredProjectsRefresh = function (project) { + project.markAsDirty(); + this.delayUpdateProjectGraph(project); + this.delayInferredProjectsRefresh(); + }; + ProjectService.prototype.delayUpdateProjectGraphs = function (projects) { + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var project = projects_2[_i]; + this.delayUpdateProjectGraph(project); + } + this.delayInferredProjectsRefresh(); }; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); var compilerOptions = convertCompilerOptions(projectCompilerOptions); compilerOptions.allowNonTsExtensions = true; - if (projectRootPath) { - this.compilerOptionsForInferredProjectsPerProjectRoot.set(projectRootPath, compilerOptions); + var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); } else { this.compilerOptionsForInferredProjects = compilerOptions; } - var updatedProjects = []; + var projectsToUpdate = []; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (projectRootPath ? - project.projectRootPath === projectRootPath : + if (canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { project.setCompilerOptions(compilerOptions); project.compileOnSaveEnabled = compilerOptions.compileOnSave; - updatedProjects.push(project); + project.markAsDirty(); + projectsToUpdate.push(project); } } - this.updateProjectGraphs(updatedProjects); - }; - ProjectService.prototype.stopWatchingDirectory = function (directory) { - this.directoryWatchers.stopWatchingDirectory(directory); + this.delayUpdateProjectGraphs(projectsToUpdate); }; ProjectService.prototype.findProject = function (projectName) { if (projectName === undefined) { return undefined; } if (server.isInferredProjectName(projectName)) { - this.ensureInferredProjectsUpToDate(); + this.ensureProjectStructuresUptoDate(); return findProjectByName(projectName, this.inferredProjects); } return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); }; - ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { - if (refreshInferredProjects) { - this.ensureInferredProjectsUpToDate(); - } + ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) { var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo && scriptInfo.getDefaultProject(); + if (ensureProject && !scriptInfo || scriptInfo.isOrphan()) { + this.ensureProjectStructuresUptoDate(); + scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + if (!scriptInfo) { + return server.Errors.ThrowNoProject(); + } + return scriptInfo.getDefaultProject(); + } + return scriptInfo && !scriptInfo.isOrphan() && scriptInfo.getDefaultProject(); }; - ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { + this.ensureProjectStructuresUptoDate(); + return this.getScriptInfo(uncheckedFileName); + }; + ProjectService.prototype.ensureProjectStructuresUptoDate = function (forceInferredProjectsRefresh) { if (this.changedFiles) { var projectsToUpdate = void 0; if (this.changedFiles.length === 1) { @@ -80937,11 +85338,20 @@ var ts; projectsToUpdate = []; for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { var f = _a[_i]; - projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + ts.addRange(projectsToUpdate, f.containingProjects); } } - this.updateProjectGraphs(projectsToUpdate); this.changedFiles = undefined; + this.updateProjectGraphs(projectsToUpdate); + } + if (this.pendingProjectUpdates.size !== 0) { + var projectsToUpdate = ts.arrayFrom(this.pendingProjectUpdates.values()); + this.pendingProjectUpdates.clear(); + this.updateProjectGraphs(projectsToUpdate); + } + if (this.pendingInferredProjectUpdate || forceInferredProjectsRefresh) { + this.pendingInferredProjectUpdate = false; + this.refreshInferredProjects(); } }; ProjectService.prototype.findContainingExternalProject = function (fileName) { @@ -80964,181 +85374,134 @@ var ts; return formatCodeSettings || this.hostConfiguration.formatCodeOptions; }; ProjectService.prototype.updateProjectGraphs = function (projects) { - var shouldRefreshInferredProjects = false; - for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { - var p = projects_2[_i]; + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var p = projects_3[_i]; if (!p.updateGraph()) { - shouldRefreshInferredProjects = true; + this.pendingInferredProjectUpdate = true; } } - if (shouldRefreshInferredProjects) { - this.refreshInferredProjects(); - } }; - ProjectService.prototype.onSourceFileChanged = function (fileName) { + ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - this.logger.info("Error: got watch notification for unknown file: " + fileName); - return; + this.logger.msg("Error: got watch notification for unknown file: " + fileName); } - if (!this.host.fileExists(fileName)) { + else if (eventKind === ts.FileWatcherEventKind.Deleted) { this.handleDeletedFile(info); } - else { - if (info && (!info.isScriptOpen())) { - if (info.containingProjects.length === 0) { - info.stopWatcher(); - this.filenameToScriptInfo.delete(info.path); - } - else { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); - } + else if (!info.isScriptOpen()) { + if (info.containingProjects.length === 0) { + this.stopWatchingScriptInfo(info); + this.filenameToScriptInfo.delete(info.path); + } + else { + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); } } }; ProjectService.prototype.handleDeletedFile = function (info) { - this.logger.info(info.fileName + " deleted"); - info.stopWatcher(); + this.stopWatchingScriptInfo(info); if (!info.isScriptOpen()) { this.filenameToScriptInfo.delete(info.path); - this.lastDeletedFile = info; var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); - this.updateProjectGraphs(containingProjects); - this.lastDeletedFile = undefined; - if (!this.eventHandler) { - return; - } - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var openFile = _a[_i]; - var event = { - eventName: server.ContextEvent, - data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } - }; - this.eventHandler(event); - } + this.delayUpdateProjectGraphs(containingProjects); } - this.printProjects(); }; - ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { var _this = this; - this.logger.info("Type root file " + fileName + " changed"); - this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", 250, function () { - project.updateTypes(); - _this.updateConfiguredProject(project); - _this.refreshInferredProjects(); - }); + return this.watchDirectory(this.host, directory, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + var configFilename = project.getConfigFilePath(); + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) { + _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + _this.delayUpdateProjectGraphAndInferredProjectsRefresh(project); + } + }, flags, "Wild card directory", project); }; - ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { - var _this = this; - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { - return; - } - this.logger.info("Detected source file changes: " + fileName); - this.throttledOperations.schedule(project.getConfigFilePath(), 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project, fileName); }); + ProjectService.prototype.getConfigFileExistenceInfo = function (project) { + return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); }; - ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project, triggerFile) { - var _this = this; - var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { - this.logger.info("Updating configured project"); - this.updateConfiguredProject(project); - this.refreshInferredProjects(); + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (eventKind === ts.FileWatcherEventKind.Deleted) { + configFileExistenceInfo.exists = false; + this.removeProject(project); + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files"); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); } - }; - ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { - var configFileName = project.getConfigFilePath(); - this.logger.info("Config file changed: " + configFileName); - var configFileErrors = this.updateConfiguredProject(project); - this.reportConfigFileDiagnostics(configFileName, configFileErrors, configFileName); - this.refreshInferredProjects(); - }; - ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.logger.info(fileName + " is not tsconfig.json"); - return; + else { + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files"); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + this.delayUpdateProjectGraph(project); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true); } - var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; - this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName); - this.logger.info("Detected newly added tsconfig file: " + fileName); - this.reloadProjects(); }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); + ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { + var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); + configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files"); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); }; ProjectService.prototype.removeProject = function (project) { this.logger.info("remove project: " + project.getRootFiles().toString()); project.close(); + if (ts.Debug.shouldAssert(1)) { + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); + } + this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { case server.ProjectKind.External: ts.unorderedRemoveItem(this.externalProjects, project); - this.projectToSizeMap.delete(project.externalProjectName); + this.projectToSizeMap.delete(project.getProjectName()); break; case server.ProjectKind.Configured: - ts.unorderedRemoveItem(this.configuredProjects, project); + this.configuredProjects.delete(project.canonicalConfigFilePath); this.projectToSizeMap.delete(project.canonicalConfigFilePath); + this.setConfigFileExistenceInfoByClosedConfiguredProject(project); break; case server.ProjectKind.Inferred: ts.unorderedRemoveItem(this.inferredProjects, project); break; } }; - ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles, projectRootPath) { - var externalProject = this.findContainingExternalProject(info.fileName); - if (externalProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - var foundConfiguredProject = false; - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - foundConfiguredProject = true; - if (addToListOfOpenFiles) { - (p).addOpenRef(); - } - } - } - if (foundConfiguredProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - if (info.containingProjects.length === 0) { - var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info, projectRootPath); - if (!this.useSingleInferredProject && !inferredProject.projectRootPath) { - for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { - var f = _c[_b]; - if (f.containingProjects.length === 0 || !inferredProject.containsScriptInfo(f)) { - continue; - } - for (var _d = 0, _e = f.containingProjects; _d < _e.length; _d++) { - var containingProject = _e[_d]; - if (containingProject.projectKind === server.ProjectKind.Inferred && - containingProject !== inferredProject && - containingProject.isRoot(f)) { - this.removeProject(containingProject); - f.attachToProject(inferredProject); - } - } + ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) { + ts.Debug.assert(info.isOrphan()); + var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || + this.getOrCreateSingleInferredProjectIfEnabled() || + this.createInferredProject(ts.getDirectoryPath(info.path)); + project.addRoot(info); + project.updateGraph(); + if (!this.useSingleInferredProject && !project.projectRootPath) { + for (var _i = 0, _a = this.inferredProjects.slice(0, this.inferredProjects.length - 1); _i < _a.length; _i++) { + var inferredProject = _a[_i]; + ts.Debug.assert(inferredProject !== project); + var roots = inferredProject.getRootScriptInfos(); + ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); + if (roots.length === 1 && roots[0].containingProjects.length > 1) { + this.removeProject(inferredProject); } } } - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } + return project; }; ProjectService.prototype.closeOpenFile = function (info) { - info.close(); - ts.unorderedRemoveItem(this.openFiles, info); + var _this = this; + var fileExists = this.host.fileExists(info.fileName); + info.close(fileExists); + this.stopWatchingConfigFilesForClosedScriptInfo(info); + this.openFiles.delete(info.path); + var canonicalFileName = this.toCanonicalFileName(info.fileName); + if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { + this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); + } var projectsToRemove; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; @@ -81146,12 +85509,14 @@ var ts; if (info.hasMixedContent) { info.registerFileUpdate(); } - if (p.deleteOpenRef() === 0) { - (projectsToRemove || (projectsToRemove = [])).push(p); - } } else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { - (projectsToRemove || (projectsToRemove = [])).push(p); + if (p.isProjectWithSingleRoot()) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + else { + p.removeFile(info, fileExists, true); + } } if (!p.languageServiceEnabled) { p.markAsDirty(); @@ -81162,21 +85527,14 @@ var ts; var project = projectsToRemove_1[_b]; this.removeProject(project); } - var orphanFiles = void 0; - for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { - var f = _d[_c]; - if (f.containingProjects.length === 0) { - (orphanFiles || (orphanFiles = [])).push(f); + this.openFiles.forEach(function (projectRootPath, path) { + var f = _this.getScriptInfoForPath(path); + if (f.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(f, projectRootPath); } - } - if (orphanFiles) { - for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { - var f = orphanFiles_1[_e]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - } + }); } - if (this.host.fileExists(info.fileName)) { + if (fileExists) { this.watchClosedScriptInfo(info); } else { @@ -81186,45 +85544,160 @@ var ts; ProjectService.prototype.deleteOrphanScriptInfoNotInAnyProject = function () { var _this = this; this.filenameToScriptInfo.forEach(function (info) { - if (!info.isScriptOpen() && info.containingProjects.length === 0) { - info.stopWatcher(); + if (!info.isScriptOpen() && info.isOrphan()) { + _this.stopWatchingScriptInfo(info); _this.filenameToScriptInfo.delete(info.path); } }); }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName, projectRootPath) { - var searchPath = ts.getDirectoryPath(fileName); - this.logger.info("Search path: " + searchPath); - var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath), projectRootPath); - if (!configFileName) { - this.logger.info("No config files found."); - return {}; - } - this.logger.info("Config file name: " + configFileName); - var project = this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; - if (!success) { - return { configFileName: configFileName, configFileErrors: errors }; + ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + if (!configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); + } + return configFileExistenceInfo.exists; + } + var openFilesImpactedByConfigFile = ts.createMap(); + openFilesImpactedByConfigFile.set(info.path, false); + var exists = this.host.fileExists(configFileName); + configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); + return exists; + }; + ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (configFileExistenceInfo) { + ts.Debug.assert(configFileExistenceInfo.exists); + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + var configFileName = project.getConfigFilePath(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); } - this.logger.info("Opened configuration file " + configFileName); - if (errors && errors.length > 0) { - return { configFileName: configFileName, configFileErrors: errors }; + } + else { + this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { + exists: true, + openFilesImpactedByConfigFile: ts.createMap() + }); + } + }; + ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); + }; + ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); + ts.Debug.assert(!!configFileExistenceInfo); + if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { + var configFileName = closedProject.getConfigFilePath(); + if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); } } else { - this.updateConfiguredProject(project); + this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); + } + }; + ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) { + var _this = this; + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + var inferredRoots = []; + var otherFiles = []; + configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) { + var info = _this.getScriptInfoForPath(key); + (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); + }); + var watches = []; + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + watches.push("Config file for the inferred project root"); + } + if (this.configuredProjects.has(canonicalConfigFilePath)) { + watches.push("Config file for the program"); + } + this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); + }; + ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { + var _this = this; + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, "Config file for the inferred project root"); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); + }; + ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; } - return { configFileName: configFileName }; }; - ProjectService.prototype.findConfigFile = function (searchPath, projectRootPath) { - while (!projectRootPath || searchPath.indexOf(projectRootPath) >= 0) { + ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { + var _this = this; + ts.Debug.assert(!info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file"); + if (infoIsRootOfInferredProject) { + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } + } + }); + }; + ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info, projectRootPath) { + var _this = this; + ts.Debug.assert(info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + configFileExistenceInfo = { + exists: _this.host.fileExists(configFileName), + openFilesImpactedByConfigFile: ts.createMap() + }; + _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + } + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root"); + if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + } + }, projectRootPath); + }; + ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { + var _this = this; + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + ts.Debug.assert(info.isScriptOpen()); + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root"); + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + }); + }; + ProjectService.prototype.forEachConfigFileLocation = function (info, action, projectRootPath) { + var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); + while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) { + var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); - if (this.host.fileExists(tsconfigFileName)) { + var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); + if (result) { return tsconfigFileName; } var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); - if (this.host.fileExists(jsconfigFileName)) { + result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json")); + if (result) { return jsconfigFileName; } var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); @@ -81235,47 +85708,59 @@ var ts; } return undefined; }; + ProjectService.prototype.getConfigFileNameForFile = function (info, projectRootPath) { + var _this = this; + ts.Debug.assert(info.isScriptOpen()); + this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); + var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + return _this.configFileExists(configFileName, canonicalConfigFilePath, info); + }, projectRootPath); + if (configFileName) { + this.logger.info("For info: " + info.fileName + " :: Config file name: " + configFileName); + } + else { + this.logger.info("For info: " + info.fileName + " :: No config files found."); + } + return configFileName; + }; ProjectService.prototype.printProjects = function () { var _this = this; - if (!this.logger.hasLevel(server.LogLevel.verbose)) { + if (!this.logger.hasLevel(server.LogLevel.normal)) { return; } + var writeProjectFileNames = this.logger.hasLevel(server.LogLevel.verbose); this.logger.startGroup(); var counter = 0; var printProjects = function (projects, counter) { - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var project = projects_3[_i]; - project.updateGraph(); + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var project = projects_4[_i]; _this.logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - _this.logger.info(project.filesToString()); + _this.logger.info(project.filesToString(writeProjectFileNames)); _this.logger.info("-----------------------------------------------"); counter++; } return counter; }; counter = printProjects(this.externalProjects, counter); - counter = printProjects(this.configuredProjects, counter); + counter = printProjects(ts.arrayFrom(this.configuredProjects.values()), counter); printProjects(this.inferredProjects, counter); this.logger.info("Open files: "); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var rootFile = _a[_i]; - this.logger.info("\t" + rootFile.fileName); - } + this.openFiles.forEach(function (projectRootPath, path) { + _this.logger.info("\tFileName: " + _this.getScriptInfoForPath(path).fileName + " ProjectRootPath: " + projectRootPath); + }); this.logger.endGroup(); }; ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { - configFileName = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); - for (var _i = 0, _a = this.configuredProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.canonicalConfigFilePath === configFileName) { - return proj; - } - } + var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); + }; + ProjectService.prototype.getConfiguredProjectByCanonicalConfigFilePath = function (canonicalConfigFilePath) { + return this.configuredProjects.get(canonicalConfigFilePath); }; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { configFilename = ts.normalizePath(configFilename); var configFileContent = this.host.readFile(configFilename); var result = ts.parseJsonText(configFilename, configFileContent); @@ -81283,27 +85768,23 @@ var ts; result.endOfFileToken = { kind: 1 }; } var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { errors.push.apply(errors, parsedCommandLine.errors); } ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { success: false, configFileErrors: errors }; - } var projectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw["extends"] !== undefined, - configHasFilesProperty: parsedCommandLine.raw["files"] !== undefined, - configHasIncludeProperty: parsedCommandLine.raw["include"] !== undefined, - configHasExcludeProperty: parsedCommandLine.raw["exclude"] !== undefined, + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave }; - return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; }; ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { @@ -81313,29 +85794,44 @@ var ts; this.projectToSizeMap.set(name, 0); this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); }); var totalNonTsFileSize = 0; - for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { - var f = fileNames_3[_i]; + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); if (ts.hasTypeScriptFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); return true; } } if (totalNonTsFileSize > availableSpace) { + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); return true; } this.projectToSizeMap.set(name, totalNonTsFileSize); return false; + function getExceedLimitMessage(context, totalNonTsFileSize) { + var files = getTop5LargestFiles(context); + return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); + } + function getTop5LargestFiles(_a) { + var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + return fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + } }; - ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typeAcquisition) { + ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typeAcquisition, undefined); + project.excludedFiles = excludedFiles; + this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(project.externalProjectName, project); + this.sendProjectTelemetry(projectFileName, project); return project; }; ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { @@ -81343,12 +85839,13 @@ var ts; return; } this.seenProjects.set(projectKey, true); - if (!this.eventHandler) + if (!this.eventHandler) { return; + } var data = { projectId: this.host.createHash(projectKey), fileStats: server.countEachFileTypes(project.getScriptInfos()), - compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilerOptions()), + compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), extends: projectOptions && projectOptions.configHasExtendsProperty, files: projectOptions && projectOptions.configHasFilesProperty, @@ -81366,8 +85863,7 @@ var ts; return "other"; } var configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); - var base = ts.getBaseFileName(configFilePath); - return base === "tsconfig.json" || base === "jsconfig.json" ? base : "other"; + return server.getBaseConfigFileName(configFilePath) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -81378,185 +85874,141 @@ var ts; }; } }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (!this.eventHandler) { - return; - } - var event = { - eventName: server.ConfigFileDiagEvent, - data: { configFileName: configFileName, diagnostics: diagnostics || server.emptyArray, triggerFile: triggerFile } - }; - this.eventHandler(event); + ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + this.updateNonInferredProjectFiles(project, files, propertyReader); + project.setTypeAcquisition(typeAcquisition); + project.updateGraph(); }; - ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host); + var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; + this.logger.info("Opened configuration file " + configFileName); + var languageServiceEnabled = !this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, languageServiceEnabled, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost); + project.configFileSpecs = configFileSpecs; + project.configFileWatcher = this.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, "Config file for the program", project); + if (languageServiceEnabled) { + project.watchWildcards(projectOptions.wildcardDirectories); + } + project.setProjectErrors(configFileErrors); var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); - project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); - if (!sizeLimitExceeded) { - this.watchConfigDirectoryForProject(project, projectOptions); - } - project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); - this.configuredProjects.push(project); - this.sendProjectTelemetry(project.getConfigFilePath(), project, projectOptions); + this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); + this.configuredProjects.set(project.canonicalConfigFilePath, project); + this.setConfigFileExistenceByNewConfiguredProject(project); + this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; - ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { - var _this = this; - if (!options.configHasFilesProperty) { - project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - } - }; - ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typeAcquisition, configFileErrors) { - var errors; - for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { - var f = files_4[_i]; - var rootFileName = propertyReader.getFileName(f); - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - var isDynamicFile = propertyReader.isDynamicFile(f); - if (isDynamicFile || this.host.fileExists(rootFileName)) { - var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFileName), clientFileName === rootFileName, undefined, scriptKind, hasMixedContent, isDynamicFile); - project.addRoot(info); + ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { + var projectRootFilesMap = project.getRootFilesMap(); + var newRootScriptInfoMap = ts.createMap(); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var f = files_3[_i]; + var newRootFile = propertyReader.getFileName(f); + var normalizedPath = server.toNormalizedPath(newRootFile); + var isDynamic = server.isDynamicFileName(normalizedPath); + var scriptInfo = void 0; + var path = void 0; + if (!isDynamic && !project.fileExists(newRootFile)) { + path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName); + var existingValue = projectRootFilesMap.get(path); + if (server.isScriptInfo(existingValue)) { + project.removeFile(existingValue, false, true); + } + projectRootFilesMap.set(path, normalizedPath); + scriptInfo = normalizedPath; } else { - (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFileName)); + var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); + path = scriptInfo.path; + if (!project.isRoot(scriptInfo)) { + project.addRoot(scriptInfo); + if (scriptInfo.isScriptOpen()) { + this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); + } + } } + newRootScriptInfoMap.set(path, scriptInfo); } - project.setProjectErrors(ts.concatenate(configFileErrors, errors)); - project.setTypeAcquisition(typeAcquisition); - project.updateGraph(); - }; - ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { - var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); - var projectOptions = conversionResult.success - ? conversionResult.projectOptions - : { files: [], compilerOptions: {}, configHasExtendsProperty: false, configHasFilesProperty: false, configHasIncludeProperty: false, configHasExcludeProperty: false, typeAcquisition: { enable: false } }; - var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); - return { - success: conversionResult.success, - project: project, - errors: project.getGlobalProjectErrors() - }; - }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors) { - var oldRootScriptInfos = project.getRootScriptInfos(); - var newRootScriptInfos = []; - var newRootScriptInfoMap = server.createNormalizedPathMap(); - var projectErrors; - var rootFilesChanged = false; - for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { - var f = newUncheckedFiles_1[_i]; - var newRootFile = propertyReader.getFileName(f); - var isDynamic = propertyReader.isDynamicFile(f); - if (!isDynamic && !this.host.fileExists(newRootFile)) { - (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); - continue; - } - var normalizedPath = server.toNormalizedPath(newRootFile); - var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); - if (!scriptInfo || !project.isRoot(scriptInfo)) { - rootFilesChanged = true; - if (!scriptInfo) { - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent, isDynamic); - } - } - newRootScriptInfos.push(scriptInfo); - newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); - } - if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { - var toAdd = void 0; - var toRemove = void 0; - for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { - var oldFile = oldRootScriptInfos_1[_a]; - if (!newRootScriptInfoMap.contains(oldFile.fileName)) { - (toRemove || (toRemove = [])).push(oldFile); - } - } - for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { - var newFile = newRootScriptInfos_1[_b]; - if (!project.isRoot(newFile)) { - (toAdd || (toAdd = [])).push(newFile); - } - } - if (toRemove) { - for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { - var f = toRemove_1[_c]; - project.removeFile(f); - } - } - if (toAdd) { - for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { - var f = toAdd_1[_d]; - if (f.isScriptOpen() && isRootFileInInferredProject(f)) { - var inferredProject = f.containingProjects[0]; - inferredProject.removeFile(f); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); - } + if (projectRootFilesMap.size > newRootScriptInfoMap.size) { + projectRootFilesMap.forEach(function (value, path) { + if (!newRootScriptInfoMap.has(path)) { + if (server.isScriptInfo(value)) { + project.removeFile(value, project.fileExists(path), true); + } + else { + projectRootFilesMap.delete(path); } - project.addRoot(f); } - } + }); } + project.markAsDirty(); + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); - project.setTypeAcquisition(newTypeAcquisition); if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); - project.updateGraph(); + this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; - ProjectService.prototype.updateConfiguredProject = function (project) { - if (!this.host.fileExists(project.getConfigFilePath())) { - this.logger.info("Config file deleted"); - this.removeProject(project); - return; - } - var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - if (!success) { - this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); - return configFileErrors; - } + ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { + var configFileSpecs = project.configFileSpecs; + var configFileName = project.getConfigFilePath(); + var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + return project.updateGraph(); + }; + ProjectService.prototype.reloadConfiguredProject = function (project) { + var host = project.getCachedDirectoryStructureHost(); + host.clearCache(); + var configFileName = project.getConfigFilePath(); + this.logger.info("Reloading configured project " + configFileName); + var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; + project.configFileSpecs = configFileSpecs; + project.setProjectErrors(configFileErrors); if (this.exceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { - project.setCompilerOptions(projectOptions.compilerOptions); - if (!project.languageServiceEnabled) { - return configFileErrors; - } project.disableLanguageService(); - project.stopWatchingDirectory(); + project.stopWatchingWildCards(); } else { project.enableLanguageService(); - this.watchConfigDirectoryForProject(project, projectOptions); - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); + project.watchWildcards(projectOptions.wildcardDirectories); + } + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.sendConfigFileDiagEvent(project, configFileName); + }; + ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { + if (!this.eventHandler) { + return; } - return configFileErrors; + this.eventHandler({ + eventName: server.ConfigFileDiagEvent, + data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile: triggerFile } + }); }; - ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (root, projectRootPath) { + ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { if (!this.useInferredProjectPerProjectRoot) { return undefined; } if (projectRootPath) { + var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (project.projectRootPath === projectRootPath) { + if (project.projectRootPath === canonicalProjectRootPath) { return project; } } - return this.createInferredProject(false, projectRootPath); + return this.createInferredProject(projectRootPath, false, projectRootPath); } var bestMatch; for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { var project = _c[_b]; if (!project.projectRootPath) continue; - if (!ts.containsPath(project.projectRootPath, root.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) continue; if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) continue; @@ -81571,11 +86023,11 @@ var ts; if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { return this.inferredProjects[0]; } - return this.createInferredProject(true); + return this.createInferredProject(undefined, true); }; - ProjectService.prototype.createInferredProject = function (isSingleInferredProject, projectRootPath) { + ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath); + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -81584,61 +86036,70 @@ var ts; } return project; }; - ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root, projectRootPath) { - var _this = this; - var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(root, projectRootPath) || - this.getOrCreateSingleInferredProjectIfEnabled() || - this.createInferredProject(); - project.addRoot(root); - this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); - project.updateGraph(); - return project; - }; - ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { - return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, undefined, undefined, hostToQueryFileExistsOn); }; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; - if (!info.hasMixedContent && !info.isDynamic) { + ts.Debug.assert(!info.fileWatcher); + if (!info.isDynamicOrHasMixedContent()) { var fileName_2 = info.fileName; - info.setWatcher(this.host.watchFile(fileName_2, function (_) { return _this.onSourceFileChanged(fileName_2); })); + info.fileWatcher = this.watchFile(this.host, fileName_2, function (_fileName, eventKind) { return _this.onSourceFileChanged(fileName_2, eventKind); }, "Closed Script info"); } }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, isDynamic) { - var info = this.getScriptInfoForNormalizedPath(fileName); + ProjectService.prototype.stopWatchingScriptInfo = function (info) { + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = undefined; + } + }; + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, true, fileContent, scriptKind, hasMixedContent); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); + var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); + var info = this.getScriptInfoForPath(path); if (!info) { - if (openedByClient || isDynamic || this.host.fileExists(fileName)) { - info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, isDynamic); - this.filenameToScriptInfo.set(info.path, info); - if (openedByClient) { - if (fileContent === undefined) { - fileContent = this.host.readFile(fileName) || ""; - } - } - else { - this.watchClosedScriptInfo(info); - } + ts.Debug.assert(ts.isRootedDiskPath(fileName) || openedByClient, "Script info with relative file name can only be open script info"); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); + var isDynamic = server.isDynamicFileName(fileName); + if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { + return; } - } - if (info) { - if (openedByClient && !info.isScriptOpen()) { - info.stopWatcher(); - info.open(fileContent); - if (hasMixedContent) { - info.registerFileUpdate(); - } + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, path); + this.filenameToScriptInfo.set(info.path, info); + if (!openedByClient) { + this.watchClosedScriptInfo(info); } - else if (fileContent !== undefined) { - info.reload(fileContent); + else if (!ts.isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } } + if (openedByClient && !info.isScriptOpen()) { + this.stopWatchingScriptInfo(info); + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } + } + else { + ts.Debug.assert(fileContent === undefined); + } return info; }; ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { - return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || + this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); }; ProjectService.prototype.getScriptInfoForPath = function (fileName) { return this.filenameToScriptInfo.get(fileName); @@ -81662,6 +86123,7 @@ var ts; } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.reloadProjects(); this.logger.info("Host file extension mappings updated"); } } @@ -81671,64 +86133,119 @@ var ts; }; ProjectService.prototype.reloadProjects = function () { this.logger.info("reload projects."); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } + this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue); this.refreshInferredProjects(); }; - ProjectService.prototype.refreshInferredProjects = function () { - this.logger.info("updating project structure from ..."); - this.printProjects(); - var orphantedFiles = []; - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - if (info.containingProjects.length === 0) { - orphantedFiles.push(info); + ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ? + function (isRootOfInferredProject) { return isRootOfInferredProject; } : + ts.returnTrue); + this.delayInferredProjectsRefresh(); + }; + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + var _this = this; + var updatedProjects = ts.createMap(); + openFiles.forEach(function (openFileValue, path) { + if (!shouldReloadProjectFor(openFileValue)) { + return; } - else { - if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { - var inferredProject = info.containingProjects[0]; - ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); - inferredProject.removeFile(info); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); + var info = _this.getScriptInfoForPath(path); + ts.Debug.assert(info.isScriptOpen()); + var configFileName = _this.getConfigFileNameForFile(info, _this.openFiles.get(path)); + if (configFileName) { + var project = _this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + _this.createConfiguredProject(configFileName); + updatedProjects.set(configFileName, true); + } + else if (!updatedProjects.has(configFileName)) { + if (delayReload) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + _this.delayUpdateProjectGraph(project); } + else { + _this.reloadConfiguredProject(project); + } + updatedProjects.set(configFileName, true); } } + }); + }; + ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) { + if (info.containingProjects.length > 1 && + info.containingProjects[0].projectKind === server.ProjectKind.Inferred && + info.containingProjects[0].isRoot(info)) { + var inferredProject = info.containingProjects[0]; + if (inferredProject.isProjectWithSingleRoot()) { + this.removeProject(inferredProject); + } + else { + inferredProject.removeFile(info, true, true); + } } - for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { - var f = orphantedFiles_1[_b]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { - var p = _d[_c]; + }; + ProjectService.prototype.refreshInferredProjects = function () { + var _this = this; + this.logger.info("refreshInferredProjects: updating project structure from ..."); + this.printProjects(); + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + if (info.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + else { + _this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); + } + }); + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var p = _a[_i]; p.updateGraph(); } + this.logger.info("refreshInferredProjects: updated project structure ..."); this.printProjects(); }; ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + var _this = this; var configFileName; + var sendConfigFileDiagEvent = false; var configFileErrors; + var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); var project = this.findContainingExternalProject(fileName); if (!project) { - (_a = this.openOrUpdateConfiguredProjectForFile(fileName, projectRootPath), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors); + configFileName = this.getConfigFileNameForFile(info, projectRootPath); if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + project = this.createConfiguredProject(configFileName); + sendConfigFileDiagEvent = true; + } } } if (project && !project.languageServiceEnabled) { project.markAsDirty(); } - var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); - this.assignScriptInfoToInferredProjectIfNecessary(info, true, projectRootPath); + if (info.isOrphan()) { + configFileName = undefined; + sendConfigFileDiagEvent = false; + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + ts.Debug.assert(!info.isOrphan()); + this.openFiles.set(info.path, projectRootPath); + if (sendConfigFileDiagEvent) { + configFileErrors = project.getAllProjectErrors(); + this.sendConfigFileDiagEvent(project, fileName); + } + this.configuredProjects.forEach(function (project) { + if (!project.hasOpenRef()) { + _this.removeProject(project); + } + }); this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; - var _a; }; ProjectService.prototype.closeClientFile = function (uncheckedFileName) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); @@ -81738,24 +86255,23 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_11 = function (proj) { + var _loop_12 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_11(proj); + _loop_12(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { var files = []; this.collectChanges(knownProjects, this.externalProjects, files); - this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, ts.arrayFrom(this.configuredProjects.values()), files); this.collectChanges(knownProjects, this.inferredProjects, files); return files; }; ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { - var recordChangedFiles = changedFiles && !openFiles && !closedFiles; if (openFiles) { for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { var file = openFiles_1[_i]; @@ -81770,18 +86286,7 @@ var ts; var file = changedFiles_2[_a]; var scriptInfo = this.getScriptInfo(file.fileName); ts.Debug.assert(!!scriptInfo); - for (var i = file.changes.length - 1; i >= 0; i--) { - var change = file.changes[i]; - scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); - } - if (recordChangedFiles) { - if (!this.changedFiles) { - this.changedFiles = [scriptInfo]; - } - else if (this.changedFiles.indexOf(scriptInfo) < 0) { - this.changedFiles.push(scriptInfo); - } - } + this.applyChangesToFile(scriptInfo, file.changes); } } if (closedFiles) { @@ -81791,14 +86296,29 @@ var ts; } } if (openFiles || closedFiles) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(true); } }; - ProjectService.prototype.closeConfiguredProject = function (configFile) { + ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) { + for (var i = changes.length - 1; i >= 0; i--) { + var change = changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (!ts.contains(this.changedFiles, scriptInfo)) { + this.changedFiles.push(scriptInfo); + } + }; + ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) { var configuredProject = this.findConfiguredProjectByProjectName(configFile); - if (configuredProject && configuredProject.deleteOpenRef() === 0) { - this.removeProject(configuredProject); - return true; + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return true; + } } return false; }; @@ -81810,13 +86330,13 @@ var ts; var shouldRefreshInferredProjects = false; for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { var configFile = configFiles_1[_i]; - if (this.closeConfiguredProject(configFile)) { + if (this.closeConfiguredProjectReferencedFromExternalProject(configFile)) { shouldRefreshInferredProjects = true; } } this.externalProjectToConfiguredProjectMap.delete(fileName); if (shouldRefreshInferredProjects && !suppressRefresh) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(true); } } else { @@ -81824,7 +86344,7 @@ var ts; if (externalProject) { this.removeProject(externalProject); if (!suppressRefresh) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(true); } } } @@ -81835,15 +86355,15 @@ var ts; ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { projectsToClose.set(externalProjectName, true); }); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var externalProject = projects_4[_i]; + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var externalProject = projects_5[_i]; this.openExternalProject(externalProject, true); projectsToClose.delete(externalProject.projectFileName); } ts.forEachKey(projectsToClose, function (externalProjectName) { _this.closeExternalProject(externalProjectName, true); }); - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(true); }; ProjectService.escapeFilenameForRegex = function (filename) { return filename.replace(this.filenameEscapeRegexp, "\\$&"); @@ -81854,26 +86374,30 @@ var ts; ProjectService.prototype.applySafeList = function (proj) { var _this = this; var rootFiles = proj.rootFiles, typeAcquisition = proj.typeAcquisition; - var types = (typeAcquisition && typeAcquisition.include) || []; + ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); + if (typeAcquisition.enable === false) { + return []; + } + var typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_12 = function (name) { - var rule = this_3.safelist[name]; + var _loop_13 = function (name) { + var rule = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_3.logger.info("Excluding files based on rule " + name); + this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { var type = _b[_a]; - if (types.indexOf(type) < 0) { - types.push(type); + if (typeAcqInclude.indexOf(type) < 0) { + typeAcqInclude.push(type); } } } if (rule.exclude) { - var _loop_13 = function (exclude) { + var _loop_14 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -81881,7 +86405,7 @@ var ts; } return exclude.map(function (groupNumberOrString) { if (typeof groupNumberOrString === "number") { - if (typeof groups[groupNumberOrString] !== "string") { + if (!ts.isString(groups[groupNumberOrString])) { _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); return "\\*"; } @@ -81896,7 +86420,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_13(exclude); + _loop_14(exclude); } } else { @@ -81907,28 +86431,49 @@ var ts; } } } - if (types.length > 0) { - proj.typeAcquisition = proj.typeAcquisition || {}; - proj.typeAcquisition.include = types; - } }; - var this_3 = this; + var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_12(name); + _loop_13(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_14 = function (i) { + var _loop_15 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } else { - filesToKeep.push(proj.rootFiles[i]); + var exclude = false; + if (typeAcquisition.enable || typeAcquisition.enableAutoDiscovery) { + var baseName = ts.getBaseFileName(normalizedNames[i].toLowerCase()); + if (ts.fileExtensionIs(baseName, "js")) { + var inferredTypingName = ts.removeFileExtension(baseName); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + if (this_3.legacySafelist[cleanedTypingName]) { + this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); + excludedFiles.push(normalizedNames[i]); + exclude = true; + var typeName = this_3.legacySafelist[cleanedTypingName]; + if (typeAcqInclude.indexOf(typeName) < 0) { + typeAcqInclude.push(typeName); + } + } + } + } + if (!exclude) { + if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { + excludedFiles.push(normalizedNames[i]); + } + else { + filesToKeep.push(proj.rootFiles[i]); + } + } } }; + var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_14(i); + _loop_15(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -81939,13 +86484,19 @@ var ts; var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; } + proj.typeAcquisition = proj.typeAcquisition || {}; + proj.typeAcquisition.include = proj.typeAcquisition.include || []; + proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || []; + if (proj.typeAcquisition.enable === undefined) { + proj.typeAcquisition.enable = server.hasNoTypeScriptSource(proj.rootFiles.map(function (f) { return f.fileName; })); + } var excludedFiles = this.applySafeList(proj); var tsConfigFiles; var rootFiles = []; for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { var file = _a[_i]; var normalized = server.toNormalizedPath(file.fileName); - if (ts.getBaseFileName(normalized) === "tsconfig.json") { + if (server.getBaseConfigFileName(normalized)) { if (this.host.fileExists(normalized)) { (tsConfigFiles || (tsConfigFiles = [])).push(normalized); } @@ -81969,7 +86520,7 @@ var ts; else { externalProject.enableLanguageService(); } - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, undefined); + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); return; } this.closeExternalProject(proj.projectFileName, true); @@ -81986,7 +86537,7 @@ var ts; var newConfig = tsConfigFiles[iNew]; var oldConfig = oldConfigFiles[iOld]; if (oldConfig < newConfig) { - this.closeConfiguredProject(oldConfig); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); iOld++; } else if (oldConfig > newConfig) { @@ -81999,7 +86550,7 @@ var ts; } } for (var i = iOld; i < oldConfigFiles.length; i++) { - this.closeConfiguredProject(oldConfigFiles[i]); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); } } } @@ -82009,21 +86560,19 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - var result = this.openConfigFile(tsconfigFile); - project = result.success && result.project; + project = this.createConfiguredProject(tsconfigFile); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { - project.addOpenRef(); + project.addExternalProjectReference(); } } } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - var newProj = this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); - newProj.excludedFiles = excludedFiles; + this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); } if (!suppressRefreshOfInferredProjects) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(true); } }; ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; @@ -82110,7 +86659,7 @@ var ts; var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); if (verboseLogging) { - logger.info(msg.type + ": " + json); + logger.info(msg.type + ":" + server.indent(json)); } var len = byteLength(json, "utf8"); return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; @@ -82188,6 +86737,15 @@ var ts; }; return MultistepOperation; }()); + function toEvent(eventName, body) { + return { + seq: 0, + type: "event", + event: eventName, + body: body + }; + } + server.toEvent = toEvent; var Session = (function () { function Session(opts) { var _this = this; @@ -82224,8 +86782,8 @@ var ts; return _this.requiredResponse(converted); }, _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { - _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); _this.changeSeq++; + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); return _this.requiredResponse(true); }, _a[server.CommandNames.Exit] = function () { @@ -82238,6 +86796,12 @@ var ts; _a[server.CommandNames.DefinitionFull] = function (request) { return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, + _a[server.CommandNames.DefinitionAndBoundSpan] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, true)); + }, + _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, false)); + }, _a[server.CommandNames.TypeDefinition] = function (request) { return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, @@ -82318,7 +86882,10 @@ var ts; return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[server.CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, true)); + }, + _a[server.CommandNames.CompletionDetailsFull] = function (request) { + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, false)); }, _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); @@ -82362,7 +86929,7 @@ var ts; }, _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.output(undefined, server.CommandNames.Configure, request.seq); + _this.doOutput(undefined, server.CommandNames.Configure, request.seq, true); return _this.notRequired(); }, _a[server.CommandNames.Reload] = function (request) { @@ -82429,6 +86996,10 @@ var ts; _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); }, + _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { + _this.applyCodeActionCommand(request.command, request.seq, request.arguments); + return _this.notRequired(); + }, _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, @@ -82480,25 +87051,22 @@ var ts; var _a; } Session.prototype.sendRequestCompletedEvent = function (requestId) { - var event = { - seq: 0, - type: "event", - event: "requestCompleted", - body: { request_seq: requestId } - }; - this.send(event); + this.event({ request_seq: requestId }, "requestCompleted"); }; Session.prototype.defaultEventHandler = function (event) { - var _this = this; switch (event.eventName) { - case server.ContextEvent: - var _a = event.data, project_1 = _a.project, fileName_3 = _a.fileName; - this.projectService.logger.info("got context event, updating diagnostics for " + fileName_3); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_3, project: project_1 }], 100); }); + case server.ProjectsUpdatedInBackgroundEvent: + var openFiles = event.data.openFiles; + this.projectsUpdatedInBackgroundEvent(openFiles); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; - this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + var _a = event.data, triggerFile = _a.triggerFile, configFile = _a.configFileName, diagnostics = _a.diagnostics; + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); + this.event({ + triggerFile: triggerFile, + configFile: configFile, + diagnostics: bakedDiags + }, "configFileDiag"); break; case server.ProjectLanguageServiceStateEvent: { var eventName = "projectLanguageServiceState"; @@ -82518,12 +87086,23 @@ var ts; } } }; + Session.prototype.projectsUpdatedInBackgroundEvent = function (openFiles) { + var _this = this; + this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); + if (openFiles.length) { + var checkList_1 = this.createCheckList(openFiles); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); }); + this.event({ + openFiles: openFiles + }, "projectsUpdatedInBackground"); + } + }; Session.prototype.logError = function (err, cmd) { var msg = "Exception on executing command " + cmd; if (err.message) { - msg += ":\n" + err.message; + msg += ":\n" + server.indent(err.message); if (err.stack) { - msg += "\n" + err.stack; + msg += "\n" + server.indent(err.stack); } } this.logger.msg(msg, server.Msg.Err); @@ -82537,43 +87116,28 @@ var ts; } this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; - Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { - var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); - var ev = { - seq: 0, - type: "event", - event: "configFileDiag", - body: { - triggerFile: triggerFile, - configFile: configFile, - diagnostics: bakedDiags - } - }; - this.send(ev); - }; - Session.prototype.event = function (info, eventName) { - var ev = { - seq: 0, - type: "event", - event: eventName, - body: info - }; - this.send(ev); + Session.prototype.event = function (body, eventName) { + this.send(toEvent(eventName, body)); }; Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { - if (reqSeq === void 0) { reqSeq = 0; } + this.doOutput(info, cmdName, reqSeq, !errorMsg, errorMsg); + }; + Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { var res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, - success: !errorMsg, + success: success, }; - if (!errorMsg) { + if (success) { res.body = info; } else { - res.message = errorMsg; + ts.Debug.assert(info === undefined); + } + if (message) { + res.message = message; } this.send(res); }; @@ -82602,16 +87166,6 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.updateProjectStructure = function () { - var _this = this; - var ms = 1500; - var seq = this.changeSeq; - this.host.setTimeout(function () { - if (_this.changeSeq === seq) { - _this.projectService.refreshInferredProjects(); - } - }, ms); - }; Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; if (requireOpen === void 0) { requireOpen = true; } @@ -82624,12 +87178,14 @@ var ts; index++; if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - next.immediate(function () { - _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); - if (checkList.length > index) { - next.delay(followMs, checkOne); - } - }); + if (_this.changeSeq === seq) { + next.immediate(function () { + _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); + if (checkList.length > index) { + next.delay(followMs, checkOne); + } + }); + } } } }; @@ -82642,14 +87198,14 @@ var ts; return; } this.logger.info("cleaning " + caption); - for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { - var p = projects_5[_i]; + for (var _i = 0, projects_6 = projects; _i < projects_6.length; _i++) { + var p = projects_6[_i]; p.getLanguageService(false).cleanupSemanticCache(); } }; Session.prototype.cleanup = function () { this.cleanProjects("inferred projects", this.projectService.inferredProjects); - this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("configured projects", ts.arrayFrom(this.projectService.configuredProjects.values())); this.cleanProjects("external projects", this.projectService.externalProjects); if (this.host.gc) { this.logger.info("host.gc()"); @@ -82721,46 +87277,62 @@ var ts; }; Session.prototype.getDefinition = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return server.emptyArray; } if (simplifiedResult) { - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); + return this.mapDefinitionInfo(definitions, project); } else { return definitions; } }; + Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var scriptInfo = project.getScriptInfo(file); + var definitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!definitionAndBoundSpan || !definitionAndBoundSpan.definitions) { + return { + definitions: server.emptyArray, + textSpan: undefined + }; + } + if (simplifiedResult) { + return { + definitions: this.mapDefinitionInfo(definitionAndBoundSpan.definitions, project), + textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo) + }; + } + return definitionAndBoundSpan; + }; + Session.prototype.mapDefinitionInfo = function (definitions, project) { + var _this = this; + return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); + }; + Session.prototype.toFileSpan = function (fileName, textSpan, project) { + var scriptInfo = project.getScriptInfo(fileName); + return { + file: fileName, + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) + }; + }; Session.prototype.getTypeDefinition = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return server.emptyArray; } - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); + return this.mapDefinitionInfo(definitions, project); }; Session.prototype.getImplementation = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var position = this.getPositionInFile(args, file); var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { return server.emptyArray; @@ -82768,12 +87340,7 @@ var ts; if (simplifiedResult) { return implementations.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan; - var scriptInfo = project.getScriptInfo(fileName); - return { - file: fileName, - start: scriptInfo.positionToLineOffset(textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) - }; + return _this.toFileSpan(fileName, textSpan, project); }); } else { @@ -82782,8 +87349,7 @@ var ts; }; Session.prototype.getOccurrences = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return server.emptyArray; @@ -82791,11 +87357,9 @@ var ts; return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString; var scriptInfo = project.getScriptInfo(fileName); - var start = scriptInfo.positionToLineOffset(textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); var result = { - start: start, - end: end, + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)), file: fileName, isWriteAccess: isWriteAccess, }; @@ -82821,8 +87385,7 @@ var ts; }; Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return server.emptyArray; @@ -82855,7 +87418,8 @@ var ts; return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); }; Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { - var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project; + project.updateGraph(); var projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, @@ -82865,8 +87429,7 @@ var ts; }; Session.prototype.getRenameInfo = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); return project.getLanguageService().getRenameInfo(file, position); }; Session.prototype.getProjects = function (args) { @@ -82899,8 +87462,7 @@ var ts; }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { var file = server.toNormalizedPath(args.file); - var info = this.projectService.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, info); + var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); if (simplifiedResult) { var defaultProject = this.getDefaultProject(args); @@ -82984,7 +87546,7 @@ var ts; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); - var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); if (simplifiedResult) { var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); @@ -83023,7 +87585,7 @@ var ts; }; } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { @@ -83035,79 +87597,78 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (this.eventHandler) { - this.eventHandler({ - eventName: "configFileDiag", - data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || server.emptyArray } - }); - } + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath); }; Session.prototype.getPosition = function (args, scriptInfo) { return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); }; - Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + Session.prototype.getPositionInFile = function (args, file) { + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + return this.getPosition(args, scriptInfo); }; - Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + Session.prototype.getFileAndProject = function (args) { + return this.getFileAndProjectWorker(args.file, args.projectFileName); }; - Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { - var file = server.toNormalizedPath(uncheckedFileName); - var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); - if (!project && errorOnMissingProject) { + Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { + var file = server.toNormalizedPath(args.file); + var project = this.getProject(args.projectFileName) || this.projectService.getDefaultProjectForFile(file, false); + if (!project) { return server.Errors.ThrowNoProject(); } + return { + file: file, + languageService: project.getLanguageService(false) + }; + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, true); return { file: file, project: project }; }; Session.prototype.getOutliningSpans = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - return project.getLanguageService(false).getOutliningSpans(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + return languageService.getOutliningSpans(file); }; Session.prototype.getTodoComments = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; return project.getLanguageService().getTodoComments(file, args.descriptors); }; Session.prototype.getDocCommentTemplate = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getDocCommentTemplateAtPosition(file, position); }; Session.prototype.getSpanOfEnclosingComment = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var onlyMultiLine = args.onlyMultiLine; - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService(false).getSpanOfEnclosingComment(file, position, onlyMultiLine); + var position = this.getPositionInFile(args, file); + return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); }; Session.prototype.getIndentation = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + var indentation = languageService.getIndentationAtPosition(file, position, options); return { position: position, indentation: indentation }; }; Session.prototype.getBreakpointStatement = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getBreakpointStatementAtPosition(file, position); }; Session.prototype.getNameOrDottedNameSpan = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getNameOrDottedNameSpan(file, position, position); }; Session.prototype.isValidBraceCompletion = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); }; Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; @@ -83131,41 +87692,41 @@ var ts; }; Session.prototype.getFormattingEditsForRange = function (args) { var _this = this; - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; Session.prototype.getFormattingEditsForRangeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + return languageService.getFormattingEditsForDocument(file, options); }; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; if (lineText && lineText.search("\\S") < 0) { - var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); var hasIndent = 0; var i = void 0, len = void 0; for (i = 0, len = lineText.length; i < len; i++) { @@ -83203,44 +87764,50 @@ var ts; var _this = this; var prefix = args.prefix || ""; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, args); if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; + if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } - }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); + }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } else { return completions; } }; - Session.prototype.getCompletionEntryDetails = function (args) { + Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - return ts.mapDefined(args.entryNames, function (entryName) { - return project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + var formattingOptions = project.projectService.getFormatCodeOptions(file); + var result = ts.mapDefined(args.entryNames, function (entryName) { + var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source); }); + return simplifiedResult + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action, scriptInfo); }) })); }) + : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { - var info = this.projectService.getScriptInfo(args.file); - var result = []; + var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); if (!info) { return server.emptyArray; } + var result = []; var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { var project = projectsToSearch_1[_i]; - if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { result.push({ projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), - projectUsesOutFile: !!project.getCompilerOptions().outFile || !!project.getCompilerOptions().out + projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out }); } } @@ -83256,23 +87823,23 @@ var ts; return false; } var scriptInfo = project.getScriptInfo(file); - return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + return project.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); }; Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } if (simplifiedResult) { - var span_18 = helpItems.applicableSpan; + var span_16 = helpItems.applicableSpan; return { items: helpItems.items, applicableSpan: { - start: scriptInfo.positionToLineOffset(span_18.start), - end: scriptInfo.positionToLineOffset(span_18.start + span_18.length) + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, @@ -83283,38 +87850,41 @@ var ts; return helpItems; } }; - Session.prototype.getDiagnostics = function (next, delay, fileNames) { + Session.prototype.createCheckList = function (fileNames, defaultProject) { var _this = this; - var checkList = ts.mapDefined(fileNames, function (uncheckedFileName) { + return ts.mapDefined(fileNames, function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); - var project = _this.projectService.getDefaultProjectForFile(fileName, true); + var project = defaultProject || _this.projectService.getDefaultProjectForFile(fileName, false); return project && { fileName: fileName, project: project }; }); + }; + Session.prototype.getDiagnostics = function (next, delay, fileNames) { + var checkList = this.createCheckList(fileNames); if (checkList.length > 0) { this.updateErrorCheck(next, checkList, delay); } }; Session.prototype.change = function (args) { - var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; - if (project) { - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); - var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - if (start >= 0) { - scriptInfo.editContent(start, end, args.insertString); - this.changeSeq++; - } - this.updateProjectStructure(); + var scriptInfo = this.projectService.getScriptInfo(args.file); + ts.Debug.assert(!!scriptInfo); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (start >= 0) { + this.changeSeq++; + this.projectService.applyChangesToFile(scriptInfo, [{ + span: { start: start, length: end - start }, + newText: args.insertString + }]); } }; Session.prototype.reload = function (args, reqSeq) { var file = server.toNormalizedPath(args.file); var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); - var project = this.projectService.getDefaultProjectForFile(file, true); - if (project) { + var info = this.projectService.getScriptInfoForNormalizedPath(file); + if (info) { this.changeSeq++; - if (project.reloadScript(file, tempFileName)) { - this.output(undefined, server.CommandNames.Reload, reqSeq); + if (info.reloadFromFile(tempFileName)) { + this.doOutput(undefined, server.CommandNames.Reload, reqSeq, true); } } }; @@ -83331,49 +87901,49 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { + Session.prototype.mapLocationNavigationBarItems = function (items, scriptInfo) { var _this = this; return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), - childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), + spans: item.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + childItems: _this.mapLocationNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var items = project.getLanguageService(false).getNavigationBarItems(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var items = languageService.getNavigationBarItems(file); return !items ? undefined : simplifiedResult - ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items; }; - Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + Session.prototype.toLocationNavigationTree = function (tree, scriptInfo) { var _this = this; return { text: tree.text, kind: tree.kind, kindModifiers: tree.kindModifiers, - spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), - childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + spans: tree.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.toLocationNavigationTree(item, scriptInfo); }) }; }; - Session.prototype.decorateSpan = function (span, scriptInfo) { + Session.prototype.toLocationTextSpan = function (span, scriptInfo) { return { start: scriptInfo.positionToLineOffset(span.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) }; }; Session.prototype.getNavigationTree = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var tree = project.getLanguageService(false).getNavigationTree(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var tree = languageService.getNavigationTree(file); return !tree ? undefined : simplifiedResult - ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree; }; Session.prototype.getNavigateToItems = function (args, simplifiedResult) { @@ -83387,14 +87957,12 @@ var ts; } return navItems.map(function (navItem) { var scriptInfo = project.getScriptInfo(navItem.fileName); - var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); var bakedItem = { name: navItem.name, kind: navItem.kind, file: navItem.fileName, - start: start, - end: end, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) }; if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { bakedItem.kindModifiers = navItem.kindModifiers; @@ -83464,33 +88032,35 @@ var ts; } }; Session.prototype.getApplicableRefactors = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; return project.getLanguageService().getApplicableRefactors(file, position || textRange); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { var _this = this; - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - var result = project.getLanguageService().getEditsForRefactor(file, args.formatOptions ? server.convertFormatOptions(args.formatOptions) : this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); + var result = project.getLanguageService().getEditsForRefactor(file, this.projectService.getFormatCodeOptions(file), position || textRange, args.refactor, args.action); if (result === undefined) { return { edits: [] }; } if (simplifiedResult) { - var file_2 = result.renameFilename; - var location = void 0; - if (file_2 !== undefined && result.renameLocation !== undefined) { - var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(file_2)); - location = renameScriptInfo.positionToLineOffset(result.renameLocation); + var renameFilename = result.renameFilename, renameLocation = result.renameLocation, edits = result.edits; + var mappedRenameLocation = void 0; + if (renameFilename !== undefined && renameLocation !== undefined) { + var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); + var snapshot = renameScriptInfo.getSnapshot(); + var oldText = snapshot.getText(0, snapshot.getLength()); + mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); } return { - renameLocation: location, - renameFilename: file_2, - edits: result.edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) + renameLocation: mappedRenameLocation, + renameFilename: renameFilename, + edits: edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) }; } else { @@ -83502,7 +88072,7 @@ var ts; if (args.errorCodes.length === 0) { return undefined; } - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); @@ -83517,6 +88087,20 @@ var ts; return codeActions; } }; + Session.prototype.applyCodeActionCommand = function (commandName, requestSeq, args) { + var _this = this; + var commands = args.command; + var _loop_16 = function (command) { + var project = this_4.getFileAndProject(command).project; + var output = function (success, message) { return _this.doOutput({}, commandName, requestSeq, success, message); }; + project.getLanguageService().applyCodeActionCommand(command).then(function (result) { output(true, result.successMessage); }, function (error) { output(false, error); }); + }; + var this_4 = this; + for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { + var command = _a[_i]; + _loop_16(command); + } + }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { var startPosition = undefined, endPosition = undefined; if (args.startPosition !== undefined) { @@ -83535,15 +88119,14 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + Session.prototype.mapCodeAction = function (_a, scriptInfo) { var _this = this; - return { - description: codeAction.description, - changes: codeAction.changes.map(function (change) { return ({ - fileName: change.fileName, - textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) - }); }) - }; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands; + var changes = unmappedChanges.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }); + return { description: description, changes: changes, commands: commands }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -83562,14 +88145,14 @@ var ts; }; Session.prototype.getBraceMatching = function (args, simplifiedResult) { var _this = this; - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + var spans = languageService.getBraceMatchingAtPosition(file, position); return !spans ? undefined : simplifiedResult - ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + ? spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }) : spans; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { @@ -83577,7 +88160,7 @@ var ts; if (languageServiceDisabled) { return; } - var fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); if (fileNamesInProject.length === 0) { return; } @@ -83615,8 +88198,7 @@ var ts; var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); }; - Session.prototype.exit = function () { - }; + Session.prototype.exit = function () { }; Session.prototype.notRequired = function () { return { responseRequired: false }; }; @@ -83654,8 +88236,8 @@ var ts; return this.executeWithRequestId(request.seq, function () { return handler(request); }); } else { - this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); - this.output(undefined, server.CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); + this.doOutput(undefined, server.CommandNames.Unknown, request.seq, false, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -83665,7 +88247,7 @@ var ts; if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("request: " + message); + this.logger.info("request:" + server.indent(message)); } } var request; @@ -83682,24 +88264,43 @@ var ts; } } if (response) { - this.output(response, request.command, request.seq); + this.doOutput(response, request.command, request.seq, true); } else if (responseRequired) { - this.output(undefined, request.command, request.seq, "No content available."); + this.doOutput(undefined, request.command, request.seq, false, "No content available."); } } catch (err) { if (err instanceof ts.OperationCanceledException) { - this.output({ canceled: true }, request.command, request.seq); + this.doOutput({ canceled: true }, request.command, request.seq, true); return; } this.logError(err, message); - this.output(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); + this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); } }; return Session; }()); server.Session = Session; + function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { + var newText = applyEdits(oldText, renameFilename, edits); + var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + server.getLocationInNewDocument = getLocationInNewDocument; + function applyEdits(text, textFilename, edits) { + for (var _i = 0, edits_3 = edits; _i < edits_3.length; _i++) { + var _a = edits_3[_i], fileName = _a.fileName, textChanges_3 = _a.textChanges; + if (fileName !== textFilename) { + continue; + } + for (var i = textChanges_3.length - 1; i >= 0; i--) { + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_8 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_8); + } + } + return text; + } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -83935,18 +88536,6 @@ var ts; this.getSnapshot(); } }; - ScriptVersionCache.prototype.reload = function (script) { - this.currentVersion++; - this.changes = []; - var snap = new LineIndexSnapshot(this.currentVersion, this, new LineIndex()); - for (var i = 0; i < this.versions.length; i++) { - this.versions[i] = undefined; - } - this.versions[this.currentVersionToIndex()] = snap; - var lm = LineIndex.linesFromText(script); - snap.index.load(lm.lines); - this.minVersion = this.currentVersion; - }; ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); }; ScriptVersionCache.prototype._getSnapshot = function () { var snap = this.versions[this.currentVersionToIndex()]; @@ -84439,9 +89028,9 @@ var ts; (function (ts) { var server; (function (server) { - var net = require("net"); var childProcess = require("child_process"); var os = require("os"); + var net = require("net"); function getGlobalTypingsCacheLocation() { switch (process.platform) { case "win32": { @@ -84574,8 +89163,7 @@ var ts; return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); } var NodeTypingsInstaller = (function () { - function NodeTypingsInstaller(telemetryEnabled, logger, host, eventPort, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, newLine) { - var _this = this; + function NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, event) { this.telemetryEnabled = telemetryEnabled; this.logger = logger; this.host = host; @@ -84583,32 +89171,31 @@ var ts; this.typingSafeListLocation = typingSafeListLocation; this.typesMapLocation = typesMapLocation; this.npmLocation = npmLocation; - this.newLine = newLine; - this.installerPidReported = false; + this.event = event; this.activeRequestCount = 0; this.requestQueue = []; this.requestMap = ts.createMap(); - if (eventPort) { - var s_1 = net.connect({ port: eventPort }, function () { - _this.socket = s_1; - _this.reportInstallerProcessId(); - }); - } } - NodeTypingsInstaller.prototype.reportInstallerProcessId = function () { - if (this.installerPidReported) { - return; + NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) { + var validationResult = ts.JsTyping.validatePackageName(name); + if (validationResult !== 0) { + return false; } - if (this.socket && this.installer) { - this.sendEvent(0, "typingsInstallerPid", { pid: this.installer.pid }); - this.installerPidReported = true; + if (this.requestedRegistry) { + return !!this.typesRegistryCache && this.typesRegistryCache.has(name); } + this.requestedRegistry = true; + this.send({ kind: "typesRegistry" }); + return false; }; - NodeTypingsInstaller.prototype.sendEvent = function (seq, event, body) { - this.socket.write(server.formatMessage({ seq: seq, type: "event", event: event, body: body }, this.logger, Buffer.byteLength, this.newLine), "utf8"); - }; - NodeTypingsInstaller.prototype.setTelemetrySender = function (telemetrySender) { - this.eventSender = telemetrySender; + NodeTypingsInstaller.prototype.installPackage = function (options) { + var _this = this; + var rq = __assign({ kind: "installPackage" }, options); + this.send(rq); + ts.Debug.assert(this.packageInstalledPromise === undefined); + return new Promise(function (resolve, reject) { + _this.packageInstalledPromise = { resolve: resolve, reject: reject }; + }); }; NodeTypingsInstaller.prototype.attach = function (projectService) { var _this = this; @@ -84635,39 +89222,42 @@ var ts; var execArgv = []; for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { var arg = _a[_i]; - var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); + var match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg); if (match) { - var currentPort = match[3] !== undefined - ? +match[3] - : match[1] === "debug" ? 5858 : 9229; + var currentPort = match[2] !== undefined + ? +match[2] + : match[1].charAt(0) === "d" ? 5858 : 9229; execArgv.push("--" + match[1] + "=" + (currentPort + 1)); break; } } this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); this.installer.on("message", function (m) { return _this.handleMessage(m); }); - this.reportInstallerProcessId(); + this.event({ pid: this.installer.pid }, "typingsInstallerPid"); process.on("exit", function () { _this.installer.kill(); }); }; NodeTypingsInstaller.prototype.onProjectClosed = function (p) { - this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); + this.send({ projectName: p.getProjectName(), kind: "closeProject" }); + }; + NodeTypingsInstaller.prototype.send = function (rq) { + this.installer.send(rq); }; NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typeAcquisition, unresolvedImports) { var _this = this; var request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); if (this.logger.hasLevel(server.LogLevel.verbose)) { if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Scheduling throttled operation: " + JSON.stringify(request)); + this.logger.info("Scheduling throttled operation:" + server.stringifyIndented(request)); } } var operationId = project.getProjectName(); var operation = function () { if (_this.logger.hasLevel(server.LogLevel.verbose)) { - _this.logger.info("Sending request: " + JSON.stringify(request)); + _this.logger.info("Sending request:" + server.stringifyIndented(request)); } - _this.installer.send(request); + _this.send(request); }; var queuedRequest = { operationId: operationId, operation: operation }; if (this.activeRequestCount < NodeTypingsInstaller.maxActiveRequestCount) { @@ -84683,39 +89273,46 @@ var ts; }; NodeTypingsInstaller.prototype.handleMessage = function (response) { if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Received response: " + JSON.stringify(response)); + this.logger.info("Received response:" + server.stringifyIndented(response)); } switch (response.kind) { + case server.EventTypesRegistry: + this.typesRegistryCache = ts.createMapFromTemplate(response.typesRegistry); + break; + case server.ActionPackageInstalled: { + var success = response.success, message = response.message; + if (success) { + this.packageInstalledPromise.resolve({ successMessage: message }); + } + else { + this.packageInstalledPromise.reject(message); + } + this.packageInstalledPromise = undefined; + this.projectService.updateTypingsForProject(response); + this.event(response, "setTypings"); + break; + } case server.EventInitializationFailed: { - if (!this.eventSender) { - break; - } var body = { message: response.message }; var eventName = "typesInstallerInitializationFailed"; - this.eventSender.event(body, eventName); + this.event(body, eventName); break; } case server.EventBeginInstallTypes: { - if (!this.eventSender) { - break; - } var body = { eventId: response.eventId, packages: response.packagesToInstall, }; var eventName = "beginInstallTypes"; - this.eventSender.event(body, eventName); + this.event(body, eventName); break; } case server.EventEndInstallTypes: { - if (!this.eventSender) { - break; - } if (this.telemetryEnabled) { var body_1 = { telemetryEventName: "typingsInstalled", @@ -84726,7 +89323,7 @@ var ts; } }; var eventName_1 = "telemetry"; - this.eventSender.event(body_1, eventName_1); + this.event(body_1, eventName_1); } var body = { eventId: response.eventId, @@ -84734,7 +89331,7 @@ var ts; success: response.installSuccess, }; var eventName = "endInstallTypes"; - this.eventSender.event(body, eventName); + this.event(body, eventName); break; } case server.ActionInvalidate: @@ -84762,9 +89359,7 @@ var ts; } } this.projectService.updateTypingsForProject(response); - if (this.socket) { - this.sendEvent(0, "setTypings", response); - } + this.event(response, "setTypings"); break; } default: @@ -84786,10 +89381,18 @@ var ts; __extends(IOSession, _super); function IOSession(options) { var _this = this; - var host = options.host, installerEventPort = options.installerEventPort, globalTypingsCacheLocation = options.globalTypingsCacheLocation, typingSafeListLocation = options.typingSafeListLocation, typesMapLocation = options.typesMapLocation, npmLocation = options.npmLocation, canUseEvents = options.canUseEvents; + var host = options.host, eventPort = options.eventPort, globalTypingsCacheLocation = options.globalTypingsCacheLocation, typingSafeListLocation = options.typingSafeListLocation, typesMapLocation = options.typesMapLocation, npmLocation = options.npmLocation, canUseEvents = options.canUseEvents; + var event = function (body, eventName) { + if (_this.constructed) { + _this.event(body, eventName); + } + else { + setImmediate(function () { return _this.event(body, eventName); }); + } + }; var typingsInstaller = disableAutomaticTypingAcquisition ? undefined - : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, host.newLine); + : new NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, event); _this = _super.call(this, { host: host, cancellationToken: cancellationToken, @@ -84804,11 +89407,44 @@ var ts; pluginProbeLocations: options.pluginProbeLocations, allowLocalPluginLoads: options.allowLocalPluginLoads }) || this; - if (telemetryEnabled && typingsInstaller) { - typingsInstaller.setTelemetrySender(_this); + _this.eventPort = eventPort; + if (_this.canUseEvents && _this.eventPort) { + var s_1 = net.connect({ port: _this.eventPort }, function () { + _this.eventSocket = s_1; + if (_this.socketEventQueue) { + for (var _i = 0, _a = _this.socketEventQueue; _i < _a.length; _i++) { + var event_1 = _a[_i]; + _this.writeToEventSocket(event_1.body, event_1.eventName); + } + _this.socketEventQueue = undefined; + } + }); } + _this.constructed = true; return _this; } + IOSession.prototype.event = function (body, eventName) { + ts.Debug.assert(this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession"); + if (this.canUseEvents && this.eventPort) { + if (!this.eventSocket) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("eventPort: event \"" + eventName + "\" queued, but socket not yet initialized"); + } + (this.socketEventQueue || (this.socketEventQueue = [])).push({ body: body, eventName: eventName }); + return; + } + else { + ts.Debug.assert(this.socketEventQueue === undefined); + this.writeToEventSocket(body, eventName); + } + } + else { + _super.prototype.event.call(this, body, eventName); + } + }; + IOSession.prototype.writeToEventSocket = function (body, eventName) { + this.eventSocket.write(server.formatMessage(server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); + }; IOSession.prototype.exit = function () { this.logger.info("Exiting..."); this.projectService.closeLog(); @@ -84870,7 +89506,7 @@ var ts; function createLogger() { var cmdLineLogFileName = server.findArgument("--logFile"); var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); - var envLogOptions = parseLoggingEnvironmentString(process.env["TSS_LOG"]); + var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); var logFileName = cmdLineLogFileName ? ts.stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile @@ -84895,7 +89531,15 @@ var ts; } fs.stat(watchedFile.fileName, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Changed); + if (err.code === "ENOENT") { + if (watchedFile.mtime.getTime() !== 0) { + watchedFile.mtime = new Date(0); + watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Deleted); + } + } + else { + watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Changed); + } } else { var oldTime = watchedFile.mtime.getTime(); @@ -84991,10 +89635,20 @@ var ts; var logger = createLogger(); var sys = ts.sys; var useWatchGuard = process.platform === "win32" && ts.getNodeMajorVersion() >= 4; + var originalWatchDirectory = sys.watchDirectory.bind(sys); + var noopWatcher = { close: ts.noop }; + function watchDirectorySwallowingException(path, callback, recursive) { + try { + return originalWatchDirectory(path, callback, recursive); + } + catch (e) { + logger.info("Exception when creating directory watcher: " + e.message); + return noopWatcher; + } + } if (useWatchGuard) { var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), undefined); var statusCache_1 = ts.createMap(); - var originalWatchDirectory_1 = sys.watchDirectory; sys.watchDirectory = function (path, callback, recursive) { var cacheKey = extractWatchDirectoryCacheKey(path, currentDrive_1); var status = cacheKey && statusCache_1.get(cacheKey); @@ -85005,9 +89659,9 @@ var ts; try { var args = [ts.combinePaths(__dirname, "watchGuard.js"), path]; if (logger.hasLevel(server.LogLevel.verbose)) { - logger.info("Starting " + process.execPath + " with args " + JSON.stringify(args)); + logger.info("Starting " + process.execPath + " with args:" + server.stringifyIndented(args)); } - childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { "ELECTRON_RUN_AS_NODE": "1" } }); + childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } }); status = true; if (logger.hasLevel(server.LogLevel.verbose)) { logger.info("WatchGuard for path " + path + " returned: OK"); @@ -85027,13 +89681,16 @@ var ts; logger.info("watchDirectory for " + path + " uses cached drive information."); } if (status) { - return originalWatchDirectory_1.call(sys, path, callback, recursive); + return watchDirectorySwallowingException(path, callback, recursive); } else { - return { close: function () { } }; + return noopWatcher; } }; } + else { + sys.watchDirectory = watchDirectorySwallowingException; + } sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); @@ -85097,8 +89754,8 @@ var ts; var options = { host: sys, cancellationToken: cancellationToken, - installerEventPort: eventPort, - canUseEvents: eventPort === undefined, + eventPort: eventPort, + canUseEvents: true, useSingleInferredProject: useSingleInferredProject, useInferredProjectPerProjectRoot: useInferredProjectPerProjectRoot, disableAutomaticTypingAcquisition: disableAutomaticTypingAcquisition, @@ -85120,5 +89777,3 @@ var ts; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); - -//# sourceMappingURL=tsserver.js.map diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 01827a24d0ae4..6fd389d170a98 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -14,9 +14,15 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { + /** + * Type of objects whose values are all of the same type. + * The `in` and `for-in` operators can *not* be safely used, + * since `Object.prototype` may be modified by outside code. + */ interface MapLike { [index: string]: T; } + /** ES6 Map interface, only read methods included. */ interface ReadonlyMap { get(key: string): T | undefined; has(key: string): boolean; @@ -26,11 +32,13 @@ declare namespace ts { values(): Iterator; entries(): Iterator<[string, T]>; } + /** ES6 Map interface. */ interface Map extends ReadonlyMap { set(key: string, value: T): this; delete(key: string): boolean; clear(): void; } + /** ES6 Iterator type. */ interface Iterator { next(): { value: T; @@ -40,6 +48,7 @@ declare namespace ts { done: true; }; } + /** Array that is only intended to be pushed to, never read. */ interface Push { push(...values: T[]): void; } @@ -50,7 +59,7 @@ declare namespace ts { pos: number; end: number; } - const enum SyntaxKind { + enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, SingleLineCommentTrivia = 2, @@ -191,159 +200,163 @@ declare namespace ts { SymbolKeyword = 137, TypeKeyword = 138, UndefinedKeyword = 139, - FromKeyword = 140, - GlobalKeyword = 141, - OfKeyword = 142, - QualifiedName = 143, - ComputedPropertyName = 144, - TypeParameter = 145, - Parameter = 146, - Decorator = 147, - PropertySignature = 148, - PropertyDeclaration = 149, - MethodSignature = 150, - MethodDeclaration = 151, - Constructor = 152, - GetAccessor = 153, - SetAccessor = 154, - CallSignature = 155, - ConstructSignature = 156, - IndexSignature = 157, - TypePredicate = 158, - TypeReference = 159, - FunctionType = 160, - ConstructorType = 161, - TypeQuery = 162, - TypeLiteral = 163, - ArrayType = 164, - TupleType = 165, - UnionType = 166, - IntersectionType = 167, - ParenthesizedType = 168, - ThisType = 169, - TypeOperator = 170, - IndexedAccessType = 171, - MappedType = 172, - LiteralType = 173, - ObjectBindingPattern = 174, - ArrayBindingPattern = 175, - BindingElement = 176, - ArrayLiteralExpression = 177, - ObjectLiteralExpression = 178, - PropertyAccessExpression = 179, - ElementAccessExpression = 180, - CallExpression = 181, - NewExpression = 182, - TaggedTemplateExpression = 183, - TypeAssertionExpression = 184, - ParenthesizedExpression = 185, - FunctionExpression = 186, - ArrowFunction = 187, - DeleteExpression = 188, - TypeOfExpression = 189, - VoidExpression = 190, - AwaitExpression = 191, - PrefixUnaryExpression = 192, - PostfixUnaryExpression = 193, - BinaryExpression = 194, - ConditionalExpression = 195, - TemplateExpression = 196, - YieldExpression = 197, - SpreadElement = 198, - ClassExpression = 199, - OmittedExpression = 200, - ExpressionWithTypeArguments = 201, - AsExpression = 202, - NonNullExpression = 203, - MetaProperty = 204, - TemplateSpan = 205, - SemicolonClassElement = 206, - Block = 207, - VariableStatement = 208, - EmptyStatement = 209, - ExpressionStatement = 210, - IfStatement = 211, - DoStatement = 212, - WhileStatement = 213, - ForStatement = 214, - ForInStatement = 215, - ForOfStatement = 216, - ContinueStatement = 217, - BreakStatement = 218, - ReturnStatement = 219, - WithStatement = 220, - SwitchStatement = 221, - LabeledStatement = 222, - ThrowStatement = 223, - TryStatement = 224, - DebuggerStatement = 225, - VariableDeclaration = 226, - VariableDeclarationList = 227, - FunctionDeclaration = 228, - ClassDeclaration = 229, - InterfaceDeclaration = 230, - TypeAliasDeclaration = 231, - EnumDeclaration = 232, - ModuleDeclaration = 233, - ModuleBlock = 234, - CaseBlock = 235, - NamespaceExportDeclaration = 236, - ImportEqualsDeclaration = 237, - ImportDeclaration = 238, - ImportClause = 239, - NamespaceImport = 240, - NamedImports = 241, - ImportSpecifier = 242, - ExportAssignment = 243, - ExportDeclaration = 244, - NamedExports = 245, - ExportSpecifier = 246, - MissingDeclaration = 247, - ExternalModuleReference = 248, - JsxElement = 249, - JsxSelfClosingElement = 250, - JsxOpeningElement = 251, - JsxClosingElement = 252, - JsxAttribute = 253, - JsxAttributes = 254, - JsxSpreadAttribute = 255, - JsxExpression = 256, - CaseClause = 257, - DefaultClause = 258, - HeritageClause = 259, - CatchClause = 260, - PropertyAssignment = 261, - ShorthandPropertyAssignment = 262, - SpreadAssignment = 263, - EnumMember = 264, - SourceFile = 265, - Bundle = 266, - JSDocTypeExpression = 267, - JSDocAllType = 268, - JSDocUnknownType = 269, - JSDocNullableType = 270, - JSDocNonNullableType = 271, - JSDocOptionalType = 272, - JSDocFunctionType = 273, - JSDocVariadicType = 274, - JSDocComment = 275, - JSDocTag = 276, - JSDocAugmentsTag = 277, - JSDocClassTag = 278, - JSDocParameterTag = 279, - JSDocReturnTag = 280, - JSDocTypeTag = 281, - JSDocTemplateTag = 282, - JSDocTypedefTag = 283, - JSDocPropertyTag = 284, - JSDocTypeLiteral = 285, - SyntaxList = 286, - NotEmittedStatement = 287, - PartiallyEmittedExpression = 288, - CommaListExpression = 289, - MergeDeclarationMarker = 290, - EndOfDeclarationMarker = 291, - Count = 292, + UniqueKeyword = 140, + FromKeyword = 141, + GlobalKeyword = 142, + OfKeyword = 143, + QualifiedName = 144, + ComputedPropertyName = 145, + TypeParameter = 146, + Parameter = 147, + Decorator = 148, + PropertySignature = 149, + PropertyDeclaration = 150, + MethodSignature = 151, + MethodDeclaration = 152, + Constructor = 153, + GetAccessor = 154, + SetAccessor = 155, + CallSignature = 156, + ConstructSignature = 157, + IndexSignature = 158, + TypePredicate = 159, + TypeReference = 160, + FunctionType = 161, + ConstructorType = 162, + TypeQuery = 163, + TypeLiteral = 164, + ArrayType = 165, + TupleType = 166, + UnionType = 167, + IntersectionType = 168, + ParenthesizedType = 169, + ThisType = 170, + TypeOperator = 171, + IndexedAccessType = 172, + MappedType = 173, + LiteralType = 174, + ObjectBindingPattern = 175, + ArrayBindingPattern = 176, + BindingElement = 177, + ArrayLiteralExpression = 178, + ObjectLiteralExpression = 179, + PropertyAccessExpression = 180, + ElementAccessExpression = 181, + CallExpression = 182, + NewExpression = 183, + TaggedTemplateExpression = 184, + TypeAssertionExpression = 185, + ParenthesizedExpression = 186, + FunctionExpression = 187, + ArrowFunction = 188, + DeleteExpression = 189, + TypeOfExpression = 190, + VoidExpression = 191, + AwaitExpression = 192, + PrefixUnaryExpression = 193, + PostfixUnaryExpression = 194, + BinaryExpression = 195, + ConditionalExpression = 196, + TemplateExpression = 197, + YieldExpression = 198, + SpreadElement = 199, + ClassExpression = 200, + OmittedExpression = 201, + ExpressionWithTypeArguments = 202, + AsExpression = 203, + NonNullExpression = 204, + MetaProperty = 205, + TemplateSpan = 206, + SemicolonClassElement = 207, + Block = 208, + VariableStatement = 209, + EmptyStatement = 210, + ExpressionStatement = 211, + IfStatement = 212, + DoStatement = 213, + WhileStatement = 214, + ForStatement = 215, + ForInStatement = 216, + ForOfStatement = 217, + ContinueStatement = 218, + BreakStatement = 219, + ReturnStatement = 220, + WithStatement = 221, + SwitchStatement = 222, + LabeledStatement = 223, + ThrowStatement = 224, + TryStatement = 225, + DebuggerStatement = 226, + VariableDeclaration = 227, + VariableDeclarationList = 228, + FunctionDeclaration = 229, + ClassDeclaration = 230, + InterfaceDeclaration = 231, + TypeAliasDeclaration = 232, + EnumDeclaration = 233, + ModuleDeclaration = 234, + ModuleBlock = 235, + CaseBlock = 236, + NamespaceExportDeclaration = 237, + ImportEqualsDeclaration = 238, + ImportDeclaration = 239, + ImportClause = 240, + NamespaceImport = 241, + NamedImports = 242, + ImportSpecifier = 243, + ExportAssignment = 244, + ExportDeclaration = 245, + NamedExports = 246, + ExportSpecifier = 247, + MissingDeclaration = 248, + ExternalModuleReference = 249, + JsxElement = 250, + JsxSelfClosingElement = 251, + JsxOpeningElement = 252, + JsxClosingElement = 253, + JsxFragment = 254, + JsxOpeningFragment = 255, + JsxClosingFragment = 256, + JsxAttribute = 257, + JsxAttributes = 258, + JsxSpreadAttribute = 259, + JsxExpression = 260, + CaseClause = 261, + DefaultClause = 262, + HeritageClause = 263, + CatchClause = 264, + PropertyAssignment = 265, + ShorthandPropertyAssignment = 266, + SpreadAssignment = 267, + EnumMember = 268, + SourceFile = 269, + Bundle = 270, + JSDocTypeExpression = 271, + JSDocAllType = 272, + JSDocUnknownType = 273, + JSDocNullableType = 274, + JSDocNonNullableType = 275, + JSDocOptionalType = 276, + JSDocFunctionType = 277, + JSDocVariadicType = 278, + JSDocComment = 279, + JSDocTypeLiteral = 280, + JSDocTag = 281, + JSDocAugmentsTag = 282, + JSDocClassTag = 283, + JSDocParameterTag = 284, + JSDocReturnTag = 285, + JSDocTypeTag = 286, + JSDocTemplateTag = 287, + JSDocTypedefTag = 288, + JSDocPropertyTag = 289, + SyntaxList = 290, + NotEmittedStatement = 291, + PartiallyEmittedExpression = 292, + CommaListExpression = 293, + MergeDeclarationMarker = 294, + EndOfDeclarationMarker = 295, + Count = 296, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -351,15 +364,15 @@ declare namespace ts { FirstReservedWord = 72, LastReservedWord = 107, FirstKeyword = 72, - LastKeyword = 142, + LastKeyword = 143, FirstFutureReservedWord = 108, LastFutureReservedWord = 116, - FirstTypeNode = 158, - LastTypeNode = 173, + FirstTypeNode = 159, + LastTypeNode = 174, FirstPunctuation = 17, LastPunctuation = 70, FirstToken = 0, - LastToken = 142, + LastToken = 143, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -368,13 +381,13 @@ declare namespace ts { LastTemplateToken = 16, FirstBinaryOperator = 27, LastBinaryOperator = 70, - FirstNode = 143, - FirstJSDocNode = 267, - LastJSDocNode = 285, - FirstJSDocTagNode = 276, - LastJSDocTagNode = 285, + FirstNode = 144, + FirstJSDocNode = 271, + LastJSDocNode = 289, + FirstJSDocTagNode = 281, + LastJSDocTagNode = 289, } - const enum NodeFlags { + enum NodeFlags { None = 0, Let = 1, Const = 2, @@ -399,10 +412,10 @@ declare namespace ts { BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, - ContextFlags = 96256, + ContextFlags = 6387712, TypeExcludesFlags = 20480, } - const enum ModifierFlags { + enum ModifierFlags { None = 0, Export = 1, Ambient = 2, @@ -422,9 +435,11 @@ declare namespace ts { TypeScriptModifier = 2270, ExportDefault = 513, } - const enum JsxFlags { + enum JsxFlags { None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, IntrinsicElement = 3, } @@ -446,6 +461,7 @@ declare namespace ts { } type DotDotDotToken = Token; type QuestionToken = Token; + type ExclamationToken = Token; type ColonToken = Token; type EqualsToken = Token; type AsteriskToken = Token; @@ -456,8 +472,12 @@ declare namespace ts { type AwaitKeywordToken = Token; type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; type ModifiersArray = NodeArray; - interface Identifier extends PrimaryExpression { + interface Identifier extends PrimaryExpression, Declaration { kind: SyntaxKind.Identifier; + /** + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. + */ escapedText: __String; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; @@ -518,6 +538,7 @@ declare namespace ts { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -552,8 +573,9 @@ declare namespace ts { } interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; - questionToken?: QuestionToken; name: PropertyName; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -587,6 +609,7 @@ declare namespace ts { dotDotDotToken?: DotDotDotToken; name: DeclarationName; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -605,6 +628,14 @@ declare namespace ts { } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; type ArrayBindingElement = BindingElement | OmittedExpression; + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; @@ -632,6 +663,7 @@ declare namespace ts { parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; } + /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; @@ -640,13 +672,13 @@ declare namespace ts { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; - body: FunctionBody; + body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; - body: FunctionBody; + body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { @@ -712,7 +744,7 @@ declare namespace ts { } interface TypeOperatorNode extends TypeNode { kind: SyntaxKind.TypeOperator; - operator: SyntaxKind.KeyOfKeyword; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; type: TypeNode; } interface IndexedAccessTypeNode extends TypeNode { @@ -747,6 +779,7 @@ declare namespace ts { interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } + /** Deprecated, please use UpdateExpression */ type IncrementExpression = UpdateExpression; interface UpdateExpression extends UnaryExpression { _updateExpressionBrand: any; @@ -927,6 +960,12 @@ declare namespace ts { parent?: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } + /** + * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to + * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be + * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type + * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) + */ interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { properties: NodeArray; } @@ -943,6 +982,7 @@ declare namespace ts { interface SuperPropertyAccessExpression extends PropertyAccessExpression { expression: SuperExpression; } + /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; @@ -1029,6 +1069,20 @@ declare namespace ts { tagName: JsxTagNameExpression; attributes: JsxAttributes; } + interface JsxFragment extends PrimaryExpression { + kind: SyntaxKind.JsxFragment; + openingFragment: JsxOpeningFragment; + children: NodeArray; + closingFragment: JsxClosingFragment; + } + interface JsxOpeningFragment extends Expression { + kind: SyntaxKind.JsxOpeningFragment; + parent?: JsxFragment; + } + interface JsxClosingFragment extends Expression { + kind: SyntaxKind.JsxClosingFragment; + parent?: JsxFragment; + } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; parent?: JsxAttributes; @@ -1056,13 +1110,16 @@ declare namespace ts { containsOnlyWhiteSpaces: boolean; parent?: JsxElement; } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { _statementBrand: any; } interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } + /** + * A list of comma-seperated expressions. This node is only created by transformations. + */ interface CommaListExpression extends Expression { kind: SyntaxKind.CommaListExpression; elements: NodeArray; @@ -1267,6 +1324,11 @@ declare namespace ts { statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; + /** + * One of: + * - import x = require("mod"); + * - import x = M.x; + */ interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; parent?: SourceFile | ModuleBlock; @@ -1282,6 +1344,7 @@ declare namespace ts { kind: SyntaxKind.ImportDeclaration; parent?: SourceFile | ModuleBlock; importClause?: ImportClause; + /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; @@ -1304,6 +1367,7 @@ declare namespace ts { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; exportClause?: NamedExports; + /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; } interface NamedImports extends Node { @@ -1400,9 +1464,15 @@ declare namespace ts { interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ interface JSDocAugmentsTag extends JSDocTag { kind: SyntaxKind.JSDocAugmentsTag; - typeExpression: JSDocTypeExpression; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; } interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; @@ -1429,7 +1499,8 @@ declare namespace ts { interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ isNameFirst: boolean; isBracketed: boolean; } @@ -1442,9 +1513,10 @@ declare namespace ts { interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: ReadonlyArray; + /** If true, then this type literal represents an *array* of its type. */ isArrayType?: boolean; } - const enum FlowFlags { + enum FlowFlags { Unreachable = 1, Start = 2, BranchLabel = 4, @@ -1521,6 +1593,14 @@ declare namespace ts { typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; isDeclarationFile: boolean; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ hasNoDefaultLib: boolean; languageVersion: ScriptTarget; } @@ -1534,47 +1614,77 @@ declare namespace ts { } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getSourceFileByPath(path: Path): SourceFile; + getSourceFile(fileName: string): SourceFile | undefined; + getSourceFileByPath(path: Path): SourceFile | undefined; getCurrentDirectory(): string; } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ fileExists(path: string): boolean; readFile(path: string): string | undefined; } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray): void; - } + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ throwIfCancellationRequested(): void; } interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ getRootFileNames(): ReadonlyArray; + /** + * Get a list of files in the program + */ getSourceFiles(): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Gets a type checker that can be used to semantically analyze source files in the program. + */ getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; } interface CustomTransformers { + /** Custom transformers to evaluate before built-in transformations. */ before?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in transformations. */ after?: TransformerFactory[]; } interface SourceMapSpan { + /** Line number in the .js file. */ emittedLine: number; + /** Column number in the .js file. */ emittedColumn: number; + /** Line number in the .ts file. */ sourceLine: number; + /** Column number in the .ts file. */ sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ sourceIndex: number; } interface SourceMapData { @@ -1589,6 +1699,7 @@ declare namespace ts { sourceMapMappings: string; sourceMapDecodedMappings: SourceMapSpan[]; } + /** Return code used by getEmitOutput function to indicate status of the function */ enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, @@ -1596,6 +1707,7 @@ declare namespace ts { } interface EmitResult { emitSkipped: boolean; + /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; emittedFiles: string[]; } @@ -1613,14 +1725,25 @@ declare namespace ts { getReturnTypeOfSignature(signature: Signature): Type; getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; + /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; + /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; + /** + * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. + * Otherwise returns its input. + * For example, at `export type T = number;`: + * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. + * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. + * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. + */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; getTypeAtLocation(node: Node): Type; @@ -1628,12 +1751,20 @@ declare namespace ts { signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + /** + * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead + * This will be removed in a future version. + */ getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; + /** + * returns unknownSignature in the case of an error. + * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. + */ + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: FunctionLike): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; @@ -1641,6 +1772,7 @@ declare namespace ts { isUnknownSymbol(symbol: Symbol): boolean; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; @@ -1651,6 +1783,8 @@ declare namespace ts { getApparentType(type: Type): Type; getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; + getBaseConstraintOfType(type: Type): Type | undefined; + getDefaultFromTypeParameter(type: Type): Type | undefined; } enum NodeBuilderFlags { None = 0, @@ -1698,8 +1832,9 @@ declare namespace ts { trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; reportPrivateInBaseOfClassExpression(propertyName: string): void; + reportInaccessibleUniqueSymbolError(): void; } - const enum TypeFormatFlags { + enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, UseTypeOfFunction = 4, @@ -1716,13 +1851,14 @@ declare namespace ts { WriteClassExpressionAsTypeLiteral = 16384, InArrayType = 32768, UseAliasDefinedOutsideCurrentScope = 65536, + AllowUniqueESSymbolType = 131072, } - const enum SymbolFormatFlags { + enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } - const enum TypePredicateKind { + enum TypePredicateKind { This = 0, Identifier = 1, } @@ -1739,7 +1875,7 @@ declare namespace ts { parameterIndex: number; } type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; - const enum SymbolFlags { + enum SymbolFlags { None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, @@ -1767,6 +1903,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, + JSContainer = 67108864, Enum = 384, Variable = 3, Value = 107455, @@ -1809,7 +1946,7 @@ declare namespace ts { exports?: SymbolTable; globalExports?: SymbolTable; } - const enum InternalSymbolName { + enum InternalSymbolName { Call = "__call", Constructor = "__constructor", New = "__new", @@ -1827,11 +1964,20 @@ declare namespace ts { ExportEquals = "export=", Default = "default", } + /** + * This represents a string whose leading underscore have been escaped by adding extra leading underscores. + * The shape of this brand is rather unique compared to others we've used. + * Instead of just an intersection of a string and an object, it is that union-ed + * with an intersection of void and an object. This makes it wholly incompatible + * with a normal string (which is good, it cannot be misused on assignment or on usage), + * while still being comparable with a normal string via === (also good) and castable from a string. + */ type __String = (string & { __escapedIdentifier: void; }) | (void & { __escapedIdentifier: void; }) | InternalSymbolName; + /** ReadonlyMap where keys are `__String`s. */ interface ReadonlyUnderscoreEscapedMap { get(key: __String): T | undefined; has(key: __String): boolean; @@ -1841,13 +1987,15 @@ declare namespace ts { values(): Iterator; entries(): Iterator<[__String, T]>; } + /** Map where keys are `__String`s. */ interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { set(key: __String, value: T): this; delete(key: __String): boolean; clear(): void; } + /** SymbolTable based on ES6 Map interface. */ type SymbolTable = UnderscoreEscapedMap; - const enum TypeFlags { + enum TypeFlags { Any = 1, String = 2, Number = 4, @@ -1858,31 +2006,34 @@ declare namespace ts { BooleanLiteral = 128, EnumLiteral = 256, ESSymbol = 512, - Void = 1024, - Undefined = 2048, - Null = 4096, - Never = 8192, - TypeParameter = 16384, - Object = 32768, - Union = 65536, - Intersection = 131072, - Index = 262144, - IndexedAccess = 524288, - NonPrimitive = 16777216, + UniqueESSymbol = 1024, + Void = 2048, + Undefined = 4096, + Null = 8192, + Never = 16384, + TypeParameter = 32768, + Object = 65536, + Union = 131072, + Intersection = 262144, + Index = 524288, + IndexedAccess = 1048576, + NonPrimitive = 33554432, + MarkerType = 134217728, Literal = 224, - Unit = 6368, + Unit = 13536, StringOrNumberLiteral = 96, - PossiblyFalsy = 7406, - StringLike = 262178, + PossiblyFalsy = 14574, + StringLike = 524322, NumberLike = 84, BooleanLike = 136, EnumLike = 272, - UnionOrIntersection = 196608, - StructuredType = 229376, - StructuredOrTypeVariable = 1032192, - TypeVariable = 540672, - Narrowable = 17810175, - NotUnionOrUnit = 16810497, + ESSymbolLike = 1536, + UnionOrIntersection = 393216, + StructuredType = 458752, + StructuredOrTypeVariable = 2064384, + TypeVariable = 1081344, + Narrowable = 35620607, + NotUnionOrUnit = 33620481, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1897,6 +2048,9 @@ declare namespace ts { freshType?: LiteralType; regularType?: LiteralType; } + interface UniqueESSymbolType extends Type { + symbol: Symbol; + } interface StringLiteralType extends LiteralType { value: string; } @@ -1905,7 +2059,7 @@ declare namespace ts { } interface EnumType extends Type { } - const enum ObjectFlags { + enum ObjectFlags { Class = 1, Interface = 2, Reference = 4, @@ -1916,11 +2070,13 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, + ContainsSpread = 1024, ClassOrInterface = 3, } interface ObjectType extends Type { objectFlags: ObjectFlags; } + /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; outerTypeParameters: TypeParameter[]; @@ -1935,6 +2091,16 @@ declare namespace ts { declaredStringIndexInfo: IndexInfo; declaredNumberIndexInfo: IndexInfo; } + /** + * Type references (ObjectFlags.Reference). When a class or interface has type parameters or + * a "this" type, references to the class or interface are made using type references. The + * typeArguments property specifies the types to substitute for the type parameters of the + * class or interface and optionally includes an extra element that specifies the type to + * substitute for "this" in the resulting instantiation. When no extra argument is present, + * the type reference itself is substituted for "this". The typeArguments property is undefined + * if the class or interface has no type parameters and the reference isn't specifying an + * explicit "this" argument. + */ interface TypeReference extends ObjectType { target: GenericType; typeArguments?: Type[]; @@ -1956,8 +2122,6 @@ declare namespace ts { interface TypeVariable extends Type { } interface TypeParameter extends TypeVariable { - constraint: Type; - default?: Type; } interface IndexedAccessType extends TypeVariable { objectType: Type; @@ -1967,7 +2131,7 @@ declare namespace ts { interface IndexType extends Type { type: TypeVariable | UnionOrIntersectionType; } - const enum SignatureKind { + enum SignatureKind { Call = 0, Construct = 1, } @@ -1976,7 +2140,7 @@ declare namespace ts { typeParameters?: TypeParameter[]; parameters: Symbol[]; } - const enum IndexKind { + enum IndexKind { String = 0, Number = 1, } @@ -1985,10 +2149,12 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } - const enum InferencePriority { - NakedTypeVariable = 1, - MappedType = 2, - ReturnType = 4, + enum InferencePriority { + Contravariant = 1, + NakedTypeVariable = 2, + MappedType = 4, + ReturnType = 8, + NeverType = 16, } interface InferenceInfo { typeParameter: TypeParameter; @@ -1998,12 +2164,21 @@ declare namespace ts { topLevel: boolean; isFixed: boolean; } - const enum InferenceFlags { + enum InferenceFlags { InferUnionTypes = 1, NoDefault = 2, AnyDefault = 4, } - const enum Ternary { + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + enum Ternary { False = 0, Maybe = 1, True = -1, @@ -2012,6 +2187,7 @@ declare namespace ts { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface DiagnosticMessage { key: string; @@ -2019,6 +2195,12 @@ declare namespace ts { code: number; message: string; } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ interface DiagnosticMessageChain { messageText: string; category: DiagnosticCategory; @@ -2107,12 +2289,15 @@ declare namespace ts { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; + strictFunctionTypes?: boolean; strictNullChecks?: boolean; + strictPropertyInitialization?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; types?: string[]; + /** Paths used to compute primary types search locations */ typeRoots?: string[]; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } @@ -2141,21 +2326,22 @@ declare namespace ts { ES2015 = 5, ESNext = 6, } - const enum JsxEmit { + enum JsxEmit { None = 0, Preserve = 1, React = 2, ReactNative = 3, } - const enum NewLineKind { + enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1, } interface LineAndCharacter { + /** 0-based. */ line: number; character: number; } - const enum ScriptKind { + enum ScriptKind { Unknown = 0, JS = 1, JSX = 2, @@ -2164,19 +2350,21 @@ declare namespace ts { External = 5, JSON = 6, } - const enum ScriptTarget { + enum ScriptTarget { ES3 = 0, ES5 = 1, ES2015 = 2, ES2016 = 3, ES2017 = 4, - ESNext = 5, - Latest = 5, + ES2018 = 5, + ESNext = 6, + Latest = 6, } - const enum LanguageVariant { + enum LanguageVariant { Standard = 0, JSX = 1, } + /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { options: CompilerOptions; typeAcquisition?: TypeAcquisition; @@ -2186,7 +2374,7 @@ declare namespace ts { wildcardDirectories?: MapLike; compileOnSave?: boolean; } - const enum WatchDirectoryFlags { + enum WatchDirectoryFlags { None = 0, Recursive = 1, } @@ -2199,45 +2387,82 @@ declare namespace ts { readFile(fileName: string): string | undefined; trace?(s: string): void; directoryExists?(directoryName: string): boolean; + /** + * Resolve a symbolic link. + * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options + */ realpath?(path: string): string; getCurrentDirectory?(): string; getDirectories?(path: string): string[]; } + /** + * Represents the result of module resolution. + * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. + * The Program will then filter results based on these flags. + * + * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. + */ interface ResolvedModule { + /** Path of the file the module was resolved to. */ resolvedFileName: string; + /** True if `resolvedFileName` comes from `node_modules`. */ isExternalLibraryImport?: boolean; } + /** + * ResolvedModule with an explicitly provided `extension` property. + * Prefer this over `ResolvedModule`. + * If changing this, remember to change `moduleResolutionIsEqualTo`. + */ interface ResolvedModuleFull extends ResolvedModule { + /** + * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. + * This is optional for backwards-compatibility, but will be added if not provided. + */ extension: Extension; packageId?: PackageId; } + /** + * Unique identifier with a package name and version. + * If changing this, remember to change `packageIdIsEqual`. + */ interface PackageId { + /** + * Name of the package. + * Should not include `@types`. + * If accessing a non-index file, this should include its name e.g. "foo/bar". + */ name: string; + /** + * Name of a submodule within this package. + * May be "". + */ subModuleName: string; + /** Version of the package, e.g. "1.2.3" */ version: string; } - const enum Extension { + enum Extension { Ts = ".ts", Tsx = ".tsx", Dts = ".d.ts", Js = ".js", Jsx = ".jsx", + Json = ".json", } interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModuleFull | undefined; + readonly resolvedModule: ResolvedModuleFull | undefined; } interface ResolvedTypeReferenceDirective { primary: boolean; - resolvedFileName?: string; + resolvedFileName: string | undefined; packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; - failedLookupLocations: string[]; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; - getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -2247,7 +2472,10 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + /** + * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files + */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string; } @@ -2259,7 +2487,7 @@ declare namespace ts { text: string; skipTrivia?: (pos: number) => number; } - const enum EmitFlags { + enum EmitFlags { SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2295,7 +2523,7 @@ declare namespace ts { readonly text: string; readonly priority?: number; } - const enum EmitHint { + enum EmitHint { SourceFile = 0, Expression = 1, IdentifierName = 2, @@ -2303,41 +2531,159 @@ declare namespace ts { Unspecified = 4, } interface TransformationContext { + /** Gets the compiler options supplied to the transformer. */ getCompilerOptions(): CompilerOptions; + /** Starts a new lexical environment. */ startLexicalEnvironment(): void; + /** Suspends the current lexical environment, usually after visiting a parameter list. */ suspendLexicalEnvironment(): void; + /** Resumes a suspended lexical environment, usually before visiting a function body. */ resumeLexicalEnvironment(): void; + /** Ends a lexical environment, returning any declarations. */ endLexicalEnvironment(): Statement[]; + /** Hoists a function declaration to the containing scope. */ hoistFunctionDeclaration(node: FunctionDeclaration): void; + /** Hoists a variable declaration to the containing scope. */ hoistVariableDeclaration(node: Identifier): void; + /** Records a request for a non-scoped emit helper in the current context. */ requestEmitHelper(helper: EmitHelper): void; + /** Gets and resets the requested non-scoped emit helpers. */ readEmitHelpers(): EmitHelper[] | undefined; + /** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */ enableSubstitution(kind: SyntaxKind): void; + /** Determines whether expression substitutions are enabled for the provided node. */ isSubstitutionEnabled(node: Node): boolean; + /** + * Hook used by transformers to substitute expressions just before they + * are emitted by the pretty printer. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ onSubstituteNode: (hint: EmitHint, node: Node) => Node; + /** + * Enables before/after emit notifications in the pretty printer for the provided + * SyntaxKind. + */ enableEmitNotification(kind: SyntaxKind): void; + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ isEmitNotificationEnabled(node: Node): boolean; + /** + * Hook used to allow transformers to capture state before or after + * the printer emits a node. + * + * NOTE: Transformation hooks should only be modified during `Transformer` initialization, + * before returning the `NodeTransformer` callback. + */ onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; } interface TransformationResult { + /** Gets the transformed source files. */ transformed: T[]; + /** Gets diagnostics for the transformation. */ diagnostics?: Diagnostic[]; + /** + * Gets a substitute for a node, if one is available; otherwise, returns the original node. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ substituteNode(hint: EmitHint, node: Node): Node; + /** + * Emits a node with possible notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + /** + * Clean up EmitNode entries on any parse-tree nodes. + */ dispose(): void; } + /** + * A function that is used to initialize and return a `Transformer` callback, which in turn + * will be used to transform one or more nodes. + */ type TransformerFactory = (context: TransformationContext) => Transformer; + /** + * A function that transforms a node. + */ type Transformer = (node: T) => T; + /** + * A function that accepts and possibly transforms a node. + */ type Visitor = (node: Node) => VisitResult; type VisitResult = T | T[] | undefined; interface Printer { + /** + * Print a node and its subtree as-is, without any emit transformations. + * @param hint A value indicating the purpose of a node. This is primarily used to + * distinguish between an `Identifier` used in an expression position, versus an + * `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you + * should just pass `Unspecified`. + * @param node The node to print. The node and its subtree are printed as-is, without any + * emit transformations. + * @param sourceFile A source file that provides context for the node. The source text of + * the file is used to emit the original source content for literals and identifiers, while + * the identifiers of the source file are used when generating unique names to avoid + * collisions. + */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a source file as-is, without any emit transformations. + */ printFile(sourceFile: SourceFile): string; + /** + * Prints a bundle of source files as-is, without any emit transformations. + */ printBundle(bundle: Bundle): string; } interface PrintHandlers { + /** + * A hook used by the Printer when generating unique names to avoid collisions with + * globally defined names that exist outside of the current source file. + */ hasGlobalName?(name: string): boolean; + /** + * A hook used by the Printer to provide notifications prior to emitting a node. A + * compatible implementation **must** invoke `emitCallback` with the provided `hint` and + * `node` values. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @param emitCallback A callback that, when invoked, will emit the node. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * onEmitNode(hint, node, emitCallback) { + * // set up or track state prior to emitting the node... + * emitCallback(hint, node); + * // restore state after emitting the node... + * } + * }); + * ``` + */ onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + /** + * A hook used by the Printer to perform just-in-time substitution of a node. This is + * primarily used by node transformations that need to substitute one node for another, + * such as replacing `myExportedVar` with `exports.myExportedVar`. + * @param hint A hint indicating the intended purpose of the node. + * @param node The node to emit. + * @example + * ```ts + * var printer = createPrinter(printerOptions, { + * substituteNode(hint, node) { + * // perform substitution if necessary... + * return node; + * } + * }); + * ``` + */ substituteNode?(hint: EmitHint, node: Node): Node; } interface PrinterOptions { @@ -2357,7 +2703,8 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.6"; + const versionMajorMinor = "2.7"; + /** The version of the TypeScript compiler release */ const version: string; } declare namespace ts { @@ -2378,28 +2725,41 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - interface System { - args: string[]; + /** + * Partial interface of the System thats needed to support the caching of directory structure + */ + interface DirectoryStructureHost { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; createDirectory(path: string): void; - getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + exit(exitCode?: number): void; + } + interface System extends DirectoryStructureHost { + args: string[]; + getFileSize?(path: string): number; + /** + * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that + * use native OS file watching + */ + watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + resolvePath(path: string): string; + getExecutingFilePath(): string; getModifiedTime?(path: string): Date; + /** + * This should be cryptographically secure. + * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) + */ createHash?(data: string): string; getMemoryUsage?(): number; - exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; @@ -2407,10 +2767,6 @@ declare namespace ts { interface FileWatcher { close(): void; } - interface DirectoryWatcher extends FileWatcher { - directoryName: string; - referenceCount: number; - } function getNodeMajorVersion(): number; let sys: System; } @@ -2433,6 +2789,14 @@ declare namespace ts { function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: Node): boolean; @@ -2440,6 +2804,10 @@ declare namespace ts { function isEmptyBindingElement(node: BindingElement): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ function validateLocaleAndSetLanguage(locale: string, sys: { getExecutingFilePath(): string; resolvePath(path: string): string; @@ -2448,23 +2816,99 @@ declare namespace ts { }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ function isParseTreeNode(node: Node): boolean; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @returns The original parse tree node if found; otherwise, undefined. + */ function getParseTreeNode(node: Node): Node; + /** + * Gets the original parse tree node for a node. + * + * @param node The original node. + * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. + * @returns The original parse tree node if found; otherwise, undefined. + */ function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ function unescapeLeadingUnderscores(identifier: __String): string; + function idText(identifier: Identifier): string; + function symbolName(symbol: Symbol): string; + /** + * Remove extra underscore from escaped identifier text content. + * @deprecated Use `id.text` for the unescaped text. + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ function unescapeIdentifier(id: string): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag that matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * Does not return tags for binding patterns, because JSDoc matches + * parameters by name and binding patterns do not have a name. + */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray | undefined; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + /** Gets the JSDoc type tag for the node if present and valid */ function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ function getJSDocType(node: Node): TypeNode | undefined; + /** + * Gets the return type node for the node if provided via JSDoc's return tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces. + */ function getJSDocReturnType(node: Node): TypeNode | undefined; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray | undefined; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -2554,6 +2998,7 @@ declare namespace ts { function isForOfStatement(node: Node): node is ForOfStatement; function isContinueStatement(node: Node): node is ContinueStatement; function isBreakStatement(node: Node): node is BreakStatement; + function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; function isReturnStatement(node: Node): node is ReturnStatement; function isWithStatement(node: Node): node is WithStatement; function isSwitchStatement(node: Node): node is SwitchStatement; @@ -2588,6 +3033,9 @@ declare namespace ts { function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; function isJsxOpeningElement(node: Node): node is JsxOpeningElement; function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxFragment(node: Node): node is JsxFragment; + function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; + function isJsxClosingFragment(node: Node): node is JsxClosingFragment; function isJsxAttribute(node: Node): node is JsxAttribute; function isJsxAttributes(node: Node): node is JsxAttributes; function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; @@ -2622,6 +3070,10 @@ declare namespace ts { function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; } declare namespace ts { + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + */ function isToken(n: Node): boolean; function isLiteralExpression(node: Node): node is LiteralExpression; function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; @@ -2636,6 +3088,11 @@ declare namespace ts { function isAccessor(node: Node): node is AccessorDeclaration; function isTypeElement(node: Node): node is TypeElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ function isTypeNode(node: Node): node is TypeNode; function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; @@ -2646,12 +3103,13 @@ declare namespace ts { function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; } declare namespace ts { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } + type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { getStartPos(): number; getToken(): SyntaxKind; @@ -2687,6 +3145,7 @@ declare namespace ts { function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; function isWhiteSpaceLike(ch: number): boolean; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; @@ -2696,6 +3155,7 @@ declare namespace ts { function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; + /** Optionally, get the shebang */ function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; @@ -2703,26 +3163,74 @@ declare namespace ts { } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic; }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic; }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + /** + * Convert the json syntax tree into the json value + */ function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; @@ -2734,15 +3242,37 @@ declare namespace ts { }; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { getOrCreateCacheForDirectory(directoryName: string): Map; } + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ interface NonRelativeModuleNameResolutionCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; } @@ -2757,17 +3287,21 @@ declare namespace ts { } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; - function createLiteral(value: string): StringLiteral; + /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ + function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - function createLiteral(sourceNode: StringLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; + /** Create a unique temporary variable for use in a loop. */ function createLoopVariable(): Identifier; + /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node): Identifier; function createToken(token: TKind): Token; function createSuper(): SuperExpression; @@ -2831,6 +3365,7 @@ declare namespace ts { function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; @@ -2998,6 +3533,8 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function createJsxAttributes(properties: ReadonlyArray): JsxAttributes; @@ -3023,8 +3560,25 @@ declare namespace ts { function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ function getMutableClone(node: T): T; + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ function createNotEmittedStatement(original: Node): NotEmittedStatement; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; @@ -3050,15 +3604,43 @@ declare namespace ts { function createVoidZero(): VoidExpression; function createExportDefault(expression: Expression): ExportAssignment; function createExternalModuleExport(exportName: Identifier): ExportDeclaration; + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ function disposeEmitNodes(sourceFile: SourceFile): void; function setTextRange(range: T, location: TextRange | undefined): T; + /** + * Sets flags that control emit behavior of a node. + */ function setEmitFlags(node: T, emitFlags: EmitFlags): T; + /** + * Gets a custom text range to use when emitting source maps. + */ function getSourceMapRange(node: Node): SourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + /** + * Create an external source map source file reference + */ function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; + /** + * Gets a custom text range to use when emitting comments. + */ function getCommentRange(node: Node): TextRange; + /** + * Sets a custom text range to use when emitting comments. + */ function setCommentRange(node: T, range: TextRange): T; function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[]): T; @@ -3066,31 +3648,131 @@ declare namespace ts { function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + /** + * Gets the constant value to emit for an expression. + */ function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + /** + * Sets the constant value to emit for an expression. + */ function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression; + /** + * Adds an EmitHelper to a node. + */ function addEmitHelper(node: T, helper: EmitHelper): T; + /** + * Add EmitHelpers to a node. + */ function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; + /** + * Removes an EmitHelper from a node. + */ function removeEmitHelper(node: Node, helper: EmitHelper): boolean; + /** + * Gets the EmitHelpers of a node. + */ function getEmitHelpers(node: Node): EmitHelper[] | undefined; + /** + * Moves matching emit helpers from a source node to a target node. + */ function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; function setOriginalNode(node: T, original: Node | undefined): T; } declare namespace ts { + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ function visitNode(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + /** + * Visits a Node using the supplied visitor, possibly returning a new Node in its place. + * + * @param node The Node to visit. + * @param visitor The callback used to visit the Node. + * @param test A callback to execute to verify the Node is valid. + * @param lift An optional callback to execute to lift a NodeArray into a valid Node. + */ function visitNode(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ function visitNodes(nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | undefined; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean): NodeArray; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody; + /** + * Resumes a suspended lexical environment and visits a function body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined; + /** + * Resumes a suspended lexical environment and visits a concise body, ending the lexical + * environment and merging hoisted declarations upon completion. + */ function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ function visitEachChild(node: T, visitor: Visitor, context: TransformationContext): T; + /** + * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. + * + * @param node The Node whose children will be visited. + * @param visitor The callback used to visit each child. + * @param context A lexical environment context for the visitor. + */ function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined; } declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -3102,8 +3784,22 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @returns A 'Program' object. + */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -3133,7 +3829,7 @@ declare namespace ts { getEscapedName(): __String; getName(): string; getDeclarations(): Declaration[] | undefined; - getDocumentationComment(): SymbolDisplayPart[]; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } interface Type { @@ -3148,13 +3844,15 @@ declare namespace ts { getNumberIndexType(): Type | undefined; getBaseTypes(): BaseType[] | undefined; getNonNullableType(): Type; + getConstraint(): Type | undefined; + getDefault(): Type | undefined; } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { @@ -3170,10 +3868,25 @@ declare namespace ts { interface SourceMapSource { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; + /** Releases all resources held by this script snapshot */ dispose?(): void; } namespace ScriptSnapshot { @@ -3189,7 +3902,11 @@ declare namespace ts { interface HostCancellationToken { isCancellationRequested(): boolean; } - interface LanguageServiceHost { + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -3209,24 +3926,34 @@ declare namespace ts { readFile?(path: string, encoding?: string): string | undefined; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; getDirectories?(directoryName: string): string[]; + /** + * Gets a set of custom transformers to use during emit. + */ getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; } interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): Diagnostic[]; getSemanticDiagnostics(fileName: string): Diagnostic[]; getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; @@ -3234,11 +3961,13 @@ declare namespace ts { getRenameInfo(fileName: string, position: number): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; @@ -3254,12 +3983,27 @@ declare namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + applyCodeActionCommand(action: CodeActionCommand): Promise; + applyCodeActionCommand(action: CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } + interface GetCompletionsAtPositionOptions { + includeExternalModuleExports: boolean; + } + interface ApplyCodeActionCommandResult { + successMessage: string; + } interface Classifications { spans: number[]; endOfLineState: EndOfLineState; @@ -3268,6 +4012,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: ClassificationTypeNames; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: ScriptElementKind; @@ -3278,11 +4028,22 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ text: string; kind: ScriptElementKind; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ spans: TextSpan[]; + /** Present if non-empty */ childItems?: NavigationTree[]; } interface TodoCommentDescriptor { @@ -3303,26 +4064,71 @@ declare namespace ts { textChanges: TextChange[]; } interface CodeAction { + /** Description of the code action to display in the UI of the editor */ description: string; + /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; - } + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + type CodeActionCommand = InstallPackageAction; + interface InstallPackageAction { + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ inlineable?: boolean; actions: RefactorActionInfo[]; } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ description: string; } + /** + * A set of edits to make in response to a refactor action, plus an optional + * location where renaming should be invoked from + */ interface RefactorEditInfo { edits: FileTextChanges[]; renameFilename: string | undefined; renameLocation: number | undefined; + commands?: CodeActionCommand[]; } interface TextInsertion { newText: string; + /** The position in newText the caret should point to after the insertion. */ caretOffset: number; } interface DocumentSpan { @@ -3344,7 +4150,7 @@ declare namespace ts { fileName: string; highlightSpans: HighlightSpan[]; } - const enum HighlightSpanKind { + enum HighlightSpanKind { none = "none", definition = "definition", reference = "reference", @@ -3430,6 +4236,10 @@ declare namespace ts { containerKind: ScriptElementKind; containerName: string; } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { displayParts: SymbolDisplayPart[]; } @@ -3492,6 +4302,13 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; isOptional: boolean; } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ interface SignatureHelpItem { isVariadic: boolean; prefixDisplayParts: SymbolDisplayPart[]; @@ -3501,6 +4318,9 @@ declare namespace ts { documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ interface SignatureHelpItems { items: SignatureHelpItem[]; applicableSpan: TextSpan; @@ -3511,6 +4331,9 @@ declare namespace ts { interface CompletionInfo { isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -3519,7 +4342,15 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ replacementSpan?: TextSpan; + hasAction?: true; + source?: string; + isRecommended?: true; } interface CompletionEntryDetails { name: string; @@ -3528,28 +4359,28 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; + codeActions?: CodeAction[]; + source?: SymbolDisplayPart[]; } interface OutliningSpan { + /** The span of the document to actually collapse. */ textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ autoCollapse: boolean; } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - const enum OutputFileType { + enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - const enum EndOfLineState { + enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, InSingleQuoteStringLiteral = 2, @@ -3578,33 +4409,82 @@ declare namespace ts { classification: TokenClass; } interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - const enum ScriptElementKind { + enum ScriptElementKind { unknown = "", warning = "warning", + /** predefined type (void) or keyword (class) */ keyword = "keyword", + /** top level script node */ scriptElement = "script", + /** module foo {} */ moduleElement = "module", + /** class X {} */ classElement = "class", + /** var x = class X {} */ localClassElement = "local class", + /** interface Y {} */ interfaceElement = "interface", + /** type T = ... */ typeElement = "type", + /** enum E */ enumElement = "enum", enumMemberElement = "enum member", + /** + * Inside module and script only + * const v = .. + */ variableElement = "var", + /** Inside function */ localVariableElement = "local var", + /** + * Inside module and script only + * function f() { } + */ functionElement = "function", + /** Inside function */ localFunctionElement = "local function", + /** class X { [public|private]* foo() {} } */ memberFunctionElement = "method", + /** class X { [public|private]* [get|set] foo:number; } */ memberGetAccessorElement = "getter", memberSetAccessorElement = "setter", + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ memberVariableElement = "property", + /** class X { constructor() { } } */ constructorImplementationElement = "constructor", + /** interface Y { ():number; } */ callSignatureElement = "call", + /** interface Y { []:number; } */ indexSignatureElement = "index", + /** interface Y { new():Y; } */ constructSignatureElement = "construct", + /** function foo(*Y*: string) */ parameterElement = "parameter", typeParameterElement = "type parameter", primitiveType = "primitive type", @@ -3614,9 +4494,12 @@ declare namespace ts { letElement = "let", directory = "directory", externalModuleName = "external module name", + /** + * + */ jsxAttribute = "JSX attribute", } - const enum ScriptElementKindModifier { + enum ScriptElementKindModifier { none = "", publicMemberModifier = "public", privateMemberModifier = "private", @@ -3626,7 +4509,7 @@ declare namespace ts { staticModifier = "static", abstractModifier = "abstract", } - const enum ClassificationTypeNames { + enum ClassificationTypeNames { comment = "comment", identifier = "identifier", keyword = "keyword", @@ -3651,7 +4534,7 @@ declare namespace ts { jsxText = "jsx text", jsxAttributeStringLiteralValue = "jsx attribute string literal value", } - const enum ClassificationType { + enum ClassificationType { comment = 1, identifier = 2, keyword = 3, @@ -3682,12 +4565,62 @@ declare namespace ts { function createClassifier(): Classifier; } declare namespace ts { + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @param version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; reportStats(): string; @@ -3718,7 +4651,8 @@ declare namespace ts { function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } declare namespace ts { - const servicesVersion = "0.5"; + /** The version of the language service API */ + const servicesVersion = "0.7"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } @@ -3730,6 +4664,11 @@ declare namespace ts { let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { @@ -3763,11 +4702,10 @@ declare namespace ts.server { interface SortedReadonlyArray extends ReadonlyArray { " __sortedArrayBrand": any; } - interface TypingInstallerRequest { + interface TypingInstallerRequestWithProjectName { readonly projectName: string; - readonly kind: "discover" | "closeProject"; } - interface DiscoverTypings extends TypingInstallerRequest { + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { readonly fileNames: string[]; readonly projectRootPath: Path; readonly compilerOptions: CompilerOptions; @@ -3776,16 +4714,32 @@ declare namespace ts.server { readonly cachePath?: string; readonly kind: "discover"; } - interface CloseProject extends TypingInstallerRequest { + interface CloseProject extends TypingInstallerRequestWithProjectName { readonly kind: "closeProject"; } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; } interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; @@ -3821,6 +4775,8 @@ declare namespace ts.server { declare namespace ts.server { const ActionSet: ActionSet; const ActionInvalidate: ActionInvalidate; + const ActionPackageInstalled: ActionPackageInstalled; + const EventTypesRegistry: EventTypesRegistry; const EventBeginInstallTypes: EventBeginInstallTypes; const EventEndInstallTypes: EventEndInstallTypes; const EventInitializationFailed: EventInitializationFailed; @@ -3830,6 +4786,10 @@ declare namespace ts.server { const EnableTelemetry = "--enableTelemetry"; const TypingSafeListLocation = "--typingSafeListLocation"; const TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ const NpmLocation = "--npmLocation"; } function hasArgument(argumentName: string): boolean; @@ -3851,17 +4811,17 @@ declare namespace ts.server { info(s: string): void; startGroup(): void; endGroup(): void; - msg(s: string, type?: Msg.Types): void; + msg(s: string, type?: Msg): void; getLogFileName(): string; } + enum Msg { + Err = "Err", + Info = "Info", + Perf = "Perf", + } namespace Msg { - type Err = "Err"; - const Err: Err; - type Info = "Info"; - const Info: Info; - type Perf = "Perf"; - const Perf: Perf; - type Types = Err | Info | Perf; + /** @deprecated Only here for backwards-compatibility. Prefer just `Msg`. */ + type Types = Msg; } function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; namespace Errors { @@ -3886,9 +4846,15 @@ declare namespace ts.server { function createNormalizedPathMap(): NormalizedPathMap; interface ProjectOptions { configHasExtendsProperty: boolean; + /** + * true if config file explicitly listed files + */ configHasFilesProperty: boolean; configHasIncludeProperty: boolean; configHasExcludeProperty: boolean; + /** + * these fields can be present in the project file + */ files?: string[]; wildcardDirectories?: Map; compilerOptions?: CompilerOptions; @@ -3898,25 +4864,12 @@ declare namespace ts.server { function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; - class ThrottledOperations { - private readonly host; - private pendingTimeouts; - constructor(host: ServerHost); - schedule(operationId: string, delay: number, cb: () => void): void; - private static run(self, operationId, cb); - } - class GcTimer { - private readonly host; - private readonly delay; - private readonly logger; - private timerId; - constructor(host: ServerHost, delay: number, logger: Logger); - scheduleCollect(): void; - private static run(self); - } } +/** + * Declaration module describing the TypeScript Server protocol + */ declare namespace ts.server.protocol { - const enum CommandTypes { + enum CommandTypes { Brace = "brace", BraceCompletion = "braceCompletion", GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", @@ -3928,6 +4881,7 @@ declare namespace ts.server.protocol { CompileOnSaveEmitFile = "compileOnSaveEmitFile", Configure = "configure", Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", Implementation = "implementation", Exit = "exit", Format = "format", @@ -3961,91 +4915,232 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", } + /** + * A TypeScript Server message + */ interface Message { + /** + * Sequence number of the message + */ seq: number; + /** + * One of "request", "response", or "event" + */ type: "request" | "response" | "event"; } + /** + * Client-initiated request message + */ interface Request extends Message { + type: "request"; + /** + * The command to execute + */ command: string; + /** + * Object containing arguments for the command + */ arguments?: any; } + /** + * Request to reload the project structure for all the opened files + */ interface ReloadProjectsRequest extends Message { command: CommandTypes.ReloadProjects; } + /** + * Server-initiated event message + */ interface Event extends Message { + type: "event"; + /** + * Name of event + */ event: string; + /** + * Event-specific information + */ body?: any; } + /** + * Response by server to client request message. + */ interface Response extends Message { + type: "response"; + /** + * Sequence number of the request message. + */ request_seq: number; + /** + * Outcome of the request. + */ success: boolean; + /** + * The command requested. + */ command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ message?: string; + /** + * Contains message body if success === true. + */ body?: any; } + /** + * Arguments for FileRequest messages. + */ interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ file: string; projectFileName?: string; } + /** + * Requests a JS Doc comment template for a given position + */ interface DocCommentTemplateRequest extends FileLocationRequest { command: CommandTypes.DocCommentTemplate; } + /** + * Response to DocCommentTemplateRequest + */ interface DocCommandTemplateResponse extends Response { body?: TextInsertion; } + /** + * A request to get TODO comments from the file + */ interface TodoCommentRequest extends FileRequest { command: CommandTypes.TodoComments; arguments: TodoCommentRequestArgs; } + /** + * Arguments for TodoCommentRequest request. + */ interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ descriptors: TodoCommentDescriptor[]; } + /** + * Response for TodoCommentRequest request. + */ interface TodoCommentsResponse extends Response { body?: TodoComment[]; } + /** + * A request to determine if the caret is inside a comment. + */ interface SpanOfEnclosingCommentRequest extends FileLocationRequest { command: CommandTypes.GetSpanOfEnclosingComment; arguments: SpanOfEnclosingCommentRequestArgs; } interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ onlyMultiLine: boolean; } + /** + * A request to get indentation for a location in file + */ interface IndentationRequest extends FileLocationRequest { command: CommandTypes.Indentation; arguments: IndentationRequestArgs; } + /** + * Response for IndentationRequest request. + */ interface IndentationResponse extends Response { body?: IndentationResult; } + /** + * Indentation result representing where indentation should be placed + */ interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ indentation: number; } + /** + * Arguments for IndentationRequest request. + */ interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ options?: EditorSettings; } + /** + * Arguments for ProjectInfoRequest request. + */ interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ needFileNameList: boolean; } + /** + * A request to get the project information of the current file. + */ interface ProjectInfoRequest extends Request { command: CommandTypes.ProjectInfo; arguments: ProjectInfoRequestArgs; } + /** + * A request to retrieve compiler options diagnostics for a project + */ interface CompilerOptionsDiagnosticsRequest extends Request { arguments: CompilerOptionsDiagnosticsRequestArgs; } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ projectFileName: string; } + /** + * Response message body for "projectInfo" request + */ interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ languageServiceDisabled?: boolean; } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ interface DiagnosticWithLinePosition { message: string; start: number; @@ -4055,318 +5150,885 @@ declare namespace ts.server.protocol { category: string; code: number; } + /** + * Response message for "projectInfo" request + */ interface ProjectInfoResponse extends Response { body?: ProjectInfo; } + /** + * Request whose sole parameter is a file name. + */ interface FileRequest extends Request { arguments: FileRequestArgs; } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ line: number; + /** + * The character offset (on the line) for the request (1-based). + */ offset: number; } type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ interface GetApplicableRefactorsRequest extends Request { command: CommandTypes.GetApplicableRefactors; arguments: GetApplicableRefactorsRequestArgs; } type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ interface GetApplicableRefactorsResponse extends Response { body?: ApplicableRefactorInfo[]; } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ inlineable?: boolean; actions: RefactorActionInfo[]; } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ description: string; } interface GetEditsForRefactorRequest extends Request { command: CommandTypes.GetEditsForRefactor; arguments: GetEditsForRefactorRequestArgs; } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { refactor: string; action: string; - formatOptions?: FormatCodeSettings; }; interface GetEditsForRefactorResponse extends Response { body?: RefactorEditInfo; } interface RefactorEditInfo { edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ renameLocation?: Location; renameFilename?: string; } + /** + * Request for the available codefixes at a specific position. + */ interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ startOffset: number; + /** + * The line number for the request (1-based). + */ endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ endOffset: number; } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ interface CodeFixRequestArgs extends FileRangeRequestArgs { + /** + * Errorcodes we want to get the fixes for. + */ errorCodes?: number[]; } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } + /** + * Response for GetCodeFixes request. + */ interface GetCodeFixesResponse extends Response { body?: CodeAction[]; } + /** + * A request whose arguments specify a file location (file, line, col). + */ interface FileLocationRequest extends FileRequest { arguments: FileLocationRequestArgs; } + /** + * A request to get codes of supported code fixes. + */ interface GetSupportedCodeFixesRequest extends Request { command: CommandTypes.GetSupportedCodeFixes; } + /** + * A response for GetSupportedCodeFixesRequest request. + */ interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ body?: string[]; } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ start: number; + /** + * Length of the span. + */ length: number; } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ filesToSearch: string[]; } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ interface DefinitionRequest extends FileLocationRequest { command: CommandTypes.Definition; } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ interface TypeDefinitionRequest extends FileLocationRequest { command: CommandTypes.TypeDefinition; } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ interface ImplementationRequest extends FileLocationRequest { command: CommandTypes.Implementation; } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ interface Location { line: number; offset: number; } + /** + * Object found in response messages defining a span of text in source code. + */ interface TextSpan { + /** + * First character of the definition. + */ start: Location; + /** + * One character past last character of the definition. + */ end: Location; } + /** + * Object found in response messages defining a span of text in a specific source file. + */ interface FileSpan extends TextSpan { + /** + * File containing text span. + */ file: string; } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } + /** + * Definition response message. Gives text range for definition. + */ interface DefinitionResponse extends Response { body?: FileSpan[]; } + interface DefinitionInfoAndBoundSpanReponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } + /** + * Definition response message. Gives text range for definition. + */ interface TypeDefinitionResponse extends Response { body?: FileSpan[]; } + /** + * Implementation response message. Gives text range for implementations. + */ interface ImplementationResponse extends Response { body?: FileSpan[]; } + /** + * Request to get brace completion for a location in the file. + */ interface BraceCompletionRequest extends FileLocationRequest { command: CommandTypes.BraceCompletion; arguments: BraceCompletionRequestArgs; } + /** + * Argument for BraceCompletionRequest request. + */ interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ openingBrace: string; } + /** + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ interface OccurrencesRequest extends FileLocationRequest { command: CommandTypes.Occurrences; } interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ isWriteAccess: boolean; + /** + * True if the occurrence is in a string, undefined otherwise; + */ isInString?: true; } interface OccurrencesResponse extends Response { body?: OccurrencesResponseItem[]; } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ interface DocumentHighlightsRequest extends FileLocationRequest { command: CommandTypes.DocumentHighlights; arguments: DocumentHighlightsRequestArgs; } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ interface HighlightSpan extends TextSpan { kind: HighlightSpanKind; } + /** + * Represents a set of highligh spans for a give name + */ interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ file: string; + /** + * Spans to highlight in file. + */ highlightSpans: HighlightSpan[]; } + /** + * Response for a DocumentHighlightsRequest request. + */ interface DocumentHighlightsResponse extends Response { body?: DocumentHighlightsItem[]; } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ interface ReferencesRequest extends FileLocationRequest { command: CommandTypes.References; } interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ lineText: string; + /** + * True if reference is a write location, false otherwise. + */ isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ isDefinition: boolean; } + /** + * The body of a "references" response message. + */ interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ symbolStartOffset: number; + /** + * The full display name of the symbol. + */ symbolDisplayString: string; } + /** + * Response to "references" request. + */ interface ReferencesResponse extends Response { body?: ReferencesResponseBody; } + /** + * Argument for RenameRequest request. + */ interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ findInStrings?: boolean; } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ interface RenameRequest extends FileLocationRequest { command: CommandTypes.Rename; arguments: RenameRequestArgs; } + /** + * Information about the item to be renamed. + */ interface RenameInfo { + /** + * True if item can be renamed. + */ canRename: boolean; + /** + * Error message if item can not be renamed. + */ localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ displayName: string; + /** + * Full display name of item to be renamed. + */ fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; } + /** + * A group of text spans, all in 'file'. + */ interface SpanGroup { + /** The file to which the spans apply */ file: string; + /** The text spans in this group */ locs: TextSpan[]; } interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ locs: ReadonlyArray; } + /** + * Rename response message. + */ interface RenameResponse extends Response { body?: RenameResponseBody; } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ interface ExternalFile { + /** + * Name of file file + */ fileName: string; + /** + * Script kind of the file + */ scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ hasMixedContent?: boolean; + /** + * Content of the file + */ content?: string; } + /** + * Represent an external project + */ interface ExternalProject { + /** + * Project name + */ projectFileName: string; + /** + * List of root files in project + */ rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ options: ExternalProjectCompilerOptions; + /** + * @deprecated typingOptions. Use typeAcquisition instead + */ typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ typeAcquisition?: TypeAcquisition; } interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ compileOnSave?: boolean; } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** + * Represents a set of changes that happen in project + */ interface ProjectChanges { + /** + * List of added files + */ added: string[]; + /** + * List of removed files + */ removed: string[]; + /** + * List of updated files + */ updated: string[]; } + /** + * Information found in a configure request. + */ interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ file?: string; + /** + * The format options to use during formatting and other code editing features. + */ formatOptions?: FormatCodeSettings; + /** + * The host's additional supported .js file extensions + */ extraFileExtensions?: JsFileExtensionInfo[]; } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ interface ConfigureRequest extends Request { command: CommandTypes.Configure; arguments: ConfigureRequestArguments; } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ interface ConfigureResponse extends Response { } + /** + * Information found in an "open" request. + */ interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ projectRootPath?: string; } type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ interface OpenRequest extends Request { command: CommandTypes.Open; arguments: OpenRequestArgs; } + /** + * Request to open or update external project + */ interface OpenExternalProjectRequest extends Request { command: CommandTypes.OpenExternalProject; arguments: OpenExternalProjectArgs; } + /** + * Arguments to OpenExternalProjectRequest request + */ type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ interface OpenExternalProjectsRequest extends Request { command: CommandTypes.OpenExternalProjects; arguments: OpenExternalProjectsArgs; } + /** + * Arguments to OpenExternalProjectsRequest + */ interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ projects: ExternalProject[]; } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ interface OpenExternalProjectResponse extends Response { } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ interface OpenExternalProjectsResponse extends Response { } + /** + * Request to close external project. + */ interface CloseExternalProjectRequest extends Request { command: CommandTypes.CloseExternalProject; arguments: CloseExternalProjectRequestArgs; } + /** + * Arguments to CloseExternalProjectRequest request + */ interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ projectFileName: string; } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ interface CloseExternalProjectResponse extends Response { } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ interface SetCompilerOptionsForInferredProjectsRequest extends Request { command: CommandTypes.CompilerOptionsForInferredProjects; arguments: SetCompilerOptionsForInferredProjectsArgs; } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ options: ExternalProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ projectRootPath?: string; } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ interface SetCompilerOptionsForInferredProjectsResponse extends Response { } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ interface ExitRequest extends Request { command: CommandTypes.Exit; } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ interface CloseRequest extends FileRequest { command: CommandTypes.Close; } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ interface CompileOnSaveAffectedFileListRequest extends FileRequest { command: CommandTypes.CompileOnSaveAffectedFileList; } + /** + * Contains a list of files that should be regenerated in a project + */ interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ projectFileName: string; + /** + * List of files names that should be recompiled + */ fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ projectUsesOutFile: boolean; } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ interface CompileOnSaveAffectedFileListResponse extends Response { body: CompileOnSaveAffectedFileListSingleProject[]; } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ interface CompileOnSaveEmitFileRequest extends FileRequest { command: CommandTypes.CompileOnSaveEmitFile; arguments: CompileOnSaveEmitFileRequestArgs; } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ forced?: boolean; } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ interface QuickInfoRequest extends FileLocationRequest { command: CommandTypes.Quickinfo; } + /** + * Body of QuickInfoResponse. + */ interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; + /** + * Starting file location of symbol. + */ start: Location; + /** + * One past last character of symbol. + */ end: Location; + /** + * Type and kind of symbol. + */ displayString: string; + /** + * Documentation associated with symbol. + */ documentation: string; + /** + * JSDoc tags associated with symbol. + */ tags: JSDocTagInfo[]; } + /** + * Quickinfo response message. + */ interface QuickInfoResponse extends Response { body?: QuickInfoResponseBody; } + /** + * Arguments for format messages. + */ interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ endOffset: number; + /** + * Format options to be used. + */ options?: FormatCodeSettings; } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ interface FormatRequest extends FileLocationRequest { command: CommandTypes.Format; arguments: FormatRequestArgs; } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ interface CodeEdit { + /** + * First character of the text span to edit. + */ start: Location; + /** + * One character past last character of the text span to edit. + */ end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ newText: string; } interface FileCodeEdits { @@ -4374,55 +6036,184 @@ declare namespace ts.server.protocol { textChanges: CodeEdit[]; } interface CodeFixResponse extends Response { + /** The code actions that are available */ body?: CodeAction[]; } interface CodeAction { + /** Description of the code action to display in the UI of the editor */ description: string; + /** Text changes to apply to each file as part of the code action */ changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; } + /** + * Format and format on key response message. + */ interface FormatResponse extends Response { body?: CodeEdit[]; } + /** + * Arguments for format on key messages. + */ interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ key: string; options?: FormatCodeSettings; } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ interface FormatOnKeyRequest extends FileLocationRequest { command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } + /** + * Arguments for completions messages. + */ interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ prefix?: string; - } + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + includeExternalModuleExports: boolean; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ interface CompletionsRequest extends FileLocationRequest { command: CommandTypes.Completions; arguments: CompletionsRequestArgs; } + /** + * Arguments for completion details request. + */ interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { - entryNames: string[]; + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: (string | CompletionEntryIdentifier)[]; } + interface CompletionEntryIdentifier { + name: string; + source: string; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ interface CompletionDetailsRequest extends FileLocationRequest { command: CommandTypes.CompletionDetails; arguments: CompletionDetailsRequestArgs; } + /** + * Part of a symbol description. + */ interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ kind: string; } + /** + * An item found in a completion response. + */ interface CompletionEntry { + /** + * The symbol's name. + */ name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ replacementSpan?: TextSpan; - } + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; + } + /** + * Additional completion entry details, available on demand + */ interface CompletionEntryDetails { + /** + * The symbol's name. + */ name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ documentation: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ tags: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + source?: SymbolDisplayPart[]; } interface CompletionsResponse extends Response { body?: CompletionEntry[]; @@ -4430,37 +6221,108 @@ declare namespace ts.server.protocol { interface CompletionDetailsResponse extends Response { body?: CompletionEntryDetails[]; } + /** + * Signature help information for a single parameter + */ interface SignatureHelpParameter { + /** + * The parameter's name + */ name: string; + /** + * Documentation of the parameter. + */ documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ isOptional: boolean; } + /** + * Represents a single signature to show in signature help. + */ interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ isVariadic: boolean; + /** + * The prefix display parts. + */ prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ tags: JSDocTagInfo[]; } + /** + * Signature help items found in the response of a signature help request. + */ interface SignatureHelpItems { + /** + * The signature help items. + */ items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ argumentIndex: number; + /** + * The argument count + */ argumentCount: number; } + /** + * Arguments of a signature help request. + */ interface SignatureHelpRequestArgs extends FileLocationRequestArgs { } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ interface SignatureHelpRequest extends FileLocationRequest { command: CommandTypes.SignatureHelp; arguments: SignatureHelpRequestArgs; } + /** + * Response object for a SignatureHelpRequest. + */ interface SignatureHelpResponse extends Response { body?: SignatureHelpItems; } + /** + * Synchronous request for semantic diagnostics of one file. + */ interface SemanticDiagnosticsSyncRequest extends FileRequest { command: CommandTypes.SemanticDiagnosticsSync; arguments: SemanticDiagnosticsSyncRequestArgs; @@ -4468,9 +6330,15 @@ declare namespace ts.server.protocol { interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { includeLinePosition?: boolean; } + /** + * Response object for synchronous sematic diagnostics request. + */ interface SemanticDiagnosticsSyncResponse extends Response { body?: Diagnostic[] | DiagnosticWithLinePosition[]; } + /** + * Synchronous request for syntactic diagnostics of one file. + */ interface SyntacticDiagnosticsSyncRequest extends FileRequest { command: CommandTypes.SyntacticDiagnosticsSync; arguments: SyntacticDiagnosticsSyncRequestArgs; @@ -4478,26 +6346,68 @@ declare namespace ts.server.protocol { interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { includeLinePosition?: boolean; } + /** + * Response object for synchronous syntactic diagnostics request. + */ interface SyntacticDiagnosticsSyncResponse extends Response { body?: Diagnostic[] | DiagnosticWithLinePosition[]; } + /** + * Arguments for GeterrForProject request. + */ interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ delay: number; } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ interface GeterrForProjectRequest extends Request { command: CommandTypes.GeterrForProject; arguments: GeterrForProjectRequestArgs; } + /** + * Arguments for geterr messages. + */ interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ delay: number; } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ interface GeterrRequest extends Request { command: CommandTypes.Geterr; arguments: GeterrRequestArgs; } type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ interface RequestCompletedEvent extends Event { event: RequestCompletedEventName; body: RequestCompletedEventBody; @@ -4505,29 +6415,76 @@ declare namespace ts.server.protocol { interface RequestCompletedEventBody { request_seq: number; } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ interface Diagnostic { + /** + * Starting file location at which text applies. + */ start: Location; + /** + * The last file location at which the text applies. + */ end: Location; + /** + * Text of diagnostic message. + */ text: string; + /** + * The category of the diagnostic message, e.g. "error" vs. "warning" + */ category: string; + /** + * The error code of the diagnostic message. + */ code?: number; + /** + * The name of the plugin reporting the message. + */ source?: string; } interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ fileName: string; } interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ file: string; + /** + * An array of diagnostic information items. + */ diagnostics: Diagnostic[]; } + /** + * Event message for "syntaxDiag" and "semanticDiag" event types. + * These events provide syntactic and semantic errors for a file. + */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; } interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ triggerFile: string; + /** + * The name of the found config file. + */ configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ diagnostics: DiagnosticWithFileName[]; } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ interface ConfigFileDiagnosticEvent extends Event { body?: ConfigFileDiagnosticEventBody; event: "configFileDiag"; @@ -4538,77 +6495,234 @@ declare namespace ts.server.protocol { body?: ProjectLanguageServiceStateEventBody; } interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ languageServiceEnabled: boolean; } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } + /** + * Arguments for reload request. + */ interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ tmpfile: string; } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ interface ReloadRequest extends FileRequest { command: CommandTypes.Reload; arguments: ReloadRequestArgs; } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ interface ReloadResponse extends Response { } + /** + * Arguments for saveto request. + */ interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ tmpfile: string; } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ interface SavetoRequest extends FileRequest { command: CommandTypes.Saveto; arguments: SavetoRequestArgs; } + /** + * Arguments for navto request message. + */ interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ searchValue: string; + /** + * Optional limit on the number of items to return. + */ maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ currentFileOnly?: boolean; projectFileName?: string; } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ interface NavtoRequest extends FileRequest { command: CommandTypes.Navto; arguments: NavtoRequestArgs; } + /** + * An item found in a navto response. + */ interface NavtoItem { + /** + * The symbol's name. + */ name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ matchKind?: string; + /** + * If this was a case sensitive or insensitive match. + */ isCaseSensitive?: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers?: string; + /** + * The file in which the symbol is found. + */ file: string; + /** + * The location within file at which the symbol is found. + */ start: Location; + /** + * One past the last character of the symbol. + */ end: Location; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ containerKind?: ScriptElementKind; } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ interface NavtoResponse extends Response { body?: NavtoItem[]; } + /** + * Arguments for change request message. + */ interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ insertString?: string; } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ interface ChangeRequest extends FileLocationRequest { command: CommandTypes.Change; arguments: ChangeRequestArgs; } + /** + * Response to "brace" request. + */ interface BraceResponse extends Response { body?: TextSpan[]; } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ interface BraceRequest extends FileLocationRequest { command: CommandTypes.Brace; } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ interface NavBarRequest extends FileRequest { command: CommandTypes.NavBar; } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ interface NavTreeRequest extends FileRequest { command: CommandTypes.NavTree; } interface NavigationBarItem { + /** + * The item's display text. + */ text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers?: string; + /** + * The definition locations of the item. + */ spans: TextSpan[]; + /** + * Optional children. + */ childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ indent: number; } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ interface NavigationTree { text: string; kind: ScriptElementKind; @@ -4639,8 +6753,17 @@ declare namespace ts.server.protocol { payload: TypingsInstalledTelemetryEventPayload; } interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ installSuccess: boolean; + /** + * version of typings installer + */ typingsInstallerVersion: string; } type BeginInstallTypesEventName = "beginInstallTypes"; @@ -4654,12 +6777,21 @@ declare namespace ts.server.protocol { body: EndInstallTypesEventBody; } interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ eventId: number; + /** + * list of packages to install + */ packages: ReadonlyArray; } interface BeginInstallTypesEventBody extends InstallTypesEventBody { } interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ success: boolean; } interface NavBarResponse extends Response { @@ -4668,7 +6800,7 @@ declare namespace ts.server.protocol { interface NavTreeResponse extends Response { body?: NavigationTree; } - const enum IndentStyle { + enum IndentStyle { None = "None", Block = "Block", Smart = "Smart", @@ -4763,16 +6895,17 @@ declare namespace ts.server.protocol { target?: ScriptTarget | ts.ScriptTarget; traceResolution?: boolean; types?: string[]; + /** Paths used to used to compute primary types search locations */ typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } - const enum JsxEmit { + enum JsxEmit { None = "None", Preserve = "Preserve", ReactNative = "ReactNative", React = "React", } - const enum ModuleKind { + enum ModuleKind { None = "None", CommonJS = "CommonJS", AMD = "AMD", @@ -4782,15 +6915,15 @@ declare namespace ts.server.protocol { ES2015 = "ES2015", ESNext = "ESNext", } - const enum ModuleResolutionKind { + enum ModuleResolutionKind { Classic = "Classic", Node = "Node", } - const enum NewLineKind { + enum NewLineKind { Crlf = "Crlf", Lf = "Lf", } - const enum ScriptTarget { + enum ScriptTarget { ES3 = "ES3", ES5 = "ES5", ES6 = "ES6", @@ -4810,12 +6943,13 @@ declare namespace ts.server { fileName: NormalizedPath; project: Project; } - interface EventSender { - event(payload: T, eventName: string): void; - } type CommandNames = protocol.CommandTypes; const CommandNames: any; function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; + type Event = (body: T, eventName: string) => void; + interface EventSender { + event: Event; + } interface SessionOptions { host: ServerHost; cancellationToken: ServerCancellationToken; @@ -4825,6 +6959,9 @@ declare namespace ts.server { byteLength: (buf: string, encoding?: string) => number; hrtime: (start?: number[]) => number[]; logger: Logger; + /** + * If falsy, all events are suppressed. + */ canUseEvents: boolean; eventHandler?: ProjectServiceEventHandler; throttleWaitMilliseconds?: number; @@ -4838,25 +6975,26 @@ declare namespace ts.server { private changeSeq; private currentRequestId; private errorCheck; - private eventHandler; - private host; + protected host: ServerHost; private readonly cancellationToken; protected readonly typingsInstaller: ITypingsInstaller; - private byteLength; + protected byteLength: (buf: string, encoding?: string) => number; private hrtime; protected logger: Logger; - private canUseEvents; + protected canUseEvents: boolean; + private eventHandler; constructor(opts: SessionOptions); private sendRequestCompletedEvent(requestId); private defaultEventHandler(event); + private projectsUpdatedInBackgroundEvent(openFiles); logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; - configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ReadonlyArray): void; - event(info: T, eventName: string): void; + event(body: T, eventName: string): void; + /** @deprecated */ output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; + private doOutput(info, cmdName, reqSeq, success, message?); private semanticCheck(file, project); private syntacticCheck(file, project); - private updateProjectStructure(); private updateErrorCheck(next, checkList, ms, requireOpen?); private cleanProjects(caption, projects); private cleanup(); @@ -4869,6 +7007,9 @@ declare namespace ts.server { private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); private getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition); private getDefinition(args, simplifiedResult); + private getDefinitionAndBoundSpan(args, simplifiedResult); + private mapDefinitionInfo(definitions, project); + private toFileSpan(fileName, textSpan, project); private getTypeDefinition(args); private getImplementation(args, simplifiedResult); private getOccurrences(args); @@ -4883,11 +7024,16 @@ declare namespace ts.server { private getDefaultProject(args); private getRenameLocations(args, simplifiedResult); private getReferences(args, simplifiedResult); + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ private openClientFile(fileName, fileContent?, scriptKind?, projectRootPath?); private getPosition(args, scriptInfo); - private getFileAndProject(args, errorOnMissingProject?); - private getFileAndProjectWithoutRefreshingInferredProjects(args, errorOnMissingProject?); - private getFileAndProjectWorker(uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject); + private getPositionInFile(args, file); + private getFileAndProject(args); + private getFileAndLanguageServiceForSyntacticOperation(args); + private getFileAndProjectWorker(uncheckedFileName, projectFileName); private getOutliningSpans(args); private getTodoComments(args); private getDocCommentTemplate(args); @@ -4903,19 +7049,20 @@ declare namespace ts.server { private getFormattingEditsAfterKeystrokeFull(args); private getFormattingEditsAfterKeystroke(args); private getCompletions(args, simplifiedResult); - private getCompletionEntryDetails(args); + private getCompletionEntryDetails(args, simplifiedResult); private getCompileOnSaveAffectedFileList(args); private emitFile(args); private getSignatureHelpItems(args, simplifiedResult); + private createCheckList(fileNames, defaultProject?); private getDiagnostics(next, delay, fileNames); private change(args); private reload(args, reqSeq); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItems(items, scriptInfo); + private mapLocationNavigationBarItems(items, scriptInfo); private getNavigationBarItems(args, simplifiedResult); - private decorateNavigationTree(tree, scriptInfo); - private decorateSpan(span, scriptInfo); + private toLocationNavigationTree(tree, scriptInfo); + private toLocationTextSpan(span, scriptInfo); private getNavigationTree(args, simplifiedResult); private getNavigateToItems(args, simplifiedResult); private getSupportedCodeFixes(); @@ -4924,8 +7071,9 @@ declare namespace ts.server { private getApplicableRefactors(args); private getEditsForRefactor(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); + private applyCodeActionCommand(commandName, requestSeq, args); private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction(codeAction, scriptInfo); + private mapCodeAction({description, changes: unmappedChanges, commands}, scriptInfo); private mapTextChangesToCodeEdits(project, textChanges); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); @@ -4935,46 +7083,16 @@ declare namespace ts.server { private notRequired(); private requiredResponse(response); private handlers; - addProtocolHandler(command: string, handler: (request: protocol.Request) => { - response?: any; - responseRequired: boolean; - }): void; + addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; private setCurrentRequest(requestId); private resetCurrentRequest(requestId); executeWithRequestId(requestId: number, f: () => T): T; - executeCommand(request: protocol.Request): { - response?: any; - responseRequired?: boolean; - }; + executeCommand(request: protocol.Request): HandlerResponse; onMessage(message: string): void; } -} -declare namespace ts.server { - interface AbsolutePositionAndLineText { - absolutePosition: number; - lineText: string | undefined; - } - class ScriptVersionCache { - private changes; - private readonly versions; - private minVersion; - private currentVersion; - private static readonly changeNumberThreshold; - private static readonly changeLengthThreshold; - private static readonly maxVersions; - private versionToIndex(version); - private currentVersionToIndex(); - edit(pos: number, deleteLen: number, insertedText?: string): void; - reload(script: string): void; - getSnapshot(): IScriptSnapshot; - private _getSnapshot(); - getSnapshotVersion(): number; - getLineInfo(line: number): AbsolutePositionAndLineText; - lineOffsetToPosition(line: number, column: number): number; - positionToLineOffset(position: number): protocol.Location; - lineToTextSpan(line: number): TextSpan; - getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; - static fromString(script: string): ScriptVersionCache; + interface HandlerResponse { + response?: {}; + responseRequired?: boolean; } } declare namespace ts.server { @@ -4982,18 +7100,18 @@ declare namespace ts.server { private readonly host; readonly fileName: NormalizedPath; readonly scriptKind: ScriptKind; - hasMixedContent: boolean; - isDynamic: boolean; + readonly hasMixedContent: boolean; + readonly path: Path; + /** + * All projects that include this file + */ readonly containingProjects: Project[]; private formatCodeSettings; - readonly path: Path; - private fileWatcher; private textStorage; - private isOpen; - constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent?: boolean, isDynamic?: boolean); + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path); isScriptOpen(): boolean; open(newText: string): void; - close(): void; + close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; getFormatCodeSettings(): FormatCodeSettings; attachToProject(project: Project): boolean; @@ -5003,65 +7121,33 @@ declare namespace ts.server { getDefaultProject(): Project; registerFileUpdate(): void; setFormatOptions(formatSettings: FormatCodeSettings): void; - setWatcher(watcher: FileWatcher): void; - stopWatcher(): void; getLatestVersion(): string; - reload(script: string): void; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): void; - getLineInfo(line: number): AbsolutePositionAndLineText; editContent(start: number, end: number, newText: string): void; markContainingProjectsAsDirty(): void; + isOrphan(): boolean; + /** + * @param line 1 based index + */ lineToTextSpan(line: number): TextSpan; + /** + * @param line 1 based index + * @param offset 1 based index + */ lineOffsetToPosition(line: number, offset: number): number; positionToLineOffset(position: number): protocol.Location; isJavaScript(): boolean; } } declare namespace ts.server { - class LSHost implements LanguageServiceHost, ModuleResolutionHost { - private readonly host; - private project; - private readonly cancellationToken; - private compilationSettings; - private readonly resolvedModuleNames; - private readonly resolvedTypeReferenceDirectives; - private readonly getCanonicalFileName; - private filesWithChangedSetOfUnresolvedImports; - private resolveModuleName; - readonly trace: (s: string) => void; - readonly realpath?: (path: string) => string; - constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); - dispose(): void; - startRecordingFilesWithChangedResolutions(): void; - finishRecordingFilesWithChangedResolutions(): Path[]; - private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult, getResultFileName, logChanges); - getNewLine(): string; - getProjectVersion(): string; - getCompilationSettings(): CompilerOptions; - useCaseSensitiveFileNames(): boolean; - getCancellationToken(): HostCancellationToken; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModuleFull[]; - getDefaultLibFileName(): string; - getScriptSnapshot(filename: string): IScriptSnapshot; - getScriptFileNames(): string[]; - getTypeRootsVersion(): number; - getScriptKind(fileName: string): ScriptKind; - getScriptVersion(filename: string): string; - getCurrentDirectory(): string; - resolvePath(path: string): string; - fileExists(file: string): boolean; - readFile(fileName: string): string | undefined; - directoryExists(path: string): boolean; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - getDirectories(path: string): string[]; - notifyFileRemoved(info: ScriptInfo): void; - setCompilationSettings(opt: CompilerOptions): void; + interface InstallPackageOptionsWithProject extends InstallPackageOptions { + projectName: string; + projectRootPath: Path; } -} -declare namespace ts.server { interface ITypingsInstaller { + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProject): Promise; enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; @@ -5072,34 +7158,14 @@ declare namespace ts.server { private readonly installer; private readonly perProjectCache; constructor(installer: ITypingsInstaller); + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProject): Promise; getTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray, forceRefresh: boolean): SortedReadonlyArray; updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]): void; deleteTypingsForProject(projectName: string): void; onProjectClosed(project: Project): void; } } -declare namespace ts.server { - function shouldEmitFile(scriptInfo: ScriptInfo): boolean; - class BuilderFileInfo { - readonly scriptInfo: ScriptInfo; - readonly project: Project; - private lastCheckedShapeSignature; - constructor(scriptInfo: ScriptInfo, project: Project); - isExternalModuleOrHasOnlyAmbientExternalModules(): boolean; - private containsOnlyAmbientModules(sourceFile); - private computeHash(text); - private getSourceFile(); - updateShapeSignature(): boolean; - } - interface Builder { - readonly project: Project; - getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; - onProjectUpdateGraph(): void; - emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; - clear(): void; - } - function createBuilder(project: Project): Builder; -} declare namespace ts.server { enum ProjectKind { Inferred = 0, @@ -5128,18 +7194,22 @@ declare namespace ts.server { create(createInfo: PluginCreateInfo): LanguageService; getExternalFiles?(proj: Project): string[]; } - interface PluginModuleFactory { - (mod: { - typescript: typeof ts; - }): PluginModule; - } - abstract class Project { - private readonly projectName; + type PluginModuleFactory = (mod: { + typescript: typeof ts; + }) => PluginModule; + /** + * The project root can be script info - if root is present, + * or it could be just normalized path if root wasnt present on the host(only for non inferred project) + */ + type ProjectRoot = ScriptInfo | NormalizedPath; + abstract class Project implements LanguageServiceHost, ModuleResolutionHost { + readonly projectName: string; readonly projectKind: ProjectKind; readonly projectService: ProjectService; private documentRegistry; private compilerOptions; compileOnSaveEnabled: boolean; + directoryStructureHost: DirectoryStructureHost; private rootFiles; private rootFilesMap; private program; @@ -5149,138 +7219,196 @@ declare namespace ts.server { private lastCachedUnresolvedImportsList; protected languageService: LanguageService; languageServiceEnabled: boolean; - protected lsHost: LSHost; - builder: Builder; + readonly trace?: (s: string) => void; + readonly realpath?: (path: string) => string; + private builder; + /** + * Set of files names that were updated since the last call to getChangesSinceVersion. + */ private updatedFileNames; + /** + * Set of files that was returned from the last call to getChangesSinceVersion. + */ private lastReportedFileNames; + /** + * Last version that was reported. + */ private lastReportedVersion; + /** + * Current project structure version. + * This property is changed in 'updateGraph' based on the set of files in program + */ private projectStructureVersion; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ private projectStateVersion; private typingFiles; - protected projectErrors: ReadonlyArray; - typesVersion: number; + private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; getCachedUnresolvedImportsPerFile_TestOnly(): UnresolvedImportsMap; static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {}; - constructor(projectName: string, projectKind: ProjectKind, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptions): Promise; + private readonly typingsCache; + getCompilationSettings(): CompilerOptions; + getCompilerOptions(): CompilerOptions; + getNewLine(): string; + getProjectVersion(): string; + getScriptFileNames(): string[]; + private getOrCreateScriptInfoAndAttachToProject(fileName); + getScriptKind(fileName: string): ScriptKind; + getScriptVersion(filename: string): string; + getScriptSnapshot(filename: string): IScriptSnapshot; + getCancellationToken(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(): string; + useCaseSensitiveFileNames(): boolean; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile(fileName: string): string | undefined; + fileExists(file: string): boolean; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + directoryExists(path: string): boolean; + getDirectories(path: string): string[]; private setInternalCompilerOptionsForEmittingJsFiles(); + /** + * Get the errors that dont have any file name associated + */ getGlobalProjectErrors(): ReadonlyArray; getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; + private ensureBuilder(); + private shouldEmitFile(scriptInfo); getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; - getProjectVersion(): string; + /** + * Returns true if emit was conducted + */ + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; enableLanguageService(): void; disableLanguageService(): void; getProjectName(): string; - abstract getProjectRootPath(): string | undefined; abstract getTypeAcquisition(): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; - updateTypes(): void; close(): void; - getCompilerOptions(): CompilerOptions; + private detachScriptInfoIfNotRoot(uncheckedFilename); + isClosed(): boolean; hasRoots(): boolean; getRootFiles(): NormalizedPath[]; - getRootFilesLSHost(): string[]; getRootScriptInfos(): ScriptInfo[]; getScriptInfos(): ScriptInfo[]; - getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; getExcludedFiles(): ReadonlyArray; getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[]; hasConfigFile(configFilePath: NormalizedPath): boolean; - getAllEmittableFiles(): string[]; containsScriptInfo(info: ScriptInfo): boolean; containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; isRoot(info: ScriptInfo): boolean; addRoot(info: ScriptInfo): void; - removeFile(info: ScriptInfo, detachFromProject?: boolean): void; + addMissingFileRoot(fileName: NormalizedPath): void; + removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; registerFileUpdate(fileName: string): void; markAsDirty(): void; private extractUnresolvedImportsFromSourceFile(file, result); + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ updateGraph(): boolean; private setTypings(typings); private updateGraphWorker(); - isWatchedMissingFile(path: Path): boolean; - getScriptInfoLSHost(fileName: string): ScriptInfo; + private detachScriptInfoFromProject(uncheckedFileName); + private addMissingFileWatcher(missingFilePath); + private isWatchedMissingFile(path); getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; - filesToString(): string; + filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; - reloadScript(filename: NormalizedPath, tempFileName?: NormalizedPath): boolean; - getReferencedFiles(path: Path): Path[]; protected removeRoot(info: ScriptInfo): void; } + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ class InferredProject extends Project { - readonly projectRootPath: string | undefined; private static readonly newName; private _isJsInferredProject; toggleJsInferredProject(isJsInferredProject: boolean): void; setCompilerOptions(options?: CompilerOptions): void; - directoriesWatchedForTsconfig: string[]; - constructor(projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, projectRootPath?: string); + /** this is canonical project root path */ + readonly projectRootPath: string | undefined; addRoot(info: ScriptInfo): void; removeRoot(info: ScriptInfo): void; - getProjectRootPath(): string; + isProjectWithSingleRoot(): boolean; close(): void; getTypeAcquisition(): TypeAcquisition; } + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successfull create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ class ConfiguredProject extends Project { - private wildcardDirectories; compileOnSaveEnabled: boolean; private typeAcquisition; - private projectFileWatcher; - private directoryWatcher; private directoriesWatchedForWildcards; - private typeRootsWatchers; readonly canonicalConfigFilePath: NormalizedPath; private plugins; - openRefCount: number; - constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); - getConfigFilePath(): string; + /** Ref count to the project when opened from external project */ + private externalProjectRefCount; + private projectErrors; + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + getConfigFilePath(): NormalizedPath; enablePlugins(): void; private enablePlugin(pluginConfigEntry, searchPaths); private enableProxy(pluginModuleFactory, configEntry); - getProjectRootPath(): string; - setProjectErrors(projectErrors: ReadonlyArray): void; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): ReadonlyArray; + /** + * Get all the project errors + */ + getAllProjectErrors(): ReadonlyArray; + setProjectErrors(projectErrors: Diagnostic[]): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; getTypeAcquisition(): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; - watchConfigFile(callback: (project: ConfiguredProject) => void): void; - watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; - watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; - watchWildcards(callback: (project: ConfiguredProject, path: string) => void): void; - stopWatchingDirectory(): void; close(): void; - addOpenRef(): void; - deleteOpenRef(): number; getEffectiveTypeRoots(): string[]; } + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ class ExternalProject extends Project { externalProjectName: string; compileOnSaveEnabled: boolean; - private readonly projectFilePath; excludedFiles: ReadonlyArray; private typeAcquisition; - constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); getExcludedFiles(): ReadonlyArray; - getProjectRootPath(): string; getTypeAcquisition(): TypeAcquisition; - setProjectErrors(projectErrors: ReadonlyArray): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; } } declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; - const ContextEvent = "context"; + const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; const ProjectInfoTelemetryEvent = "projectInfo"; - interface ContextEvent { - eventName: typeof ContextEvent; + interface ProjectsUpdatedInBackgroundEvent { + eventName: typeof ProjectsUpdatedInBackgroundEvent; data: { - project: Project; - fileName: NormalizedPath; + openFiles: string[]; }; } interface ConfigFileDiagEvent { @@ -5298,13 +7426,20 @@ declare namespace ts.server { languageServiceEnabled: boolean; }; } + /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ interface ProjectInfoTelemetryEvent { readonly eventName: typeof ProjectInfoTelemetryEvent; readonly data: ProjectInfoTelemetryEventData; } interface ProjectInfoTelemetryEventData { + /** Cryptographically secure hash of project file location. */ readonly projectId: string; + /** Count of file extensions seen in the project. */ readonly fileStats: FileStats; + /** + * Any compiler options that might contain paths will be taken out. + * Enum compiler options will be converted to strings. + */ readonly compilerOptions: CompilerOptions; readonly extends: boolean | undefined; readonly files: boolean | undefined; @@ -5315,6 +7450,7 @@ declare namespace ts.server { readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; readonly projectType: "external" | "configured"; readonly languageServiceEnabled: boolean; + /** TypeScript version used by the server. */ readonly version: string; } interface ProjectInfoTypeAcquisitionData { @@ -5329,10 +7465,8 @@ declare namespace ts.server { readonly tsx: number; readonly dts: number; } - type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent; - interface ProjectServiceEventHandler { - (event: ProjectServiceEvent): void; - } + type ProjectServiceEvent = ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent; + type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { match: RegExp; @@ -5342,12 +7476,17 @@ declare namespace ts.server { } interface TypesMapFile { typesMap: SafeList; - simpleMap: string[]; + simpleMap: { + [libName: string]: string; + }; } function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; + /** + * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. + */ function combineProjectOutput(projects: ReadonlyArray, action: (project: Project) => ReadonlyArray, comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; @@ -5375,22 +7514,57 @@ declare namespace ts.server { class ProjectService { readonly typingsCache: TypingsCache; private readonly documentRegistry; + /** + * Container of all known scripts + */ private readonly filenameToScriptInfo; + /** + * maps external project file name to list of config files that were the part of this project + */ private readonly externalProjectToConfiguredProjectMap; + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ readonly externalProjects: ExternalProject[]; + /** + * projects built from openFileRoots + */ readonly inferredProjects: InferredProject[]; - readonly configuredProjects: ConfiguredProject[]; - readonly openFiles: ScriptInfo[]; + /** + * projects specified by a tsconfig.json file + */ + readonly configuredProjects: Map; + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + readonly openFiles: Map; + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + private readonly openFilesWithNonRootedDiskPath; private compilerOptionsForInferredProjects; private compilerOptionsForInferredProjectsPerProjectRoot; + /** + * Project size for configured or external projects + */ private readonly projectToSizeMap; - private readonly directoryWatchers; + /** + * This is a map of config file paths existance that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + */ + private readonly configFileExistenceInfoCache; private readonly throttledOperations; private readonly hostConfiguration; private safelist; + private legacySafelist; private changedFiles; + private pendingProjectUpdates; + private pendingInferredProjectUpdate; + readonly currentDirectory: string; readonly toCanonicalFileName: (f: string) => string; - lastDeletedFile: ScriptInfo; readonly host: ServerHost; readonly logger: Logger; readonly cancellationToken: HostCancellationToken; @@ -5403,70 +7577,162 @@ declare namespace ts.server { readonly pluginProbeLocations: ReadonlyArray; readonly allowLocalPluginLoads: boolean; readonly typesMapLocation: string | undefined; + /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; constructor(opts: ProjectServiceOptions); - ensureInferredProjectsUpToDate_TestOnly(): void; - getCompilerOptionsForInferredProjects(): CompilerOptions; - onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean): void; + private createWatcherLog(watchType, project); + toPath(fileName: string): Path; private loadTypesMap(); - updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; + private delayInferredProjectsRefresh(); + private delayUpdateProjectGraph(project); + private sendProjectsUpdatedInBackgroundEvent(); + private delayUpdateProjectGraphs(projects); setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; - stopWatchingDirectory(directory: string): void; - findProject(projectName: string): Project; - getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project; - private ensureInferredProjectsUpToDate(); + findProject(projectName: string): Project | undefined; + getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project; + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo; + /** + * Ensures the project structures are upto date + * This means, + * - if there are changedFiles (the files were updated but their containing project graph was not upto date), + * their project graph is updated + * - If there are pendingProjectUpdates (scheduled to be updated with delay so they can batch update the graph if there are several changes in short time span) + * their project graph is updated + * - If there were project graph updates and/or there was pending inferred project update and/or called forced the inferred project structure refresh + * Inferred projects are created/updated/deleted based on open files states + * @param forceInferredProjectsRefresh when true updates the inferred projects even if there is no pending work to update the files/project structures + */ + private ensureProjectStructuresUptoDate(forceInferredProjectsRefresh?); private findContainingExternalProject(fileName); getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; private updateProjectGraphs(projects); - private onSourceFileChanged(fileName); + private onSourceFileChanged(fileName, eventKind); private handleDeletedFile(info); - private onTypeRootFileChanged(project, fileName); - private onSourceFileInDirectoryChangedForConfiguredProject(project, fileName); - private handleChangeInSourceFileForConfiguredProject(project, triggerFile); - private onConfigChangedForConfiguredProject(project); - private onConfigFileAddedForInferredProject(fileName); - private getCanonicalFileName(fileName); + private onConfigChangedForConfiguredProject(project, eventKind); + /** + * This is the callback function for the config file add/remove/change at any location + * that matters to open script info but doesnt have configured project open + * for the config file + */ + private onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); private removeProject(project); - private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles, projectRootPath?); + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ private closeOpenFile(info); private deleteOrphanScriptInfoNotInAnyProject(); - private openOrUpdateConfiguredProjectForFile(fileName, projectRootPath?); - private findConfigFile(searchPath, projectRootPath?); + private configFileExists(configFileName, canonicalConfigFilePath, info); + private setConfigFileExistenceByNewConfiguredProject(project); + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + private configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo); + private setConfigFileExistenceInfoByClosedConfiguredProject(closedProject); + private logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, status); + /** + * Create the watcher for the configFileExistenceInfo + */ + private createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project + */ + private closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + private stopWatchingConfigFilesForClosedScriptInfo(info); + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + private forEachConfigFileLocation(info, action, projectRootPath?); + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + private getConfigFileNameForFile(info, projectRootPath); private printProjects(); private findConfiguredProjectByProjectName(configFileName); + private getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); private findExternalProjectByProjectName(projectFileName); - private convertConfigFileContentToProjectOptions(configFilename); + private convertConfigFileContentToProjectOptions(configFilename, cachedDirectoryStructureHost); private exceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader); - private createAndAddExternalProject(projectFileName, files, options, typeAcquisition); + private createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles); private sendProjectTelemetry(projectKey, project, projectOptions?); - private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile); - private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?); - private watchConfigDirectoryForProject(project, options); - private addFilesToProjectAndUpdateGraph(project, files, propertyReader, clientFileName, typeAcquisition, configFileErrors); - private openConfigFile(configFileName, clientFileName?); - private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors); - private updateConfiguredProject(project); - private getOrCreateInferredProjectForProjectRootPathIfEnabled(root, projectRootPath); + private addFilesToNonInferredProjectAndUpdateGraph(project, files, propertyReader, typeAcquisition); + private createConfiguredProject(configFileName); + private updateNonInferredProjectFiles(project, files, propertyReader); + private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave); + private sendConfigFileDiagEvent(project, triggerFile); + private getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath); private getOrCreateSingleInferredProjectIfEnabled(); - private createInferredProject(isSingleInferredProject?, projectRootPath?); - createInferredProjectWithRootFileIfNecessary(root: ScriptInfo, projectRootPath?: string): InferredProject; - getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; + private createInferredProject(currentDirectory, isSingleInferredProject?, projectRootPath?); getScriptInfo(uncheckedFileName: string): ScriptInfo; - watchClosedScriptInfo(info: ScriptInfo): void; - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, isDynamic?: boolean): ScriptInfo; + private watchClosedScriptInfo(info); + private stopWatchingScriptInfo(info); + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: DirectoryStructureHost): ScriptInfo; + private getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent?, scriptKind?, hasMixedContent?, hostToQueryFileExistsOn?); + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfoForPath(fileName: Path): ScriptInfo; setHostConfiguration(args: protocol.ConfigureRequestArguments): void; closeLog(): void; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ reloadProjects(): void; - refreshInferredProjects(): void; + private delayReloadConfiguredProjectForFiles(configFileExistenceInfo, ignoreIfNotRootOfInferredProject); + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If the there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + private reloadConfiguredProjectForFiles(openFiles, delayReload, shouldReloadProjectFor); + /** + * Remove the root of inferred project if script info is part of another project + */ + private removeRootOfInferredProjectIfNowPartOfOtherProject(info); + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + private refreshInferredProjects(); + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ closeClientFile(uncheckedFileName: string): void; private collectChanges(lastKnownProjectVersions, currentProjects, result); - private closeConfiguredProject(configFile); + private closeConfiguredProjectReferencedFromExternalProject(configFile); closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; openExternalProjects(projects: protocol.ExternalProject[]): void; + /** Makes a filename safe to insert in a RegExp */ private static readonly filenameEscapeRegexp; private static escapeFilenameForRegex(filename); resetSafeList(): void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index cbc35cf18766d..a65ef12d20047 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -34,6 +34,15 @@ var __extends = (this && this.__extends) || (function () { })(); var 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 = {})); + // token > SyntaxKind.Identifer => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync var SyntaxKind; (function (SyntaxKind) { SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; @@ -42,17 +51,23 @@ var ts; SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; + // Punctuation SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; @@ -94,6 +109,7 @@ var ts; SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; + // Assignments SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; @@ -107,7 +123,9 @@ var ts; SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; + // Identifiers SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; + // Reserved words SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; @@ -144,6 +162,7 @@ var ts; SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; + // Strict mode reserved words SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; @@ -153,6 +172,7 @@ var ts; SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; + // Contextual keywords SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; @@ -176,159 +196,185 @@ var ts; SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; - SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; - SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; - SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; - SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; - SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; - SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; - SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; - SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; - SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; - SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; - SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 270] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 140] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 141] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 142] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 143] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 144] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 145] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 146] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 147] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 148] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 149] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 150] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 151] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 152] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 153] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 154] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 155] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 156] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 157] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 158] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 159] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 160] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 161] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 162] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 163] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 164] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 165] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 166] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 167] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 168] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 169] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 170] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 171] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 172] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 173] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 174] = "LiteralType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 175] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 176] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 177] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 178] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 179] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 180] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 181] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 182] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 183] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 184] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 185] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 186] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 187] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 188] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 189] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 190] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 191] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 192] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 193] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 194] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 195] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 196] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 197] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 198] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 199] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 200] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 201] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 202] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 203] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 204] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 205] = "MetaProperty"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 206] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 207] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 208] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 209] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 210] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 211] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 212] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 213] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 214] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 215] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 216] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 217] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 218] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 219] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 220] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 221] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 222] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 223] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 224] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 225] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 226] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 227] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 228] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 229] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 230] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 231] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 232] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 233] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 234] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 235] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 236] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 237] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 238] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 239] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 240] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 241] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 242] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 243] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 244] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 245] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 246] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 247] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 248] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 249] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 250] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 251] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 252] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 253] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 254] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 255] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 256] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 257] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 258] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 259] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 260] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 261] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 262] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 263] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 264] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 265] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 266] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 267] = "SpreadAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 268] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 269] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 270] = "Bundle"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 271] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 272] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 273] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 274] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 275] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 276] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 277] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 278] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 279] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 280] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocTag"] = 281] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 282] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 283] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 284] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 285] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 286] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 287] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 288] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 289] = "JSDocPropertyTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 290] = "SyntaxList"; + // Transformation nodes + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 291] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 292] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 293] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 294] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 295] = "EndOfDeclarationMarker"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 296] = "Count"; + // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -336,15 +382,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 143] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 159] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 174] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 143] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -353,11 +399,13 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 144] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 271] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 289] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 281] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 289] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 143] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -381,12 +429,25 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // This flag will be set when the parser encounters a dynamic import expression so that module resolution + // will not have to walk the tree if the flag is not set. However, this flag is just a approximation because + // once it is set, the flag never gets cleared (hence why it's named "PossiblyContainsDynamicImport"). + // During editing, if dynamic import is removed, incremental parsing will *NOT* update this flag. This means that the tree will always be traversed + // during module resolution. However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 2097152] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 4194304] = "InWithStatement"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; - NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 6387712] = "ContextFlags"; + // Exclude these flags when parsing a Type NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); var ModifierFlags; @@ -405,6 +466,7 @@ var ts; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; @@ -413,16 +475,20 @@ var ts; var JsxFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); + /* @internal */ var RelationComparisonResult; (function (RelationComparisonResult) { RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + /*@internal*/ var GeneratedIdentifierKind; (function (GeneratedIdentifierKind) { GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; @@ -431,16 +497,22 @@ var ts; GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); - var NumericLiteralFlags; - (function (NumericLiteralFlags) { - NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; - NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; - NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; - NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; - NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; - })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + /* @internal */ + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -459,39 +531,49 @@ var ts; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); - var OperationCanceledException = (function () { + var OperationCanceledException = /** @class */ (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; + /* @internal */ var StructureIsReused; (function (StructureIsReused) { StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); + /** Return code used by getEmitOutput function to indicate status of the function */ var ExitStatus; (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; + // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); @@ -513,19 +595,30 @@ var ts; TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + // even though `T` can't be accessed in the current scope. + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + /* @internal */ var SymbolAccessibility; (function (SymbolAccessibility) { SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + /* @internal */ var SyntheticSymbolKind; (function (SyntheticSymbolKind) { SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; @@ -536,10 +629,16 @@ var ts; TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ + /* @internal */ var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; @@ -548,6 +647,7 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 8] = "Promise"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; + // with call signatures. TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); var SymbolFlags; @@ -579,6 +679,9 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -586,7 +689,11 @@ var ts; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; @@ -611,13 +718,20 @@ var ts; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; - SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); + /* @internal */ var EnumKind; (function (EnumKind) { EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; - EnumKind[EnumKind["Literal"] = 1] = "Literal"; + EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type) })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); + /* @internal */ var CheckFlags; (function (CheckFlags) { CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; @@ -630,6 +744,7 @@ var ts; CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -651,6 +766,7 @@ var ts; InternalSymbolName["ExportEquals"] = "export="; InternalSymbolName["Default"] = "default"; })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); + /* @internal */ var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; @@ -687,42 +803,60 @@ var ts; TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 32768] = "Object"; - TypeFlags[TypeFlags["Union"] = 65536] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 262144] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; - TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 2048] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 8192] = "Null"; + TypeFlags[TypeFlags["Never"] = 16384] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 65536] = "Object"; + TypeFlags[TypeFlags["Union"] = 131072] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 524288] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; + /* @internal */ + TypeFlags[TypeFlags["FreshLiteral"] = 2097152] = "FreshLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsWideningType"] = 4194304] = "ContainsWideningType"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 8388608] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 16777216] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 33554432] = "NonPrimitive"; + /* @internal */ + TypeFlags[TypeFlags["JsxAttributes"] = 67108864] = "JsxAttributes"; + TypeFlags[TypeFlags["MarkerType"] = 134217728] = "MarkerType"; + /* @internal */ + TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; + TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; - TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + /* @internal */ + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; + /* @internal */ + TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 33585807] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 524322] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; - TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 2064384] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; + // 'Narrowable' types are types where narrowing actually narrows. + // This *should* be every type other than null, undefined, void, and never + TypeFlags[TypeFlags["Narrowable"] = 35620607] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 33620481] = "NotUnionOrUnit"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 12582912] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 29360128] = "PropagatingFlags"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -736,8 +870,18 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -750,9 +894,11 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -760,19 +906,34 @@ var ts; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ var Ternary; (function (Ternary) { Ternary[Ternary["False"] = 0] = "False"; Ternary[Ternary["Maybe"] = 1] = "Maybe"; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); + /* @internal */ var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + /// exports.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + // F.name = expr SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; @@ -825,14 +986,16 @@ var ts; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; (function (LanguageVariant) { LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); + /* @internal */ var DiagnosticStyle; (function (DiagnosticStyle) { DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; @@ -843,6 +1006,7 @@ var ts; WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + /* @internal */ var CharacterCodes; (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; @@ -852,6 +1016,7 @@ var ts; CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters CharacterCodes[CharacterCodes["space"] = 32] = "space"; CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; @@ -977,10 +1142,14 @@ var ts; Extension["Dts"] = ".d.ts"; Extension["Js"] = ".js"; Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; })(Extension = ts.Extension || (ts.Extension = {})); + /* @internal */ var TransformFlags; (function (TransformFlags) { TransformFlags[TransformFlags["None"] = 0] = "None"; + // Facts + // - Flags used to indicate that a node or subtree contains syntax that requires transformation. TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; @@ -993,6 +1162,8 @@ var ts; TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + // Markers + // - Flags used to indicate that a subtree contains a specific transformation. TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; @@ -1010,7 +1181,12 @@ var ts; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + // Assertions + // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; @@ -1019,6 +1195,9 @@ var ts; TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + // Scope Exclusions + // - Bitmasks that exclude flags from propagating out of a specific context + // into the subtree flags of their container. TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; @@ -1033,6 +1212,8 @@ var ts; TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + // Masks + // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -1066,8 +1247,13 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; - EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); + /** + * Used by the checker, this enum keeps track of external emit helpers that should be type + * checked. + */ + /* @internal */ var ExternalEmitHelpers; (function (ExternalEmitHelpers) { ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; @@ -1086,13 +1272,19 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; + // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; + // Helpers included by ES2017 for..await..of ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; + // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1103,21 +1295,29 @@ var ts; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); +/*@internal*/ var ts; (function (ts) { + /** Gets a timestamp with (at least) ms resolution */ ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ (function (ts) { var performance; (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (_markName) { }; + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; var enabled = false; var profilerStart = 0; var counts; var marks; var measures; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ function mark(markName) { if (enabled) { marks.set(markName, ts.timestamp()); @@ -1126,6 +1326,15 @@ var ts; } } performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ function measure(measureName, startMarkName, endMarkName) { if (enabled) { var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); @@ -1134,20 +1343,36 @@ var ts; } } performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ function getCount(markName) { return counts && counts.get(markName) || 0; } performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ function getDuration(measureName) { return measures && measures.get(measureName) || 0; } performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ function forEachMeasure(cb) { measures.forEach(function (measure, key) { cb(key, measure); }); } performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ function enable() { counts = ts.createMap(); marks = ts.createMap(); @@ -1156,36 +1381,50 @@ var ts; profilerStart = ts.timestamp(); } performance.enable = enable; + /** Disables performance measurements for the compiler. */ function disable() { enabled = false; } performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/// +/// var ts; (function (ts) { - ts.versionMajorMinor = "2.6"; + // 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 = "2.7"; + /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); +/* @internal */ (function (ts) { - ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; - ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + /** Create a MapLike with good performance. */ function createDictionaryObject() { - var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // 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 MapCtr(); } ts.createMap = createMap; + /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { return new MapCtr(); } @@ -1203,6 +1442,8 @@ var ts; ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new 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]); @@ -1211,9 +1452,12 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name var 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 = (function () { + var MapIterator = /** @class */ (function () { function MapIterator(data, selector) { this.index = 0; this.data = data; @@ -1230,7 +1474,7 @@ var ts; }; return MapIterator; }()); - return (function () { + return /** @class */ (function () { function class_1() { this.data = createDictionaryObject(); this.size = 0; @@ -1246,6 +1490,7 @@ var ts; return this; }; class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator return key in this.data; }; class_1.prototype.delete = function (key) { @@ -1284,16 +1529,15 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } ts.length = length; + /** + * 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 forEach(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1306,6 +1550,17 @@ var ts; return undefined; } ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1321,10 +1576,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1336,6 +1593,11 @@ var ts; return map; } ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ function every(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1357,6 +1619,17 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -1366,6 +1639,10 @@ var ts; return -1; } ts.findIndex = findIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ function findMap(array, callback) { for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); @@ -1376,11 +1653,12 @@ var ts; Debug.fail(); } ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (equalityComparer(v, value)) { return true; } } @@ -1443,22 +1721,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1485,6 +1747,14 @@ var ts; return result; } ts.map = map; + function mapIterator(iter, mapFn) { + return { next: next }; + function next() { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + } + ts.mapIterator = mapIterator; function sameMap(array, f) { var result; if (array) { @@ -1505,12 +1775,17 @@ var ts; return result || array; } ts.sameMap = sameMap; + /** + * Flattens an array containing a mix of array or non-array elements. + * + * @param array The array to flatten. + */ function flatten(array) { var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1524,6 +1799,12 @@ var ts; return result; } ts.flatten = flatten; + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ function flatMap(array, mapfn) { var result; if (array) { @@ -1550,8 +1831,14 @@ var ts; if (done) break; var res = mapfn(value); - if (res) - result.push.apply(result, res); + if (res) { + if (isArray(res)) { + result.push.apply(result, res); + } + else { + result.push(res); + } + } } return result; } @@ -1592,6 +1879,24 @@ var ts; return result; } ts.mapDefined = mapDefined; + function mapDefinedIter(iter, mapFn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapFn(value); + if (res !== undefined) { + result.push(res); + } + } + return result; + } + ts.mapDefinedIter = mapDefinedIter; + /** + * Computes the first matching span of elements and returns a tuple of the first span + * and the remaining elements. + */ function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1604,6 +1909,13 @@ var ts; return undefined; } ts.span = span; + /** + * Maps contiguous spans of values with the same key. + * + * @param array The array to map. + * @param keyfn A callback used to select the key for an element. + * @param mapfn A callback used to map a contiguous chunk of values to a single value. + */ function spanMap(array, keyfn, mapfn) { var result; if (array) { @@ -1654,8 +1966,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1676,25 +1988,79 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - function deduplicate(array, areEqual) { - var result; - if (array) { - result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } - } - result.push(item); - } + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } ts.deduplicate = deduplicate; - function arrayIsEqualTo(array1, array2, equaler) { + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (!array1 || !array2) { return array1 === array2; } @@ -1702,8 +2068,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { + if (!equalityComparer(array1[i], array2[i])) { return false; } } @@ -1747,35 +2112,66 @@ var ts; return result || array; } ts.compact = compact; - function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { - if (comparer === void 0) { comparer = compareValues; } - if (offsetA === void 0) { offsetA = 0; } - if (offsetB === void 0) { offsetB = 0; } + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; var result = []; - outer: for (; offsetB < arrayB.length; offsetB++) { - inner: for (; offsetA < arrayA.length; offsetA++) { + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1: break inner; - case 0: continue outer; - case 1: continue inner; + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; } } - result.push(arrayB[offsetB]); } return result; } ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + // Note: we need the following type assertion because of GH #17069 result += v[prop]; } return result; } ts.sum = sum; + /** + * Appends a value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param value The value to append to the array. If `value` is `undefined`, nothing is + * appended. + */ function append(to, value) { if (value === undefined) return to; @@ -1785,27 +2181,43 @@ var ts; return to; } ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } + /** + * Appends a range of value to an array, returning the array. + * + * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array + * is created if `value` was appended. + * @param from The values to append to the array. If `from` is `undefined`, nothing is + * appended. If an element of `from` is `undefined`, that element is not appended. + * @param start The offset in `from` at which to start copying values. + * @param end The offset in `from` at which to stop copying values (non-inclusive). + */ function addRange(to, from, start, end) { - if (from === undefined) + if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); end = end === undefined ? from.length : toOffset(from, end); for (var i = start; i < end && i < from.length; i++) { - var v = from[i]; - if (v !== undefined) { + if (from[i] !== undefined) { to.push(from[i]); } } return to; } ts.addRange = addRange; - function pushIfUnique(array, toAdd) { - if (contains(array, toAdd)) { + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { return false; } else { @@ -1814,9 +2226,12 @@ var ts; } } ts.pushIfUnique = pushIfUnique; - function appendIfUnique(array, toAdd) { + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { if (array) { - pushIfUnique(array, toAdd); + pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -1824,12 +2239,54 @@ var ts; } } ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function best(iter, isBetter) { + var x = iter.next(); + if (x.done) { + return undefined; + } + var best = x.value; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return best; + } + if (isBetter(value, best)) { + best = value; + } + } + } + ts.best = best; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ function stableSort(array, comparer) { - if (comparer === void 0) { comparer = compareValues; } - return array - .map(function (_, i) { return i; }) - .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) - .map(function (i) { return array[i]; }); + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); } ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { @@ -1842,6 +2299,10 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ function elementAt(array, offset) { if (array) { offset = toOffset(array, offset); @@ -1852,14 +2313,33 @@ var ts; return undefined; } ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ function firstOrUndefined(array) { return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ function lastOrUndefined(array) { return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -1878,26 +2358,36 @@ var ts; return result; } ts.replaceElement = replaceElement; - function binarySearch(array, value, comparer, offset) { + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { if (!array || array.length === 0) { return -1; } var low = offset || 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; + var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); - var midValue = array[middle]; - if (comparer(midValue, value) === 0) { - return middle; - } - else if (comparer(midValue, value) > 0) { - high = middle - 1; - } - else { - low = middle + 1; + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; } } return ~low; @@ -1927,39 +2417,30 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial, start, count) { - if (array) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start > size - 1 ? size - 1 : start; - var end = count === undefined || pos - count < 0 ? 0 : pos - count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos--; - } - else { - result = initial; - } - while (pos >= end) { - result = f(result, array[pos], pos); - pos--; - } - return result; - } - } - return initial; - } - ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ function hasProperty(map, key) { return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ function getOwnKeys(map) { var keys = []; for (var key in map) { @@ -2036,7 +2517,14 @@ var ts; return t; } ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (left === right) return true; if (!left || !right) @@ -2045,7 +2533,7 @@ var ts; if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + if (!equalityComparer(left[key], right[key])) return false; } } @@ -2060,13 +2548,22 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2128,10 +2625,24 @@ var ts; } } } + /** + * Tests whether a value is an array. + */ function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -2142,10 +2653,19 @@ var ts; Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } ts.cast = cast; - function noop() { } + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); } @@ -2242,6 +2762,7 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; + /* internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -2298,98 +2819,246 @@ var ts; return headChain; } ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ function compareValues(a, b) { - if (a === b) - return 0; - if (a === undefined) - return -1; - if (b === undefined) - return 1; - return a < b ? -1 : 1; + return compareComparableValues(a, b); } ts.compareValues = compareValues; - function compareStrings(a, b, ignoreCase) { + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { if (a === b) - return 0; + return 0 /* EqualTo */; if (a === undefined) - return -1; + return -1 /* LessThan */; if (b === undefined) - return 1; - if (ignoreCase) { - if (ts.collator) { - var result = ts.localeCompareIsCorrect ? - ts.collator.compare(a, b) : - a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); - return result < 0 ? -1 : result > 0 ? 1 : 0; - } - a = a.toUpperCase(); - b = b.toUpperCase(); - if (a === b) - return 0; - } - return a < b ? -1 : 1; - } - ts.compareStrings = compareStrings; - function compareStringsCaseInsensitive(a, b) { - return compareStrings(a, b, true); + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; } ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } function compareDiagnostics(d1, d2) { - return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || compareMessageText(d1.messageText, d2.messageText) || - 0; + 0 /* EqualTo */; } ts.compareDiagnostics = compareDiagnostics; function compareMessageText(text1, text2) { while (text1 && text2) { - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + // We still have both chains. + var string1 = isString(text1) ? text1 : text1.messageText; + var string2 = isString(text2) ? text2 : text2.messageText; + var res = compareStringsCaseSensitive(string1, string2); if (res) { return res; } - text1 = typeof text1 === "string" ? undefined : text1.next; - text2 = typeof text2 === "string" ? undefined : text2.next; + text1 = isString(text1) ? undefined : text1.next; + text2 = isString(text2) ? undefined : text2.next; } if (!text1 && !text2) { - return 0; + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; } - return text1 ? 1 : -1; + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; } function sortAndDeduplicateDiagnostics(diagnostics) { - return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + return sortAndDeduplicate(diagnostics, compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function deduplicateSortedDiagnostics(diagnostics) { - if (diagnostics.length < 2) { - return diagnostics; - } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; - if (!isDupe) { - newDiagnostics.push(currentDiagnostic); - previousDiagnostic = currentDiagnostic; - } - } - return newDiagnostics; - } - ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; function normalizeSlashes(path) { return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { - if (path.charCodeAt(0) === 47) { - if (path.charCodeAt(1) !== 47) + if (path.charCodeAt(0) === 47 /* slash */) { + if (path.charCodeAt(1) !== 47 /* slash */) return 1; var p1 = path.indexOf("/", 2); if (p1 < 0) @@ -2399,11 +3068,15 @@ var ts; return p1 + 1; return p2 + 1; } - if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(1) === 58 /* colon */) { + if (path.charCodeAt(2) === 47 /* slash */) return 3; - return 2; } + // Per RFC 1738 'file' URI schema has the shape file:/// + // if is omitted then it is assumed that host value is 'localhost', + // however slash after the omitted is not removed. + // file:///folder1/file1 - this is a correct URI + // file://folder2/file2 - this is an incorrect URI if (path.lastIndexOf("file:///", 0) === 0) { return "file:///".length; } @@ -2414,8 +3087,13 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47; + var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; @@ -2426,6 +3104,8 @@ var ts; normalized.pop(); } else { + // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, + // e.g. "path//file.ts". Drop these before re-joining the parts. if (part) { normalized.push(part); } @@ -2452,6 +3132,7 @@ var ts; } } ts.normalizePathAndParts = normalizePathAndParts; + /** A path ending with '/' refers to a directory only, never a file. */ function pathEndsWithDirectorySeparator(path) { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; } @@ -2461,25 +3142,26 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; + /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ function moduleHasNonRelativeName(moduleName) { return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; + return compilerOptions.target || 0 /* ES3 */; } ts.getEmitScriptTarget = getEmitScriptTarget; function getEmitModuleKind(compilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : - getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; } ts.getEmitModuleKind = getEmitModuleKind; function getEmitModuleResolutionKind(compilerOptions) { @@ -2490,14 +3172,26 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { + if (str.charCodeAt(i) === 42 /* asterisk */) { if (!seenAsterisk) { seenAsterisk = true; } else { + // have already seen asterisk return false; } } @@ -2512,7 +3206,7 @@ var ts; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); } ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { @@ -2523,6 +3217,7 @@ var ts; path = normalizeSlashes(path); var rootLength = getRootLength(path); if (rootLength === 0) { + // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); } @@ -2540,25 +3235,40 @@ var ts; } ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { + // Get root length of http://www.website.com/folder1/folder2/ + // In this example the root is: http://www.website.com/ + // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; + // Initial root length is http:// part var rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { - if (url.charCodeAt(rootLength) === 47) { + // Consume all immediate slashes in the protocol + // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// + if (url.charCodeAt(rootLength) === 47 /* slash */) { rootLength++; } else { + // non slash character means we continue proceeding to next component of root search break; } } + // there are no parts after http:// just return current string as the pathComponent if (rootLength === urlLength) { return [url]; } + // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); if (indexOfNextSlash !== -1) { + // Found the "/" after the website.com so the root is length of http://www.website.com/ + // and get components after the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } else { + // Can't find the host assume the rest of the string as component + // but make sure we append "/" to it as root is not joined using "/" + // eg. if url passed in was http://website.com we want to use root as [http://website.com/] + // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; } } @@ -2574,14 +3284,18 @@ var ts; var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { + // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } + // Find the component that differs var joinStartIndex; for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } } + // Get the relative path if (joinStartIndex) { var relativePath = ""; var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); @@ -2592,6 +3306,7 @@ var ts; } return relativePath + relativePathComponents.join(ts.directorySeparator); } + // Cant find the relative path, get the absolute path var absolutePath = getNormalizedPathFromPathComponents(pathComponents); if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { absolutePath = "file:///" + absolutePath; @@ -2626,6 +3341,10 @@ var ts; return path; } ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + /** + * Adds a trailing directory separator to a path, if it does not already have one. + * @param path The path. + */ function ensureTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) !== ts.directorySeparator) { return path + ts.directorySeparator; @@ -2635,19 +3354,20 @@ var ts; ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; function comparePaths(a, b, currentDirectory, ignoreCase) { if (a === b) - return 0; + return 0 /* EqualTo */; if (a === undefined) - return -1; + return -1 /* LessThan */; if (b === undefined) - return 1; + return 1 /* GreaterThan */; a = removeTrailingDirectorySeparator(a); b = removeTrailingDirectorySeparator(b); var aComponents = getNormalizedPathComponents(a, currentDirectory); var bComponents = getNormalizedPathComponents(b, currentDirectory); var sharedLength = Math.min(aComponents.length, bComponents.length); + var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; for (var i = 0; i < sharedLength; i++) { - var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); - if (result !== 0) { + var result = comparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { return result; } } @@ -2668,9 +3388,9 @@ var ts; if (childComponents.length < parentComponents.length) { return false; } + var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { - var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); - if (result !== 0) { + if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } } @@ -2690,8 +3410,16 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -2708,17 +3436,34 @@ var ts; return false; } ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. var reservedCharacterPattern = /[^\w\s\/]/g; - var wildcardCharCodes = [42, 63]; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory seperators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } }; var directoriesMatcher = { singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } }; @@ -2738,6 +3483,7 @@ var ts; return undefined; } var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". var terminator = usage === "exclude" ? "($|/)" : "$"; return "^(" + pattern + ")" + terminator; } @@ -2750,6 +3496,10 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } @@ -2764,6 +3514,8 @@ var ts; if (usage !== "exclude" && lastComponent === "**") { return undefined; } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. components[0] = removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); @@ -2788,15 +3540,24 @@ var ts; } if (usage !== "exclude") { var componentPattern = ""; - if (component.charCodeAt(0) === 42) { + // The * and ? wildcards should not match directories or files that start with . if they + // appear first in a component. Dotted directories and files can be included explicitly + // like so: **/.*/.* + if (component.charCodeAt(0) === 42 /* asterisk */) { componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; component = component.substr(1); } - else if (component.charCodeAt(0) === 63) { + else if (component.charCodeAt(0) === 63 /* question */) { componentPattern += "[^./]"; component = component.substr(1); } componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + // Patterns should not include subfolders like node_modules unless they are + // explicitly included as part of the path. + // + // As an optimization, if the component pattern is the same as the component, + // then there definitely were no wildcard characters and we do not need to + // add the exclusion pattern. if (componentPattern !== component) { subpattern += implicitExcludePathRegexPattern; } @@ -2833,13 +3594,15 @@ var ts; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); + var comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive; var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var regexFlag = useCaseSensitiveFileNames ? "" : "i"; var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -2847,26 +3610,25 @@ var ts; return flatten(results); function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - files = files.slice().sort(comparer); var _loop_1 = function (current) { - var name_1 = combinePaths(path, current); + var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name_1, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; if (!includeFileRegexes) { - results[0].push(name_1); + results[0].push(name); } else { var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); if (includeIndex !== -1) { - results[includeIndex].push(name_1); + results[includeIndex].push(name); } } }; - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; + for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + var current = _b[_i]; _loop_1(current); } if (depth !== undefined) { @@ -2875,34 +3637,44 @@ var ts; return; } } - directories = directories.slice().sort(comparer); - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var current = directories_1[_b]; - var name_2 = combinePaths(path, current); + for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name_2, absoluteName, depth); + visitDirectory(name, absoluteName, depth); } } } } ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). var basePaths = [path]; if (includes) { + // Storage for literal base paths amongst the include patterns. var includeBasePaths = []; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { 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 = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { var includeBasePath = includeBasePaths_1[_a]; _loop_2(includeBasePath); @@ -2913,6 +3685,7 @@ var ts; function getIncludeBasePath(absolute) { var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { + // No "*" or "?" in the path return !hasExtension(absolute) ? absolute : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); @@ -2920,37 +3693,47 @@ var ts; return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } function ensureScriptKind(fileName, scriptKind) { - return scriptKind || getScriptKindFromFileName(fileName) || 3; + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { - case ".js": - return 1; - case ".jsx": - return 2; - case ".ts": - return 3; - case ".tsx": - return 4; - case ".json": - return 6; + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; default: - return 0; + return 0 /* Unknown */; } } ts.getScriptKindFromFileName = getScriptKindFromFileName; - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -2974,6 +3757,11 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ var ExtensionPriority; (function (ExtensionPriority) { ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; @@ -2987,31 +3775,39 @@ var ts; return adjustExtensionPriority(i, supportedExtensions); } } - return 0; + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; } ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ function adjustExtensionPriority(extensionPriority, supportedExtensions) { - if (extensionPriority < 2) { - return 0; + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; } else if (extensionPriority < supportedExtensions.length) { - return 2; + return 2 /* DeclarationAndJavaScriptFiles */; } else { return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { - if (extensionPriority < 2) { - return 2; + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; } else { return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -3035,6 +3831,16 @@ var ts; return (removeFileExtension(path) + newExtension); } ts.changeExtension = changeExtension; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; function Symbol(flags, name) { this.flags = flags; this.escapedName = name; @@ -3046,16 +3852,15 @@ var ts; this.checker = checker; } } - function Signature() { - } + function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { this.id = 0; this.kind = kind; this.pos = pos; this.end = end; - this.flags = 0; - this.modifierFlagsCache = 0; - this.transformFlags = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; } @@ -3083,7 +3888,7 @@ var ts; })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { - Debug.currentAssertionLevel = 0; + Debug.currentAssertionLevel = 0 /* None */; Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; @@ -3151,6 +3956,7 @@ var ts; } Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); + /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItem(array, item) { for (var i = 0; i < array.length; i++) { if (array[i] === item) { @@ -3161,7 +3967,9 @@ var ts; return false; } ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; } @@ -3169,14 +3977,17 @@ var ts; } ts.orderedRemoveItemAt = orderedRemoveItemAt; function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. array[index] = array[array.length - 1]; array.pop(); } ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ function unorderedRemoveItem(array, item) { unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); } ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ function unorderedRemoveFirstItemWhere(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i])) { @@ -3191,6 +4002,11 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ function matchPatternOrExact(patternStrings, candidate) { var patterns = []; for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { @@ -3200,6 +4016,7 @@ var ts; patterns.push(pattern); } else if (patternString === candidate) { + // pattern was matched as is - no need to search further return patternString; } } @@ -3211,13 +4028,19 @@ var ts; return prefix + "*" + suffix; } ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ function matchedText(pattern, candidate) { Debug.assert(isPatternMatch(pattern, candidate)); return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); } ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ function findBestPatternMatch(values, getPattern, candidate) { var matchedValue = undefined; + // use length of prefix as betterness criteria var longestMatchPrefixLength = -1; for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { var v = values_1[_i]; @@ -3237,6 +4060,7 @@ var ts; endsWith(candidate, suffix); } function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); var indexOfStar = pattern.indexOf("*"); return indexOfStar === -1 ? undefined : { @@ -3246,13 +4070,20 @@ var ts; } ts.tryParsePattern = tryParsePattern; function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; return !(pos >= 0); } ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ function extensionIsTypeScript(ext) { - return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } ts.extensionIsTypeScript = extensionIsTypeScript; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); if (ext !== undefined) { @@ -3269,6 +4100,16 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3277,11 +4118,192 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; - function assertTypeIsNever(_) { } + function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; + function createCachedDirectoryStructureHost(host) { + var cachedReadDirectoryResult = createMap(); + var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); + var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, + newLine: host.newLine, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + write: function (s) { return host.write(s); }, + writeFile: writeFile, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: createDirectory, + getCurrentDirectory: getCurrentDirectory, + getDirectories: getDirectories, + readDirectory: readDirectory, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache, + exit: function (code) { return host.exit(code); } + }; + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + } + else { + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (parentResult) { + var baseName = getBaseNameOfFileName(fileOrDirectory); + if (parentResult) { + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + } + } + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; })(ts || (ts = {})); +/// var ts; (function (ts) { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ function setStackTraceLimit() { if (Error.stackTraceLimit < 100) { Error.stackTraceLimit = 100; @@ -3310,14 +4332,16 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { + var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); + // One file can have multiple watchers var fileWatcherCallbacks = ts.createMultiMap(); return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { @@ -3337,7 +4361,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3358,9 +4382,11 @@ var ts; fileWatcherCallbacks.remove(filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = typeof relativeFileName !== "string" + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + var fileName = !ts.isString(relativeFileName) ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); + // Some applications save a working file via rename operations if ((eventName === "change" || eventName === "rename")) { var callbacks = fileWatcherCallbacks.get(fileName); if (callbacks) { @@ -3376,11 +4402,14 @@ var ts; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { return false; } + // If this file exists under a different case, we must be case-insensitve. return !fileExists(swapCase(__filename)); } + /** Convert all lowercase chars to uppercase, and vice-versa */ function swapCase(s) { return s.replace(/\w/g, function (ch) { var up = ch.toUpperCase(); @@ -3389,6 +4418,82 @@ var ts; } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { + return; + } + callback(fileName, eventKind); + } + } + function fsWatchDirectory(directoryName, callback, recursive) { + var options; + /** Watcher for the directory depending on whether it is missing or present */ + var watcher = !directoryExists(directoryName) ? + watchMissingDirectory() : + watchPresentDirectory(); + return { + close: function () { + // Close the watcher (either existing directory watcher or missing directory watcher) + watcher.close(); + } + }; + /** + * Watch the directory that is currently present + * and when the watched directory is deleted, switch to missing directory watcher + */ + function watchPresentDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + var dirWatcher = _fs.watch(directoryName, options, callback); + dirWatcher.on("error", function () { + if (!directoryExists(directoryName)) { + // Deleting directory + watcher = watchMissingDirectory(); + // Call the callback for current directory + callback("rename", ""); + } + }); + return dirWatcher; + } + /** + * Watch the directory that is missing + * and switch to existing directory when the directory is created + */ + function watchMissingDirectory() { + return fsWatchFile(directoryName, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { + watcher.close(); + watcher = watchPresentDirectory(); + // Call the callback for current directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + callback("rename", ""); + } + }); + } + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -3396,7 +4501,9 @@ var ts; var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { - len &= ~1; + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; // Round down to a multiple of 2 for (var i = 0; i < len; i += 2) { var temp = buffer[i]; buffer[i] = buffer[i + 1]; @@ -3405,21 +4512,25 @@ var ts; return buffer.toString("utf16le", 2); } if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected return buffer.toString("utf16le", 2); } if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected return buffer.toString("utf8", 3); } + // Default is UTF-8 with no byte order mark return buffer.toString("utf8"); } function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } var fd; try { fd = _fs.openSync(fileName, "w"); - _fs.writeSync(fd, data, undefined, "utf8"); + _fs.writeSync(fd, data, /*position*/ undefined, "utf8"); } finally { if (fd !== undefined) { @@ -3434,13 +4545,15 @@ var ts; var directories = []; for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var entry = entries_1[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } - var name_3 = ts.combinePaths(path, entry); + var name = ts.combinePaths(path, entry); var stat = void 0; try { - stat = _fs.statSync(name_3); + stat = _fs.statSync(name); } catch (e) { continue; @@ -3470,8 +4583,8 @@ var ts; try { var stat = _fs.statSync(path); switch (entryKind) { - case 0: return stat.isFile(); - case 1: return stat.isDirectory(); + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); } } catch (e) { @@ -3479,15 +4592,14 @@ var ts; } } function fileExists(path) { - return fileSystemEntryExists(path, 0); + return fileSystemEntryExists(path, 0 /* File */); } function directoryExists(path) { - return fileSystemEntryExists(path, 1); + return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); + return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -3505,43 +4617,21 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); - return { - close: function () { return _fs.unwatchFile(fileName, fileChanged); } - }; - } - function fileChanged(curr, prev) { - var isCurrZero = +curr.mtime === 0; - var isPrevZero = +prev.mtime === 0; - var created = !isCurrZero && isPrevZero; - var deleted = isCurrZero && !isPrevZero; - var eventKind = created - ? FileWatcherEventKind.Created - : deleted - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { - return; - } - callback(fileName, eventKind); + return fsWatchFile(fileName, callback, pollingInterval); } }, watchDirectory: function (directoryName, callback, recursive) { - var options; - if (!directoryExists(directoryName)) { - return noOpFileWatcher; - } - if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - return _fs.watch(directoryName, options, function (eventName, relativeFileName) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return fsWatchDirectory(directoryName, function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); } - }); + }, recursive); }, resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, @@ -3588,7 +4678,7 @@ var ts; return stat.size; } } - catch (e) { } + catch (_a) { } return 0; }, exit: function (exitCode) { @@ -3602,7 +4692,8 @@ var ts; try { require("source-map-support").install(); } - catch (e) { + catch (_a) { + // Could not enable source maps. } }, setTimeout: setTimeout, @@ -3618,11 +4709,13 @@ var ts; useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, write: ChakraHost.echo, readFile: function (path, _encoding) { + // encoding is automatically handled by the implementation in ChakraHost return ChakraHost.readFile(path); }, writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } ChakraHost.writeFile(path, data); }, @@ -3644,7 +4737,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -3657,9 +4750,12 @@ var ts; sys = getChakraSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify sys = getNodeSystem(); } if (sys) { + // patch writefile to create folder before writing the file var originalWriteFile_1 = sys.writeFile; sys.writeFile = function (path, data, writeBom) { var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); @@ -3673,18 +4769,23 @@ var ts; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) - ? 1 - : 0; + ? 1 /* Normal */ + : 0 /* None */; } if (ts.sys && ts.sys.debugMode) { ts.Debug.isDebugging = true; } })(ts || (ts = {})); +// +// generated from './diagnosticInformationMap.generated.ts' by '../../scripts/processDiagnosticMessages.js' +/// +/* @internal */ var ts; (function (ts) { function diag(code, category, key, message) { return { code: code, category: category, key: key, message: message }; } + // tslint:disable-next-line variable-name ts.Diagnostics = { Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), @@ -3809,11 +4910,11 @@ var ts; An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), @@ -3894,6 +4995,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "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."), @@ -3913,6 +5015,13 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4114,7 +5223,7 @@ var ts; No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), - Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), @@ -4130,7 +5239,7 @@ var ts; await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), @@ -4159,14 +5268,16 @@ var ts; Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), - Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4240,6 +5351,11 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "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."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4263,16 +5379,16 @@ var ts; Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), @@ -4315,6 +5431,14 @@ var ts; Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4343,6 +5467,7 @@ var ts; File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -4356,7 +5481,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -4458,7 +5583,6 @@ var ts; Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), - The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), @@ -4514,6 +5638,8 @@ var ts; Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), 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."), @@ -4563,6 +5689,13 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4580,39 +5713,54 @@ var ts; super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), - Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), - Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), - Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), - Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), - Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), - Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), - Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), - Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), - Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), - Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), - Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), - Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), - Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), - Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), - Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), + Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), }; })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { ts.emptyArray = []; @@ -4645,12 +5793,15 @@ var ts; writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + // Completely ignore indentation for string writers. And map newlines to + // a single space. writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, clear: function () { return str = ""; }, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; } @@ -4717,23 +5868,31 @@ var ts; return false; } ts.hasChangesInResolutions = hasChangesInResolutions; + // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.flags & 131072) !== 0; + return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.flags & 262144)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || + if (!(node.flags & 262144 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.flags |= 131072; + node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */; } - node.flags |= 262144; + // Also mark that we've propagated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.flags |= 262144 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 265) { + while (node && node.kind !== 269 /* SourceFile */) { node = node.parent; } return node; @@ -4741,11 +5900,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 207: - case 235: - case 214: - case 215: - case 216: + case 208 /* Block */: + case 236 /* CaseBlock */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return true; } return false; @@ -4756,6 +5915,7 @@ var ts; return ts.getLineStarts(sourceFile)[line]; } ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. function nodePosToString(node) { var file = getSourceFileOfNode(node); var loc = ts.getLineAndCharacterOfPosition(file, node.pos); @@ -4768,12 +5928,19 @@ var ts; var lineIndex = line; var sourceText = sourceFile.text; if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF return sourceText.length - 1; } else { + // current line start var start = lineStarts[lineIndex]; + // take the start position of the next line - 1 = it should be some line break var pos = lineStarts[lineIndex + 1] - 1; ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { pos--; } @@ -4781,21 +5948,40 @@ var ts; } } ts.getEndLinePosition = getEndLinePosition; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. function nodeIsMissing(node) { if (node === undefined) { return true; } - return node.pos === node.end && node.pos >= 0 && node.kind !== 1; + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; } ts.nodeIsMissing = nodeIsMissing; function nodeIsPresent(node) { return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { - if (text.charCodeAt(commentPos + 1) === 47 && + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && commentPos + 2 < commentEnd && - text.charCodeAt(commentPos + 2) === 47) { + text.charCodeAt(commentPos + 2) === 47 /* slash */) { var textSubStr = text.substring(commentPos, commentEnd); return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) || @@ -4807,21 +5993,27 @@ var ts; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { return node.pos; } if (ts.isJSDocNode(node)) { - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { + // For a syntax list, it is possible that one of its children has JSDocComment nodes, while + // the syntax list itself considers them as normal trivia. Therefore if we simply skip + // trivia for the list, we may have skipped the JSDocComment as well. So we should process its + // first child to determine the actual position of its first token. + if (node.kind === 290 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -4855,135 +6047,164 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ function indexOfNode(nodeArray, node) { - return ts.binarySearch(nodeArray, node, compareNodePos); + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } ts.indexOfNode = indexOfNode; - function compareNodePos(_a, _b) { - var aPos = _a.pos; - var bPos = _b.pos; - return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; - } + /** + * Gets flags that control emit behavior of a node. + */ function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + // If we can't reach the original source text, use the canonical form if it's a number, + // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { - case 9: + case 9 /* StringLiteral */: if (node.singleQuote) { - return "'" + escapeText(node.text, 39) + "'"; + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { - return '"' + escapeText(node.text, 34) + '"'; - } - case 13: - return "`" + escapeText(node.text, 96) + "`"; - case 14: - return "`" + escapeText(node.text, 96) + "${"; - case 15: - return "}" + escapeText(node.text, 96) + "${"; - case 16: - return "}" + escapeText(node.text, 96) + "`"; - case 8: - case 12: + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + case 13 /* NoSubstitutionTemplateLiteral */: + return "`" + escapeText(node.text, 96 /* backtick */) + "`"; + case 14 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings + return "`" + escapeText(node.text, 96 /* backtick */) + "${"; + case 15 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings + return "}" + escapeText(node.text, 96 /* backtick */) + "${"; + case 16 /* TemplateTail */: + return "}" + escapeText(node.text, 96 /* backtick */) + "`"; + case 8 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { - return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; + // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); } ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. + * @param identifier The identifier to escape + */ function escapeIdentifier(identifier) { return identifier; } ts.escapeIdentifier = escapeIdentifier; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || + return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 226 && node.parent.kind === 260; + return node.kind === 227 /* VariableDeclaration */ && node.parent.kind === 264 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 233 && - (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + return node && node.kind === 234 /* ModuleDeclaration */ && + (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node && node.kind === 233 && (!node.body); + // The only kind of module that can be missing a body is a shorthand ambient module. + return node && node.kind === 234 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 || - node.kind === 233 || + return node.kind === 269 /* SourceFile */ || + node.kind === 234 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { - return !!(module.flags & 512); + return !!(module.flags & 512 /* GlobalAugmentation */); } ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; function isExternalModuleAugmentation(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module if (!node || !isAmbientModule(node)) { return false; } switch (node.parent.kind) { - case 265: + case 269 /* SourceFile */: return ts.isExternalModule(node.parent); - case 234: + case 235 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 265: - case 235: - case 260: - case 233: - case 214: - case 215: - case 216: - case 152: - case 151: - case 153: - case 154: - case 228: - case 186: - case 187: + case 269 /* SourceFile */: + case 236 /* CaseBlock */: + case 264 /* CatchClause */: + case 234 /* ModuleDeclaration */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; - case 207: + case 208 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block return parentNode && !ts.isFunctionLike(parentNode); } return false; @@ -4991,25 +6212,25 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 155: - case 156: - case 150: - case 157: - case 160: - case 161: - case 273: - case 229: - case 199: - case 230: - case 231: - case 282: - case 228: - case 151: - case 152: - case 153: - case 154: - case 186: - case 187: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 287 /* JSDocTemplateTag */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; default: ts.assertTypeIsNever(node); @@ -5017,6 +6238,18 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -5027,6 +6260,9 @@ var ts; } } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. function declarationNameToString(name) { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } @@ -5037,12 +6273,12 @@ var ts; ts.getNameFromIndexInfo = getNameFromIndexInfo; function getTextOfPropertyName(name) { switch (name.kind) { - case 71: + case 71 /* Identifier */: return name.escapedText; - case 9: - case 8: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); - case 144: + case 145 /* ComputedPropertyName */: if (isStringOrNumericLiteral(name.expression)) { return escapeLeadingUnderscores(name.expression.text); } @@ -5052,23 +6288,23 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { - case 71: - return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); - case 143: + case 71 /* Identifier */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 144 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179: + case 180 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); } } ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { @@ -5085,7 +6321,7 @@ var ts; } ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; function getSpanOfTokenAtPosition(sourceFile, pos) { - var scanner = ts.createScanner(sourceFile.languageVersion, true, sourceFile.languageVariant, sourceFile.text, undefined, pos); + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); scanner.scan(); var start = scanner.getTokenPos(); return ts.createTextSpanFromBounds(start, scanner.getTextPos()); @@ -5093,10 +6329,12 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207) { + if (node.body && node.body.kind === 208 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { + // The arrow function spans multiple lines, + // make the error span be the first line, inclusive. return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); } } @@ -5105,32 +6343,37 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 265: - var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); + case 269 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 226: - case 176: - case 229: - case 199: - case 230: - case 233: - case 232: - case 264: - case 228: - case 186: - case 151: - case 153: - case 154: - case 231: + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 232 /* TypeAliasDeclaration */: errorNode = node.name; break; - case 187: + case 188 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. return getSpanOfTokenAtPosition(sourceFile, node.pos); } var pos = nodeIsMissing(errorNode) @@ -5144,47 +6387,48 @@ var ts; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isConstEnumDeclaration(node) { - return node.kind === 232 && isConst(node); + return node.kind === 233 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { - return !!(ts.getCombinedNodeFlags(node) & 2) - || !!(ts.getCombinedModifierFlags(node) & 2048); + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */) + || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(ts.getCombinedNodeFlags(node) & 1); + return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 181 && n.expression.kind === 97; + return n.kind === 182 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 181 && n.expression.kind === 91; + return n.kind === 182 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isPrologueDirective(node) { - return node.kind === 210 - && node.expression.kind === 9; + return node.kind === 211 /* ExpressionStatement */ + && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return node.kind !== 10 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; + return node.kind !== 10 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 || - node.kind === 145 || - node.kind === 186 || - node.kind === 187 || - node.kind === 185) ? + var commentRanges = (node.kind === 147 /* Parameter */ || + node.kind === 146 /* TypeParameter */ || + node.kind === 187 /* FunctionExpression */ || + node.kind === 188 /* ArrowFunction */ || + node.kind === 186 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); + // True if the comment starts with '/**' but not if it is '/**/' return ts.filter(commentRanges, function (comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 42 && - text.charCodeAt(comment.pos + 3) !== 47; + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; }); } ts.getJSDocCommentRanges = getJSDocCommentRanges; @@ -5193,69 +6437,81 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (158 <= node.kind && node.kind <= 173) { + if (159 /* FirstTypeNode */ <= node.kind && node.kind <= 174 /* LastTypeNode */) { return true; } switch (node.kind) { - case 119: - case 133: - case 136: - case 122: - case 137: - case 139: - case 130: + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 136 /* StringKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 139 /* UndefinedKeyword */: + case 130 /* NeverKeyword */: return true; - case 105: - return node.parent.kind !== 190; - case 201: + case 105 /* VoidKeyword */: + return node.parent.kind !== 191 /* VoidExpression */; + case 202 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 71: - if (node.parent.kind === 143 && node.parent.right === node) { + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 71 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 179 && node.parent.name === node) { + else if (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 143: - case 179: - case 99: - var parent_1 = node.parent; - if (parent_1.kind === 162) { + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */ || node.kind === 180 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 144 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 99 /* ThisKeyword */: + var parent = node.parent; + if (parent.kind === 163 /* TypeQuery */) { return false; } - if (158 <= parent_1.kind && parent_1.kind <= 173) { + // Do not recursively call isPartOfTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isPartOfTypeNode would consider the qualified name A.B a type node. + // Only C and A.B.C are type nodes. + if (159 /* FirstTypeNode */ <= parent.kind && parent.kind <= 174 /* LastTypeNode */) { return true; } - switch (parent_1.kind) { - case 201: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 145: - return node === parent_1.constraint; - case 149: - case 148: - case 146: - case 226: - return node === parent_1.type; - case 228: - case 186: - case 187: - case 152: - case 151: - case 150: - case 153: - case 154: - return node === parent_1.type; - case 155: - case 156: - case 157: - return node === parent_1.type; - case 184: - return node === parent_1.type; - case 181: - case 182: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 183: + switch (parent.kind) { + case 202 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 146 /* TypeParameter */: + return node === parent.constraint; + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 147 /* Parameter */: + case 227 /* VariableDeclaration */: + return node === parent.type; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return node === parent.type; + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + return node === parent.type; + case 185 /* TypeAssertionExpression */: + return node === parent.type; + case 182 /* CallExpression */: + case 183 /* NewExpression */: + return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + case 184 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } } @@ -5272,27 +6528,29 @@ var ts; return false; } ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { switch (node.kind) { - case 219: + case 220 /* ReturnStatement */: return visitor(node); - case 235: - case 207: - case 211: - case 212: - case 213: - case 214: - case 215: - case 216: - case 220: - case 221: - case 257: - case 258: - case 222: - case 224: - case 260: + case 236 /* CaseBlock */: + case 208 /* Block */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 221 /* WithStatement */: + case 222 /* SwitchStatement */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -5302,40 +6560,53 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 197: + case 198 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 232: - case 230: - case 233: - case 231: - case 229: - case 199: + case 233 /* EnumDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. return; default: if (ts.isFunctionLike(node)) { - var name_4 = node.name; - if (name_4 && name_4.kind === 144) { - traverse(name_4.expression); + var name = node.name; + if (name && name.kind === 145 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(name.expression); return; } } else if (!isPartOfTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. ts.forEachChild(node, traverse); } } } } ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ function getRestParameterElementType(node) { - if (node && node.kind === 164) { + if (node && node.kind === 165 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 159) { + else if (node && node.kind === 160 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -5343,32 +6614,55 @@ var ts; } } ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 231 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 164 /* TypeLiteral */: + return node.members; + case 179 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; function isVariableLike(node) { if (node) { switch (node.kind) { - case 176: - case 264: - case 146: - case 261: - case 149: - case 148: - case 262: - case 226: + case 177 /* BindingElement */: + case 268 /* EnumMember */: + case 147 /* Parameter */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 266 /* ShorthandPropertyAssignment */: + case 227 /* VariableDeclaration */: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 228 /* VariableDeclarationList */ + && node.parent.parent.kind === 209 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return true; } return false; @@ -5379,7 +6673,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 222) { + if (node.statement.kind !== 223 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -5387,30 +6681,30 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 && ts.isFunctionLike(node.parent); + return node && node.kind === 208 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 151 && node.parent.kind === 178; + return node && node.kind === 152 /* MethodDeclaration */ && node.parent.kind === 179 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 && - (node.parent.kind === 178 || - node.parent.kind === 199); + return node.kind === 152 /* MethodDeclaration */ && + (node.parent.kind === 179 /* ObjectLiteralExpression */ || + node.parent.kind === 200 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { - return predicate && predicate.kind === 1; + return predicate && predicate.kind === 1 /* Identifier */; } ts.isIdentifierTypePredicate = isIdentifierTypePredicate; function isThisTypePredicate(predicate) { - return predicate && predicate.kind === 0; + return predicate && predicate.kind === 0 /* This */; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 261) { + if (property.kind === 265 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); } @@ -5432,57 +6726,80 @@ var ts; return undefined; } switch (node.kind) { - case 144: + case 145 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. if (ts.isClassLike(node.parent.parent)) { return node; } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. node = node.parent; break; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 147 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. node = node.parent; } break; - case 187: + case 188 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } - case 228: - case 186: - case 233: - case 149: - case 148: - case 151: - case 150: - case 152: - case 153: - case 154: - case 155: - case 156: - case 157: - case 232: - case 265: + // falls through + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 234 /* ModuleDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 233 /* EnumDeclaration */: + case 269 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; function getNewTargetContainer(node) { - var container = getThisContainer(node, false); + var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 152: - case 228: - case 186: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return container; } } return undefined; } ts.getNewTargetContainer = getNewTargetContainer; + /** + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; @@ -5490,28 +6807,34 @@ var ts; return node; } switch (node.kind) { - case 144: + case 145 /* ComputedPropertyName */: node = node.parent; break; - case 228: - case 186: - case 187: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: if (!stopOnFunctions) { continue; } - case 149: - case 148: - case 151: - case 150: - case 152: - case 153: - case 154: + // falls through + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return node; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 147 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. node = node.parent; } break; @@ -5520,208 +6843,227 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 || func.kind === 187) { + if (func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */) { var prev = func; - var parent_2 = func.parent; - while (parent_2.kind === 185) { - prev = parent_2; - parent_2 = parent_2.parent; + var parent = func.parent; + while (parent.kind === 186 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; } - if (parent_2.kind === 181 && parent_2.expression === prev) { - return parent_2; + if (parent.kind === 182 /* CallExpression */ && parent.expression === prev) { + return parent; } } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + /** + * Determines whether a node is a property or element access expression for `super`. + */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 179 || kind === 180) - && node.expression.kind === 97; + return (kind === 180 /* PropertyAccessExpression */ || kind === 181 /* ElementAccessExpression */) + && node.expression.kind === 97 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 180 /* PropertyAccessExpression */ || kind === 181 /* ElementAccessExpression */) + && node.expression.kind === 99 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 159: + case 160 /* TypeReference */: return node.typeName; - case 201: + case 202 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; - case 71: - case 143: + case 71 /* Identifier */: + case 144 /* QualifiedName */: return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 183) { + if (node.kind === 184 /* TaggedTemplateExpression */) { return node.tag; } else if (ts.isJsxOpeningLikeElement(node)) { return node.tagName; } + // Will either be a CallExpression, NewExpression, or Decorator. return node.expression; } ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { + function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 229: + case 230 /* ClassDeclaration */: + // classes are valid targets return true; - case 149: - return node.parent.kind === 229; - case 153: - case 154: - case 151: + case 150 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return parent.kind === 230 /* ClassDeclaration */; + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && node.parent.kind === 229; - case 146: - return node.parent.body !== undefined - && (node.parent.kind === 152 - || node.parent.kind === 151 - || node.parent.kind === 154) - && node.parent.parent.kind === 229; + && parent.kind === 230 /* ClassDeclaration */; + case 147 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return parent.body !== undefined + && (parent.kind === 153 /* Constructor */ + || parent.kind === 152 /* MethodDeclaration */ + || parent.kind === 155 /* SetAccessor */) + && grandparent.kind === 230 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { + function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node); + && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { + function childIsDecorated(node, parent) { switch (node.kind) { - case 229: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151: - case 154: - return ts.forEach(node.parameters, nodeIsDecorated); + case 230 /* ClassDeclaration */: + return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 152 /* MethodDeclaration */: + case 155 /* SetAccessor */: + return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 251 || - parent.kind === 250 || - parent.kind === 252) { + if (parent.kind === 252 /* JsxOpeningElement */ || + parent.kind === 251 /* JsxSelfClosingElement */ || + parent.kind === 253 /* JsxClosingElement */) { return parent.tagName === node; } return false; } ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { + function isExpressionNode(node) { switch (node.kind) { - case 97: - case 95: - case 101: - case 86: - case 12: - case 177: - case 178: - case 179: - case 180: - case 181: - case 182: - case 183: - case 202: - case 184: - case 203: - case 185: - case 186: - case 199: - case 187: - case 190: - case 188: - case 189: - case 192: - case 193: - case 194: - case 195: - case 198: - case 196: - case 13: - case 200: - case 249: - case 250: - case 197: - case 191: - case 204: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 12 /* RegularExpressionLiteral */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 184 /* TaggedTemplateExpression */: + case 203 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 204 /* NonNullExpression */: + case 186 /* ParenthesizedExpression */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 195 /* BinaryExpression */: + case 196 /* ConditionalExpression */: + case 199 /* SpreadElement */: + case 197 /* TemplateExpression */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 201 /* OmittedExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 198 /* YieldExpression */: + case 192 /* AwaitExpression */: + case 205 /* MetaProperty */: return true; - case 143: - while (node.parent.kind === 143) { + case 144 /* QualifiedName */: + while (node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 || isJSXTagName(node); - case 71: - if (node.parent.kind === 162 || isJSXTagName(node)) { + return node.parent.kind === 163 /* TypeQuery */ || isJSXTagName(node); + case 71 /* Identifier */: + if (node.parent.kind === 163 /* TypeQuery */ || isJSXTagName(node)) { return true; } - case 8: - case 9: - case 99: + // falls through + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 99 /* ThisKeyword */: return isInExpressionContext(node); default: return false; } } - ts.isPartOfExpression = isPartOfExpression; + ts.isExpressionNode = isExpressionNode; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 264: - case 261: - case 176: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 268 /* EnumMember */: + case 265 /* PropertyAssignment */: + case 177 /* BindingElement */: return parent.initializer === node; - case 210: - case 211: - case 212: - case 213: - case 219: - case 220: - case 221: - case 257: - case 223: + case 211 /* ExpressionStatement */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 220 /* ReturnStatement */: + case 221 /* WithStatement */: + case 222 /* SwitchStatement */: + case 261 /* CaseClause */: + case 224 /* ThrowStatement */: return parent.expression === node; - case 214: + case 215 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 228 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 215: - case 216: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 228 /* VariableDeclarationList */) || forInStatement.expression === node; - case 184: - case 202: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return node === parent.expression; - case 205: + case 206 /* TemplateSpan */: return node === parent.expression; - case 144: + case 145 /* ComputedPropertyName */: return node === parent.expression; - case 147: - case 256: - case 255: - case 263: + case 148 /* Decorator */: + case 260 /* JsxExpression */: + case 259 /* JsxSpreadAttribute */: + case 267 /* SpreadAssignment */: return true; - case 201: + case 202 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: - return isPartOfExpression(parent); + return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind === 248; + return node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 249 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -5730,7 +7072,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind !== 248; + return node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 249 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -5738,42 +7080,63 @@ var ts; } ts.isSourceFileJavaScript = isSourceFileJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536); + return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; function isInJSDoc(node) { - return node && !!(node.flags & 1048576); + return node && !!(node.flags & 1048576 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; + /** + * Returns true if the node is a CallExpression to the identifier 'require' with + * exactly one argument (of the form 'require("name")'). + * This function does not test if the node is in a JavaScript file or not. + */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181) { + if (callExpression.kind !== 182 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 || expression.escapedText !== "require") { + if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; + return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { - return charCode === 39 || charCode === 34; + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; + /** + * Returns true if the node is a variable declaration whose initializer is a function or class expression. + * This function does not test if the node is in a JavaScript file or not. + */ function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226) { + if (s.valueDeclaration && s.valueDeclaration.kind === 227 /* VariableDeclaration */) { var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); + return declaration.initializer && (declaration.initializer.kind === 187 /* FunctionExpression */ || declaration.initializer.kind === 200 /* ClassExpression */); } return false; } ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; function getRightMostAssignedExpression(node) { - while (isAssignmentExpression(node, true)) { + while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { node = node.right; } return node; @@ -5787,75 +7150,87 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { - return 0; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getSpecialPropertyAssignmentKind(expr) { + if (!isInJavaScriptFile(expr)) { + return 0 /* None */; } - var expr = expression; - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { - return 0; + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 180 /* PropertyAccessExpression */) { + return 0 /* None */; } var lhs = expr.left; - if (lhs.expression.kind === 71) { + if (lhs.expression.kind === 71 /* Identifier */) { var lhsId = lhs.expression; if (lhsId.escapedText === "exports") { - return 1; + // exports.name = expr + return 1 /* ExportsProperty */; } else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { - return 2; + // module.exports = expr + return 2 /* ModuleExports */; } else { - return 5; + // F.x = expr + return 5 /* Property */; } } - else if (lhs.expression.kind === 99) { - return 4; + else if (lhs.expression.kind === 99 /* ThisKeyword */) { + return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 179) { + else if (lhs.expression.kind === 180 /* PropertyAccessExpression */) { + // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 71) { + if (innerPropertyAccess.expression.kind === 71 /* Identifier */) { + // module.exports.name = expr var innerPropertyAccessIdentifier = innerPropertyAccess.expression; if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { - return 1; + return 1 /* ExportsProperty */; } if (innerPropertyAccess.name.escapedText === "prototype") { - return 3; + return 3 /* PrototypeProperty */; } } } - return 0; + return 0 /* None */; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isSpecialPropertyDeclaration(expr) { + return isInJavaScriptFile(expr) && + expr.parent && expr.parent.kind === 211 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function getExternalModuleName(node) { - if (node.kind === 238) { + if (node.kind === 239 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 237) { + if (node.kind === 238 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 248) { + if (reference.kind === 249 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 244) { + if (node.kind === 245 /* ExportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 233 && node.name.kind === 9) { + if (isModuleWithStringLiteralName(node)) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 237) { + if (node.kind === 238 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 241 /* NamespaceImport */) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 238 + return node.kind === 239 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } @@ -5863,13 +7238,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 146: - case 151: - case 150: - case 262: - case 261: - case 149: - case 148: + case 147 /* Parameter */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 266 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -5877,7 +7252,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 273 && + return node.kind === 277 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; @@ -5890,37 +7265,62 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 58 /* EqualsToken */ && + node.expression.right; + } + ts.getSourceOfAssignment = getSourceOfAssignment; + function getSingleInitializerOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0].initializer === child) && + node.declarationList.declarations[0].initializer; + } + ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; + function getSingleVariableOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0] === child) && + node.declarationList.declarations[0]; + } + ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; + function getNestedModuleDeclaration(node) { + return node.kind === 234 /* ModuleDeclaration */ && + node.body && + node.body.kind === 234 /* ModuleDeclaration */ && + node.body; + } + ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocCommentsAndTagsWorker(variableStatementNode); - } - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 && - parent.operatorToken.kind === 58 && - parent.parent.kind === 210; - if (isSourceOfAssignmentExpressionStatement) { + if (parent && (parent.kind === 265 /* PropertyAssignment */ || getNestedModuleDeclaration(parent))) { + getJSDocCommentsAndTagsWorker(parent); + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + if (parent && parent.parent && + (getSingleVariableOfVariableStatement(parent.parent, node) || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - var isModuleDeclaration = node.kind === 233 && - parent && parent.kind === 233; - var isPropertyAssignmentExpression = parent && parent.kind === 261; - if (isModuleDeclaration || isPropertyAssignmentExpression) { + if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatement(parent.parent.parent, node)) { + getJSDocCommentsAndTagsWorker(parent.parent.parent); + } + if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || + node.kind === 180 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 211 /* ExpressionStatement */) { getJSDocCommentsAndTagsWorker(parent); } - if (node.kind === 146) { + // Pull parameter comments from declaring function as well + if (node.kind === 147 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { @@ -5932,6 +7332,7 @@ var ts; } } ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ function getParameterSymbolFromJSDoc(node) { if (node.symbol) { return node.symbol; @@ -5940,17 +7341,29 @@ var ts; return undefined; } var name = node.name.escapedText; - ts.Debug.assert(node.parent.kind === 275); - var func = node.parent.parent; - if (!ts.isFunctionLike(func)) { + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { return undefined; } - var parameter = ts.find(func.parameters, function (p) { - return p.name.kind === 71 && p.name.escapedText === name; - }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + var host = getJSDocHost(node); + var decl = getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatement(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getJSDocHost(node) { + ts.Debug.assert(node.parent.kind === 279 /* JSDocComment */); + return node.parent.parent; + } + ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { var name = node.name.escapedText; var typeParameters = node.parent.parent.parent.typeParameters; @@ -5958,27 +7371,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -5989,55 +7389,71 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 194: + case 195 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 ? 1 : 2 : - 0; - case 192: - case 193: + binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : + 0 /* None */; + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; - return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; - case 215: - case 216: - return parent.initializer === node ? 1 : 0; - case 185: - case 177: - case 198: + return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; + case 186 /* ParenthesizedExpression */: + case 178 /* ArrayLiteralExpression */: + case 199 /* SpreadElement */: node = parent; break; - case 262: + case 266 /* ShorthandPropertyAssignment */: if (parent.name !== node) { - return 0; + return 0 /* None */; } node = parent.parent; break; - case 261: + case 265 /* PropertyAssignment */: if (parent.name === node) { - return 0; + return 0 /* None */; } node = parent.parent; break; default: - return 0; + return 0 /* None */; } parent = node.parent; } } ts.getAssignmentTargetKind = getAssignmentTargetKind; + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. + // (Note that `p` is not a target in the above examples, only `a`.) function isAssignmentTarget(node) { - return getAssignmentTargetKind(node) !== 0; + return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 169 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 186 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; + // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 179 && node.kind !== 180) { + if (node.kind !== 180 /* PropertyAccessExpression */ && node.kind !== 181 /* ElementAccessExpression */) { return false; } - node = node.parent; - while (node && node.kind === 185) { - node = node.parent; - } - return node && node.kind === 188; + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 189 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -6049,87 +7465,92 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; + // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { switch (name.kind) { - case 71: - case 9: - case 8: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: return ts.isDeclaration(name.parent) && name.parent.name === name; default: return false; } } ts.isDeclarationName = isDeclarationName; + // See GH#16030 function isAnyDeclarationName(name) { switch (name.kind) { - case 71: - case 9: - case 8: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: if (ts.isDeclaration(name.parent)) { return name.parent.name === name; } var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; default: return false; } } ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { - return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 144 && + return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + node.parent.kind === 145 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + // Return true if the given identifier is classified as an IdentifierName function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 149: - case 148: - case 151: - case 150: - case 153: - case 154: - case 264: - case 261: - case 179: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 268 /* EnumMember */: + case 265 /* PropertyAssignment */: + case 180 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access return parent.name === node; - case 143: + case 144 /* QualifiedName */: + // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 143) { + while (parent.kind === 144 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 162; + return parent.kind === 163 /* TypeQuery */; } return false; - case 176: - case 242: + case 177 /* BindingElement */: + case 243 /* ImportSpecifier */: + // Property name in binding element or import specifier return parent.propertyName === node; - case 246: - case 253: + case 247 /* ExportSpecifier */: + case 257 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute return true; } return false; } ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = + // export default function isAliasSymbolDeclaration(node) { - return node.kind === 237 || - node.kind === 236 || - node.kind === 239 && !!node.name || - node.kind === 240 || - node.kind === 242 || - node.kind === 246 || - node.kind === 243 && exportAssignmentIsAlias(node); + return node.kind === 238 /* ImportEqualsDeclaration */ || + node.kind === 237 /* NamespaceExportDeclaration */ || + node.kind === 240 /* ImportClause */ && !!node.name || + node.kind === 241 /* NamespaceImport */ || + node.kind === 243 /* ImportSpecifier */ || + node.kind === 247 /* ExportSpecifier */ || + node.kind === 244 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -6137,17 +7558,17 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85); + var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108); + var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85); + var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; @@ -6213,11 +7634,24 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 72 <= token && token <= 142; + return 72 /* FirstKeyword */ <= token && token <= 143 /* LastKeyword */; } ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 117 /* FirstContextualKeyword */ <= token && token <= 143 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; function isTrivia(token) { - return 2 <= token && token <= 7; + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } ts.isTrivia = isTrivia; var FunctionFlags; @@ -6230,76 +7664,88 @@ var ts; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { if (!node) { - return 4; + return 4 /* Invalid */; } - var flags = 0; + var flags = 0 /* Normal */; switch (node.kind) { - case 228: - case 186: - case 151: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: if (node.asteriskToken) { - flags |= 1; + flags |= 1 /* Generator */; } - case 187: - if (hasModifier(node, 256)) { - flags |= 2; + // falls through + case 188 /* ArrowFunction */: + if (hasModifier(node, 256 /* Async */)) { + flags |= 2 /* Async */; } break; } if (!node.body) { - flags |= 4; + flags |= 4 /* Invalid */; } return flags; } ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 228: - case 186: - case 187: - case 151: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined - && hasModifier(node, 256); + && hasModifier(node, 256 /* Async */); } return false; } ts.isAsyncFunction = isAsyncFunction; function isStringOrNumericLiteral(node) { var kind = node.kind; - return kind === 9 - || kind === 8; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 144 && + return name.kind === 145 /* ComputedPropertyName */ && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ function isWellKnownSymbolSyntactically(node) { return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71) { + if (name.kind === 71 /* Identifier */) { return name.escapedText; } - if (name.kind === 9 || name.kind === 8) { + if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 144) { + if (name.kind === 145 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.escapedText; - return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } - else if (nameExpression.kind === 9 || nameExpression.kind === 8) { + else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(nameExpression.text); } } @@ -6308,11 +7754,11 @@ var ts; ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function getTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 71) { - return ts.unescapeLeadingUnderscores(node.escapedText); + if (node.kind === 71 /* Identifier */) { + return ts.idText(node); } - if (node.kind === 9 || - node.kind === 8) { + if (node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { return node.text; } } @@ -6321,11 +7767,11 @@ var ts; ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { if (node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { return node.escapedText; } - if (node.kind === 9 || - node.kind === 8) { + if (node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(node.text); } } @@ -6336,8 +7782,11 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + /** + * Includes the word "Symbol" with unicode escapes + */ function isESSymbolIdentifier(node) { - return node.kind === 71 && node.escapedText === "Symbol"; + return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { @@ -6346,11 +7795,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 146; + return root.kind === 147 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 176) { + while (node.kind === 177 /* BindingElement */) { node = node.parent.parent; } return node; @@ -6358,15 +7807,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 152 - || kind === 186 - || kind === 228 - || kind === 187 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 233 - || kind === 265; + return kind === 153 /* Constructor */ + || kind === 187 /* FunctionExpression */ + || kind === 229 /* FunctionDeclaration */ + || kind === 188 /* ArrowFunction */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 234 /* ModuleDeclaration */ + || kind === 269 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -6385,55 +7834,55 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 182: - return hasArguments ? 0 : 1; - case 192: - case 189: - case 190: - case 188: - case 191: - case 195: - case 197: - return 1; - case 194: + case 183 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 193 /* PrefixUnaryExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 192 /* AwaitExpression */: + case 196 /* ConditionalExpression */: + case 198 /* YieldExpression */: + return 1 /* Right */; + case 195 /* BinaryExpression */: switch (operator) { - case 40: - case 58: - case 59: - case 60: - case 62: - case 61: - case 63: - case 64: - case 65: - case 66: - case 67: - case 68: - case 70: - case 69: - return 1; - } - } - return 0; + case 40 /* AsteriskAsteriskToken */: + case 58 /* EqualsToken */: + case 59 /* PlusEqualsToken */: + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 70 /* CaretEqualsToken */: + case 69 /* BarEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; } ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 194) { + if (expression.kind === 195 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 192 || expression.kind === 193) { + else if (expression.kind === 193 /* PrefixUnaryExpression */ || expression.kind === 194 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -6443,108 +7892,109 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 99: - case 97: - case 71: - case 95: - case 101: - case 86: - case 8: - case 9: - case 177: - case 178: - case 186: - case 187: - case 199: - case 249: - case 250: - case 12: - case 13: - case 196: - case 185: - case 200: + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 71 /* Identifier */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 200 /* ClassExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 197 /* TemplateExpression */: + case 186 /* ParenthesizedExpression */: + case 201 /* OmittedExpression */: return 19; - case 183: - case 179: - case 180: + case 184 /* TaggedTemplateExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: return 18; - case 182: + case 183 /* NewExpression */: return hasArguments ? 18 : 17; - case 181: + case 182 /* CallExpression */: return 17; - case 193: + case 194 /* PostfixUnaryExpression */: return 16; - case 192: - case 189: - case 190: - case 188: - case 191: + case 193 /* PrefixUnaryExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 192 /* AwaitExpression */: return 15; - case 194: + case 195 /* BinaryExpression */: switch (operatorKind) { - case 51: - case 52: + case 51 /* ExclamationToken */: + case 52 /* TildeToken */: return 15; - case 40: - case 39: - case 41: - case 42: + case 40 /* AsteriskAsteriskToken */: + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: return 14; - case 37: - case 38: + case 37 /* PlusToken */: + case 38 /* MinusToken */: return 13; - case 45: - case 46: - case 47: + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: return 12; - case 27: - case 30: - case 29: - case 31: - case 92: - case 93: + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + case 92 /* InKeyword */: + case 93 /* InstanceOfKeyword */: return 11; - case 32: - case 34: - case 33: - case 35: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: return 10; - case 48: + case 48 /* AmpersandToken */: return 9; - case 50: + case 50 /* CaretToken */: return 8; - case 49: + case 49 /* BarToken */: return 7; - case 53: + case 53 /* AmpersandAmpersandToken */: return 6; - case 54: + case 54 /* BarBarToken */: return 5; - case 58: - case 59: - case 60: - case 62: - case 61: - case 63: - case 64: - case 65: - case 66: - case 67: - case 68: - case 70: - case 69: + case 58 /* EqualsToken */: + case 59 /* PlusEqualsToken */: + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 70 /* CaretEqualsToken */: + case 69 /* BarEqualsToken */: return 3; - case 26: + case 26 /* CommaToken */: return 0; default: return -1; } - case 195: + case 196 /* ConditionalExpression */: return 4; - case 197: + case 198 /* YieldExpression */: return 2; - case 198: + case 199 /* SpreadElement */: return 1; - case 289: + case 293 /* CommaListExpression */: return 0; default: return -1; @@ -6554,6 +8004,7 @@ var ts; function createDiagnosticCollection() { var nonFileDiagnostics = []; var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; var diagnosticsModified = false; var modificationCount = 0; return { @@ -6579,6 +8030,11 @@ var ts; } } else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); @@ -6587,6 +8043,7 @@ var ts; } function getGlobalDiagnostics() { sortAndDeduplicate(); + hasReadNonFileDiagnostics = true; return nonFileDiagnostics; } function getDiagnostics(fileName) { @@ -6616,6 +8073,11 @@ var ts; } } ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var backtickQuoteEscapedCharsRegExp = /[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; @@ -6633,12 +8095,17 @@ var ts; "\`": "\\\`", "\u2028": "\\u2028", "\u2029": "\\u2029", - "\u0085": "\\u0085" + "\u0085": "\\u0085" // nextLine }); var escapedNullRegExp = /\\0[0-9]/g; + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ function escapeString(s, quoteChar) { - var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : - quoteChar === 39 ? singleQuoteEscapedCharsRegExp : + var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : + quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } @@ -6650,8 +8117,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -6662,6 +8129,8 @@ var ts; var nonAsciiCharacters = /[^\u0000-\u007F]/g; function escapeNonAsciiString(s, quoteChar) { s = escapeString(s, quoteChar); + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : s; @@ -6761,11 +8230,14 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); - var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); return ts.removeFileExtension(relativePath); } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; @@ -6783,19 +8255,29 @@ var ts; ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); - var outputDir = options.declarationDir || options.outDir; + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir ? getSourceFilePathInNewDir(sourceFile, host, outputDir) : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + /** + * Gets the source files that are expected to have an emit output. + * + * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support + * transformations. + * + * @param host An EmitHost. + * @param targetSourceFile An optional target source file to emit. + */ function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); @@ -6806,6 +8288,7 @@ var ts; } } ts.getSourceFilesToEmit = getSourceFilesToEmit; + /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } @@ -6834,7 +8317,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 152 && nodeIsPresent(member.body)) { + if (member.kind === 153 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -6846,6 +8329,7 @@ var ts; return accessor.parameters[hasThis ? 1 : 0]; } } + /** Get the type annotation for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { var parameter = getSetAccessorValueParameter(accessor); return parameter && parameter.type; @@ -6865,11 +8349,11 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 && identifierIsThisKeyword(node); + return node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99; + return id.originalKeywordKind === 99 /* ThisKeyword */; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { @@ -6879,10 +8363,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 153) { + if (accessor.kind === 154 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 154) { + else if (accessor.kind === 155 /* SetAccessor */) { setAccessor = accessor; } else { @@ -6891,8 +8375,8 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 153 || member.kind === 154) - && hasModifier(member, 32) === hasModifier(accessor, 32)) { + if ((member.kind === 154 /* GetAccessor */ || member.kind === 155 /* SetAccessor */) + && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -6902,10 +8386,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 153 && !getAccessor) { + if (member.kind === 154 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 154 && !setAccessor) { + if (member.kind === 155 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -6920,37 +8404,53 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node) { + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node) { + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node) { + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node) { + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter); + return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -6958,6 +8458,7 @@ var ts; } ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + // If the leading comments start on different line than the start of node, write new line if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); @@ -6965,6 +8466,7 @@ var ts; } ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + // If the leading comments start on different line than the start of node, write new line if (pos !== commentPos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { writer.writeLine(); @@ -6997,15 +8499,25 @@ var ts; } } ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; if (node.pos === 0) { leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); } } else { + // removeComments is false, just get detached as normal and bypass the process to filter comment leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { @@ -7017,6 +8529,9 @@ var ts; var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. break; } } @@ -7024,11 +8539,15 @@ var ts; lastComment = comment; } if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } @@ -7040,7 +8559,7 @@ var ts; } ts.emitDetachedComments = emitDetachedComments; function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (text.charCodeAt(commentPos + 1) === 42) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); var lineCount = lineMap.length; var firstCommentLineIndent = void 0; @@ -7049,29 +8568,50 @@ var ts; ? text.length + 1 : lineMap[currentLine + 1]; if (pos !== commentPos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment if (firstCommentLineIndent === undefined) { firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); } + // These are number of spaces writer is going to write at current indent var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); if (spacesToEmit > 0) { var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) while (numberOfSingleSpacesToEmit) { writer.rawWrite(" "); numberOfSingleSpacesToEmit--; } } else { + // No spaces to emit write empty string writer.rawWrite(""); } } + // Write the comment line text writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { + // Single line comment of style //.... writer.write(text.substring(commentPos, commentEnd)); } } @@ -7080,92 +8620,105 @@ var ts; var end = Math.min(commentEnd, nextLineStart - 1); var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { + // trimmed forward and ending spaces text writer.write(currentLineText); if (end !== commentEnd) { writer.writeLine(); } } else { + // Empty string - make sure we write empty line writer.writeLiteral(newLine); } } function calculateIndent(text, pos, end) { var currentLineIndent = 0; for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { - if (text.charCodeAt(pos) === 9) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); } else { + // Single space currentLineIndent++; } } return currentLineIndent; } function hasModifiers(node) { - return getModifierFlags(node) !== 0; + return getModifierFlags(node) !== 0 /* None */; } ts.hasModifiers = hasModifiers; function hasModifier(node, flags) { return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; function getSelectedModifierFlags(node, flags) { return getModifierFlags(node) & flags; } ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { - if (node.modifierFlagsCache & 536870912) { - return node.modifierFlagsCache & ~536870912; + if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { + return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; } var flags = getModifierFlagsNoCache(node); - node.modifierFlagsCache = flags | 536870912; + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; return flags; } ts.getModifierFlags = getModifierFlags; function getModifierFlagsNoCache(node) { - var flags = 0; + var flags = 0 /* None */; if (node.modifiers) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; flags |= modifierToFlag(modifier.kind); } } - if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { - flags |= 1; + if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { + flags |= 1 /* Export */; } return flags; } ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { - case 115: return 32; - case 114: return 4; - case 113: return 16; - case 112: return 8; - case 117: return 128; - case 84: return 1; - case 124: return 2; - case 76: return 2048; - case 79: return 512; - case 120: return 256; - case 131: return 64; - } - return 0; + case 115 /* StaticKeyword */: return 32 /* Static */; + case 114 /* PublicKeyword */: return 4 /* Public */; + case 113 /* ProtectedKeyword */: return 16 /* Protected */; + case 112 /* PrivateKeyword */: return 8 /* Private */; + case 117 /* AbstractKeyword */: return 128 /* Abstract */; + case 84 /* ExportKeyword */: return 1 /* Export */; + case 124 /* DeclareKeyword */: return 2 /* Ambient */; + case 76 /* ConstKeyword */: return 2048 /* Const */; + case 79 /* DefaultKeyword */: return 512 /* Default */; + case 120 /* AsyncKeyword */: return 256 /* Async */; + case 131 /* ReadonlyKeyword */: return 64 /* Readonly */; + } + return 0 /* None */; } ts.modifierToFlag = modifierToFlag; function isLogicalOperator(token) { - return token === 54 - || token === 53 - || token === 51; + return token === 54 /* BarBarToken */ + || token === 53 /* AmpersandAmpersandToken */ + || token === 51 /* ExclamationToken */; } ts.isLogicalOperator = isLogicalOperator; function isAssignmentOperator(token) { - return token >= 58 && token <= 70; + return token >= 58 /* FirstAssignment */ && token <= 70 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; + /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 && - node.parent.token === 85 && + if (node.kind === 202 /* ExpressionWithTypeArguments */ && + node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } @@ -7174,16 +8727,16 @@ var ts; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 + ? node.operatorToken.kind === 58 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { - if (isAssignmentExpression(node, true)) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 178 - || kind === 177; + return kind === 179 /* ObjectLiteralExpression */ + || kind === 178 /* ArrayLiteralExpression */; } return false; } @@ -7193,31 +8746,31 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 + return node.kind === 202 /* ExpressionWithTypeArguments */ && isEntityNameExpression(node.expression) && node.parent - && node.parent.token === 108 + && node.parent.token === 108 /* ImplementsKeyword */ && node.parent.parent && ts.isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 || - node.kind === 179 && isEntityNameExpression(node.expression); + return node.kind === 71 /* Identifier */ || + node.kind === 180 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 && node.parent.right === node) || - (node.parent.kind === 179 && node.parent.name === node); + return (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 178 && + return expression.kind === 179 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 177 && + return expression.kind === 178 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -7226,17 +8779,23 @@ var ts; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isExportDefaultSymbol(symbol) { - return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } + /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ function getExpandedCharCodes(input) { var output = []; var length = input.length; for (var i = 0; i < length; i++) { var charCode = input.charCodeAt(i); + // handel utf8 if (charCode < 0x80) { output.push(charCode); } @@ -7262,6 +8821,9 @@ var ts; return output; } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ function convertToBase64(input) { var result = ""; var charCodes = getExpandedCharCodes(input); @@ -7269,16 +8831,21 @@ var ts; var length = charCodes.length; var byte1, byte2, byte3, byte4; while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit byte1 = charCodes[i] >> 2; byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). if (i + 1 >= length) { byte3 = byte4 = 64; } else if (i + 2 >= length) { byte4 = 64; } + // Write to the output result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); i += 3; } @@ -7287,19 +8854,19 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options) { + function getNewLineCharacter(options, system) { switch (options.newLine) { - case 0: + case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; - case 1: + case 1 /* LineFeed */: return lineFeed; } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; + return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ function formatEnum(value, enumObject, isFlags) { if (value === void 0) { value = 0; } var members = getEnumMembers(enumObject); @@ -7332,70 +8899,105 @@ var ts; } function getEnumMembers(enumObject) { var result = []; - for (var name_5 in enumObject) { - var value = enumObject[name_5]; + for (var name in enumObject) { + var value = enumObject[name]; if (typeof value === "number") { - result.push([value, name_5]); + result.push([value, name]); } } return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); } function formatSyntaxKind(kind) { - return formatEnum(kind, ts.SyntaxKind, false); + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } ts.formatSyntaxKind = formatSyntaxKind; function formatModifierFlags(flags) { - return formatEnum(flags, ts.ModifierFlags, true); + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); } ts.formatModifierFlags = formatModifierFlags; function formatTransformFlags(flags) { - return formatEnum(flags, ts.TransformFlags, true); + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); } ts.formatTransformFlags = formatTransformFlags; function formatEmitFlags(flags) { - return formatEnum(flags, ts.EmitFlags, true); + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); } ts.formatEmitFlags = formatEmitFlags; function formatSymbolFlags(flags) { - return formatEnum(flags, ts.SymbolFlags, true); + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); } ts.formatSymbolFlags = formatSymbolFlags; function formatTypeFlags(flags) { - return formatEnum(flags, ts.TypeFlags, true); + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); } ts.formatTypeFlags = formatTypeFlags; function formatObjectFlags(flags) { - return formatEnum(flags, ts.ObjectFlags, true); + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); } ts.formatObjectFlags = formatObjectFlags; + /** + * Creates a new TextRange from the provided pos and end. + * + * @param pos The start position. + * @param end The end position. + */ function createRange(pos, end) { return { pos: pos, end: end }; } ts.createRange = createRange; + /** + * Creates a new TextRange from a provided range with a new end position. + * + * @param range A TextRange. + * @param end The new end position. + */ function moveRangeEnd(range, end) { return createRange(range.pos, end); } ts.moveRangeEnd = moveRangeEnd; + /** + * Creates a new TextRange from a provided range with a new start position. + * + * @param range A TextRange. + * @param pos The new Start position. + */ function moveRangePos(range, pos) { return createRange(pos, range.end); } ts.moveRangePos = moveRangePos; + /** + * Moves the start position of a range past any decorators. + */ function moveRangePastDecorators(node) { return node.decorators && node.decorators.length > 0 ? moveRangePos(node, node.decorators.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; + /** + * Moves the start position of a range past any decorators or modifiers. + */ function moveRangePastModifiers(node) { return node.modifiers && node.modifiers.length > 0 ? moveRangePos(node, node.modifiers.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; + /** + * Determines whether a TextRange has the same start and end positions. + * + * @param range A TextRange. + */ function isCollapsedRange(range) { return range.pos === range.end; } ts.isCollapsedRange = isCollapsedRange; + /** + * Creates a new TextRange for a token at the provides start position. + * + * @param pos The start position. + * @param token The token. + */ function createTokenRange(pos, token) { return createRange(pos, pos + ts.tokenToString(token).length); } @@ -7429,12 +9031,16 @@ var ts; return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; + /** + * Determines whether a name was originally the declaration name of an enum or namespace + * declaration. + */ function isDeclarationNameOfEnumOrNamespace(node) { var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 232: - case 233: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -7449,106 +9055,187 @@ var ts; return node.initializer !== undefined; } function isWatchSet(options) { + // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; function getCheckFlags(symbol) { - return symbol.flags & 33554432 ? symbol.checkFlags : 0; + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; function getDeclarationModifierFlagsFromSymbol(s) { if (s.valueDeclaration) { var flags = ts.getCombinedModifierFlags(s.valueDeclaration); - return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; } - if (getCheckFlags(s) & 6) { + if (getCheckFlags(s) & 6 /* Synthetic */) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : - 16; - var staticModifier = checkFlags & 512 ? 32 : 0; + var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } - if (s.flags & 4194304) { - return 4 | 32; + if (s.flags & 4194304 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; } return 0; } ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; - function levenshtein(s1, s2) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - for (var i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (var i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (var j = 1; j < s2.length + 1; j++) { - current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - var tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; function skipAlias(symbol, checker) { - return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; } ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ function getCombinedLocalAndExportSymbolFlags(symbol) { return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; function isWriteOnlyAccess(node) { - return accessKind(node) === 1; + return accessKind(node) === 1 /* Write */; } ts.isWriteOnlyAccess = isWriteOnlyAccess; function isWriteAccess(node) { - return accessKind(node) !== 0; + return accessKind(node) !== 0 /* Read */; } ts.isWriteAccess = isWriteAccess; var AccessKind; (function (AccessKind) { + /** Only reads from a variable. */ AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; })(AccessKind || (AccessKind = {})); function accessKind(node) { var parent = node.parent; if (!parent) - return 0; + return 0 /* Read */; switch (parent.kind) { - case 193: - case 192: + case 194 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: var operator = parent.operator; - return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; - case 194: + return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 195 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; - case 179: - return parent.name !== node ? 0 : accessKind(parent); + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + case 180 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: - return 0; + return 0 /* Read */; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 210 ? 1 : 2; + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && parent.parent.kind === 211 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + 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); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 65536 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 5: + case 6 /* ESNext */: return "lib.esnext.full.d.ts"; - case 4: + case 4 /* ES2017 */: return "lib.es2017.full.d.ts"; - case 3: + case 3 /* ES2016 */: return "lib.es2016.full.d.ts"; - case 2: - return "lib.es6.d.ts"; + case 2 /* ES2015 */: + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. default: return "lib.d.ts"; } @@ -7566,6 +9253,7 @@ var ts; return position >= span.start && position < textSpanEnd(span); } ts.textSpanContainsPosition = textSpanContainsPosition; + // Returns true if 'span' contains 'other'. function textSpanContainsTextSpan(span, other) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); } @@ -7643,6 +9331,14 @@ var ts; } ts.createTextChangeRange = createTextChangeRange; ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ function collapseTextChangeRangesAcrossMultipleVersions(changes) { if (changes.length === 0) { return ts.unchangedTextChangeRange; @@ -7650,12 +9346,93 @@ var ts; if (changes.length === 1) { return changes[0]; } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. var change0 = changes[0]; var oldStartN = change0.span.start; var oldEndN = textSpanEnd(change0.span); var newEndN = oldStartN + change0.newLength; for (var i = 1; i < changes.length; i++) { var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; var newEnd1 = newEndN; @@ -7666,13 +9443,13 @@ var ts; oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } - return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 145) { + if (d && d.kind === 146 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 231 /* InterfaceDeclaration */) { return current; } } @@ -7680,7 +9457,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 153 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -7698,7 +9475,7 @@ var ts; } ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 || ts.isBindingPattern(node))) { + while (node && (node.kind === 177 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -7706,35 +9483,46 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 226) { + if (node.kind === 227 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228 /* VariableDeclarationList */) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209 /* VariableStatement */) { flags |= ts.getModifierFlags(node); } return flags; } ts.getCombinedModifierFlags = getCombinedModifierFlags; + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 226) { + if (node.kind === 227 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209 /* VariableStatement */) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /** + * Checks to see if the locale is in the appropriate format, + * and if it is, attempts to set the appropriate language. + */ function validateLocaleAndSetLanguage(locale, sys, errors) { var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { @@ -7745,9 +9533,13 @@ var ts; } var language = matchResult[1]; var territory = matchResult[3]; + // First try the entire locale, then fall back to just language if that's all we have. + // Either ways do not fail, and fallback to the English diagnostic strings. if (!trySetLanguageAndTerritory(language, territory, errors)) { - trySetLanguageAndTerritory(language, undefined, errors); + trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } + // Set the UI locale for string collation + ts.setUILocale(locale); function trySetLanguageAndTerritory(language, territory, errors) { var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); @@ -7759,6 +9551,7 @@ var ts; if (!sys.fileExists(filePath)) { return false; } + // TODO: Add codePage support for readFile? var fileContents = ""; try { fileContents = sys.readFile(filePath); @@ -7791,8 +9584,13 @@ var ts; return !nodeTest || nodeTest(node) ? node : undefined; } ts.getOriginalNode = getOriginalNode; + /** + * Gets a value indicating whether a node originated in the parse tree. + * + * @param node The node to test. + */ function isParseTreeNode(node) { - return (node.flags & 8) === 0; + return (node.flags & 8 /* Synthesized */) === 0; } ts.isParseTreeNode = isParseTreeNode; function getParseTreeNode(node, nodeTest) { @@ -7806,48 +9604,75 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + /** + * Remove extra underscore from escaped identifier text content. + * + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ function unescapeLeadingUnderscores(identifier) { var id = identifier; - return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; } ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; + /** + * Remove extra underscore from escaped identifier text content. + * @deprecated Use `id.text` for the unescaped text. + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ function unescapeIdentifier(id) { return id; } ts.unescapeIdentifier = unescapeIdentifier; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ function nameForNamelessJSDocTypedef(declaration) { var hostNode = declaration.parent.parent; if (!hostNode) { return undefined; } + // Covers classes, functions - any named declaration host node if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } + // Covers remaining cases switch (hostNode.kind) { - case 208: + case 209 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 210: + case 211 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 179: + case 180 /* PropertyAccessExpression */: return expr.name; - case 180: + case 181 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } return undefined; - case 1: + case 1 /* EndOfFileToken */: return undefined; - case 185: { + case 186 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 222: { + case 223 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -7869,68 +9694,115 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 71 /* Identifier */: + return declaration; + case 289 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 144 /* QualifiedName */) { + return name.right; + } + break; + } + case 195 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + case 288 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 244 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag that matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * Does not return tags for binding patterns, because JSDoc matches + * parameters by name and binding patterns do not have a name. + */ function getJSDocParameterTags(param) { if (param.name && ts.isIdentifier(param.name)) { - var name_6 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_6; }); + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); } + // a binding pattern doesn't have a name, so it's not possible to match it a JSDoc parameter, which is identified by name return undefined; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); + return !!getFirstJSDocTag(node, 284 /* JSDocParameterTag */); } ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); + return getFirstJSDocTag(node, 282 /* JSDocAugmentsTag */); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); + return getFirstJSDocTag(node, 283 /* JSDocClassTag */); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); + return getFirstJSDocTag(node, 285 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); + return getFirstJSDocTag(node, 287 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 281); + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } return undefined; } ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { + var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */); + if (!tag && node.kind === 147 /* Parameter */) { var paramTags = getJSDocParameterTags(node); if (paramTags) { tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); @@ -7939,706 +9811,768 @@ var ts; return tag && tag.typeExpression && tag.typeExpression.type; } ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc's return tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces. + */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; } ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node) { var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ function getFirstJSDocTag(node, kind) { var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { + // Literals function isNumericLiteral(node) { - return node.kind === 8; + return node.kind === 8 /* NumericLiteral */; } ts.isNumericLiteral = isNumericLiteral; function isStringLiteral(node) { - return node.kind === 9; + return node.kind === 9 /* StringLiteral */; } ts.isStringLiteral = isStringLiteral; function isJsxText(node) { - return node.kind === 10; + return node.kind === 10 /* JsxText */; } ts.isJsxText = isJsxText; function isRegularExpressionLiteral(node) { - return node.kind === 12; + return node.kind === 12 /* RegularExpressionLiteral */; } ts.isRegularExpressionLiteral = isRegularExpressionLiteral; function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13; + return node.kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals function isTemplateHead(node) { - return node.kind === 14; + return node.kind === 14 /* TemplateHead */; } ts.isTemplateHead = isTemplateHead; function isTemplateMiddle(node) { - return node.kind === 15; + return node.kind === 15 /* TemplateMiddle */; } ts.isTemplateMiddle = isTemplateMiddle; function isTemplateTail(node) { - return node.kind === 16; + return node.kind === 16 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; function isIdentifier(node) { - return node.kind === 71; + return node.kind === 71 /* Identifier */; } ts.isIdentifier = isIdentifier; + // Names function isQualifiedName(node) { - return node.kind === 143; + return node.kind === 144 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 144; + return node.kind === 145 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 145; + return node.kind === 146 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 146; + return node.kind === 147 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 147; + return node.kind === 148 /* Decorator */; } ts.isDecorator = isDecorator; + // TypeMember function isPropertySignature(node) { - return node.kind === 148; + return node.kind === 149 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 149; + return node.kind === 150 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 150; + return node.kind === 151 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 151; + return node.kind === 152 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 152; + return node.kind === 153 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 153; + return node.kind === 154 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 154; + return node.kind === 155 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 155; + return node.kind === 156 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 156; + return node.kind === 157 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 157; + return node.kind === 158 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + // Type function isTypePredicateNode(node) { - return node.kind === 158; + return node.kind === 159 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 159; + return node.kind === 160 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 160; + return node.kind === 161 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 161; + return node.kind === 162 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 162; + return node.kind === 163 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 163; + return node.kind === 164 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 164; + return node.kind === 165 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 165; + return node.kind === 166 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 166; + return node.kind === 167 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 167; + return node.kind === 168 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 168; + return node.kind === 169 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 169; + return node.kind === 170 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 170; + return node.kind === 171 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 171; + return node.kind === 172 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 172; + return node.kind === 173 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 173; + return node.kind === 174 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; + // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 174; + return node.kind === 175 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 175; + return node.kind === 176 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 176; + return node.kind === 177 /* BindingElement */; } ts.isBindingElement = isBindingElement; + // Expression function isArrayLiteralExpression(node) { - return node.kind === 177; + return node.kind === 178 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 178; + return node.kind === 179 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 179; + return node.kind === 180 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 180; + return node.kind === 181 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 181; + return node.kind === 182 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 182; + return node.kind === 183 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 183; + return node.kind === 184 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 184; + return node.kind === 185 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 185; + return node.kind === 186 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 292 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 186; + return node.kind === 187 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 187; + return node.kind === 188 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 188; + return node.kind === 189 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 191; + return node.kind === 192 /* AwaitExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 190; + return node.kind === 191 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 191; + return node.kind === 192 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 192; + return node.kind === 193 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 193; + return node.kind === 194 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 194; + return node.kind === 195 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 195; + return node.kind === 196 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 196; + return node.kind === 197 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 197; + return node.kind === 198 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 198; + return node.kind === 199 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 199; + return node.kind === 200 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 200; + return node.kind === 201 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 201; + return node.kind === 202 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 202; + return node.kind === 203 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 203; + return node.kind === 204 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 204; + return node.kind === 205 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; + // Misc function isTemplateSpan(node) { - return node.kind === 205; + return node.kind === 206 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 206; + return node.kind === 207 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; + // Block function isBlock(node) { - return node.kind === 207; + return node.kind === 208 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 208; + return node.kind === 209 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 209; + return node.kind === 210 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 210; + return node.kind === 211 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 211; + return node.kind === 212 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 212; + return node.kind === 213 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 213; + return node.kind === 214 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 214; + return node.kind === 215 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 215; + return node.kind === 216 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 216; + return node.kind === 217 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 217; + return node.kind === 218 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 218; + return node.kind === 219 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 219 /* BreakStatement */ || node.kind === 218 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 219; + return node.kind === 220 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 220; + return node.kind === 221 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 221; + return node.kind === 222 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 222; + return node.kind === 223 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 223; + return node.kind === 224 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 224; + return node.kind === 225 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 225; + return node.kind === 226 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 226; + return node.kind === 227 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 227; + return node.kind === 228 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 228; + return node.kind === 229 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 229; + return node.kind === 230 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 230; + return node.kind === 231 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 231; + return node.kind === 232 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 232; + return node.kind === 233 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 233; + return node.kind === 234 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 234; + return node.kind === 235 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 235; + return node.kind === 236 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 236; + return node.kind === 237 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 237; + return node.kind === 238 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 238; + return node.kind === 239 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 239; + return node.kind === 240 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 240; + return node.kind === 241 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 241; + return node.kind === 242 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 242; + return node.kind === 243 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 243; + return node.kind === 244 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 244; + return node.kind === 245 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 245; + return node.kind === 246 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 246; + return node.kind === 247 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 247; + return node.kind === 248 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; + // Module References function isExternalModuleReference(node) { - return node.kind === 248; + return node.kind === 249 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; + // JSX function isJsxElement(node) { - return node.kind === 249; + return node.kind === 250 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 250; + return node.kind === 251 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 251; + return node.kind === 252 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 252; + return node.kind === 253 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 254 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 255 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 256 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 253; + return node.kind === 257 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 254; + return node.kind === 258 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 255; + return node.kind === 259 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 256; + return node.kind === 260 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; + // Clauses function isCaseClause(node) { - return node.kind === 257; + return node.kind === 261 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 258; + return node.kind === 262 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 259; + return node.kind === 263 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 260; + return node.kind === 264 /* CatchClause */; } ts.isCatchClause = isCatchClause; + // Property assignments function isPropertyAssignment(node) { - return node.kind === 261; + return node.kind === 265 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 262; + return node.kind === 266 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 263; + return node.kind === 267 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; + // Enum function isEnumMember(node) { - return node.kind === 264; + return node.kind === 268 /* EnumMember */; } ts.isEnumMember = isEnumMember; + // Top-level nodes function isSourceFile(node) { - return node.kind === 265; + return node.kind === 269 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 266; + return node.kind === 270 /* Bundle */; } ts.isBundle = isBundle; + // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 267; + return node.kind === 271 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 268; + return node.kind === 272 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 269; + return node.kind === 273 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 270; + return node.kind === 274 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 271; + return node.kind === 275 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 272; + return node.kind === 276 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 273; + return node.kind === 277 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 274; + return node.kind === 278 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 275; + return node.kind === 279 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 277; + return node.kind === 282 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocParameterTag(node) { - return node.kind === 279; + return node.kind === 284 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 280; + return node.kind === 285 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 281; + return node.kind === 286 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 282; + return node.kind === 287 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 283; + return node.kind === 288 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 284; + return node.kind === 289 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 284 || node.kind === 279; + return node.kind === 289 /* JSDocPropertyTag */ || node.kind === 284 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 285; + return node.kind === 280 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; })(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. (function (ts) { + /* @internal */ function isSyntaxList(n) { - return n.kind === 286; + return n.kind === 290 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; + /* @internal */ function isNode(node) { return isNodeKind(node.kind); } ts.isNode = isNode; + /* @internal */ function isNodeKind(kind) { - return kind >= 143; + return kind >= 144 /* FirstNode */; } ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + */ function isToken(n) { - return n.kind >= 0 && n.kind <= 142; + return n.kind >= 0 /* FirstToken */ && n.kind <= 143 /* LastToken */; } ts.isToken = isToken; + // Node Arrays + /* @internal */ function isNodeArray(array) { return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ function isLiteralKind(kind) { - return 8 <= kind && kind <= 13; + return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; } ts.isLiteralKind = isLiteralKind; function isLiteralExpression(node) { return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ function isTemplateLiteralKind(kind) { - return 13 <= kind && kind <= 16; + return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; - return kind === 15 - || kind === 16; + return kind === 15 /* TemplateMiddle */ + || kind === 16 /* TemplateTail */; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isStringTextContainingNode(node) { - switch (node.kind) { - case 9: - case 14: - case 15: - case 16: - case 13: - return true; - default: - return false; - } + return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. + return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ function isModifierKind(token) { switch (token) { - case 117: - case 120: - case 76: - case 124: - case 79: - case 84: - case 114: - case 112: - case 113: - case 131: - case 115: + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 79 /* DefaultKeyword */: + case 84 /* ExportKeyword */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 115 /* StaticKeyword */: return true; } return false; @@ -8650,203 +10584,243 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 143 - || kind === 71; + return kind === 144 /* QualifiedName */ + || kind === 71 /* Identifier */; } ts.isEntityName = isEntityName; function isPropertyName(node) { var kind = node.kind; - return kind === 71 - || kind === 9 - || kind === 8 - || kind === 144; + return kind === 71 /* Identifier */ + || kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 145 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; - return kind === 71 - || kind === 174 - || kind === 175; + return kind === 71 /* Identifier */ + || kind === 175 /* ObjectBindingPattern */ + || kind === 176 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; + // Functions function isFunctionLike(node) { return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; + /* @internal */ function isFunctionLikeDeclaration(node) { return node && isFunctionLikeDeclarationKind(node.kind); } ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 228: - case 151: - case 152: - case 153: - case 154: - case 186: - case 187: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; default: return false; } } + /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 150: - case 155: - case 156: - case 157: - case 160: - case 273: - case 161: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 161 /* FunctionType */: + case 277 /* JSDocFunctionType */: + case 162 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); } } ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ function isFunctionOrModuleBlock(node) { return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); } ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; + // Classes function isClassElement(node) { var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 157 - || kind === 206 - || kind === 247; + return kind === 153 /* Constructor */ + || kind === 150 /* PropertyDeclaration */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 158 /* IndexSignature */ + || kind === 207 /* SemicolonClassElement */ + || kind === 248 /* MissingDeclaration */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); + return node && (node.kind === 230 /* ClassDeclaration */ || node.kind === 200 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); + return node && (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */); } ts.isAccessor = isAccessor; + // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 156 - || kind === 155 - || kind === 148 - || kind === 150 - || kind === 157 - || kind === 247; + return kind === 157 /* ConstructSignature */ + || kind === 156 /* CallSignature */ + || kind === 149 /* PropertySignature */ + || kind === 151 /* MethodSignature */ + || kind === 158 /* IndexSignature */ + || kind === 248 /* MissingDeclaration */; } ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 261 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 247; + return kind === 265 /* PropertyAssignment */ + || kind === 266 /* ShorthandPropertyAssignment */ + || kind === 267 /* SpreadAssignment */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 248 /* MissingDeclaration */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) - || kind === 119 - || kind === 133 - || kind === 134 - || kind === 122 - || kind === 136 - || kind === 137 - || kind === 99 - || kind === 105 - || kind === 139 - || kind === 95 - || kind === 130 - || kind === 201; - } + return (kind >= 159 /* FirstTypeNode */ && kind <= 174 /* LastTypeNode */) + || kind === 119 /* AnyKeyword */ + || kind === 133 /* NumberKeyword */ + || kind === 134 /* ObjectKeyword */ + || kind === 122 /* BooleanKeyword */ + || kind === 136 /* StringKeyword */ + || kind === 137 /* SymbolKeyword */ + || kind === 99 /* ThisKeyword */ + || kind === 105 /* VoidKeyword */ + || kind === 139 /* UndefinedKeyword */ + || kind === 95 /* NullKeyword */ + || kind === 130 /* NeverKeyword */ + || kind === 202 /* ExpressionWithTypeArguments */ + || kind === 272 /* JSDocAllType */ + || kind === 273 /* JSDocUnknownType */ + || kind === 274 /* JSDocNullableType */ + || kind === 275 /* JSDocNonNullableType */ + || kind === 276 /* JSDocOptionalType */ + || kind === 277 /* JSDocFunctionType */ + || kind === 278 /* JSDocVariadicType */; + } + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ function isTypeNode(node) { return isTypeNodeKind(node.kind); } ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 160: - case 161: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return true; } return false; } ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 175 - || kind === 174; + return kind === 176 /* ArrayBindingPattern */ + || kind === 175 /* ObjectBindingPattern */; } return false; } ts.isBindingPattern = isBindingPattern; + /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 177 - || kind === 178; + return kind === 178 /* ArrayLiteralExpression */ + || kind === 179 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 176 - || kind === 200; + return kind === 177 /* BindingElement */ + || kind === 201 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 226: - case 146: - case 176: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 177 /* BindingElement */: return true; } return false; } ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ function isBindingOrAssignmentPattern(node) { return isObjectBindingOrAssignmentPattern(node) || isArrayBindingOrAssignmentPattern(node); } ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 174: - case 178: + case 175 /* ObjectBindingPattern */: + case 179 /* ObjectLiteralExpression */: return true; } return false; } ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: return true; } return false; } ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 179 - || kind === 143; + return kind === 180 /* PropertyAccessExpression */ + || kind === 144 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 251: - case 250: - case 181: - case 182: - case 183: - case 147: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 184 /* TaggedTemplateExpression */: + case 148 /* Decorator */: return true; default: return false; @@ -8854,97 +10828,106 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 181 || node.kind === 182; + return node.kind === 182 /* CallExpression */ || node.kind === 183 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 196 - || kind === 13; + return kind === 197 /* TemplateExpression */ + || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; + /* @internal */ function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 179: - case 180: - case 182: - case 181: - case 249: - case 250: - case 183: - case 177: - case 185: - case 178: - case 199: - case 186: - case 71: - case 12: - case 8: - case 9: - case 13: - case 196: - case 86: - case 95: - case 99: - case 101: - case 97: - case 203: - case 204: - case 91: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 183 /* NewExpression */: + case 182 /* CallExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 184 /* TaggedTemplateExpression */: + case 178 /* ArrayLiteralExpression */: + case 186 /* ParenthesizedExpression */: + case 179 /* ObjectLiteralExpression */: + case 200 /* ClassExpression */: + case 187 /* FunctionExpression */: + case 71 /* Identifier */: + case 12 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 197 /* TemplateExpression */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 99 /* ThisKeyword */: + case 101 /* TrueKeyword */: + case 97 /* SuperKeyword */: + case 204 /* NonNullExpression */: + case 205 /* MetaProperty */: + case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression return true; default: return false; } } + /* @internal */ function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 192: - case 193: - case 188: - case 189: - case 190: - case 191: - case 184: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 192 /* AwaitExpression */: + case 185 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); } } + /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 193: + case 194 /* PostfixUnaryExpression */: return true; - case 192: - return expr.operator === 43 || - expr.operator === 44; + case 193 /* PrefixUnaryExpression */: + return expr.operator === 43 /* PlusPlusToken */ || + expr.operator === 44 /* MinusMinusToken */; default: return false; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; + /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isExpressionNode` if not in transforms. + */ function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 195: - case 197: - case 187: - case 194: - case 198: - case 202: - case 200: - case 289: - case 288: + case 196 /* ConditionalExpression */: + case 198 /* YieldExpression */: + case 188 /* ArrowFunction */: + case 195 /* BinaryExpression */: + case 199 /* SpreadElement */: + case 203 /* AsExpression */: + case 201 /* OmittedExpression */: + case 293 /* CommaListExpression */: + case 292 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -8952,169 +10935,190 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 184 - || kind === 202; + return kind === 185 /* TypeAssertionExpression */ + || kind === 203 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; + /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 292 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 291 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ function isNotEmittedOrPartiallyEmittedNode(node) { return isNotEmittedStatement(node) || isPartiallyEmittedExpression(node); } ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + // Statement function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 214: - case 215: - case 216: - case 212: - case 213: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return true; - case 222: + case 223 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; + /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 215 || node.kind === 216; + return node.kind === 216 /* ForInStatement */ || node.kind === 217 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ function isConciseBody(node) { return ts.isBlock(node) || isExpression(node); } ts.isConciseBody = isConciseBody; + /* @internal */ function isFunctionBody(node) { return ts.isBlock(node); } ts.isFunctionBody = isFunctionBody; + /* @internal */ function isForInitializer(node) { return ts.isVariableDeclarationList(node) || isExpression(node); } ts.isForInitializer = isForInitializer; + /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233 - || kind === 71; + return kind === 235 /* ModuleBlock */ + || kind === 234 /* ModuleDeclaration */ + || kind === 71 /* Identifier */; } ts.isModuleBody = isModuleBody; + /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233; + return kind === 235 /* ModuleBlock */ + || kind === 234 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; + /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; - return kind === 71 - || kind === 233; + return kind === 71 /* Identifier */ + || kind === 234 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 241 - || kind === 240; + return kind === 242 /* NamedImports */ + || kind === 241 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 233 || node.kind === 232; + return node.kind === 234 /* ModuleDeclaration */ || node.kind === 233 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 - || kind === 229 - || kind === 199 - || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 - || kind === 151 - || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 - || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 283; + return kind === 188 /* ArrowFunction */ + || kind === 177 /* BindingElement */ + || kind === 230 /* ClassDeclaration */ + || kind === 200 /* ClassExpression */ + || kind === 153 /* Constructor */ + || kind === 233 /* EnumDeclaration */ + || kind === 268 /* EnumMember */ + || kind === 247 /* ExportSpecifier */ + || kind === 229 /* FunctionDeclaration */ + || kind === 187 /* FunctionExpression */ + || kind === 154 /* GetAccessor */ + || kind === 240 /* ImportClause */ + || kind === 238 /* ImportEqualsDeclaration */ + || kind === 243 /* ImportSpecifier */ + || kind === 231 /* InterfaceDeclaration */ + || kind === 257 /* JsxAttribute */ + || kind === 152 /* MethodDeclaration */ + || kind === 151 /* MethodSignature */ + || kind === 234 /* ModuleDeclaration */ + || kind === 237 /* NamespaceExportDeclaration */ + || kind === 241 /* NamespaceImport */ + || kind === 147 /* Parameter */ + || kind === 265 /* PropertyAssignment */ + || kind === 150 /* PropertyDeclaration */ + || kind === 149 /* PropertySignature */ + || kind === 155 /* SetAccessor */ + || kind === 266 /* ShorthandPropertyAssignment */ + || kind === 232 /* TypeAliasDeclaration */ + || kind === 146 /* TypeParameter */ + || kind === 227 /* VariableDeclaration */ + || kind === 288 /* JSDocTypedefTag */; } function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 - || kind === 230 - || kind === 231 - || kind === 232 - || kind === 233 - || kind === 238 - || kind === 237 - || kind === 244 - || kind === 243 - || kind === 236; + return kind === 229 /* FunctionDeclaration */ + || kind === 248 /* MissingDeclaration */ + || kind === 230 /* ClassDeclaration */ + || kind === 231 /* InterfaceDeclaration */ + || kind === 232 /* TypeAliasDeclaration */ + || kind === 233 /* EnumDeclaration */ + || kind === 234 /* ModuleDeclaration */ + || kind === 239 /* ImportDeclaration */ + || kind === 238 /* ImportEqualsDeclaration */ + || kind === 245 /* ExportDeclaration */ + || kind === 244 /* ExportAssignment */ + || kind === 237 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 - || kind === 217 - || kind === 225 - || kind === 212 - || kind === 210 - || kind === 209 - || kind === 215 - || kind === 216 - || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 - || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 287 - || kind === 291 - || kind === 290; - } + return kind === 219 /* BreakStatement */ + || kind === 218 /* ContinueStatement */ + || kind === 226 /* DebuggerStatement */ + || kind === 213 /* DoStatement */ + || kind === 211 /* ExpressionStatement */ + || kind === 210 /* EmptyStatement */ + || kind === 216 /* ForInStatement */ + || kind === 217 /* ForOfStatement */ + || kind === 215 /* ForStatement */ + || kind === 212 /* IfStatement */ + || kind === 223 /* LabeledStatement */ + || kind === 220 /* ReturnStatement */ + || kind === 222 /* SwitchStatement */ + || kind === 224 /* ThrowStatement */ + || kind === 225 /* TryStatement */ + || kind === 209 /* VariableStatement */ + || kind === 214 /* WhileStatement */ + || kind === 221 /* WithStatement */ + || kind === 291 /* NotEmittedStatement */ + || kind === 295 /* EndOfDeclarationMarker */ + || kind === 294 /* MergeDeclarationMarker */; + } + /* @internal */ function isDeclaration(node) { - if (node.kind === 145) { - return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + if (node.kind === 146 /* TypeParameter */) { + return node.parent.kind !== 287 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } ts.isDeclaration = isDeclaration; + /* @internal */ function isDeclarationStatement(node) { return isDeclarationStatementKind(node.kind); } ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ function isStatementButNotDeclaration(node) { return isStatementKindButNotDeclarationKind(node.kind); } ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ function isStatement(node) { var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) @@ -9123,224 +11127,303 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 207) + if (node.kind !== 208 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 224 || node.parent.kind === 260) { + if (node.parent.kind === 225 /* TryStatement */ || node.parent.kind === 264 /* CatchClause */) { return false; } } return !ts.isFunctionBlock(node); } + // Module references + /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 248 - || kind === 143 - || kind === 71; + return kind === 249 /* ExternalModuleReference */ + || kind === 144 /* QualifiedName */ + || kind === 71 /* Identifier */; } ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ function isJsxTagNameExpression(node) { var kind = node.kind; - return kind === 99 - || kind === 71 - || kind === 179; + return kind === 99 /* ThisKeyword */ + || kind === 71 /* Identifier */ + || kind === 180 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; + return kind === 250 /* JsxElement */ + || kind === 260 /* JsxExpression */ + || kind === 251 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */ + || kind === 254 /* JsxFragment */; } ts.isJsxChild = isJsxChild; + /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 253 - || kind === 255; + return kind === 257 /* JsxAttribute */ + || kind === 259 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; - return kind === 9 - || kind === 256; + return kind === 9 /* StringLiteral */ + || kind === 260 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 251 - || kind === 250; + return kind === 252 /* JsxOpeningElement */ + || kind === 251 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 257 - || kind === 258; + return kind === 261 /* CaseClause */ + || kind === 262 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 285; + return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 275 || isJSDocTag(node); + return node.kind === 279 /* JSDocComment */ || isJSDocTag(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ function isJSDocTag(node) { - return node.kind >= 276 && node.kind <= 285; + return node.kind >= 281 /* FirstJSDocTagNode */ && node.kind <= 289 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 155 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 154 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); +/// +/// var ts; (function (ts) { + /* @internal */ function tokenIsIdentifierOrKeyword(token) { - return token >= 71; + return token >= 71 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; var textToToken = ts.createMapFromTemplate({ - "abstract": 117, - "any": 119, - "as": 118, - "boolean": 122, - "break": 72, - "case": 73, - "catch": 74, - "class": 75, - "continue": 77, - "const": 76, - "constructor": 123, - "debugger": 78, - "declare": 124, - "default": 79, - "delete": 80, - "do": 81, - "else": 82, - "enum": 83, - "export": 84, - "extends": 85, - "false": 86, - "finally": 87, - "for": 88, - "from": 140, - "function": 89, - "get": 125, - "if": 90, - "implements": 108, - "import": 91, - "in": 92, - "instanceof": 93, - "interface": 109, - "is": 126, - "keyof": 127, - "let": 110, - "module": 128, - "namespace": 129, - "never": 130, - "new": 94, - "null": 95, - "number": 133, - "object": 134, - "package": 111, - "private": 112, - "protected": 113, - "public": 114, - "readonly": 131, - "require": 132, - "global": 141, - "return": 96, - "set": 135, - "static": 115, - "string": 136, - "super": 97, - "switch": 98, - "symbol": 137, - "this": 99, - "throw": 100, - "true": 101, - "try": 102, - "type": 138, - "typeof": 103, - "undefined": 139, - "var": 104, - "void": 105, - "while": 106, - "with": 107, - "yield": 116, - "async": 120, - "await": 121, - "of": 142, - "{": 17, - "}": 18, - "(": 19, - ")": 20, - "[": 21, - "]": 22, - ".": 23, - "...": 24, - ";": 25, - ",": 26, - "<": 27, - ">": 29, - "<=": 30, - ">=": 31, - "==": 32, - "!=": 33, - "===": 34, - "!==": 35, - "=>": 36, - "+": 37, - "-": 38, - "**": 40, - "*": 39, - "/": 41, - "%": 42, - "++": 43, - "--": 44, - "<<": 45, - ">": 46, - ">>>": 47, - "&": 48, - "|": 49, - "^": 50, - "!": 51, - "~": 52, - "&&": 53, - "||": 54, - "?": 55, - ":": 56, - "=": 58, - "+=": 59, - "-=": 60, - "*=": 61, - "**=": 62, - "/=": 63, - "%=": 64, - "<<=": 65, - ">>=": 66, - ">>>=": 67, - "&=": 68, - "|=": 69, - "^=": 70, - "@": 57, + "abstract": 117 /* AbstractKeyword */, + "any": 119 /* AnyKeyword */, + "as": 118 /* AsKeyword */, + "boolean": 122 /* BooleanKeyword */, + "break": 72 /* BreakKeyword */, + "case": 73 /* CaseKeyword */, + "catch": 74 /* CatchKeyword */, + "class": 75 /* ClassKeyword */, + "continue": 77 /* ContinueKeyword */, + "const": 76 /* ConstKeyword */, + "constructor": 123 /* ConstructorKeyword */, + "debugger": 78 /* DebuggerKeyword */, + "declare": 124 /* DeclareKeyword */, + "default": 79 /* DefaultKeyword */, + "delete": 80 /* DeleteKeyword */, + "do": 81 /* DoKeyword */, + "else": 82 /* ElseKeyword */, + "enum": 83 /* EnumKeyword */, + "export": 84 /* ExportKeyword */, + "extends": 85 /* ExtendsKeyword */, + "false": 86 /* FalseKeyword */, + "finally": 87 /* FinallyKeyword */, + "for": 88 /* ForKeyword */, + "from": 141 /* FromKeyword */, + "function": 89 /* FunctionKeyword */, + "get": 125 /* GetKeyword */, + "if": 90 /* IfKeyword */, + "implements": 108 /* ImplementsKeyword */, + "import": 91 /* ImportKeyword */, + "in": 92 /* InKeyword */, + "instanceof": 93 /* InstanceOfKeyword */, + "interface": 109 /* InterfaceKeyword */, + "is": 126 /* IsKeyword */, + "keyof": 127 /* KeyOfKeyword */, + "let": 110 /* LetKeyword */, + "module": 128 /* ModuleKeyword */, + "namespace": 129 /* NamespaceKeyword */, + "never": 130 /* NeverKeyword */, + "new": 94 /* NewKeyword */, + "null": 95 /* NullKeyword */, + "number": 133 /* NumberKeyword */, + "object": 134 /* ObjectKeyword */, + "package": 111 /* PackageKeyword */, + "private": 112 /* PrivateKeyword */, + "protected": 113 /* ProtectedKeyword */, + "public": 114 /* PublicKeyword */, + "readonly": 131 /* ReadonlyKeyword */, + "require": 132 /* RequireKeyword */, + "global": 142 /* GlobalKeyword */, + "return": 96 /* ReturnKeyword */, + "set": 135 /* SetKeyword */, + "static": 115 /* StaticKeyword */, + "string": 136 /* StringKeyword */, + "super": 97 /* SuperKeyword */, + "switch": 98 /* SwitchKeyword */, + "symbol": 137 /* SymbolKeyword */, + "this": 99 /* ThisKeyword */, + "throw": 100 /* ThrowKeyword */, + "true": 101 /* TrueKeyword */, + "try": 102 /* TryKeyword */, + "type": 138 /* TypeKeyword */, + "typeof": 103 /* TypeOfKeyword */, + "undefined": 139 /* UndefinedKeyword */, + "unique": 140 /* UniqueKeyword */, + "var": 104 /* VarKeyword */, + "void": 105 /* VoidKeyword */, + "while": 106 /* WhileKeyword */, + "with": 107 /* WithKeyword */, + "yield": 116 /* YieldKeyword */, + "async": 120 /* AsyncKeyword */, + "await": 121 /* AwaitKeyword */, + "of": 143 /* OfKeyword */, + "{": 17 /* OpenBraceToken */, + "}": 18 /* CloseBraceToken */, + "(": 19 /* OpenParenToken */, + ")": 20 /* CloseParenToken */, + "[": 21 /* OpenBracketToken */, + "]": 22 /* CloseBracketToken */, + ".": 23 /* DotToken */, + "...": 24 /* DotDotDotToken */, + ";": 25 /* SemicolonToken */, + ",": 26 /* CommaToken */, + "<": 27 /* LessThanToken */, + ">": 29 /* GreaterThanToken */, + "<=": 30 /* LessThanEqualsToken */, + ">=": 31 /* GreaterThanEqualsToken */, + "==": 32 /* EqualsEqualsToken */, + "!=": 33 /* ExclamationEqualsToken */, + "===": 34 /* EqualsEqualsEqualsToken */, + "!==": 35 /* ExclamationEqualsEqualsToken */, + "=>": 36 /* EqualsGreaterThanToken */, + "+": 37 /* PlusToken */, + "-": 38 /* MinusToken */, + "**": 40 /* AsteriskAsteriskToken */, + "*": 39 /* AsteriskToken */, + "/": 41 /* SlashToken */, + "%": 42 /* PercentToken */, + "++": 43 /* PlusPlusToken */, + "--": 44 /* MinusMinusToken */, + "<<": 45 /* LessThanLessThanToken */, + ">": 46 /* GreaterThanGreaterThanToken */, + ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 48 /* AmpersandToken */, + "|": 49 /* BarToken */, + "^": 50 /* CaretToken */, + "!": 51 /* ExclamationToken */, + "~": 52 /* TildeToken */, + "&&": 53 /* AmpersandAmpersandToken */, + "||": 54 /* BarBarToken */, + "?": 55 /* QuestionToken */, + ":": 56 /* ColonToken */, + "=": 58 /* EqualsToken */, + "+=": 59 /* PlusEqualsToken */, + "-=": 60 /* MinusEqualsToken */, + "*=": 61 /* AsteriskEqualsToken */, + "**=": 62 /* AsteriskAsteriskEqualsToken */, + "/=": 63 /* SlashEqualsToken */, + "%=": 64 /* PercentEqualsToken */, + "<<=": 65 /* LessThanLessThanEqualsToken */, + ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 68 /* AmpersandEqualsToken */, + "|=": 69 /* BarEqualsToken */, + "^=": 70 /* CaretEqualsToken */, + "@": 57 /* AtToken */, }); + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { return false; } + // Perform binary search in one of the Unicode range maps var lo = 0; var hi = map.length; var mid; while (lo + 1 < hi) { mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning mid -= mid % 2; if (map[mid] <= code && code <= map[mid + 1]) { return true; @@ -9354,14 +11437,14 @@ var ts; } return false; } - function isUnicodeIdentifierStart(code, languageVersion) { - return languageVersion >= 1 ? + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) : lookupInUnicodeMap(code, unicodeES3IdentifierStart); } ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; function isUnicodeIdentifierPart(code, languageVersion) { - return languageVersion >= 1 ? + return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) : lookupInUnicodeMap(code, unicodeES3IdentifierPart); } @@ -9377,10 +11460,12 @@ var ts; return tokenStrings[t]; } ts.tokenToString = tokenToString; + /* @internal */ function stringToToken(s) { return textToToken.get(s); } ts.stringToToken = stringToToken; + /* @internal */ function computeLineStarts(text) { var result = new Array(); var pos = 0; @@ -9389,16 +11474,17 @@ var ts; var ch = text.charCodeAt(pos); pos++; switch (ch) { - case 13: - if (text.charCodeAt(pos) === 10) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { pos++; } - case 10: + // falls through + case 10 /* lineFeed */: result.push(lineStart); lineStart = pos; break; default: - if (ch > 127 && isLineBreak(ch)) { + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { result.push(lineStart); lineStart = pos; } @@ -9413,6 +11499,7 @@ var ts; return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); var res = lineStarts[line] + character; @@ -9420,18 +11507,30 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res <= debugText.length); + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline } return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ function getLineStarts(sourceFile) { return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); } ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position); + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. lineNumber = ~lineNumber - 1; ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); } @@ -9449,86 +11548,107 @@ var ts; return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); } ts.isWhiteSpaceLike = isWhiteSpaceLike; + /** Does not include line breaks. For that, see isWhiteSpaceLike. */ function isWhiteSpaceSingleLine(ch) { - return ch === 32 || - ch === 9 || - ch === 11 || - ch === 12 || - ch === 160 || - ch === 133 || - ch === 5760 || - ch >= 8192 && ch <= 8203 || - ch === 8239 || - ch === 8287 || - ch === 12288 || - ch === 65279; + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; } ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine; function isLineBreak(ch) { - return ch === 10 || - ch === 13 || - ch === 8232 || - ch === 8233; + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; } ts.isLineBreak = isLineBreak; function isDigit(ch) { - return ch >= 48 && ch <= 57; + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; } + /* @internal */ function isOctalDigit(ch) { - return ch >= 48 && ch <= 55; + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; } ts.isOctalDigit = isOctalDigit; function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia var ch = text.charCodeAt(pos); switch (ch) { - case 13: - case 10: - case 9: - case 11: - case 12: - case 32: - case 47: - case 60: - case 124: - case 61: - case 62: + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia return true; - case 35: + case 35 /* hash */: + // Only if its the beginning can we have #! trivia return pos === 0; default: - return ch > 127; + return ch > 127 /* maxAsciiCharacter */; } } ts.couldStartTrivia = couldStartTrivia; + /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { if (stopAtComments === void 0) { stopAtComments = false; } if (ts.positionIsSynthesized(pos)) { return pos; } + // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); switch (ch) { - case 13: - if (text.charCodeAt(pos + 1) === 10) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; } - case 10: + // falls through + case 10 /* lineFeed */: pos++; if (stopAfterLineBreak) { return pos; } continue; - case 9: - case 11: - case 12: - case 32: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: pos++; continue; - case 47: + case 47 /* slash */: if (stopAtComments) { break; } - if (text.charCodeAt(pos + 1) === 47) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; while (pos < text.length) { if (isLineBreak(text.charCodeAt(pos))) { @@ -9538,10 +11658,10 @@ var ts; } continue; } - if (text.charCodeAt(pos + 1) === 42) { + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { pos += 2; while (pos < text.length) { - if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) === 47) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; break; } @@ -9550,23 +11670,23 @@ var ts; continue; } break; - case 60: - case 124: - case 61: - case 62: + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); continue; } break; - case 35: + case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); continue; } break; default: - if (ch > 127 && (isWhiteSpaceLike(ch))) { + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { pos++; continue; } @@ -9576,9 +11696,12 @@ var ts; } } ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. var mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text, pos) { ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { var ch = text.charCodeAt(pos); if ((pos + mergeConflictMarkerLength) < text.length) { @@ -9587,8 +11710,8 @@ var ts; return false; } } - return ch === 61 || - text.charCodeAt(pos + mergeConflictMarkerLength) === 32; + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; } } return false; @@ -9599,16 +11722,18 @@ var ts; } var ch = text.charCodeAt(pos); var len = text.length; - if (ch === 60 || ch === 62) { + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { while (pos < len && !isLineBreak(text.charCodeAt(pos))) { pos++; } } else { - ts.Debug.assert(ch === 124 || ch === 61); + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. while (pos < len) { var currentChar = text.charCodeAt(pos); - if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -9618,6 +11743,7 @@ var ts; } var shebangTriviaRegex = /^#!.*/; function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file ts.Debug.assert(pos === 0); return shebangTriviaRegex.test(text); } @@ -9626,6 +11752,26 @@ var ts; pos = pos + shebang.length; return pos; } + /** + * Invokes a callback for each comment range following the provided position. + * + * Single-line comment ranges include the leading double-slash characters but not the ending + * line break. Multi-line comment ranges include the leading slash-asterisk and trailing + * asterisk-slash characters. + * + * @param reduce If true, accumulates the result of calling the callback in a fashion similar + * to reduceLeft. If false, iteration stops when the callback returns a truthy value. + * @param text The source text to scan. + * @param pos The position at which to start scanning. + * @param trailing If false, whitespace is skipped until the first line break and comments + * between that location and the next token are returned. If true, comments occurring + * between the given position and the next line break are returned. + * @param cb The callback to execute as each comment range is encountered. + * @param state A state value to pass to each iteration of the callback. + * @param initial An initial value to pass when accumulating results (when "reduce" is true). + * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy + * return value of the callback. + */ function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { var pendingPos; var pendingEnd; @@ -9637,11 +11783,12 @@ var ts; scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { - case 13: - if (text.charCodeAt(pos + 1) === 10) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; } - case 10: + // falls through + case 10 /* lineFeed */: pos++; if (trailing) { break scan; @@ -9651,20 +11798,20 @@ var ts; pendingHasTrailingNewLine = true; } continue; - case 9: - case 11: - case 12: - case 32: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: pos++; continue; - case 47: + case 47 /* slash */: var nextChar = text.charCodeAt(pos + 1); var hasTrailingNewLine = false; - if (nextChar === 47 || nextChar === 42) { - var kind = nextChar === 47 ? 2 : 3; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; var startPos = pos; pos += 2; - if (nextChar === 47) { + if (nextChar === 47 /* slash */) { while (pos < text.length) { if (isLineBreak(text.charCodeAt(pos))) { hasTrailingNewLine = true; @@ -9675,7 +11822,7 @@ var ts; } else { while (pos < text.length) { - if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) === 47) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; break; } @@ -9686,6 +11833,7 @@ var ts; if (hasPendingCommentRange) { accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); if (!reduce && accumulator) { + // If we are not reducing and we have a truthy result, return it. return accumulator; } hasPendingCommentRange = false; @@ -9700,7 +11848,7 @@ var ts; } break scan; default: - if (ch > 127 && (isWhiteSpaceLike(ch))) { + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) { if (hasPendingCommentRange && isLineBreak(ch)) { pendingHasTrailingNewLine = true; } @@ -9716,19 +11864,19 @@ var ts; return accumulator; } function forEachLeadingCommentRange(text, pos, cb, state) { - return iterateCommentRanges(false, text, pos, false, cb, state); + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state); } ts.forEachLeadingCommentRange = forEachLeadingCommentRange; function forEachTrailingCommentRange(text, pos, cb, state) { - return iterateCommentRanges(false, text, pos, true, cb, state); + return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state); } ts.forEachTrailingCommentRange = forEachTrailingCommentRange; function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { - return iterateCommentRanges(true, text, pos, false, cb, state, initial); + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); } ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange; function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { - return iterateCommentRanges(true, text, pos, true, cb, state, initial); + return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); } ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange; function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) { @@ -9739,13 +11887,14 @@ var ts; return comments; } function getLeadingCommentRanges(text, pos) { - return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); } ts.getLeadingCommentRanges = getLeadingCommentRanges; function getTrailingCommentRanges(text, pos) { - return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined); } ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ function getShebang(text) { var match = shebangTriviaRegex.exec(text); if (match) { @@ -9754,17 +11903,18 @@ var ts; } ts.getShebang = getShebang; function isIdentifierStart(ch, languageVersion) { - return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || - ch === 36 || ch === 95 || - ch > 127 && isUnicodeIdentifierStart(ch, languageVersion); + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); } ts.isIdentifierStart = isIdentifierStart; function isIdentifierPart(ch, languageVersion) { - return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || - ch >= 48 && ch <= 57 || ch === 36 || ch === 95 || - ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + /* @internal */ function isIdentifierText(name, languageVersion) { if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { return false; @@ -9777,18 +11927,20 @@ var ts; return true; } ts.isIdentifierText = isIdentifierText; + // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { - if (languageVariant === void 0) { languageVariant = 0; } + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + // Current position (end position of text of current token) var pos; + // end of text var end; + // Start position of whitespace before current token var startPos; + // Start position of text of current token var tokenPos; var token; var tokenValue; - var precedingLineBreak; - var hasExtendedUnicodeEscape; - var tokenIsUnterminated; - var numericLiteralFlags; + var tokenFlags; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -9797,12 +11949,12 @@ var ts; getTokenPos: function () { return tokenPos; }, getTokenText: function () { return text.substring(tokenPos, pos); }, getTokenValue: function () { return tokenValue; }, - hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, - hasPrecedingLineBreak: function () { return precedingLineBreak; }, - isIdentifier: function () { return token === 71 || token > 107; }, - isReservedWord: function () { return token >= 72 && token <= 107; }, - isUnterminated: function () { return tokenIsUnterminated; }, - getNumericLiteralFlags: function () { return numericLiteralFlags; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, + isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, @@ -9831,16 +11983,16 @@ var ts; var start = pos; while (isDigit(text.charCodeAt(pos))) pos++; - if (text.charCodeAt(pos) === 46) { + if (text.charCodeAt(pos) === 46 /* dot */) { pos++; while (isDigit(text.charCodeAt(pos))) pos++; } var end = pos; - if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { pos++; - numericLiteralFlags = 2; - if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) + tokenFlags |= 16 /* Scientific */; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; if (isDigit(text.charCodeAt(pos))) { pos++; @@ -9861,25 +12013,33 @@ var ts; } return +(text.substring(start, pos)); } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ function scanExactNumberOfHexDigits(count) { - return scanHexDigits(count, false); + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning -1 if the given number of digits was unavailable. + */ function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(count, true); + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); } function scanHexDigits(minCount, scanAsManyAsPossible) { var digits = 0; var value = 0; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); - if (ch >= 48 && ch <= 57) { - value = value * 16 + ch - 48; + if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { + value = value * 16 + ch - 48 /* _0 */; } - else if (ch >= 65 && ch <= 70) { - value = value * 16 + ch - 65 + 10; + else if (ch >= 65 /* A */ && ch <= 70 /* F */) { + value = value * 16 + ch - 65 /* A */ + 10; } - else if (ch >= 97 && ch <= 102) { - value = value * 16 + ch - 97 + 10; + else if (ch >= 97 /* a */ && ch <= 102 /* f */) { + value = value * 16 + ch - 97 /* a */ + 10; } else { break; @@ -9892,8 +12052,8 @@ var ts; } return value; } - function scanString(allowEscapes) { - if (allowEscapes === void 0) { allowEscapes = true; } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -9901,7 +12061,7 @@ var ts; while (true) { if (pos >= end) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -9911,15 +12071,15 @@ var ts; pos++; break; } - if (ch === 92 && allowEscapes) { + if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; continue; } - if (isLineBreak(ch)) { + if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -9927,8 +12087,12 @@ var ts; } return result; } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ function scanTemplateAndSetTokenValue() { - var startedWithBacktick = text.charCodeAt(pos) === 96; + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; pos++; var start = pos; var contents = ""; @@ -9936,34 +12100,39 @@ var ts; while (true) { if (pos >= end) { contents += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); - resultingToken = startedWithBacktick ? 13 : 16; + resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; break; } var currChar = text.charCodeAt(pos); - if (currChar === 96) { + // '`' + if (currChar === 96 /* backtick */) { contents += text.substring(start, pos); pos++; - resultingToken = startedWithBacktick ? 13 : 16; + resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; break; } - if (currChar === 36 && pos + 1 < end && text.charCodeAt(pos + 1) === 123) { + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { contents += text.substring(start, pos); pos += 2; - resultingToken = startedWithBacktick ? 14 : 15; + resultingToken = startedWithBacktick ? 14 /* TemplateHead */ : 15 /* TemplateMiddle */; break; } - if (currChar === 92) { + // Escape character + if (currChar === 92 /* backslash */) { contents += text.substring(start, pos); contents += scanEscapeSequence(); start = pos; continue; } - if (currChar === 13) { + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { contents += text.substring(start, pos); pos++; - if (pos < end && text.charCodeAt(pos) === 10) { + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { pos++; } contents += "\n"; @@ -9985,40 +12154,46 @@ var ts; var ch = text.charCodeAt(pos); pos++; switch (ch) { - case 48: + case 48 /* _0 */: return "\0"; - case 98: + case 98 /* b */: return "\b"; - case 116: + case 116 /* t */: return "\t"; - case 110: + case 110 /* n */: return "\n"; - case 118: + case 118 /* v */: return "\v"; - case 102: + case 102 /* f */: return "\f"; - case 114: + case 114 /* r */: return "\r"; - case 39: + case 39 /* singleQuote */: return "\'"; - case 34: + case 34 /* doubleQuote */: return "\""; - case 117: - if (pos < end && text.charCodeAt(pos) === 123) { - hasExtendedUnicodeEscape = true; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + tokenFlags |= 8 /* ExtendedUnicodeEscape */; pos++; return scanExtendedUnicodeEscape(); } - return scanHexadecimalEscape(4); - case 120: - return scanHexadecimalEscape(2); - case 13: - if (pos < end && text.charCodeAt(pos) === 10) { + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { pos++; } - case 10: - case 8232: - case 8233: + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: return ""; default: return String.fromCharCode(ch); @@ -10037,6 +12212,7 @@ var ts; function scanExtendedUnicodeEscape() { var escapedValue = scanMinimumNumberOfHexDigits(1); var isInvalidExtendedEscape = false; + // Validate the value of the digit if (escapedValue < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); isInvalidExtendedEscape = true; @@ -10049,7 +12225,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } - else if (text.charCodeAt(pos) === 125) { + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. pos++; } else { @@ -10061,6 +12238,7 @@ var ts; } return utf16EncodeAsString(escapedValue); } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. function utf16EncodeAsString(codePoint) { ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); if (codePoint <= 65535) { @@ -10070,8 +12248,10 @@ var ts; var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; return String.fromCharCode(codeUnit1, codeUnit2); } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. function peekUnicodeEscape() { - if (pos + 5 < end && text.charCodeAt(pos + 1) === 117) { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { var start_1 = pos; pos += 2; var value = scanExactNumberOfHexDigits(4); @@ -10088,13 +12268,14 @@ var ts; if (isIdentifierPart(ch, languageVersion)) { pos++; } - else if (ch === 92) { + else if (ch === 92 /* backslash */) { ch = peekUnicodeEscape(); if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { break; } result += text.substring(start, pos); result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters pos += 6; start = pos; } @@ -10106,25 +12287,28 @@ var ts; return result; } function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter var len = tokenValue.length; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); - if (ch >= 97 && ch <= 122) { + if (ch >= 97 /* a */ && ch <= 122 /* z */) { token = textToToken.get(tokenValue); if (token !== undefined) { return token; } } } - return token = 71; + return token = 71 /* Identifier */; } function scanBinaryOrOctalDigits(base) { ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. var numberOfDigits = 0; while (true) { var ch = text.charCodeAt(pos); - var valueOfCh = ch - 48; + var valueOfCh = ch - 48 /* _0 */; if (!isDigit(ch) || valueOfCh >= base) { break; } @@ -10132,6 +12316,7 @@ var ts; pos++; numberOfDigits++; } + // Invalid binaryIntegerLiteral or octalIntegerLiteral if (numberOfDigits === 0) { return -1; } @@ -10139,46 +12324,45 @@ var ts; } function scan() { startPos = pos; - hasExtendedUnicodeEscape = false; - precedingLineBreak = false; - tokenIsUnterminated = false; - numericLiteralFlags = 0; + tokenFlags = 0; while (true) { tokenPos = pos; if (pos >= end) { - return token = 1; + return token = 1 /* EndOfFileToken */; } var ch = text.charCodeAt(pos); - if (ch === 35 && pos === 0 && isShebangTrivia(text, pos)) { + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); if (skipTrivia) { continue; } else { - return token = 6; + return token = 6 /* ShebangTrivia */; } } switch (ch) { - case 10: - case 13: - precedingLineBreak = true; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; if (skipTrivia) { pos++; continue; } else { - if (ch === 13 && pos + 1 < end && text.charCodeAt(pos + 1) === 10) { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF pos += 2; } else { pos++; } - return token = 4; + return token = 4 /* NewLineTrivia */; } - case 9: - case 11: - case 12: - case 32: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: if (skipTrivia) { pos++; continue; @@ -10187,89 +12371,90 @@ var ts; while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { pos++; } - return token = 5; + return token = 5 /* WhitespaceTrivia */; } - case 33: - if (text.charCodeAt(pos + 1) === 61) { - if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 35; + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 35 /* ExclamationEqualsEqualsToken */; } - return pos += 2, token = 33; + return pos += 2, token = 33 /* ExclamationEqualsToken */; } pos++; - return token = 51; - case 34: - case 39: + return token = 51 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: tokenValue = scanString(); - return token = 9; - case 96: + return token = 9 /* StringLiteral */; + case 96 /* backtick */: return token = scanTemplateAndSetTokenValue(); - case 37: - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 64; + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* PercentEqualsToken */; } pos++; - return token = 42; - case 38: - if (text.charCodeAt(pos + 1) === 38) { - return pos += 2, token = 53; + return token = 42 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 53 /* AmpersandAmpersandToken */; } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 68; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 68 /* AmpersandEqualsToken */; } pos++; - return token = 48; - case 40: + return token = 48 /* AmpersandToken */; + case 40 /* openParen */: pos++; - return token = 19; - case 41: + return token = 19 /* OpenParenToken */; + case 41 /* closeParen */: pos++; - return token = 20; - case 42: - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 61; - } - if (text.charCodeAt(pos + 1) === 42) { - if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 62; + return token = 20 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 62 /* AsteriskAsteriskEqualsToken */; } - return pos += 2, token = 40; + return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; - return token = 39; - case 43: - if (text.charCodeAt(pos + 1) === 43) { - return pos += 2, token = 43; + return token = 39 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 43 /* PlusPlusToken */; } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 59; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 59 /* PlusEqualsToken */; } pos++; - return token = 37; - case 44: + return token = 37 /* PlusToken */; + case 44 /* comma */: pos++; - return token = 26; - case 45: - if (text.charCodeAt(pos + 1) === 45) { - return pos += 2, token = 44; + return token = 26 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 44 /* MinusMinusToken */; } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 60; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 60 /* MinusEqualsToken */; } pos++; - return token = 38; - case 46: + return token = 38 /* MinusToken */; + case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); - return token = 8; + return token = 8 /* NumericLiteral */; } - if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { - return pos += 3, token = 24; + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 24 /* DotDotDotToken */; } pos++; - return token = 23; - case 47: - if (text.charCodeAt(pos + 1) === 47) { + return token = 23 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; while (pos < end) { if (isLineBreak(text.charCodeAt(pos))) { @@ -10281,21 +12466,25 @@ var ts; continue; } else { - return token = 2; + return token = 2 /* SingleLineCommentTrivia */; } } - if (text.charCodeAt(pos + 1) === 42) { + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } var commentClosed = false; while (pos < end) { var ch_1 = text.charCodeAt(pos); - if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; commentClosed = true; break; } if (isLineBreak(ch_1)) { - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; } pos++; } @@ -10306,17 +12495,19 @@ var ts; continue; } else { - tokenIsUnterminated = !commentClosed; - return token = 3; + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; } } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 63; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 63 /* SlashEqualsToken */; } pos++; - return token = 41; - case 48: - if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { + return token = 41 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; var value = scanMinimumNumberOfHexDigits(1); if (value < 0) { @@ -10324,158 +12515,163 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 8; - return token = 8; + tokenFlags |= 64 /* HexSpecifier */; + return token = 8 /* NumericLiteral */; } - else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) { + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - var value = scanBinaryOrOctalDigits(2); + var value = scanBinaryOrOctalDigits(/* base */ 2); if (value < 0) { error(ts.Diagnostics.Binary_digit_expected); value = 0; } tokenValue = "" + value; - numericLiteralFlags = 16; - return token = 8; + tokenFlags |= 128 /* BinarySpecifier */; + return token = 8 /* NumericLiteral */; } - else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) { + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - var value = scanBinaryOrOctalDigits(8); + var value = scanBinaryOrOctalDigits(/* base */ 8); if (value < 0) { error(ts.Diagnostics.Octal_digit_expected); value = 0; } tokenValue = "" + value; - numericLiteralFlags = 32; - return token = 8; + tokenFlags |= 256 /* OctalSpecifier */; + return token = 8 /* NumericLiteral */; } + // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); - numericLiteralFlags = 4; - return token = 8; - } - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: + tokenFlags |= 32 /* Octal */; + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: tokenValue = scanNumber(); - return token = 8; - case 58: + return token = 8 /* NumericLiteral */; + case 58 /* colon */: pos++; - return token = 56; - case 59: + return token = 56 /* ColonToken */; + case 59 /* semicolon */: pos++; - return token = 25; - case 60: + return token = 25 /* SemicolonToken */; + case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } else { - return token = 7; + return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 60) { - if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 65; + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 65 /* LessThanLessThanEqualsToken */; } - return pos += 2, token = 45; + return pos += 2, token = 45 /* LessThanLessThanToken */; } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 30; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 30 /* LessThanEqualsToken */; } - if (languageVariant === 1 && - text.charCodeAt(pos + 1) === 47 && - text.charCodeAt(pos + 2) !== 42) { - return pos += 2, token = 28; + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 28 /* LessThanSlashToken */; } pos++; - return token = 27; - case 61: + return token = 27 /* LessThanToken */; + case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } else { - return token = 7; + return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 61) { - if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 34; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 34 /* EqualsEqualsEqualsToken */; } - return pos += 2, token = 32; + return pos += 2, token = 32 /* EqualsEqualsToken */; } - if (text.charCodeAt(pos + 1) === 62) { - return pos += 2, token = 36; + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 36 /* EqualsGreaterThanToken */; } pos++; - return token = 58; - case 62: + return token = 58 /* EqualsToken */; + case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } else { - return token = 7; + return token = 7 /* ConflictMarkerTrivia */; } } pos++; - return token = 29; - case 63: + return token = 29 /* GreaterThanToken */; + case 63 /* question */: pos++; - return token = 55; - case 91: + return token = 55 /* QuestionToken */; + case 91 /* openBracket */: pos++; - return token = 21; - case 93: + return token = 21 /* OpenBracketToken */; + case 93 /* closeBracket */: pos++; - return token = 22; - case 94: - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 70; + return token = 22 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* CaretEqualsToken */; } pos++; - return token = 50; - case 123: + return token = 50 /* CaretToken */; + case 123 /* openBrace */: pos++; - return token = 17; - case 124: + return token = 17 /* OpenBraceToken */; + case 124 /* bar */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } else { - return token = 7; + return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 124) { - return pos += 2, token = 54; + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 54 /* BarBarToken */; } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 69; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* BarEqualsToken */; } pos++; - return token = 49; - case 125: + return token = 49 /* BarToken */; + case 125 /* closeBrace */: pos++; - return token = 18; - case 126: + return token = 18 /* CloseBraceToken */; + case 126 /* tilde */: pos++; - return token = 52; - case 64: + return token = 52 /* TildeToken */; + case 64 /* at */: pos++; - return token = 57; - case 92: + return token = 57 /* AtToken */; + case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { pos += 6; @@ -10484,14 +12680,14 @@ var ts; } error(ts.Diagnostics.Invalid_character); pos++; - return token = 0; + return token = 0 /* Unknown */; default: if (isIdentifierStart(ch, languageVersion)) { pos++; while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) pos++; tokenValue = text.substring(tokenPos, pos); - if (ch === 92) { + if (ch === 92 /* backslash */) { tokenValue += scanIdentifierParts(); } return token = getIdentifierToken(); @@ -10501,69 +12697,75 @@ var ts; continue; } else if (isLineBreak(ch)) { - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; pos++; continue; } error(ts.Diagnostics.Invalid_character); pos++; - return token = 0; + return token = 0 /* Unknown */; } } } function reScanGreaterToken() { - if (token === 29) { - if (text.charCodeAt(pos) === 62) { - if (text.charCodeAt(pos + 1) === 62) { - if (text.charCodeAt(pos + 2) === 61) { - return pos += 3, token = 67; + if (token === 29 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } - return pos += 2, token = 47; + return pos += 2, token = 47 /* GreaterThanGreaterThanGreaterThanToken */; } - if (text.charCodeAt(pos + 1) === 61) { - return pos += 2, token = 66; + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 66 /* GreaterThanGreaterThanEqualsToken */; } pos++; - return token = 46; + return token = 46 /* GreaterThanGreaterThanToken */; } - if (text.charCodeAt(pos) === 61) { + if (text.charCodeAt(pos) === 61 /* equals */) { pos++; - return token = 31; + return token = 31 /* GreaterThanEqualsToken */; } } return token; } function reScanSlashToken() { - if (token === 41 || token === 63) { + if (token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; var inCharacterClass = false; while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. if (p >= end) { - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } var ch = text.charCodeAt(p); if (isLineBreak(ch)) { - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. inEscape = false; } - else if (ch === 47 && !inCharacterClass) { + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. p++; break; } - else if (ch === 91) { + else if (ch === 91 /* openBracket */) { inCharacterClass = true; } - else if (ch === 92) { + else if (ch === 92 /* backslash */) { inEscape = true; } - else if (ch === 93) { + else if (ch === 93 /* closeBracket */) { inCharacterClass = false; } p++; @@ -10573,12 +12775,15 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12; + token = 12 /* RegularExpressionLiteral */; } return token; } + /** + * Unconditionally back up and scan a template expression portion. + */ function reScanTemplateToken() { - ts.Debug.assert(token === 18, "'reScanTemplateToken' should only be called on a '}'"); + ts.Debug.assert(token === 18 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; return token = scanTemplateAndSetTokenValue(); } @@ -10589,34 +12794,43 @@ var ts; function scanJsxToken() { startPos = tokenPos = pos; if (pos >= end) { - return token = 1; + return token = 1 /* EndOfFileToken */; } var char = text.charCodeAt(pos); - if (char === 60) { - if (text.charCodeAt(pos + 1) === 47) { + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; - return token = 28; + return token = 28 /* LessThanSlashToken */; } pos++; - return token = 27; + return token = 27 /* LessThanToken */; } - if (char === 123) { + if (char === 123 /* openBrace */) { pos++; - return token = 17; + return token = 17 /* OpenBraceToken */; } + // First non-whitespace character on this line. var firstNonWhitespace = 0; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitspace, while (pos < end) { char = text.charCodeAt(pos); - if (char === 123) { + if (char === 123 /* openBrace */) { break; } - if (char === 60) { + if (char === 60 /* lessThan */) { if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); - return token = 7; + return token = 7 /* ConflictMarkerTrivia */; } break; } + // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. + // i.e (- : whitespace) + //
---- + //
becomes
+ // + //
----
becomes
----
if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } @@ -10625,14 +12839,16 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 : 10; + return firstNonWhitespace === -1 ? 11 /* JsxTextAllWhiteSpaces */ : 10 /* JsxText */; } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { var firstCharPosition = pos; while (pos < end) { var ch = text.charCodeAt(pos); - if (ch === 45 || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { pos++; } else { @@ -10646,71 +12862,89 @@ var ts; function scanJsxAttributeValue() { startPos = pos; switch (text.charCodeAt(pos)) { - case 34: - case 39: - tokenValue = scanString(false); - return token = 9; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(/*jsxAttributeString*/ true); + return token = 9 /* StringLiteral */; default: + // If this scans anything other than `{`, it's a parse error. return scan(); } } function scanJSDocToken() { if (pos >= end) { - return token = 1; + return token = 1 /* EndOfFileToken */; } startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); switch (ch) { - case 9: - case 11: - case 12: - case 32: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { pos++; } - return token = 5; - case 64: + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + pos++; + return token = 57 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + pos++; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: pos++; - return token = 57; - case 10: - case 13: + return token = 39 /* AsteriskToken */; + case 123 /* openBrace */: pos++; - return token = 4; - case 42: + return token = 17 /* OpenBraceToken */; + case 125 /* closeBrace */: pos++; - return token = 39; - case 123: + return token = 18 /* CloseBraceToken */; + case 91 /* openBracket */: pos++; - return token = 17; - case 125: + return token = 21 /* OpenBracketToken */; + case 93 /* closeBracket */: pos++; - return token = 18; - case 91: + return token = 22 /* CloseBracketToken */; + case 60 /* lessThan */: pos++; - return token = 21; - case 93: + return token = 27 /* LessThanToken */; + case 62 /* greaterThan */: pos++; - return token = 22; - case 61: + return token = 29 /* GreaterThanToken */; + case 61 /* equals */: pos++; - return token = 58; - case 44: + return token = 58 /* EqualsToken */; + case 44 /* comma */: pos++; - return token = 26; - case 46: + return token = 26 /* CommaToken */; + case 46 /* dot */: pos++; - return token = 23; + if (text.substr(tokenPos, pos + 2) === "...") { + pos += 2; + return token = 24 /* DotDotDotToken */; + } + return token = 23 /* DotToken */; + case 33 /* exclamation */: + pos++; + return token = 51 /* ExclamationToken */; + case 63 /* question */: + pos++; + return token = 55 /* QuestionToken */; } - if (isIdentifierStart(ch, 5)) { + if (isIdentifierStart(ch, 6 /* Latest */)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } - return token = 71; + tokenValue = text.substring(tokenPos, pos); + return token = 71 /* Identifier */; } else { - return pos += 1, token = 0; + return pos += 1, token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -10719,15 +12953,17 @@ var ts; var saveTokenPos = tokenPos; var saveToken = token; var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; + var saveTokenFlags = tokenFlags; var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. if (!result || isLookahead) { pos = savePos; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; - precedingLineBreak = savePrecedingLineBreak; + tokenFlags = saveTokenFlags; } return result; } @@ -10737,10 +12973,8 @@ var ts; var saveStartPos = startPos; var saveTokenPos = tokenPos; var saveToken = token; - var savePrecedingLineBreak = precedingLineBreak; var saveTokenValue = tokenValue; - var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - var saveTokenIsUnterminated = tokenIsUnterminated; + var saveTokenFlags = tokenFlags; setText(text, start, length); var result = callback(); end = saveEnd; @@ -10748,17 +12982,15 @@ var ts; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; - precedingLineBreak = savePrecedingLineBreak; tokenValue = saveTokenValue; - hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; - tokenIsUnterminated = saveTokenIsUnterminated; + tokenFlags = saveTokenFlags; return result; } function lookAhead(callback) { - return speculationHelper(callback, true); + return speculationHelper(callback, /*isLookahead*/ true); } function tryScan(callback) { - return speculationHelper(callback, false); + return speculationHelper(callback, /*isLookahead*/ false); } function getText() { return text; @@ -10782,15 +13014,15 @@ var ts; pos = textPos; startPos = textPos; tokenPos = textPos; - token = 0; - precedingLineBreak = false; + token = 0 /* Unknown */; tokenValue = undefined; - hasExtendedUnicodeEscape = false; - tokenIsUnterminated = false; + tokenFlags = 0; } } ts.createScanner = createScanner; })(ts || (ts = {})); +/// +/// var ts; (function (ts) { var SignatureFlags; @@ -10803,15 +13035,17 @@ var ts; SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; + // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 265) { + if (kind === 269 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 71) { + else if (kind === 71 /* Identifier */) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); } else if (!ts.isNodeKind(kind)) { @@ -10839,60 +13073,74 @@ var ts; } } } + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 142) { + if (!node || node.kind <= 143 /* LastToken */) { return; } switch (node.kind) { - case 143: + case 144 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 145: + case 146 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 262: + case 266 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 263: + case 267 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 146: - case 149: - case 148: - case 261: - case 226: - case 176: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 160: - case 161: - case 155: - case 156: - case 157: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 151: - case 150: - case 152: - case 153: - case 154: - case 186: - case 228: - case 187: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -10903,287 +13151,291 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 159: + case 160 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 158: + case 159 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 162: + case 163 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 163: + case 164 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 164: + case 165 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 165: + case 166 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 166: - case 167: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 168: - case 170: + case 169 /* ParenthesizedType */: + case 171 /* TypeOperator */: return visitNode(cbNode, node.type); - case 171: + case 172 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 172: + case 173 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 173: + case 174 /* LiteralType */: return visitNode(cbNode, node.literal); - case 174: - case 175: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 177: + case 178 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 178: + case 179 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 179: + case 180 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 180: + case 181 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 181: - case 182: + case 182 /* CallExpression */: + case 183 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 183: + case 184 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 184: + case 185 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 185: + case 186 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 188: + case 189 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 189: + case 190 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 190: + case 191 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 192: + case 193 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 197: + case 198 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 191: + case 192 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 193: + case 194 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 194: + case 195 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 202: + case 203 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 203: + case 204 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 204: + case 205 /* MetaProperty */: return visitNode(cbNode, node.name); - case 195: + case 196 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 198: + case 199 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 207: - case 234: + case 208 /* Block */: + case 235 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 265: + case 269 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 208: + case 209 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 227: + case 228 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 210: + case 211 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 211: + case 212 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 212: + case 213 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 213: + case 214 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 214: + case 215 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 215: + case 216 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 216: + case 217 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 217: - case 218: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: return visitNode(cbNode, node.label); - case 219: + case 220 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 220: + case 221 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221: + case 222 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 235: + case 236 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 257: + case 261 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 258: + case 262 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 222: + case 223 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 223: + case 224 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 224: + case 225 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 260: + case 264 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 147: + case 148 /* Decorator */: return visitNode(cbNode, node.expression); - case 229: - case 199: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 230: + case 231 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 231: + case 232 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 232: + case 233 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 264: + case 268 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 233: + case 234 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 237: + case 238 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 238: + case 239 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 239: + case 240 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 236: + case 237 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 240: + case 241 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 241: - case 245: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 244: + case 245 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 243: + case 244 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 196: + case 197 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 205: + case 206 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: + case 145 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 259: + case 263 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 201: + case 202 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 248: + case 249 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 247: + case 248 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 289: + case 293 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 249: + case 250 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 250: - case 251: + case 254 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.attributes); - case 254: + case 258 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 253: + case 257 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 255: + case 259 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 256: + case 260 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 252: + case 253 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 267: + case 271 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 271: + case 275 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 270: + case 274 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 272: + case 276 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 273: + case 277 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 274: + case 278 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 275: + case 279 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 279: - case 284: + case 284 /* JSDocParameterTag */: + case 289 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -11192,17 +13444,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 280: + case 285 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 281: + case 286 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 277: - return visitNode(cbNode, node.typeExpression); - case 282: + case 282 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.class); + case 287 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 283: + case 288 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 267) { + node.typeExpression.kind === 271 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -11210,7 +13462,7 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 285: + case 280 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -11218,7 +13470,7 @@ var ts; } } return; - case 288: + case 292 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -11226,7 +13478,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -11236,40 +13488,70 @@ var ts; return Parser.parseIsolatedEntityName(text, languageVersion); } ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ function parseJsonText(fileName, sourceText) { return Parser.parseJsonText(fileName, sourceText); } ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts function isExternalModule(file) { return file.externalModuleIndicator !== undefined; } ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - newSourceFile.flags |= (sourceFile.flags & 524288); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 524288 /* PossiblyContainsDynamicImport */); return newSourceFile; } ts.updateSourceFile = updateSourceFile; + /* @internal */ function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. Parser.fixupParentReferences(result.jsDoc); } return result; } ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. function parseJSDocTypeExpressionForTests(content, start, length) { return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); } ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. var Parser; (function (Parser) { - var scanner = ts.createScanner(5, true); - var disallowInAndDecoratorContext = 2048 | 8192; + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; + // tslint:enable variable-name var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -11279,7 +13561,80 @@ var ts; var identifiers; var identifierCount; var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); @@ -11290,29 +13645,33 @@ var ts; } Parser.parseSourceFile = parseSourceFile; function parseIsolatedEntityName(content, languageVersion) { - initializeState(content, languageVersion, undefined, 1); + // Choice of `isDeclarationFile` should be arbitrary + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. nextToken(); - var entityName = parseEntityName(true); - var isInvalid = token() === 1 && !parseDiagnostics.length; + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; clearState(); return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2, undefined, 6); - sourceFile = createSourceFile(fileName, 2, 6); + initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); var result = sourceFile; + // Prime the scanner. nextToken(); - if (token() === 1) { + if (token() === 1 /* EndOfFileToken */) { sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 || - lookAhead(function () { return token() === 9; })) { + else if (token() === 17 /* OpenBraceToken */ || + lookAhead(function () { return token() === 9 /* StringLiteral */; })) { result.jsonObject = parseObjectLiteralExpression(); - sourceFile.endOfFileToken = parseExpectedToken(1, false, ts.Diagnostics.Unexpected_token); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Unexpected_token); } else { - parseExpected(17); + parseExpected(17 /* OpenBraceToken */); } sourceFile.parseDiagnostics = parseDiagnostics; clearState(); @@ -11320,7 +13679,8 @@ var ts; } Parser.parseJsonText = parseJsonText; function getLanguageVariant(scriptKind) { - return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0; + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; } function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); @@ -11334,16 +13694,28 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); scanner.setLanguageVariant(getLanguageVariant(scriptKind)); } function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. scanner.setText(""); scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. parseDiagnostics = undefined; sourceFile = undefined; identifiers = undefined; @@ -11351,12 +13723,17 @@ var ts; sourceText = undefined; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 2097152 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; + // Prime the scanner. nextToken(); processReferenceComments(sourceFile); - sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -11374,22 +13751,30 @@ var ts; for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; + if (jsDoc) { + if (!node.jsDoc) { + node.jsDoc = [jsDoc]; + } + else { + node.jsDoc.push(jsDoc); + } } - node.jsDoc.push(jsDoc); } } return node; } function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. var parent = rootNode; forEachChild(rootNode, visitNode); return; function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing if (n.parent !== parent) { n.parent = parent; var saveParent = parent; @@ -11408,15 +13793,17 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(269 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.isDeclarationFile = isDeclarationFile; sourceFile.scriptKind = scriptKind; return sourceFile; } @@ -11429,72 +13816,90 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 2048); + setContextFlag(val, 2048 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 4096); + setContextFlag(val, 4096 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 8192); + setContextFlag(val, 8192 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 16384); + setContextFlag(val, 16384 /* AwaitContext */); } function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). var contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { - setContextFlag(false, contextFlagsToClear); + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); var result = func(); - setContextFlag(true, contextFlagsToClear); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); return result; } + // no need to do anything special as we are not in any of the requested contexts return func(); } function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). var contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { - setContextFlag(true, contextFlagsToSet); + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); var result = func(); - setContextFlag(false, contextFlagsToSet); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); return result; } + // no need to do anything special as we are already in all of the requested contexts return func(); } function allowInAnd(func) { - return doOutsideOfContext(2048, func); + return doOutsideOfContext(2048 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(2048, func); + return doInsideOfContext(2048 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(4096, func); + return doInsideOfContext(4096 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(8192, func); + return doInsideOfContext(8192 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(16384, func); + return doInsideOfContext(16384 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(16384, func); + return doOutsideOfContext(16384 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(4096 | 16384, func); + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(4096); + return inContext(4096 /* YieldContext */); } function inDisallowInContext() { - return inContext(2048); + return inContext(2048 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(8192); + return inContext(8192 /* DecoratorContext */); } function inAwaitContext() { - return inContext(16384); + return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -11502,10 +13907,13 @@ var ts; parseErrorAtPosition(start, length, message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. var lastError = ts.lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; } function scanError(message, length) { @@ -11515,6 +13923,12 @@ var ts; function getNodePos() { return scanner.getStartPos(); } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. function token() { return currentToken; } @@ -11540,14 +13954,25 @@ var ts; return currentToken = scanner.scanJsxAttributeValue(); } function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. var result = isLookAhead ? scanner.lookAhead(callback) : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. if (!result || isLookAhead) { currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; @@ -11555,23 +13980,37 @@ var ts; } return result; } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ function lookAhead(callback) { - return speculationHelper(callback, true); + return speculationHelper(callback, /*isLookAhead*/ true); } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ function tryParse(callback) { - return speculationHelper(callback, false); + return speculationHelper(callback, /*isLookAhead*/ false); } + // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 71) { + if (token() === 71 /* Identifier */) { return true; } - if (token() === 116 && inYieldContext()) { + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 116 /* YieldKeyword */ && inYieldContext()) { return false; } - if (token() === 121 && inAwaitContext()) { + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 107; + return token() > 107 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } @@ -11581,6 +14020,7 @@ var ts; } return true; } + // Report specific message if provided with one. Otherwise, report generic fallback message. if (diagnosticMessage) { parseErrorAtCurrentToken(diagnosticMessage); } @@ -11612,32 +14052,43 @@ var ts; return finishNode(node); } function canParseSemicolon() { - if (token() === 25) { + // If there's a real semicolon, then we can always parse it out. + if (token() === 25 /* SemicolonToken */) { return true; } - return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 25) { + if (token() === 25 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. nextToken(); } return true; } else { - return parseExpected(25); + return parseExpected(25 /* SemicolonToken */); } } function createNode(kind, pos) { nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind) { + var node = createNode(kind); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); } - return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return node; } function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. var length = elements.length; var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; @@ -11649,9 +14100,12 @@ var ts; if (contextFlags) { node.flags |= contextFlags; } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.flags |= 32768; + node.flags |= 32768 /* ThisNodeHasError */; } return node; } @@ -11662,8 +14116,8 @@ var ts; else { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); - if (kind === 71) { + var result = createNode(kind); + if (kind === 71 /* Identifier */) { result.escapedText = ""; } else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { @@ -11678,50 +14132,61 @@ var ts; } return identifier; } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { - var node = createNode(71); - if (token() !== 71) { + var node = createNode(71 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 71 /* Identifier */) { node.originalKeywordKind = token(); } node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); nextToken(); return finishNode(node); } - var reportAtCurrentPosition = token() === 1; - return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { + if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { var node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === 21) { + if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker(true); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); } function parseComputedPropertyName() { - var node = createNode(144); - parseExpected(21); + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(145 /* ComputedPropertyName */); + parseExpected(21 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. node.expression = allowInAnd(parseExpression); - parseExpected(22); + parseExpected(22 /* CloseBracketToken */); return finishNode(node); } function parseContextualModifier(t) { @@ -11735,20 +14200,21 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; + if (token() === 76 /* ConstKeyword */) { + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; } - if (token() === 84) { + if (token() === 84 /* ExportKeyword */) { nextToken(); - if (token() === 79) { + if (token() === 79 /* DefaultKeyword */) { return lookAhead(nextTokenCanFollowDefaultKeyword); } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); } - if (token() === 79) { + if (token() === 79 /* DefaultKeyword */) { return nextTokenCanFollowDefaultKeyword(); } - if (token() === 115) { + if (token() === 115 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } @@ -11758,83 +14224,108 @@ var ts; return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 21 - || token() === 17 - || token() === 39 - || token() === 24 + return token() === 21 /* OpenBracketToken */ + || token() === 17 /* OpenBraceToken */ + || token() === 39 /* AsteriskToken */ + || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenCanFollowDefaultKeyword() { nextToken(); - return token() === 75 || token() === 89 || - token() === 109 || - (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || + token() === 109 /* InterfaceKeyword */ || + (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } + // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); if (node) { return true; } switch (parsingContext) { - case 0: - case 1: - case 3: - return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); - case 2: - return token() === 73 || token() === 79; - case 4: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); - case 5: - return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); - case 6: - return token() === 21 || isLiteralPropertyName(); - case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); - case 17: + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + case 17 /* RestProperties */: return isLiteralPropertyName(); - case 9: - return token() === 21 || token() === 24 || isLiteralPropertyName(); - case 7: - if (token() === 17) { + case 9 /* ObjectBindingElements */: + return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 17 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); } else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } - case 8: + case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); - case 10: - return token() === 26 || token() === 24 || isIdentifierOrPattern(); - case 18: + case 10 /* ArrayBindingElements */: + return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 18 /* TypeParameters */: return isIdentifier(); - case 11: - case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); - case 16: + case 11 /* ArgumentExpressions */: + case 15 /* ArrayLiteralMembers */: + return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: return isStartOfParameter(); - case 19: - case 20: - return token() === 26 || isStartOfType(); - case 21: + case 19 /* TypeArguments */: + case 20 /* TupleElementTypes */: + return token() === 26 /* CommaToken */ || isStartOfType(); + case 21 /* HeritageClauses */: return isHeritageClause(); - case 22: + case 22 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); - case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; - case 14: + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + case 14 /* JsxChildren */: return true; } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17); - if (nextToken() === 18) { + ts.Debug.assert(token() === 17 /* OpenBraceToken */); + if (nextToken() === 18 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements var next = nextToken(); - return next === 26 || next === 17 || next === 85 || next === 108; + return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; } return true; } @@ -11846,9 +14337,13 @@ var ts; nextToken(); return ts.tokenIsIdentifierOrKeyword(token()); } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 || - token() === 85) { + if (token() === 108 /* ImplementsKeyword */ || + token() === 85 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -11857,76 +14352,93 @@ var ts; nextToken(); return isStartOfExpression(); } + // True if positioned at a list terminator function isListTerminator(kind) { - if (token() === 1) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. return true; } switch (kind) { - case 1: - case 2: - case 4: - case 5: - case 6: - case 12: - case 9: - case 22: - return token() === 18; - case 3: - return token() === 18 || token() === 73 || token() === 79; - case 7: - return token() === 17 || token() === 85 || token() === 108; - case 8: + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 22 /* ImportOrExportSpecifiers */: + return token() === 18 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 18: - return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; - case 11: - return token() === 20 || token() === 25; - case 15: - case 20: - case 10: - return token() === 22; - case 16: - case 17: - return token() === 20 || token() === 22; - case 19: - return token() !== 26; - case 21: - return token() === 17 || token() === 18; - case 13: - return token() === 29 || token() === 41; - case 14: - return token() === 27 && lookAhead(nextTokenIsSlash); + case 18 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 20 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 22 /* CloseBracketToken */; + case 16 /* Parameters */: + case 17 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 19 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 26 /* CommaToken */; + case 21 /* HeritageClauses */: + return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); } } function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of if (isInOrOfKeyword(token())) { return true; } - if (token() === 36) { + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 36 /* EqualsGreaterThanToken */) { return true; } + // Keep trying to parse out variable declarators. return false; } + // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 23; kind++) { + for (var kind = 0; kind < 23 /* Count */; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, true) || isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } } return false; } + // Parses a list of elements function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var list = []; var listPos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement(kind, false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); list.push(element); continue; @@ -11946,82 +14458,141 @@ var ts; return parseElement(); } function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. if (parseErrorBeforeNextFinishedNode) { return undefined; } if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. if (ts.nodeIsMissing(node)) { return undefined; } + // Can't reuse a node that intersected the change range. if (node.intersectsChange) { return undefined; } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 96256; + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 6387712 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. if (!canReuseNode(node, parsingContext)) { return undefined; } return node; } function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. scanner.setTextPos(node.end); nextToken(); return node; } function canReuseNode(node, parsingContext) { switch (parsingContext) { - case 5: + case 5 /* ClassMembers */: return isReusableClassMember(node); - case 2: + case 2 /* SwitchClauses */: return isReusableSwitchClause(node); - case 0: - case 1: - case 3: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: return isReusableStatement(node); - case 6: + case 6 /* EnumMembers */: return isReusableEnumMember(node); - case 4: + case 4 /* TypeMembers */: return isReusableTypeMember(node); - case 8: + case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); - case 16: + case 16 /* Parameters */: return isReusableParameter(node); - case 17: + case 17 /* RestProperties */: return false; - case 21: - case 18: - case 20: - case 19: - case 11: - case 12: - case 7: - case 13: - case 14: + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 21 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 18 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 20 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 19 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: } return false; } function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 152: - case 157: - case 153: - case 154: - case 149: - case 206: + case 153 /* Constructor */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 207 /* SemicolonClassElement */: return true; - case 151: + case 152 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 && - methodDeclaration.name.originalKeywordKind === 123; + var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; return !nameIsConstructor; } } @@ -12030,8 +14601,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 257: - case 258: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: return true; } } @@ -12040,70 +14611,86 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 228: - case 208: - case 207: - case 211: - case 210: - case 223: - case 219: - case 221: - case 218: - case 217: - case 215: - case 216: - case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: - case 225: - case 238: - case 237: - case 244: - case 243: - case 233: - case 229: - case 230: - case 232: - case 231: + case 229 /* FunctionDeclaration */: + case 209 /* VariableStatement */: + case 208 /* Block */: + case 212 /* IfStatement */: + case 211 /* ExpressionStatement */: + case 224 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 222 /* SwitchStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 210 /* EmptyStatement */: + case 225 /* TryStatement */: + case 223 /* LabeledStatement */: + case 213 /* DoStatement */: + case 226 /* DebuggerStatement */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 232 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 264; + return node.kind === 268 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 156: - case 150: - case 157: - case 148: - case 155: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 149 /* PropertySignature */: + case 156 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { + if (node.kind !== 227 /* VariableDeclaration */) { return false; } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray result.hasTrailingComma = true; } return result; @@ -12192,10 +14798,11 @@ var ts; return createMissingList(); } function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); - while (parseOptional(23)) { - if (token() === 27) { + while (parseOptional(23 /* DotToken */)) { + if (token() === 27 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting entity.jsdocDotPos = dotPos; break; } @@ -12205,42 +14812,64 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(143, entity.pos); + var node = createNode(144 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); } function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { - return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(196); + var template = createNode(197 /* TemplateExpression */); template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); + ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15); + } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(205); + var span = createNode(206 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 18) { + if (token() === 18 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateMiddleOrTemplateTail(); } else { - literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); + literal = parseExpectedToken(16 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); } span.literal = literal; return finishNode(span); @@ -12250,12 +14879,12 @@ var ts; } function parseTemplateHead() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); + ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); return fragment; } function parseTemplateMiddleOrTemplateTail() { var fragment = parseLiteralLikeNode(token()); - ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); + ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); return fragment; } function parseLiteralLikeNode(kind) { @@ -12268,72 +14897,89 @@ var ts; if (scanner.isUnterminated()) { node.isUnterminated = true; } - if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getTokenFlags() & 496 /* NumericLiteralFlags */; } nextToken(); finishNode(node); return node; } + // TYPES function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); + var node = createNode(160 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(158, lhs.pos); + var node = createNode(159 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(169); + var node = createNode(170 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType() { - var result = createNode(268); + var result = createNode(272 /* JSDocAllType */); nextToken(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); + // skip the ? nextToken(); - if (token() === 26 || - token() === 18 || - token() === 20 || - token() === 29 || - token() === 58 || - token() === 49) { - var result = createNode(269, pos); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 26 /* CommaToken */ || + token() === 18 /* CloseBraceToken */ || + token() === 20 /* CloseParenToken */ || + token() === 29 /* GreaterThanToken */ || + token() === 58 /* EqualsToken */ || + token() === 49 /* BarToken */) { + var result = createNode(273 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(270, pos); + var result = createNode(274 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNode(273); + var result = createNodeWithJSDoc(277 /* JSDocFunctionType */); nextToken(); - fillSignature(56, 4 | 32, result); - return addJSDocComment(finishNode(result)); + fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); } - var node = createNode(159); + var node = createNode(160 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(146); - if (token() === 99 || token() === 94) { + var parameter = createNode(147 /* Parameter */); + if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { parameter.name = parseIdentifierName(); - parseExpected(56); + parseExpected(56 /* ColonToken */); } parameter.type = parseType(); return finishNode(parameter); @@ -12341,133 +14987,189 @@ var ts; function parseJSDocNodeWithType(kind) { var result = createNode(kind); nextToken(); - result.type = parseType(); + result.type = parseNonArrayType(); return finishNode(result); } function parseTypeQuery() { - var node = createNode(162); - parseExpected(103); - node.exprName = parseEntityName(true); + var node = createNode(163 /* TypeQuery */); + parseExpected(103 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(145); + var node = createNode(146 /* TypeParameter */); node.name = parseIdentifier(); - if (parseOptional(85)) { + if (parseOptional(85 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. if (isStartOfType() || !isStartOfExpression()) { node.constraint = parseType(); } else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the > as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } - if (parseOptional(58)) { + if (parseOptional(58 /* EqualsToken */)) { node.default = parseType(); } return finishNode(node); } function parseTypeParameters() { - if (token() === 27) { - return parseBracketedList(18, parseTypeParameter, 27, 29); + if (token() === 27 /* LessThanToken */) { + return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } } function parseParameterType() { - if (parseOptional(56)) { + if (parseOptional(56 /* ColonToken */)) { return parseType(); } return undefined; } function isStartOfParameter() { - return token() === 24 || + return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 || - isStartOfType(true); + token() === 57 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ true); } - function parseParameter(requireEqualsToken) { - var node = createNode(146); - if (token() === 99) { - node.name = createIdentifier(true); + function parseParameter() { + var node = createNodeWithJSDoc(147 /* Parameter */); + if (token() === 99 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. nextToken(); } - node.questionToken = parseOptionalToken(55); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); node.type = parseParameterType(); - node.initializer = parseInitializer(true, requireEqualsToken); - return addJSDocComment(finishNode(node)); + node.initializer = parseInitializer(); + return finishNode(node); } function fillSignature(returnToken, flags, signature) { - if (!(flags & 32)) { + if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4)); + signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); } function parseReturnType(returnToken, isType) { return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; } function shouldParseReturnType(returnToken, isType) { - if (returnToken === 36) { + if (returnToken === 36 /* EqualsGreaterThanToken */) { parseExpected(returnToken); return true; } - else if (parseOptional(56)) { + else if (parseOptional(56 /* ColonToken */)) { return true; } - else if (isType && token() === 36) { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56)); + else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); nextToken(); return true; } return false; } function parseParameterList(flags) { - if (parseExpected(19)) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (parseExpected(19 /* OpenParenToken */)) { var savedYieldContext = inYieldContext(); var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1)); - setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && (flags & 8)) { + if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { + // Caller insisted that we had to end with a ) We didn't. So just return + // undefined here. return undefined; } return result; } - return (flags & 8) ? undefined : createMissingList(); + // We didn't even have an open paren. If the caller requires a complete parameter list, + // we definitely can't provide that. However, if they're ok with an incomplete one, + // then just return an empty set of parameters. + return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); } function parseTypeMemberSemicolon() { - if (parseOptional(26)) { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(26 /* CommaToken */)) { return; } + // Didn't have a comma. We must have a (possible ASI) semicolon. parseSemicolon(); } function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { - parseExpected(94); + var node = createNodeWithJSDoc(kind); + if (kind === 157 /* ConstructSignature */) { + parseExpected(94 /* NewKeyword */); } - fillSignature(56, 4, node); + fillSignature(56 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); + return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // nextToken(); - if (token() === 24 || token() === 22) { + if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { return true; } if (ts.isModifierKind(token())) { @@ -12480,105 +15182,114 @@ var ts; return false; } else { + // Skip the identifier nextToken(); } - if (token() === 56 || token() === 26) { + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { return true; } - if (token() !== 55) { + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 55 /* QuestionToken */) { return false; } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 56 || token() === 26 || token() === 22; + return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 21, 22); + function parseIndexSignatureDeclaration(node) { + node.kind = 158 /* IndexSignature */; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, 4, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + node.kind = 151 /* MethodSignature */; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(56 /* ColonToken */, 4 /* Type */, node); } else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - if (token() === 58) { - property.initializer = parseNonParameterInitializer(); + node.kind = 149 /* PropertySignature */; + node.type = parseTypeAnnotation(); + if (token() === 58 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + node.initializer = parseInitializer(); } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); } + parseTypeMemberSemicolon(); + return finishNode(node); } function isTypeMemberStart() { - if (token() === 19 || token() === 27) { + // Return true if we have the start of a signature member + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return true; } var idToken; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier while (ts.isModifierKind(token())) { idToken = true; nextToken(); } - if (token() === 21) { + // Index signatures and computed property names are type members + if (token() === 21 /* OpenBracketToken */) { return true; } + // Try to get the first property-like token following all modifiers if (isLiteralPropertyName()) { idToken = true; nextToken(); } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration if (idToken) { - return token() === 19 || - token() === 27 || - token() === 55 || - token() === 56 || - token() === 26 || + return token() === 19 /* OpenParenToken */ || + token() === 27 /* LessThanToken */ || + token() === 55 /* QuestionToken */ || + token() === 56 /* ColonToken */ || + token() === 26 /* CommaToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 19 || token() === 27) { - return parseSignatureMember(155); + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseSignatureMember(156 /* CallSignature */); } - if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(156); + if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(157 /* ConstructSignature */); } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + return parseIndexSignatureDeclaration(node); } - return parsePropertyOrMethodSignature(fullStart, modifiers); + return parsePropertyOrMethodSignature(node); } function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === 19 || token() === 27; + return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(163); + var node = createNode(164 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; - if (parseExpected(17)) { - members = parseList(4, parseTypeMember); - parseExpected(18); + if (parseExpected(17 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(18 /* CloseBraceToken */); } else { members = createMissingList(); @@ -12587,64 +15298,64 @@ var ts; } function isStartOfMappedType() { nextToken(); - if (token() === 131) { + if (token() === 131 /* ReadonlyKeyword */) { nextToken(); } - return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; + return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(145); + var node = createNode(146 /* TypeParameter */); node.name = parseIdentifier(); - parseExpected(92); + parseExpected(92 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(172); - parseExpected(17); - node.readonlyToken = parseOptionalToken(131); - parseExpected(21); + var node = createNode(173 /* MappedType */); + parseExpected(17 /* OpenBraceToken */); + node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); + parseExpected(21 /* OpenBracketToken */); node.typeParameter = parseMappedTypeParameter(); - parseExpected(22); - node.questionToken = parseOptionalToken(55); + parseExpected(22 /* CloseBracketToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); node.type = parseTypeAnnotation(); parseSemicolon(); - parseExpected(18); + parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseTupleType() { - var node = createNode(165); - node.elementTypes = parseBracketedList(20, parseType, 21, 22); + var node = createNode(166 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(168); - parseExpected(19); + var node = createNode(169 /* ParenthesizedType */); + parseExpected(19 /* OpenParenToken */); node.type = parseType(); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { - parseExpected(94); + var node = createNodeWithJSDoc(kind); + if (kind === 162 /* ConstructorType */) { + parseExpected(94 /* NewKeyword */); } - fillSignature(36, 4, node); - return addJSDocComment(finishNode(node)); + fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 23 ? undefined : node; + return token() === 23 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(173); + var node = createNode(174 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(192); - unaryMinusExpression.operator = 38; + unaryMinusExpression = createNode(193 /* PrefixUnaryExpression */); + unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } - var expression = token() === 101 || token() === 86 + var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -12656,56 +15367,55 @@ var ts; return finishNode(node); } function nextTokenIsNumericLiteral() { - return nextToken() === 8; + return nextToken() === 8 /* NumericLiteral */; } function parseNonArrayType() { switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 139: - case 130: - case 134: + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 137 /* SymbolKeyword */: + case 122 /* BooleanKeyword */: + case 139 /* UndefinedKeyword */: + case 130 /* NeverKeyword */: + case 134 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); - case 39: + case 39 /* AsteriskToken */: return parseJSDocAllType(); - case 55: + case 55 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); - case 89: + case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 24: - return parseJSDocNodeWithType(274); - case 51: - return parseJSDocNodeWithType(271); - case 13: - case 9: - case 8: - case 101: - case 86: + case 51 /* ExclamationToken */: + return parseJSDocNodeWithType(275 /* JSDocNonNullableType */); + case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: return parseLiteralTypeNode(); - case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(true) : parseTypeReference(); - case 105: - case 95: + case 38 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + case 105 /* VoidKeyword */: + case 95 /* NullKeyword */: return parseTokenNode(); - case 99: { + case 99 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } - case 103: + case 103 /* TypeOfKeyword */: return parseTypeQuery(); - case 17: + case 17 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21: + case 21 /* OpenBracketToken */: return parseTupleType(); - case 19: + case 19 /* OpenParenToken */: return parseParenthesizedType(); default: return parseTypeReference(); @@ -12713,36 +15423,39 @@ var ts; } function isStartOfType(inStartOfParameter) { switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 105: - case 139: - case 95: - case 99: - case 103: - case 130: - case 17: - case 21: - case 27: - case 49: - case 48: - case 94: - case 9: - case 8: - case 101: - case 86: - case 134: - case 39: - case 55: - case 51: - case 24: + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 140 /* UniqueKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 99 /* ThisKeyword */: + case 103 /* TypeOfKeyword */: + case 130 /* NeverKeyword */: + case 17 /* OpenBraceToken */: + case 21 /* OpenBracketToken */: + case 27 /* LessThanToken */: + case 49 /* BarToken */: + case 48 /* AmpersandToken */: + case 94 /* NewKeyword */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 134 /* ObjectKeyword */: + case 39 /* AsteriskToken */: + case 55 /* QuestionToken */: + case 51 /* ExclamationToken */: + case 24 /* DotDotDotToken */: return true; - case 38: + case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); - case 19: + case 19 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); @@ -12750,60 +15463,74 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 || isStartOfParameter() || isStartOfType(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } - function parseJSDocPostfixTypeOrHigher() { + function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); - var kind = getKind(token()); - if (!kind) - return type; + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 58 /* EqualsToken */: + // only parse postfix = inside jsdoc, because it's ambiguous elsewhere + if (!(contextFlags & 1048576 /* JSDoc */)) { + return type; + } + type = createJSDocPostfixType(276 /* JSDocOptionalType */, type); + break; + case 51 /* ExclamationToken */: + type = createJSDocPostfixType(275 /* JSDocNonNullableType */, type); + break; + case 55 /* QuestionToken */: + type = createJSDocPostfixType(274 /* JSDocNullableType */, type); + break; + case 21 /* OpenBracketToken */: + parseExpected(21 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(172 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(165 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; + } + } + return type; + } + function createJSDocPostfixType(kind, type) { nextToken(); var postfix = createNode(kind, type.pos); postfix.type = type; return finishNode(postfix); - function getKind(tokenKind) { - switch (tokenKind) { - case 58: - return contextFlags & 1048576 ? 272 : undefined; - case 51: - return 271; - case 55: - return 270; - } - } - } - function parseArrayTypeOrHigher() { - var type = parseJSDocPostfixTypeOrHigher(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); - } - } - return type; } function parseTypeOperator(operator) { - var node = createNode(170); + var node = createNode(171 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseTypeOperatorOrHigher() { - switch (token()) { - case 127: - return parseTypeOperator(127); + var operator = token(); + switch (operator) { + case 127 /* KeyOfKeyword */: + case 140 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 24 /* DotDotDotToken */: { + var result = createNode(278 /* JSDocVariadicType */); + nextToken(); + result.type = parsePostfixTypeOrHigher(); + return finishNode(result); + } } - return parseArrayTypeOrHigher(); + return parsePostfixTypeOrHigher(); } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { parseOptional(operator); @@ -12820,26 +15547,28 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + return parseUnionOrIntersectionType(168 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + return parseUnionOrIntersectionType(167 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 27) { + if (token() === 27 /* LessThanToken */) { return true; } - return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { if (ts.isModifierKind(token())) { + // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 99) { + if (isIdentifier() || token() === 99 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 21 || token() === 17) { + if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -12848,17 +15577,26 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 || token() === 24) { + if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + // ( ) + // ( ... return true; } if (skipParameterStart()) { - if (token() === 56 || token() === 26 || - token() === 55 || token() === 58) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || + token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = return true; } - if (token() === 20) { + if (token() === 20 /* CloseParenToken */) { nextToken(); - if (token() === 36) { + if (token() === 36 /* EqualsGreaterThanToken */) { + // ( xxx ) => return true; } } @@ -12869,7 +15607,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); + var node = createNode(159 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -12880,48 +15618,51 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } } function parseType() { - return doOutsideOfContext(20480, parseTypeWorker); + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); + return parseFunctionOrConstructorType(161 /* FunctionType */); } - if (token() === 94) { - return parseFunctionOrConstructorType(161); + if (token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(162 /* ConstructorType */); } return parseUnionTypeOrHigher(); } function parseTypeAnnotation() { - return parseOptional(56) ? parseType() : undefined; + return parseOptional(56 /* ColonToken */) ? parseType() : undefined; } + // EXPRESSIONS function isStartOfLeftHandSideExpression() { switch (token()) { - case 99: - case 97: - case 95: - case 101: - case 86: - case 8: - case 9: - case 13: - case 14: - case 19: - case 21: - case 17: - case 89: - case 75: - case 94: - case 41: - case 63: - case 71: + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 19 /* OpenParenToken */: + case 21 /* OpenBracketToken */: + case 17 /* OpenBraceToken */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 94 /* NewKeyword */: + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + case 71 /* Identifier */: return true; - case 91: + case 91 /* ImportKeyword */: return lookAhead(nextTokenIsOpenParenOrLessThan); default: return isIdentifier(); @@ -12932,20 +15673,27 @@ var ts; return true; } switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 43: - case 44: - case 27: - case 121: - case 116: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 80 /* DeleteKeyword */: + case 103 /* TypeOfKeyword */: + case 105 /* VoidKeyword */: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 27 /* LessThanToken */: + case 121 /* AwaitKeyword */: + case 116 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. return true; default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. if (isBinaryOperator()) { return true; } @@ -12953,63 +15701,114 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 17 && - token() !== 89 && - token() !== 75 && - token() !== 57 && + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 17 /* OpenBraceToken */ && + token() !== 89 /* FunctionKeyword */ && + token() !== 75 /* ClassKeyword */ && + token() !== 57 /* AtToken */ && isStartOfExpression(); } function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; - while ((operatorToken = parseOptionalToken(26))) { + while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return expr; } - function parseInitializer(inParameter, requireEqualsToken) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - if (inParameter && requireEqualsToken) { - var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); - result.escapedText = "= not found"; - return result; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); + function parseInitializer() { + return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). if (isYieldExpression()) { return parseYieldExpression(); } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { return arrowExpression; } - var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 71 && token() === 36) { + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like > > = becoming >>= if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } + // It wasn't an assignment or a lambda. This is a conditional expression: return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116) { + if (token() === 116 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. if (inYieldContext()) { return true; } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); } return false; @@ -13019,198 +15818,301 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(197); + var node = createNode(198 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 39 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39); + (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. return finishNode(node); } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(187, asyncModifier.pos); + node = createNode(188 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(187, identifier.pos); + node = createNode(188 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(146, identifier.pos); + var parameter = createNode(147 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); - node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - node.body = parseArrowFunctionExpressionBody(!!asyncModifier); + node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); } function tryParseParenthesizedArrowFunctionExpression() { var triState = isParenthesizedArrowFunctionExpression(); - if (triState === 0) { + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. return undefined; } - var arrowFunction = triState === 1 - ? parseParenthesizedArrowFunctionExpressionHead(true) + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = ts.hasModifier(arrowFunction, 256); + var isAsync = ts.hasModifier(arrowFunction, 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 36 || lastToken === 17) + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); + return finishNode(arrowFunction); } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 19 || token() === 27 || token() === 120) { + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 36) { - return 1; + if (token() === 36 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; } - return 0; + // Definitely not a parenthesized arrow function. + return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120) { + if (token() === 120 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { - return 0; + return 0 /* False */; } - if (token() !== 19 && token() !== 27) { - return 0; + if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + return 0 /* False */; } } var first = token(); var second = nextToken(); - if (first === 19) { - if (second === 20) { + if (first === 19 /* OpenParenToken */) { + if (second === 20 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. var third = nextToken(); switch (third) { - case 36: - case 56: - case 17: - return 1; + case 36 /* EqualsGreaterThanToken */: + case 56 /* ColonToken */: + case 17 /* OpenBraceToken */: + return 1 /* True */; default: - return 0; - } - } - if (second === 21 || second === 17) { - return 2; - } - if (second === 24) { - return 1; - } + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 24 /* DotDotDotToken */) { + return 1 /* True */; + } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. if (!isIdentifier()) { - return 0; - } - if (nextToken() === 56) { - return 1; + return 0 /* False */; + } + switch (nextToken()) { + case 56 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 55 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 26 /* CommaToken */: + case 58 /* EqualsToken */: + case 20 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; } - return 2; + // It is definitely not an arrow function + return 0 /* False */; } else { - ts.Debug.assert(first === 27); + ts.Debug.assert(first === 27 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. if (!isIdentifier()) { - return 0; + return 0 /* False */; } - if (sourceFile.languageVariant === 1) { + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { var isArrowFunctionInJsx = lookAhead(function () { var third = nextToken(); - if (third === 85) { + if (third === 85 /* ExtendsKeyword */) { var fourth = nextToken(); switch (fourth) { - case 58: - case 29: + case 58 /* EqualsToken */: + case 29 /* GreaterThanToken */: return false; default: return true; } } - else if (third === 26) { + else if (third === 26 /* CommaToken */) { return true; } return false; }); if (isArrowFunctionInJsx) { - return 1; + return 1 /* True */; } - return 0; + return 0 /* False */; } - return 2; + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; } } function parsePossibleParenthesizedArrowFunctionExpressionHead() { - return parseParenthesizedArrowFunctionExpressionHead(false); + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 120) { - if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 120 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); - var expr = parseBinaryExpressionOrHigher(0); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); } } return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 120) { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 120 /* AsyncKeyword */) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 36) { - return 0; + // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + return 0 /* False */; } - var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { - return 1; + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + return 1 /* True */; } } - return 0; + return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); + var node = createNodeWithJSDoc(188 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); - var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); + // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { return undefined; } - if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || - ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17) { - return parseFunctionBlock(isAsync ? 2 : 0); + if (token() === 17 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } - if (token() !== 25 && - token() !== 89 && - token() !== 75 && + if (token() !== 25 /* SemicolonToken */ && + token() !== 89 /* FunctionKeyword */ && + token() !== 75 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { - return parseFunctionBlock(16 | (isAsync ? 2 : 0)); + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); } return isAsync ? doInAwaitContext(parseAssignmentExpressionOrHigher) : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); } function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(55); + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(55 /* QuestionToken */); if (!questionToken) { return leftOperand; } - var node = createNode(195, leftOperand.pos); + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(196 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); + node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -13219,22 +16121,50 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 || t === 142; + return t === 92 /* InKeyword */ || t === 143 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 40 ? + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 92 && inDisallowInContext()) { + if (token() === 92 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 118) { + if (token() === 118 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' if (scanner.hasPrecedingLineBreak()) { break; } @@ -13250,117 +16180,147 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 92) { + if (inDisallowInContext() && token() === 92 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { switch (token()) { - case 54: + case 54 /* BarBarToken */: return 1; - case 53: + case 53 /* AmpersandAmpersandToken */: return 2; - case 49: + case 49 /* BarToken */: return 3; - case 50: + case 50 /* CaretToken */: return 4; - case 48: + case 48 /* AmpersandToken */: return 5; - case 32: - case 33: - case 34: - case 35: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: return 7; - case 45: - case 46: - case 47: + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: return 8; - case 37: - case 38: + case 37 /* PlusToken */: + case 38 /* MinusToken */: return 9; - case 39: - case 41: - case 42: + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: return 10; - case 40: + case 40 /* AsteriskAsteriskToken */: return 11; } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); + var node = createNode(195 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(202, left.pos); + var node = createNode(203 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(192); + var node = createNode(193 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(188); + var node = createNode(189 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(189); + var node = createNode(190 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(190); + var node = createNode(191 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function isAwaitExpression() { - if (token() === 121) { + if (token() === 121 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } + // here we are using similar heuristics as 'isYieldExpression' return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); } return false; } function parseAwaitExpression() { - var node = createNode(191); + var node = createNode(192 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 ? + return token() === 40 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : updateExpression; } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40) { + if (token() === 40 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { + if (simpleUnaryExpression.kind === 185 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -13369,63 +16329,108 @@ var ts; } return simpleUnaryExpression; } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ function parseSimpleUnaryExpression() { switch (token()) { - case 37: - case 38: - case 52: - case 51: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: return parsePrefixUnaryExpression(); - case 80: + case 80 /* DeleteKeyword */: return parseDeleteExpression(); - case 103: + case 103 /* TypeOfKeyword */: return parseTypeOfExpression(); - case 105: + case 105 /* VoidKeyword */: return parseVoidExpression(); - case 27: + case 27 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression return parseTypeAssertion(); - case 121: + case 121 /* AwaitKeyword */: if (isAwaitExpression()) { return parseAwaitExpression(); } + // falls through default: return parseUpdateExpression(); } } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 121: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 80 /* DeleteKeyword */: + case 103 /* TypeOfKeyword */: + case 105 /* VoidKeyword */: + case 121 /* AwaitKeyword */: return false; - case 27: - if (sourceFile.languageVariant !== 1) { + case 27 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { return false; } + // We are in JSX context and the token is part of JSXElement. + // falls through default: return true; } } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ function parseUpdateExpression() { - if (token() === 43 || token() === 44) { - var node = createNode(192); + if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { + var node = createNode(193 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); + if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(194 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -13434,70 +16439,174 @@ var ts; return expression; } function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - sourceFile.flags |= 524288; + if (token() === 91 /* ImportKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } else { - expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. return parseCallExpressionRest(expression); } function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation) Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. var expression = parsePrimaryExpression(); return parseMemberExpressionRest(expression); } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 19 || token() === 23 || token() === 21) { + if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { return expression; } - var node = createNode(179, expression.pos); + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(180 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(true); + parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } function tagNamesAreEquivalent(lhs, rhs) { if (lhs.kind !== rhs.kind) { return false; } - if (lhs.kind === 71) { + if (lhs.kind === 71 /* Identifier */) { return lhs.escapedText === rhs.escapedText; } - if (lhs.kind === 99) { + if (lhs.kind === 99 /* ThisKeyword */) { return true; } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); + if (opening.kind === 252 /* JsxOpeningElement */) { + var node = createNode(250 /* JsxElement */, opening.pos); node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); + node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } + else if (opening.kind === 255 /* JsxOpeningFragment */) { + var node = createNode(254 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } else { - ts.Debug.assert(opening.kind === 250); + ts.Debug.assert(opening.kind === 251 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements result = opening; } - if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 27 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); + var badNode = createNode(195 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26, false, undefined); + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -13505,38 +16614,47 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); - node.containsOnlyWhiteSpaces = currentToken === 11; + var node = createNode(10 /* JsxText */); + node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token()) { - case 10: - case 11: + case 10 /* JsxText */: + case 11 /* JsxTextAllWhiteSpaces */: return parseJsxText(); - case 17: - return parseJsxExpression(false); - case 27: - return parseJsxElementOrSelfClosingElement(false); + case 17 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 27 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); } ts.Debug.fail("Unknown JSX child kind " + token()); } - function parseJsxChildren(openingTagName) { + function parseJsxChildren(openingTag) { var list = []; var listPos = getNodePos(); var saveParsingContext = parsingContext; - parsingContext |= 1 << 14; + parsingContext |= 1 << 14 /* JsxChildren */; while (true) { currentToken = scanner.reScanJsxToken(); - if (token() === 28) { + if (token() === 28 /* LessThanSlashToken */) { + // Closing tag break; } - else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + else if (token() === 1 /* EndOfFileToken */) { + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + var openingTagName = openingTag.tagName; + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + } break; } - else if (token() === 7) { + else if (token() === 7 /* ConflictMarkerTrivia */) { break; } var child = parseJsxChild(); @@ -13548,30 +16666,38 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(254); - jsxAttributes.properties = parseList(13, parseJsxAttribute); + var jsxAttributes = createNode(258 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); - parseExpected(27); + parseExpected(27 /* LessThanToken */); + if (token() === 29 /* GreaterThanToken */) { + parseExpected(29 /* GreaterThanToken */); + var node_1 = createNode(255 /* JsxOpeningFragment */, fullStart); + return finishNode(node_1); + } var tagName = parseJsxElementName(); var attributes = parseJsxAttributes(); var node; - if (token() === 29) { - node = createNode(251, fullStart); + if (token() === 29 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(252 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { - parseExpected(41); + parseExpected(41 /* SlashToken */); if (inExpressionContext) { - parseExpected(29); + parseExpected(29 /* GreaterThanToken */); } else { - parseExpected(29, undefined, false); + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(250, fullStart); + node = createNode(251 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -13579,115 +16705,139 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 99 ? + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 99 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); - while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); + while (parseOptional(23 /* DotToken */)) { + var propertyAccess = createNode(180 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); } return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(256); - parseExpected(17); - if (token() !== 18) { - node.dotDotDotToken = parseOptionalToken(24); + var node = createNode(260 /* JsxExpression */); + parseExpected(17 /* OpenBraceToken */); + if (token() !== 18 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { - parseExpected(18); + parseExpected(18 /* CloseBraceToken */); } else { - parseExpected(18, undefined, false); + parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseJsxAttribute() { - if (token() === 17) { + if (token() === 17 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(253); + var node = createNode(257 /* JsxAttribute */); node.name = parseIdentifierName(); - if (token() === 58) { + if (token() === 58 /* EqualsToken */) { switch (scanJsxAttributeValue()) { - case 9: + case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; default: - node.initializer = parseJsxExpression(true); + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); break; } } return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(255); - parseExpected(17); - parseExpected(24); + var node = createNode(259 /* JsxSpreadAttribute */); + parseExpected(17 /* OpenBraceToken */); + parseExpected(24 /* DotDotDotToken */); node.expression = parseExpression(); - parseExpected(18); + parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); - parseExpected(28); + var node = createNode(253 /* JsxClosingElement */); + parseExpected(28 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { - parseExpected(29); + parseExpected(29 /* GreaterThanToken */); } else { - parseExpected(29, undefined, false); + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(256 /* JsxClosingFragment */); + parseExpected(28 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + var unexpectedTagName = parseJsxElementName(); + parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(184); - parseExpected(27); + var node = createNode(185 /* TypeAssertionExpression */); + parseExpected(27 /* LessThanToken */); node.type = parseType(); - parseExpected(29); + parseExpected(29 /* GreaterThanToken */); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseMemberExpressionRest(expression) { while (true) { - var dotToken = parseOptionalToken(23); + var dotToken = parseOptionalToken(23 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } - if (token() === 51 && !scanner.hasPrecedingLineBreak()) { + if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(203, expression.pos); + var nonNullExpression = createNode(204 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } - if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { + var indexedAccess = createNode(181 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - if (token() !== 22) { + // It's not uncommon for a user to write: "new Type[]". + // Check for that common pattern and report a better error message. + if (token() !== 22 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { + if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } - parseExpected(22); + parseExpected(22 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } - if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); + if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { + var tagExpression = createNode(184 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 13 + tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -13699,20 +16849,24 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 27) { + if (token() === 27 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); continue; } - else if (token() === 19) { - var callExpr = createNode(181, expression.pos); + else if (token() === 19 /* OpenParenToken */) { + var callExpr = createNode(182 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -13722,234 +16876,247 @@ var ts; } } function parseArgumentList() { - parseExpected(19); - var result = parseDelimitedList(11, parseArgumentExpression); - parseExpected(20); + parseExpected(19 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(20 /* CloseParenToken */); return result; } function parseTypeArgumentsInExpression() { - if (!parseOptional(27)) { + if (!parseOptional(27 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(19, parseType); - if (!parseExpected(29)) { + var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + if (!parseExpected(29 /* GreaterThanToken */)) { + // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : undefined; } function canFollowTypeArgumentsInExpression() { switch (token()) { - case 19: - case 23: - case 20: - case 22: - case 56: - case 25: - case 55: - case 32: - case 34: - case 33: - case 35: - case 53: - case 54: - case 50: - case 48: - case 49: - case 18: - case 1: + case 19 /* OpenParenToken */: // foo( + // this case are the only case where this token can legally follow a type argument + // list. So we definitely want to treat this as a type arg list. + case 23 /* DotToken */: // foo. + case 20 /* CloseParenToken */: // foo) + case 22 /* CloseBracketToken */: // foo] + case 56 /* ColonToken */: // foo: + case 25 /* SemicolonToken */: // foo; + case 55 /* QuestionToken */: // foo? + case 32 /* EqualsEqualsToken */: // foo == + case 34 /* EqualsEqualsEqualsToken */: // foo === + case 33 /* ExclamationEqualsToken */: // foo != + case 35 /* ExclamationEqualsEqualsToken */: // foo !== + case 53 /* AmpersandAmpersandToken */: // foo && + case 54 /* BarBarToken */: // foo || + case 50 /* CaretToken */: // foo ^ + case 48 /* AmpersandToken */: // foo & + case 49 /* BarToken */: // foo | + case 18 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */:// foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. return true; - case 26: - case 17: + case 26 /* CommaToken */: // foo, + case 17 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. default: + // Anything else treat as an expression. return false; } } function parsePrimaryExpression() { switch (token()) { - case 8: - case 9: - case 13: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: return parseLiteralNode(); - case 99: - case 97: - case 95: - case 101: - case 86: + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: return parseTokenNode(); - case 19: + case 19 /* OpenParenToken */: return parseParenthesizedExpression(); - case 21: + case 21 /* OpenBracketToken */: return parseArrayLiteralExpression(); - case 17: + case 17 /* OpenBraceToken */: return parseObjectLiteralExpression(); - case 120: + case 120 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { break; } return parseFunctionExpression(); - case 75: + case 75 /* ClassKeyword */: return parseClassExpression(); - case 89: + case 89 /* FunctionKeyword */: return parseFunctionExpression(); - case 94: + case 94 /* NewKeyword */: return parseNewExpression(); - case 41: - case 63: - if (reScanSlashToken() === 12) { + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { return parseLiteralNode(); } break; - case 14: + case 14 /* TemplateHead */: return parseTemplateExpression(); } return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(185); - parseExpected(19); + var node = createNodeWithJSDoc(186 /* ParenthesizedExpression */); + parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20); - return addJSDocComment(finishNode(node)); + parseExpected(20 /* CloseParenToken */); + return finishNode(node); } function parseSpreadElement() { - var node = createNode(198); - parseExpected(24); + var node = createNode(199 /* SpreadElement */); + parseExpected(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : + return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 26 /* CommaToken */ ? createNode(201 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(177); - parseExpected(21); + var node = createNode(178 /* ArrayLiteralExpression */); + parseExpected(21 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } - node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(22); + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(22 /* CloseBracketToken */); return finishNode(node); } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(24 /* DotDotDotToken */)) { + node.kind = 267 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 154 /* GetAccessor */); } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 155 /* SetAccessor */); } - var asteriskToken = parseOptionalToken(39); + var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); - } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); + node.name = parsePropertyName(); + // Disallowing of optional property assignments happens in the grammar checker. + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(58); + node.kind = 266 /* ShorthandPropertyAssignment */; + var equalsToken = parseOptionalToken(58 /* EqualsToken */); if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; - parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); + node.kind = 265 /* PropertyAssignment */; + parseExpected(56 /* ColonToken */); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } + return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(178); - parseExpected(17); + var node = createNode(179 /* ObjectLiteralExpression */); + parseExpected(17 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } - node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(18); + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var node = createNode(186); + var node = createNodeWithJSDoc(187 /* FunctionExpression */); node.modifiers = parseModifiers(); - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - var isGenerator = node.asteriskToken ? 1 : 0; - var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + parseExpected(89 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(56, isGenerator | isAsync, node); + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { var fullStart = scanner.getStartPos(); - parseExpected(94); - if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); - } - var node = createNode(182, fullStart); + parseExpected(94 /* NewKeyword */); + if (parseOptional(23 /* DotToken */)) { + var node_2 = createNode(205 /* MetaProperty */, fullStart); + node_2.keywordToken = 94 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); + } + var node = createNode(183 /* NewExpression */, fullStart); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 19) { + if (node.typeArguments || token() === 19 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); } + // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); - if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { + var node = createNode(208 /* Block */); + if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } - node.statements = parseList(1, parseStatement); - parseExpected(18); + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(18 /* CloseBraceToken */); } else { node.statements = createMissingList(); @@ -13958,98 +17125,104 @@ var ts; } function parseFunctionBlock(flags, diagnosticMessage) { var savedYieldContext = inYieldContext(); - setYieldContext(!!(flags & 1)); + setYieldContext(!!(flags & 1 /* Yield */)); var savedAwaitContext = inAwaitContext(); - setAwaitContext(!!(flags & 2)); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var block = parseBlock(!!(flags & 16), diagnosticMessage); + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return block; } function parseEmptyStatement() { - var node = createNode(209); - parseExpected(25); + var node = createNode(210 /* EmptyStatement */); + parseExpected(25 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(211); - parseExpected(90); - parseExpected(19); + var node = createNode(212 /* IfStatement */); + parseExpected(90 /* IfKeyword */); + parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82) ? parseStatement() : undefined; + node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; return finishNode(node); } function parseDoStatement() { - var node = createNode(212); - parseExpected(81); + var node = createNode(213 /* DoStatement */); + parseExpected(81 /* DoKeyword */); node.statement = parseStatement(); - parseExpected(106); - parseExpected(19); + parseExpected(106 /* WhileKeyword */); + parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20); - parseOptional(25); + parseExpected(20 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(25 /* SemicolonToken */); return finishNode(node); } function parseWhileStatement() { - var node = createNode(213); - parseExpected(106); - parseExpected(19); + var node = createNode(214 /* WhileStatement */); + parseExpected(106 /* WhileKeyword */); + parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); node.statement = parseStatement(); return finishNode(node); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); - parseExpected(88); - var awaitToken = parseOptionalToken(121); - parseExpected(19); + parseExpected(88 /* ForKeyword */); + var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); + parseExpected(19 /* OpenParenToken */); var initializer = undefined; - if (token() !== 25) { - if (token() === 104 || token() === 110 || token() === 76) { - initializer = parseVariableDeclarationList(true); + if (token() !== 25 /* SemicolonToken */) { + if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { initializer = disallowInAnd(parseExpression); } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); + if (awaitToken ? parseExpected(143 /* OfKeyword */) : parseOptional(143 /* OfKeyword */)) { + var forOfStatement = createNode(217 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } - else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); + else if (parseOptional(92 /* InKeyword */)) { + var forInStatement = createNode(216 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(214, pos); + var forStatement = createNode(215 /* ForStatement */, pos); forStatement.initializer = initializer; - parseExpected(25); - if (token() !== 25 && token() !== 20) { + parseExpected(25 /* SemicolonToken */); + if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } - parseExpected(25); - if (token() !== 20) { + parseExpected(25 /* SemicolonToken */); + if (token() !== 20 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } - parseExpected(20); + parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forStatement; } forOrForInOrForOfStatement.statement = parseStatement(); @@ -14057,7 +17230,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); + parseExpected(kind === 219 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -14065,8 +17238,8 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(219); - parseExpected(96); + var node = createNode(220 /* ReturnStatement */); + parseExpected(96 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); } @@ -14074,97 +17247,110 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(220); - parseExpected(107); - parseExpected(19); + var node = createNode(221 /* WithStatement */); + parseExpected(107 /* WithKeyword */); + parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); + parseExpected(20 /* CloseParenToken */); + node.statement = doInsideOfContext(4194304 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(257); - parseExpected(73); + var node = createNode(261 /* CaseClause */); + parseExpected(73 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); - parseExpected(56); - node.statements = parseList(3, parseStatement); + parseExpected(56 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(258); - parseExpected(79); - parseExpected(56); - node.statements = parseList(3, parseStatement); + var node = createNode(262 /* DefaultClause */); + parseExpected(79 /* DefaultKeyword */); + parseExpected(56 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 73 ? parseCaseClause() : parseDefaultClause(); + return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(221); - parseExpected(98); - parseExpected(19); + var node = createNode(222 /* SwitchStatement */); + parseExpected(98 /* SwitchKeyword */); + parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); - parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); - parseExpected(17); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); - parseExpected(18); + parseExpected(20 /* CloseParenToken */); + var caseBlock = createNode(236 /* CaseBlock */); + parseExpected(17 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(18 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); } function parseThrowStatement() { - var node = createNode(223); - parseExpected(100); + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(224 /* ThrowStatement */); + parseExpected(100 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } + // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(224); - parseExpected(102); - node.tryBlock = parseBlock(false); - node.catchClause = token() === 74 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 87) { - parseExpected(87); - node.finallyBlock = parseBlock(false); + var node = createNode(225 /* TryStatement */); + parseExpected(102 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 87 /* FinallyKeyword */) { + parseExpected(87 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(260); - parseExpected(74); - if (parseOptional(19)) { + var result = createNode(264 /* CatchClause */); + parseExpected(74 /* CatchKeyword */); + if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); } else { + // Keep shape of node to avoid degrading performance. result.variableDeclaration = undefined; } - result.block = parseBlock(false); + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(225); - parseExpected(78); + var node = createNode(226 /* DebuggerStatement */); + parseExpected(78 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); - if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); + if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { + node.kind = 223 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); } else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; + node.kind = 211 /* ExpressionStatement */; + node.expression = expression; parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); } + return finishNode(node); } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); @@ -14172,60 +17358,82 @@ var ts; } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === 75 && !scanner.hasPrecedingLineBreak(); + return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 89 && !scanner.hasPrecedingLineBreak(); + return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { switch (token()) { - case 104: - case 110: - case 76: - case 89: - case 75: - case 83: + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: return true; - case 109: - case 138: + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 109 /* InterfaceKeyword */: + case 138 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); - case 128: - case 129: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117: - case 120: - case 124: - case 112: - case 113: - case 114: - case 131: + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 124 /* DeclareKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 131 /* ReadonlyKeyword */: nextToken(); + // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; - case 141: + case 142 /* GlobalKeyword */: nextToken(); - return token() === 17 || token() === 71 || token() === 84; - case 91: + return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; + case 91 /* ImportKeyword */: nextToken(); - return token() === 9 || token() === 39 || - token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); - case 84: + return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 84 /* ExportKeyword */: nextToken(); - if (token() === 58 || token() === 39 || - token() === 17 || token() === 79 || - token() === 118) { + if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || + token() === 118 /* AsKeyword */) { return true; } continue; - case 115: + case 115 /* StaticKeyword */: nextToken(); continue; default: @@ -14238,47 +17446,52 @@ var ts; } function isStartOfStatement() { switch (token()) { - case 57: - case 25: - case 17: - case 104: - case 110: - case 89: - case 75: - case 83: - case 90: - case 81: - case 106: - case 88: - case 77: - case 72: - case 96: - case 107: - case 98: - case 100: - case 102: - case 78: - case 74: - case 87: + case 57 /* AtToken */: + case 25 /* SemicolonToken */: + case 17 /* OpenBraceToken */: + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: + case 90 /* IfKeyword */: + case 81 /* DoKeyword */: + case 106 /* WhileKeyword */: + case 88 /* ForKeyword */: + case 77 /* ContinueKeyword */: + case 72 /* BreakKeyword */: + case 96 /* ReturnKeyword */: + case 107 /* WithKeyword */: + case 98 /* SwitchKeyword */: + case 100 /* ThrowKeyword */: + case 102 /* TryKeyword */: + case 78 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: return true; - case 91: + case 91 /* ImportKeyword */: return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); - case 76: - case 84: + case 76 /* ConstKeyword */: + case 84 /* ExportKeyword */: return isStartOfDeclaration(); - case 120: - case 124: - case 109: - case 128: - case 129: - case 138: - case 141: + case 120 /* AsyncKeyword */: + case 124 /* DeclareKeyword */: + case 109 /* InterfaceKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + case 138 /* TypeKeyword */: + case 142 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement return true; - case 114: - case 112: - case 113: - case 115: - case 131: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -14286,73 +17499,76 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 17 || token() === 21; + return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; } function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token()) { - case 25: + case 25 /* SemicolonToken */: return parseEmptyStatement(); - case 17: - return parseBlock(false); - case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 110: + case 17 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 104 /* VarKeyword */: + return parseVariableStatement(createNodeWithJSDoc(227 /* VariableDeclaration */)); + case 110 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227 /* VariableDeclaration */)); } break; - case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 90: + case 89 /* FunctionKeyword */: + return parseFunctionDeclaration(createNodeWithJSDoc(229 /* FunctionDeclaration */)); + case 75 /* ClassKeyword */: + return parseClassDeclaration(createNodeWithJSDoc(230 /* ClassDeclaration */)); + case 90 /* IfKeyword */: return parseIfStatement(); - case 81: + case 81 /* DoKeyword */: return parseDoStatement(); - case 106: + case 106 /* WhileKeyword */: return parseWhileStatement(); - case 88: + case 88 /* ForKeyword */: return parseForOrForInOrForOfStatement(); - case 77: - return parseBreakOrContinueStatement(217); - case 72: - return parseBreakOrContinueStatement(218); - case 96: + case 77 /* ContinueKeyword */: + return parseBreakOrContinueStatement(218 /* ContinueStatement */); + case 72 /* BreakKeyword */: + return parseBreakOrContinueStatement(219 /* BreakStatement */); + case 96 /* ReturnKeyword */: return parseReturnStatement(); - case 107: + case 107 /* WithKeyword */: return parseWithStatement(); - case 98: + case 98 /* SwitchKeyword */: return parseSwitchStatement(); - case 100: + case 100 /* ThrowKeyword */: return parseThrowStatement(); - case 102: - case 74: - case 87: + case 102 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: return parseTryStatement(); - case 78: + case 78 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 57: + case 57 /* AtToken */: return parseDeclaration(); - case 120: - case 109: - case 138: - case 128: - case 129: - case 124: - case 76: - case 83: - case 84: - case 91: - case 112: - case 113: - case 114: - case 117: - case 115: - case 131: - case 141: + case 120 /* AsyncKeyword */: + case 109 /* InterfaceKeyword */: + case 138 /* TypeKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 83 /* EnumKeyword */: + case 84 /* ExportKeyword */: + case 91 /* ImportKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + case 142 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -14360,239 +17576,266 @@ var ts; } return parseExpressionOrLabeledStatement(); } + function isDeclareModifier(modifier) { + return modifier.kind === 124 /* DeclareKeyword */; + } function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 2097152 /* Ambient */; + } + return doInsideOfContext(2097152 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { switch (token()) { - case 104: - case 110: - case 76: - return parseVariableStatement(fullStart, decorators, modifiers); - case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: - case 128: - case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 84: + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + return parseVariableStatement(node); + case 89 /* FunctionKeyword */: + return parseFunctionDeclaration(node); + case 75 /* ClassKeyword */: + return parseClassDeclaration(node); + case 109 /* InterfaceKeyword */: + return parseInterfaceDeclaration(node); + case 138 /* TypeKeyword */: + return parseTypeAliasDeclaration(node); + case 83 /* EnumKeyword */: + return parseEnumDeclaration(node); + case 142 /* GlobalKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + return parseModuleDeclaration(node); + case 91 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(node); + case 84 /* ExportKeyword */: nextToken(); switch (token()) { - case 79: - case 58: - return parseExportAssignment(fullStart, decorators, modifiers); - case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + case 79 /* DefaultKeyword */: + case 58 /* EqualsToken */: + return parseExportAssignment(node); + case 118 /* AsKeyword */: + return parseNamespaceExportDeclaration(node); default: - return parseExportDeclaration(fullStart, decorators, modifiers); + return parseExportDeclaration(node); } default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); + if (node.decorators || node.modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var missing = createMissingNode(248 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); } } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 17 && canParseSemicolon()) { + if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(flags, diagnosticMessage); } + // DECLARATIONS function parseArrayBindingElement() { - if (token() === 26) { - return createNode(200); + if (token() === 26 /* CommaToken */) { + return createNode(201 /* OmittedExpression */); } - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); + var node = createNode(177 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); + var node = createNode(177 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56) { + if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { node.name = propertyName; } else { - parseExpected(56); + parseExpected(56 /* ColonToken */); node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(174); - parseExpected(17); - node.elements = parseDelimitedList(9, parseObjectBindingElement); - parseExpected(18); + var node = createNode(175 /* ObjectBindingPattern */); + parseExpected(17 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(175); - parseExpected(21); - node.elements = parseDelimitedList(10, parseArrayBindingElement); - parseExpected(22); + var node = createNode(176 /* ArrayBindingPattern */); + parseExpected(21 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(22 /* CloseBracketToken */); return finishNode(node); } function isIdentifierOrPattern() { - return token() === 17 || token() === 21 || isIdentifier(); + return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 21) { + if (token() === 21 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 17) { + if (token() === 17 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); } - function parseVariableDeclaration() { - var node = createNode(226); + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(227 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 71 /* Identifier */ && + token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); + var node = createNode(228 /* VariableDeclarationList */); switch (token()) { - case 104: + case 104 /* VarKeyword */: break; - case 110: - node.flags |= 1; + case 110 /* LetKeyword */: + node.flags |= 1 /* Let */; break; - case 76: - node.flags |= 2; + case 76 /* ConstKeyword */: + node.flags |= 2 /* Const */; break; default: ts.Debug.fail(); } nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 143 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(node); } function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20; + return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.declarationList = parseVariableDeclarationList(false); + function parseVariableStatement(node) { + node.kind = 209 /* VariableStatement */; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); - var isGenerator = node.asteriskToken ? 1 : 0; - var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, node); + function parseFunctionDeclaration(node) { + node.kind = 229 /* FunctionDeclaration */; + parseExpected(89 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(123); - fillSignature(56, 0, node); - node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + function parseConstructorDeclaration(node) { + node.kind = 153 /* Constructor */; + parseExpected(123 /* ConstructorKeyword */); + fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return finishNode(node); } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; - var isGenerator = asteriskToken ? 1 : 0; - var isAsync = ts.hasModifier(method, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); - parseSemicolon(); - return addJSDocComment(finishNode(property)); + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 152 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + function parsePropertyDeclaration(node) { + node.kind = 150 /* PropertyDeclaration */; + if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); } + node.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); + parseSemicolon(); + return finishNode(node); } - function parseNonParameterInitializer() { - return parseInitializer(false); + function parsePropertyOrMethodDeclaration(node) { + var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); + } + return parsePropertyDeclaration(node); } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseAccessorDeclaration(node, kind) { + node.kind = kind; node.name = parsePropertyName(); - fillSignature(56, 0, node); - node.body = parseFunctionBlockOrSemicolon(0); - return addJSDocComment(finishNode(node)); + fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return finishNode(node); } function isClassMemberModifier(idToken) { switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 131: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: return true; default: return false; @@ -14600,38 +17843,57 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 57) { + if (token() === 57 /* AtToken */) { return true; } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. while (ts.isModifierKind(token())) { idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token() === 39) { + if (token() === 39 /* AsteriskToken */) { return true; } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. if (isLiteralPropertyName()) { idToken = token(); nextToken(); } - if (token() === 21) { + // Index signatures and computed properties are class members; we can parse. + if (token() === 21 /* OpenBracketToken */) { return true; } + // If we were able to get any potential identifier... if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 135 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { return true; } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. switch (token()) { - case 19: - case 27: - case 56: - case 58: - case 55: + case 19 /* OpenParenToken */: // Method declaration + case 27 /* LessThanToken */: // Generic Method declaration + case 56 /* ColonToken */: // Type Annotation for declaration + case 58 /* EqualsToken */: // Initializer for declaration + case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on. return true; default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) return canParseSemicolon(); } } @@ -14642,23 +17904,32 @@ var ts; var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); - if (!parseOptional(57)) { + if (!parseOptional(57 /* AtToken */)) { break; } - var decorator = createNode(147, decoratorStart); + var decorator = createNode(148 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); } return list && createNodeArray(list, listPos); } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ function parseModifiers(permitInvalidConstAsModifier) { var list; var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); - if (token() === 76 && permitInvalidConstAsModifier) { + if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -14675,7 +17946,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120) { + if (token() === 120 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -14685,179 +17956,192 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 25) { - var result = createNode(206); + if (token() === 25 /* SemicolonToken */) { + var result = createNode(207 /* SemicolonClassElement */); nextToken(); return finishNode(result); } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 154 /* GetAccessor */); + } + if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 155 /* SetAccessor */); } - if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); + if (token() === 123 /* ConstructorKeyword */) { + return parseConstructorDeclaration(node); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + return parseIndexSignatureDeclaration(node); } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 39 || - token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); - } - if (decorators || modifiers) { - var name_7 = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); - } + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 39 /* AsteriskToken */ || + token() === 21 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(node); + } + if (node.decorators || node.modifiers) { + // treat this as a property declaration with a missing name. + node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 200 /* ClassExpression */); } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 230 /* ClassDeclaration */); } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(75); + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; + parseExpected(75 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17)) { + if (parseExpected(17 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); - parseExpected(18); + parseExpected(18 /* CloseBraceToken */); } else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases return isIdentifier() && !isImplementsClause() ? parseIdentifier() : undefined; } function isImplementsClause() { - return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(21, parseHeritageClause); + return parseList(21 /* HeritageClauses */, parseHeritageClause); } return undefined; } function parseHeritageClause() { var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(259); + if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { + var node = createNode(263 /* HeritageClause */); node.token = tok; nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(201); + var node = createNode(202 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } + node.typeArguments = tryParseTypeArguments(); return finishNode(node); } + function tryParseTypeArguments() { + return token() === 27 /* LessThanToken */ + ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + : undefined; + } function isHeritageClause() { - return token() === 85 || token() === 108; + return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; } function parseClassMembers() { - return parseList(5, parseClassElement); + return parseList(5 /* ClassMembers */, parseClassElement); } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(109); + function parseInterfaceDeclaration(node) { + node.kind = 231 /* InterfaceDeclaration */; + parseExpected(109 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(138); + function parseTypeAliasDeclaration(node) { + node.kind = 232 /* TypeAliasDeclaration */; + parseExpected(138 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - parseExpected(58); + parseExpected(58 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); + var node = createNodeWithJSDoc(268 /* EnumMember */); node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(83); + function parseEnumDeclaration(node) { + node.kind = 233 /* EnumDeclaration */; + parseExpected(83 /* EnumKeyword */); node.name = parseIdentifier(); - if (parseExpected(17)) { - node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(18); + if (parseExpected(17 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(18 /* CloseBraceToken */); } else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); - if (parseExpected(17)) { - node.statements = parseList(1, parseStatement); - parseExpected(18); + var node = createNode(235 /* ModuleBlock */); + if (parseExpected(17 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(18 /* CloseBraceToken */); } else { node.statements = createMissingList(); } return finishNode(node); } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); - var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 234 /* ModuleDeclaration */; + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; node.flags |= flags; node.name = parseIdentifier(); - node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + node.body = parseOptional(23 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 234 /* ModuleDeclaration */; + if (token() === 142 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); - node.flags |= 512; + node.flags |= 512 /* GlobalAugmentation */; } else { node.name = parseLiteralNode(); node.name.text = internIdentifier(node.name.text); } - if (token() === 17) { + if (token() === 17 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -14865,136 +18149,163 @@ var ts; } return finishNode(node); } - function parseModuleDeclaration(fullStart, decorators, modifiers) { + function parseModuleDeclaration(node) { var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + if (token() === 142 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(node); } - else if (parseOptional(129)) { - flags |= 16; + else if (parseOptional(129 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; } else { - parseExpected(128); - if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + parseExpected(128 /* ModuleKeyword */); + if (token() === 9 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(node); } } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { - return token() === 132 && + return token() === 132 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { - return nextToken() === 19; + return nextToken() === 19 /* OpenParenToken */; } function nextTokenIsSlash() { - return nextToken() === 41; - } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; - parseExpected(118); - parseExpected(129); - exportDeclaration.name = parseIdentifier(); + return nextToken() === 41 /* SlashToken */; + } + function parseNamespaceExportDeclaration(node) { + node.kind = 237 /* NamespaceExportDeclaration */; + parseExpected(118 /* AsKeyword */); + parseExpected(129 /* NamespaceKeyword */); + node.name = parseIdentifier(); parseSemicolon(); - return finishNode(exportDeclaration); + return finishNode(node); } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(91); + function parseImportDeclarationOrImportEqualsDeclaration(node) { + parseExpected(91 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); - } - } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; - if (identifier || - token() === 39 || - token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); - } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); + if (token() !== 26 /* CommaToken */ && token() !== 141 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); + } + } + // Import statement + node.kind = 239 /* ImportDeclaration */; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || // import id + token() === 39 /* AsteriskToken */ || // import * + token() === 17 /* OpenBraceToken */) { + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(141 /* FromKeyword */); + } + node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); - return finishNode(importDeclaration); - } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; - parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); + return finishNode(node); + } + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 238 /* ImportEqualsDeclaration */; + node.name = identifier; + parseExpected(58 /* EqualsToken */); + node.moduleReference = parseModuleReference(); parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); + return finishNode(node); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(240 /* ImportClause */, fullStart); if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding importClause.name = identifier; } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports if (!importClause.name || - parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + parseOptional(26 /* CommaToken */)) { + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(242 /* NamedImports */); } return finishNode(importClause); } function parseModuleReference() { return isExternalModuleReference() ? parseExternalModuleReference() - : parseEntityName(false); + : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(248); - parseExpected(132); - parseExpected(19); + var node = createNode(249 /* ExternalModuleReference */); + parseExpected(132 /* RequireKeyword */); + parseExpected(19 /* OpenParenToken */); node.expression = parseModuleSpecifier(); - parseExpected(20); + parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9) { + if (token() === 9 /* StringLiteral */) { var result = parseLiteralNode(); result.text = internIdentifier(result.text); return result; } else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. return parseExpression(); } } function parseNamespaceImport() { - var namespaceImport = createNode(240); - parseExpected(39); - parseExpected(118); + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(241 /* NamespaceImport */); + parseExpected(39 /* AsteriskToken */); + parseExpected(118 /* AsKeyword */); namespaceImport.name = parseIdentifier(); return finishNode(namespaceImport); } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 242 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); + return parseImportOrExportSpecifier(247 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); + return parseImportOrExportSpecifier(243 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 118) { + if (token() === 118 /* AsKeyword */) { node.propertyName = identifierName; - parseExpected(118); + parseExpected(118 /* AsKeyword */); checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); @@ -15003,53 +18314,56 @@ var ts; else { node.name = identifierName; } - if (kind === 242 && checkIdentifierIsKeyword) { + if (kind === 243 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(39)) { - parseExpected(140); + function parseExportDeclaration(node) { + node.kind = 245 /* ExportDeclaration */; + if (parseOptional(39 /* AsteriskToken */)) { + parseExpected(141 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); + node.exportClause = parseNamedImportsOrExports(246 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 141 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(141 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } parseSemicolon(); return finishNode(node); } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(58)) { + function parseExportAssignment(node) { + node.kind = 244 /* ExportAssignment */; + if (parseOptional(58 /* EqualsToken */)) { node.isExportEquals = true; } else { - parseExpected(79); + parseExpected(79 /* DefaultKeyword */); } node.expression = parseAssignmentExpressionOrHigher(); parseSemicolon(); return finishNode(node); } function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); + var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); var referencedFiles = []; var typeReferenceDirectives = []; var amdDependencies = []; var amdModuleName; var checkJsDirective = undefined; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. while (true) { var kind = triviaScanner.scan(); - if (kind !== 2) { + if (kind !== 2 /* SingleLineCommentTrivia */) { if (ts.isTrivia(kind)) { continue; } @@ -15105,7 +18419,7 @@ var ts; var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment); if (checkJsDirectiveMatchResult) { checkJsDirective = { - enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", true) === 0, + enabled: ts.equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"), end: range.end, pos: range.pos }; @@ -15120,11 +18434,11 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return ts.hasModifier(node, 1) - || node.kind === 237 && node.moduleReference.kind === 248 - || node.kind === 238 - || node.kind === 243 - || node.kind === 244 + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 249 /* ExternalModuleReference */ + || node.kind === 239 /* ImportDeclaration */ + || node.kind === 244 /* ExportAssignment */ + || node.kind === 245 /* ExportDeclaration */ ? node : undefined; }); @@ -15154,7 +18468,7 @@ var ts; ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; + ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -15165,8 +18479,8 @@ var ts; var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = createSourceFile("file.js", 5, 1); + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -15175,20 +18489,21 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression(requireBraces) { - var result = createNode(267, scanner.getTokenPos()); - if (!parseExpected(17) && requireBraces) { - return undefined; + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(271 /* JSDocTypeExpression */, scanner.getTokenPos()); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); + result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); + if (!mayOmitBraces || hasBrace) { + parseExpected(18 /* CloseBraceToken */); } - result.type = doInsideOfContext(1048576, parseType); - parseExpected(18); fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = { languageVariant: 0, text: content }; + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); @@ -15203,7 +18518,7 @@ var ts; if (comment) { comment.parent = parent; } - if (ts.isInJavaScriptFile(parent)) { + if (contextFlags & 65536 /* JavaScriptFile */) { if (!sourceFile.jsDocDiagnostics) { sourceFile.jsDocDiagnostics = []; } @@ -15240,13 +18555,18 @@ var ts; var tagsEnd; var comments = []; var result; + // Check for /** (JSDoc opening part) if (!isJsDocStart(content, start)) { return result; } + // + 3 for leading /**, - 5 in total for /** */ scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. var advanceToken = true; - var state = 1; + var state = 1 /* SawAsterisk */; var margin = undefined; + // + 4 for leading '/** ' var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; function pushComment(text) { if (!margin) { @@ -15256,21 +18576,24 @@ var ts; indent += text.length; } nextJSDocToken(); - while (token() === 5) { + while (token() === 5 /* WhitespaceTrivia */) { nextJSDocToken(); } - if (token() === 4) { - state = 0; + if (token() === 4 /* NewLineTrivia */) { + state = 0 /* BeginningOfLine */; indent = 0; nextJSDocToken(); } - while (token() !== 1) { + while (token() !== 1 /* EndOfFileToken */) { switch (token()) { - case 57: - if (state === 0 || state === 1) { + case 57 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); parseTag(indent); - state = 0; + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; advanceToken = false; margin = undefined; indent++; @@ -15279,29 +18602,35 @@ var ts; pushComment(scanner.getTokenText()); } break; - case 4: + case 4 /* NewLineTrivia */: comments.push(scanner.getTokenText()); - state = 0; + state = 0 /* BeginningOfLine */; indent = 0; break; - case 39: + case 39 /* AsteriskToken */: var asterisk = scanner.getTokenText(); - if (state === 1 || state === 2) { - state = 2; + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; pushComment(asterisk); } else { - state = 1; + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; indent += asterisk.length; } break; - case 71: + case 71 /* Identifier */: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. pushComment(scanner.getTokenText()); - state = 2; + state = 2 /* SavingComments */; break; - case 5: + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); - if (state === 2) { + if (state === 2 /* SavingComments */) { comments.push(whitespace); } else if (margin !== undefined && indent + whitespace.length > margin) { @@ -15309,10 +18638,11 @@ var ts; } indent += whitespace.length; break; - case 1: + case 1 /* EndOfFileToken */: break; default: - state = 2; + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } @@ -15339,25 +18669,25 @@ var ts; } } function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42; + return content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */; } function createJSDocComment() { - var result = createNode(275, start); + var result = createNode(279 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } function skipWhitespace() { - while (token() === 5 || token() === 4) { + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } } function parseTag(indent) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getTokenPos()); + ts.Debug.assert(token() === 57 /* AtToken */); + var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15369,6 +18699,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -15378,7 +18709,7 @@ var ts; case "arg": case "argument": case "param": - tag = parseParameterOrPropertyTag(atToken, tagName, 1); + tag = parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */); break; case "return": case "returns": @@ -15402,13 +18733,14 @@ var ts; tag = parseUnknownTag(atToken, tagName); } if (!tag) { + // a badly malformed tag should not be added to the list of tags return; } addTag(tag, parseTagComments(indent + tag.end - tag.pos)); } function parseTagComments(indent) { var comments = []; - var state = 0; + var state = 0 /* BeginningOfLine */; var margin; function pushComment(text) { if (!margin) { @@ -15417,41 +18749,47 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { + while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { switch (token()) { - case 4: - if (state >= 1) { - state = 0; + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; comments.push(scanner.getTokenText()); } indent = 0; break; - case 57: + case 57 /* AtToken */: + // Done break; - case 5: - if (state === 2) { + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); } else { var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; } break; - case 39: - if (state === 0) { - state = 1; + case 39 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; indent += scanner.getTokenText().length; break; } + // record the * as a comment + // falls through default: - state = 2; + state = 2 /* SavingComments */; // leading identifiers start recording as well pushComment(scanner.getTokenText()); break; } - if (token() === 57) { + if (token() === 57 /* AtToken */) { + // Done break; } nextJSDocToken(); @@ -15461,7 +18799,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(276, atToken.pos); + var result = createNode(281 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -15479,25 +18817,27 @@ var ts; } function tryParseTypeExpression() { skipWhitespace(); - return token() === 17 ? parseJSDocTypeExpression() : undefined; + return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { - var isBracketed = parseOptional(21); + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(21 /* OpenBracketToken */); var name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); - if (parseOptionalToken(58)) { + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(58 /* EqualsToken */)) { parseExpression(); } - parseExpected(22); + parseExpected(22 /* CloseBracketToken */); } return { name: name, isBracketed: isBracketed }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { - case 134: + case 134 /* ObjectKeyword */: return true; - case 164: + case 165 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; @@ -15512,9 +18852,9 @@ var ts; if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var result = target === 1 ? - createNode(279, atToken.pos) : - createNode(284, atToken.pos); + var result = target === 1 /* Parameter */ ? + createNode(284 /* JSDocParameterTag */, atToken.pos) : + createNode(289 /* JSDocPropertyTag */, atToken.pos); var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -15530,21 +18870,21 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var typeLiteralExpression = createNode(271 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { if (!children) { children = []; } children.push(child); } if (children) { - jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 164) { + if (typeExpression.type.kind === 165 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -15553,35 +18893,55 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + if (ts.forEach(tags, function (t) { return t.kind === 285 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(280, atToken.pos); + var result = createNode(285 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + if (ts.forEach(tags, function (t) { return t.kind === 286 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(281, atToken.pos); + var result = createNode(286 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = parseJSDocTypeExpression(true); + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = parseJSDocTypeExpression(true); - var result = createNode(277, atToken.pos); + var result = createNode(282 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = typeExpression; + result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(17 /* OpenBraceToken */); + var node = createNode(202 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(/*createIfMissing*/ true); + while (parseOptional(23 /* DotToken */)) { + var prop = createNode(180 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } function parseClassTag(atToken, tagName) { - var tag = createNode(278, atToken.pos); + var tag = createNode(283 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); @@ -15589,15 +18949,17 @@ var ts; function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(283, atToken.pos); + var typedefTag = createNode(288 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); if (typedefTag.fullName) { var rightNode = typedefTag.fullName; while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; + if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { + // if node is identifier - use it as name + // otherwise use name of the rightmost part that we were able to parse + typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; break; } rightNode = rightNode.body; @@ -15610,11 +18972,11 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = scanner.getStartPos(); - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(285, start_3); + jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 281) { + if (child.kind === 286 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -15630,10 +18992,10 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 164) { + if (typeExpression && typeExpression.type.kind === 165 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -15642,14 +19004,14 @@ var ts; function parseJSDocTypeNameWithNamespace(flags) { var pos = scanner.getTokenPos(); var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); + if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(234 /* ModuleDeclaration */, pos); jsDocNamespaceNode.flags |= flags; jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); return finishNode(jsDocNamespaceNode); } - if (typeNameOrNamespaceName && flags & 4) { + if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { typeNameOrNamespaceName.isInJSDocNamespace = true; } return typeNameOrNamespaceName; @@ -15673,10 +19035,10 @@ var ts; while (true) { nextJSDocToken(); switch (token()) { - case 57: + case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 279 && + if (child && child.kind === 284 /* JSDocParameterTag */ && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -15684,27 +19046,27 @@ var ts; } seenAsterisk = false; break; - case 4: + case 4 /* NewLineTrivia */: canParseTag = true; seenAsterisk = false; break; - case 39: + case 39 /* AsteriskToken */: if (seenAsterisk) { canParseTag = false; } seenAsterisk = true; break; - case 71: + case 71 /* Identifier */: canParseTag = false; break; - case 1: + case 1 /* EndOfFileToken */: return false; } } } function tryParseChildTag(target) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); + ts.Debug.assert(token() === 57 /* AtToken */); + var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15714,35 +19076,36 @@ var ts; } switch (tagName.escapedText) { case "type": - return target === 0 && parseTypeTag(atToken, tagName); + return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); } return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } + // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name_8 = parseJSDocIdentifierName(); + var name = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_8) { + if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145, name_8.pos); - typeParameter.name = name_8; + var typeParameter = createNode(146 /* TypeParameter */, name.pos); + typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 26) { + if (token() === 26 /* CommaToken */) { nextJSDocToken(); skipWhitespace(); } @@ -15750,7 +19113,7 @@ var ts; break; } } - var result = createNode(282, atToken.pos); + var result = createNode(287 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -15761,16 +19124,19 @@ var ts; return currentToken = scanner.scanJSDocToken(); } function parseJSDocEntityName() { - var entity = parseJSDocIdentifierName(true); - if (parseOptional(21)) { - parseExpected(22); + var entity = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(21 /* OpenBracketToken */)) { + parseExpected(22 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. } - while (parseOptional(23)) { - var name_9 = parseJSDocIdentifierName(true); - if (parseOptional(21)) { - parseExpected(22); + while (parseOptional(23 /* DotToken */)) { + var name = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(21 /* OpenBracketToken */)) { + parseExpected(22 /* CloseBracketToken */); } - entity = createQualifiedName(entity, name_9); + entity = createQualifiedName(entity, name); } return entity; } @@ -15778,7 +19144,7 @@ var ts; if (createIfMissing === void 0) { createIfMissing = false; } if (!ts.tokenIsIdentifierOrKeyword(token())) { if (createIfMissing) { - return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } else { parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); @@ -15787,7 +19153,7 @@ var ts; } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); - var result = createNode(71, pos); + var result = createNode(71 /* Identifier */, pos); result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); finishNode(result, end); nextJSDocToken(); @@ -15800,27 +19166,72 @@ var ts; var IncrementalParser; (function (IncrementalParser) { function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. return sourceFile; } if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); - } + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. var incrementalSourceFile = sourceFile; ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); incrementalSourceFile.hasBeenIncrementallyParsed = true; var oldText = sourceFile.text; var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. var changeRange = extendToAffectedRange(sourceFile, textChangeRange); checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -15837,6 +19248,8 @@ var ts; if (aggressiveChecks && shouldCheckNode(node)) { text = oldText.substring(node.pos, node.end); } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. if (node._children) { node._children = undefined; } @@ -15866,9 +19279,9 @@ var ts; } function shouldCheckNode(node) { switch (node.kind) { - case 9: - case 8: - case 71: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 71 /* Identifier */: return true; } return false; @@ -15877,11 +19290,63 @@ var ts; ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. element.end += delta; } else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. element.end = Math.min(element.end, changeRangeNewEnd); } ts.Debug.assert(element.pos <= element.end); @@ -15906,30 +19371,43 @@ var ts; function visitNode(child) { ts.Debug.assert(child.pos <= child.end); if (child.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); return; } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. var fullEnd = child.end; if (fullEnd >= changeStart) { child.intersectsChange = true; child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); checkNodePositions(child, aggressiveChecks); return; } + // Otherwise, the node is entirely before the change range. No need to do anything with it. ts.Debug.assert(fullEnd < changeStart); } function visitArray(array) { ts.Debug.assert(array.pos <= array.end); if (array.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); return; } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. var fullEnd = array.end; if (fullEnd >= changeStart) { array.intersectsChange = true; array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { var node = array_9[_i]; @@ -15937,12 +19415,26 @@ var ts; } return; } + // Otherwise, the array is entirely before the change range. No need to do anything with it. ts.Debug.assert(fullEnd < changeStart); } } function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. var maxLookahead = 1; var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. for (var i = 0; start > 0 && i <= maxLookahead; i++) { var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); ts.Debug.assert(nearestNode.pos <= start); @@ -15986,23 +19478,54 @@ var ts; } function visit(child) { if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. return; } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. if (child.pos <= position) { if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. bestResult = child; } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. return true; } else { ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. lastNodeEntirelyBeforePosition = child; } } else { ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. return true; } } @@ -16011,7 +19534,7 @@ var ts; var oldText = sourceFile.text; if (textChangeRange) { ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); - if (aggressiveChecks || ts.Debug.shouldAssert(3)) { + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); var newTextPrefix = newText.substr(0, textChangeRange.span.start); ts.Debug.assert(oldTextPrefix === newTextPrefix); @@ -16026,42 +19549,68 @@ var ts; var currentArrayIndex = 0; ts.Debug.assert(currentArrayIndex < currentArray.length); var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = -1; + var lastQueriedPosition = -1 /* Value */; return { currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { currentArrayIndex++; current = currentArray[currentArrayIndex]; } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. if (!current || current.pos !== position) { findHighestListElementThatStartsAtPosition(position); } } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. ts.Debug.assert(!current || current.pos === position); return current; } }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. currentArray = undefined; - currentArrayIndex = -1; + currentArrayIndex = -1 /* Value */; current = undefined; + // Recurse into the source file to find the highest node at this position. forEachChild(sourceFile, visitNode, visitArray); return; function visitNode(node) { if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. return true; } + // position wasn't in this node, have to keep searching. return false; } function visitArray(array) { if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. for (var i = 0; i < array.length; i++) { var child = array[i]; if (child) { if (child.pos === position) { + // Found the right node. We're done. currentArray = array; currentArrayIndex = i; current = child; @@ -16069,6 +19618,8 @@ var ts; } else { if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. forEachChild(child, visitNode, visitArray); return true; } @@ -16076,6 +19627,7 @@ var ts; } } } + // position wasn't in this array, have to keep searching. return false; } } @@ -16085,11 +19637,22 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } })(ts || (ts = {})); +/// +/// +/// +/// +/// var ts; (function (ts) { + /* @internal */ ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + /* @internal */ ts.optionDeclarations = [ + // CommandLine only options { name: "help", shortName: "h", @@ -16150,35 +19713,37 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, }, + // Basic { name: "target", shortName: "t", type: ts.createMapFromTemplate({ - "es3": 0, - "es5": 1, - "es6": 2, - "es2015": 2, - "es2016": 3, - "es2017": 4, - "esnext": 5, + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, }), paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", shortName: "m", type: ts.createMapFromTemplate({ - "none": ts.ModuleKind.None, - "commonjs": ts.ModuleKind.CommonJS, - "amd": ts.ModuleKind.AMD, - "system": ts.ModuleKind.System, - "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES2015, - "es2015": ts.ModuleKind.ES2015, - "esnext": ts.ModuleKind.ESNext + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -16191,17 +19756,21 @@ var ts; element: { name: "lib", type: ts.createMapFromTemplate({ + // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", + // Host only "dom": "lib.dom.d.ts", "dom.iterable": "lib.dom.iterable.d.ts", "webworker": "lib.webworker.d.ts", "scripthost": "lib.scripthost.d.ts", + // ES2015 Or ESNext By-feature options "es2015.core": "lib.es2015.core.d.ts", "es2015.collection": "lib.es2015.collection.d.ts", "es2015.generator": "lib.es2015.generator.d.ts", @@ -16216,6 +19785,7 @@ var ts; "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", + "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -16239,9 +19809,9 @@ var ts; { name: "jsx", type: ts.createMapFromTemplate({ - "preserve": 1, - "react-native": 3, - "react": 2 + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -16321,6 +19891,7 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule }, + // Strict Type Checks { name: "strict", type: "boolean", @@ -16342,6 +19913,20 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, { name: "noImplicitThis", type: "boolean", @@ -16356,6 +19941,7 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file }, + // Additional Checks { name: "noUnusedLocals", type: "boolean", @@ -16384,11 +19970,12 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement }, + // Module Resolution { name: "moduleResolution", type: ts.createMapFromTemplate({ - "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic, + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, }), paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, @@ -16402,6 +19989,8 @@ var ts; description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names }, { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is name: "paths", type: "object", isTSConfigOnly: true, @@ -16409,6 +19998,8 @@ var ts; description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl }, { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is name: "rootDirs", type: "list", isTSConfigOnly: true, @@ -16454,6 +20045,7 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks, }, + // Source Maps { name: "sourceRoot", type: "string", @@ -16482,6 +20074,7 @@ var ts; category: ts.Diagnostics.Source_Map_Options, description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set }, + // Experimental { name: "experimentalDecorators", type: "boolean", @@ -16494,6 +20087,7 @@ var ts; category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, + // Advanced { name: "jsxFactory", type: "string", @@ -16534,6 +20128,7 @@ var ts; name: "out", type: "string", isFilePath: false, + // for correct behaviour, please use outFile category: ts.Diagnostics.Advanced_Options, paramType: ts.Diagnostics.FILE, description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, @@ -16571,8 +20166,8 @@ var ts; { name: "newLine", type: ts.createMapFromTemplate({ - "crlf": 0, - "lf": 1 + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ }), paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Advanced_Options, @@ -16689,6 +20284,7 @@ var ts; description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, { + // A list of plugins to load in the language service name: "plugins", type: "list", isTSConfigOnly: true, @@ -16699,8 +20295,12 @@ var ts; description: ts.Diagnostics.List_of_language_service_plugins } ]; + /* @internal */ ts.typeAcquisitionDeclarations = [ { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ name: "enableAutoDiscovery", type: "boolean", }, @@ -16725,13 +20325,16 @@ var ts; } } ]; + /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, - target: 1, + target: 1 /* ES5 */, strict: true }; var optionNameMapCache; + /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { var result = { enable: typeAcquisition.enableAutoDiscovery, @@ -16758,6 +20361,7 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } + /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } @@ -16766,10 +20370,12 @@ var ts; var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } + /* @internal */ function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ function parseListTypeOption(opt, value, errors) { if (value === void 0) { value = ""; } value = trimString(value); @@ -16805,16 +20411,17 @@ var ts; while (i < args.length) { var s = args[i]; i++; - if (s.charCodeAt(0) === 64) { + if (s.charCodeAt(0) === 64 /* at */) { parseResponseFile(s.slice(1)); } - else if (s.charCodeAt(0) === 45) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); } @@ -16824,8 +20431,10 @@ var ts; i++; break; case "boolean": + // boolean flag has optional value true, false, others var optValue = args[i]; options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value if (optValue === "false" || optValue === "true") { i++; } @@ -16841,6 +20450,7 @@ var ts; i++; } break; + // If not a primitive, the possible types are specified in what is effectively a map of options. default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); i++; @@ -16866,14 +20476,14 @@ var ts; var args = []; var pos = 0; while (true) { - while (pos < text.length && text.charCodeAt(pos) <= 32) + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) pos++; if (pos >= text.length) break; var start = pos; - if (text.charCodeAt(start) === 34) { + if (text.charCodeAt(start) === 34 /* doubleQuote */) { pos++; - while (pos < text.length && text.charCodeAt(pos) !== 34) + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) pos++; if (pos < text.length) { args.push(text.substring(start + 1, pos)); @@ -16884,7 +20494,7 @@ var ts; } } else { - while (text.charCodeAt(pos) > 32) + while (text.charCodeAt(pos) > 32 /* space */) pos++; args.push(text.substring(start, pos)); } @@ -16897,6 +20507,7 @@ var ts; if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. if (allowShort) { var short = shortOptionNames.get(optionName); if (short !== undefined) { @@ -16905,11 +20516,20 @@ var ts; } return optionNameMap.get(optionName); } + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { @@ -16918,9 +20538,13 @@ var ts; }; } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ function readJsonConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; function tryReadFile(fileName, readFile) { @@ -16991,20 +20615,27 @@ var ts; } return _tsconfigRootOptions; } + /** + * Convert the json syntax tree into the json value + */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, undefined, undefined); + return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value + */ function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { if (!sourceFile.jsonObject) { return {}; } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, + /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { var result = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 261) { + if (element.kind !== 265 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -17022,19 +20653,24 @@ var ts; var value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== "undefined") { result[keyText] = value; + // Notify key value set, if user asked for it if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root (parentOption || knownOptions === knownRootOptions)) { var isValidOptionValue = isCompilerOptionsValue(option, value); if (parentOption) { if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); } } else if (knownOptions === knownRootOptions) { if (isValidOptionValue) { + // Notify about the valid root key value being set jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); } else if (!option) { + // Notify about the unknown root key value being set jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); } } @@ -17048,47 +20684,62 @@ var ts; } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { - case 101: + case 101 /* TrueKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return true; - case 86: + case 86 /* FalseKeyword */: reportInvalidOptionValue(option && option.type !== "boolean"); return false; - case 95: - reportInvalidOptionValue(option && option.name === "extends"); - return null; - case 9: + case 95 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 9 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); var text = valueExpression.text; - if (option && typeof option.type !== "string") { + if (option && !ts.isString(option.type)) { var customOption = option; + // Validate custom option type if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); } } return text; - case 8: + case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 178: + case 193 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 179 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed if (option) { var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); } else { - return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 177: + case 178 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } + // Not in expected format if (option) { - reportInvalidOptionValue(true); + reportInvalidOptionValue(/*isError*/ true); } else { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); @@ -17101,31 +20752,38 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : - typeof option.type === "string" ? option.type : "string"; + ts.isString(option.type) ? option.type : "string"; } function isCompilerOptionsValue(option, value) { if (option) { if (isNullOrUndefined(value)) - return true; + return true; // All options are undefinable/nullable if (option.type === "list") { return ts.isArray(value); } - var expectedType = typeof option.type === "string" ? option.type : "string"; + var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType return undefined; } else if (optionDefinition.type === "list") { @@ -17136,6 +20794,7 @@ var ts; } } function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { if (mapValue === value) { return key; @@ -17145,31 +20804,36 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_3 = function (name_10) { - if (ts.hasProperty(options, name_10)) { - if (optionsNameMap.has(name_10) && optionsNameMap.get(name_10).category === ts.Diagnostics.Command_line_Options) { + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; } - var value = options[name_10]; - var optionDefinition = optionsNameMap.get(name_10.toLowerCase()); + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap_1) { - result.set(name_10, value); + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + result.set(name, value); } else { if (optionDefinition.type === "list") { - result.set(name_10, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { - result.set(name_10, getNameOfCompilerOptionValue(value, customTypeMap_1)); + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } }; - for (var name_10 in options) { - _loop_3(name_10); + for (var name in options) { + _loop_3(name); } return result; } @@ -17193,6 +20857,7 @@ var ts; return Array(paddingLength + 1).join(" "); } function writeConfigurations() { + // Filter applicable options to place in the file var categorizedOptions = ts.createMultiMap(); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; @@ -17201,6 +20866,7 @@ var ts; categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } } + // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; @@ -17226,10 +20892,12 @@ var ts; marginLength = Math.max(optionName.length, marginLength); } }); + // Write the output var tab = makePadding(2); var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; @@ -17251,14 +20919,29 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); } ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ function setConfigFileInOptions(options, configFile) { if (configFile) { Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); @@ -17266,23 +20949,36 @@ var ts; } ts.setConfigFileInOptions = setConfigFileInOptions; function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { + // Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -17290,14 +20986,15 @@ var ts; raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec }; function getFileNames() { - var fileNames; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - fileNames = raw["files"]; - if (fileNames.length === 0) { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -17306,35 +21003,35 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } } - if (fileNames === undefined && includeSpecs === undefined) { + if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } return result; } @@ -17344,12 +21041,26 @@ var ts; } } } + /*@internal*/ + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + /*@internal*/ + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); @@ -17359,6 +21070,7 @@ var ts; parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { @@ -17377,6 +21089,7 @@ var ts; raw_1.compileOnSave = baseRaw_1.compileOnSave; } ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition } } return ownConfig; @@ -17386,11 +21099,13 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { - if (typeof json.extends !== "string") { + if (!ts.isString(json.extends)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { @@ -17454,12 +21169,13 @@ var ts; } function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); @@ -17478,11 +21194,12 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { @@ -17502,7 +21219,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -17562,7 +21279,7 @@ var ts; if (optType === "list" && ts.isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors); } - else if (typeof optType !== "string") { + else if (!ts.isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); } return normalizeNonListOptionValue(opt, basePath, value); @@ -17576,13 +21293,13 @@ var ts; return undefined; if (option.type === "list") { var listOption_1 = option; - if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else if (typeof option.type !== "string") { - return option.type.get(typeof value === "string" ? value.toLowerCase() : value); + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -17613,37 +21330,155 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path with multiple recursive directory wildcards. + * Matches **\** and **\a\**, but not **\a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \*\* # matches a recursive directory wildcard "**" + * ($|\/) # matches either the end of the string or a directory separator. + */ var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); - if (include) { - include = validateSpecs(include, errors, false, jsonSourceFile, "include"); - } - if (exclude) { - exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); - } - var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); - if (fileNames) { - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } - if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { @@ -17655,9 +21490,11 @@ var ts; var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); return { fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + spec: spec }; } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter(function (spec) { var diag = specToDiagnostic(spec, allowTrailingRecursion); @@ -17694,7 +21531,22 @@ var ts; return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); var wildcardDirectories = {}; @@ -17712,12 +21564,13 @@ var ts; var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; - if (flags === 1) { + if (flags === 1 /* Recursive */) { recursiveKeys.push(key); } } } } + // Remove any subpaths under an existing recursively watched directory. for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { @@ -17736,18 +21589,26 @@ var ts; if (match) { return { key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), - flags: watchRecursivePattern.test(spec) ? 1 : 0 + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ }; } if (ts.isImplicitGlob(spec)) { - return { key: spec, flags: 1 }; + return { key: spec, flags: 1 /* Recursive */ }; } return undefined; } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); - for (var i = 0; i < adjustedExtensionPriority; i++) { + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { @@ -17756,6 +21617,14 @@ var ts; } return false; } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); @@ -17765,12 +21634,27 @@ var ts; wildcardFiles.delete(lowerPriorityPath); } } + /** + * Gets a case sensitive key. + * + * @param key The original key. + */ function caseSensitiveKeyMapper(key) { return key; } + /** + * Gets a case insensitive key. + * + * @param key The original key. + */ function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + /** + * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ function convertCompilerOptionsForTelemetry(opts) { var out = {}; for (var key in opts) { @@ -17786,11 +21670,11 @@ var ts; ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; function getOptionValueWithEmptyStrings(value, option) { switch (option.type) { - case "object": + case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "". return ""; - case "string": + case "string":// Could be any arbitrary string -- use empty string instead. return ""; - case "number": + case "number":// Allow numbers, but be sure to check it's actually a number. return typeof value === "number" ? value : ""; case "boolean": return typeof value === "boolean" ? value : ""; @@ -17806,12 +21690,15 @@ var ts; } } })(ts || (ts = {})); +/// +/// var ts; (function (ts) { function trace(host) { host.trace(ts.formatMessage.apply(undefined, arguments)); } ts.trace = trace; + /* @internal */ function isTraceEnabled(compilerOptions, host) { return compilerOptions.traceResolution && host.trace !== undefined; } @@ -17820,14 +21707,19 @@ var ts; return r && { path: r.path, extension: r.ext, packageId: packageId }; } function noPackageId(r) { - return withPackageId(undefined, r); + return withPackageId(/*packageId*/ undefined, r); } + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; + Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { if (!resolved) { return undefined; @@ -17841,6 +21733,7 @@ var ts; failedLookupLocations: failedLookupLocations }; } + /** Reads from "main" or "types"/"typings" depending on `extensions`. */ function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { @@ -17851,7 +21744,7 @@ var ts; return; } var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { + if (!ts.isString(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); } @@ -17870,6 +21763,7 @@ var ts; return jsonText ? JSON.parse(jsonText) : {}; } catch (e) { + // gracefully handle if readFile fails or returns not JSON return {}; } } @@ -17889,12 +21783,17 @@ var ts; } } ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ function getDefaultTypeRoots(currentDirectory, host) { if (!host.directoryExists) { return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. } var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -17904,6 +21803,11 @@ var ts; return typeRoots; } var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; @@ -17945,6 +21849,7 @@ var ts; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { + // Check primary library paths if (typeRoots && typeRoots.length) { if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); @@ -17969,10 +21874,11 @@ var ts; var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); + var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -17987,10 +21893,20 @@ var ts; } } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json if (options.types) { return options.types; } + // Walk the primary type lookup locations var result = []; if (host.directoryExists && host.getDirectories) { var typeRoots = getEffectiveTypeRoots(options, host); @@ -18002,8 +21918,12 @@ var ts; var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { + // Return just the type directive names result.push(ts.getBaseFileName(normalized)); } } @@ -18044,22 +21964,38 @@ var ts; function get(directory) { return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ function set(directory, result) { var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing if (directoryPathMap.has(path)) { return; } directoryPathMap.set(path, result); var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + // find common prefix between directory and resolved file name + // this common prefix should be the shorted path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts var commonPrefix = getCommonPrefix(path, resolvedFileName); var current = path; while (true) { - var parent_3 = ts.getDirectoryPath(current); - if (parent_3 === current || directoryPathMap.has(parent_3)) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { break; } - directoryPathMap.set(parent_3, result); - current = parent_3; + directoryPathMap.set(parent, result); + current = parent; if (current === commonPrefix) { break; } @@ -18070,10 +22006,12 @@ var ts; return undefined; } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs var i = 0; while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } + // find last directory separator before position i var sep = directory.lastIndexOf(ts.directorySeparator, i); if (sep < 0) { return undefined; @@ -18121,6 +22059,7 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); + // put result in per-module name cache var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); if (perModuleNameCache) { perModuleNameCache.set(containingDirectory, result); @@ -18138,6 +22077,66 @@ var ts; return result; } ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); @@ -18158,6 +22157,9 @@ var ts; var matchedNormalizedPrefix; for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location var normalizedRoot = ts.normalizePath(rootDir); if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { normalizedRoot += ts.directorySeparator; @@ -18177,6 +22179,7 @@ var ts; trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); } var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } @@ -18187,9 +22190,11 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); } + // then try to resolve using remaining entries in rootDirs for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { var rootDir = _c[_b]; if (rootDir === matchedRootDir) { + // skip the initially matched entry continue; } var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); @@ -18215,6 +22220,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); } + // string is for exact match var matchedPattern = undefined; if (state.compilerOptions.paths) { if (state.traceEnabled) { @@ -18223,8 +22229,8 @@ var ts; matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -18234,9 +22240,10 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } + // A path mapping may have an extension, in contrast to an import, which should omit it. var extension = ts.tryGetExtensionFromPath(candidate); if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, false, state); + var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (path_1 !== undefined) { return noPackageId({ path: path_1, ext: extension }); } @@ -18253,11 +22260,17 @@ var ts; } } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); } ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } @@ -18275,7 +22288,7 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); @@ -18291,11 +22304,13 @@ var ts; if (!compilerOptions.preserveSymlinks) { resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); } + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } @@ -18340,18 +22355,27 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + /* @internal */ function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist return !host.directoryExists || host.directoryExists(directoryName); } ts.directoryProbablyExists = directoryProbablyExists; function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); } + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" if (ts.hasJavaScriptFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { @@ -18361,8 +22385,10 @@ var ts; return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); } } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); @@ -18370,17 +22396,18 @@ var ts; } switch (extensions) { case Extensions.DtsOnly: - return tryExtension(".d.ts"); + return tryExtension(".d.ts" /* Dts */); case Extensions.TypeScript: - return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: - return tryExtension(".js") || tryExtension(".jsx"); + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); return path && { path: path, ext: ext }; } } + /** Return the file if it exists. */ function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { @@ -18425,14 +22452,15 @@ var ts; var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; - return { packageJsonContent: packageJsonContent, packageId: packageId }; + return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocations.push(packageJsonPath); - return { packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined }; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { @@ -18451,39 +22479,57 @@ var ts; trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); if (result) { + // It won't have a `packageId` set, because we disabled `considerPackageJson`. ts.Debug.assert(result.packageId === undefined); return { path: result.path, ext: result.extension }; } } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { var ext = ts.tryGetExtensionFromPath(path); return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined; } + /** True if `extension` is one of the supported `extensions`. */ function extensionIsOk(extensions, extension) { switch (extensions) { case Extensions.JavaScript: - return extension === ".js" || extension === ".jsx"; + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; case Extensions.TypeScript: - return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; case Extensions.DtsOnly: - return extension === ".d.ts"; + return extension === ".d.ts" /* Dts */; } } function pathToPackageJson(directory) { return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); + if (packageInfo.found) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); + } + else { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. + packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + } + } var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); } + /* @internal */ function getPackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { @@ -18491,15 +22537,17 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); } function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); if (resolutionFromCache) { @@ -18509,6 +22557,7 @@ var ts; } }); } + /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { if (typesOnly === void 0) { typesOnly = false; } var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); @@ -18532,24 +22581,35 @@ var ts; return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); } } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" } } - return moduleName; + return packageName; } + /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -18571,7 +22631,7 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -18579,28 +22639,35 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + // Climb up parent directories looking for a module. + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); } } } ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -18609,26 +22676,20 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } - 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 || (ts = {})); +/// +/// +/* @internal */ var ts; (function (ts) { var ModuleInstanceState; @@ -18638,48 +22699,80 @@ var ts; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { - if (node.kind === 230 || node.kind === 231) { - return 0; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { - return 0; - } - else if (node.kind === 234) { - var state_1 = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state_1 = 2; - return false; - case 1: - state_1 = 1; - return true; + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 233 /* EnumDeclaration */: + if (ts.isConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 235 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 234 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 71 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; } - }); - return state_1; - } - else if (node.kind === 233) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1; - } - else if (node.kind === 71 && node.isInJSDocNamespace) { - return 0; - } - else { - return 1; } + return 1 /* Instantiated */; } - ts.getModuleInstanceState = getModuleInstanceState; var ContainerFlags; (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer"; ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike"; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; @@ -18704,6 +22797,7 @@ var ts; var blockScopeContainer; var lastContainer; var seenThisKeyword; + // state used by control flow analysis var currentFlow; var currentBreakTarget; var currentContinueTarget; @@ -18713,15 +22807,29 @@ var ts; var preSwitchCaseFlow; var activeLabels; var hasExplicitReturn; + // state used for emit helpers var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; - var Symbol; + var Symbol; // tslint:disable-line variable-name var classifiableNames; - var unreachableFlow = { flags: 1 }; - var reportedUnreachableFlow = { flags: 1 }; - var subtreeTransformFlags = 0; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -18752,12 +22860,13 @@ var ts; currentFalseTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - emitFlags = 0; - subtreeTransformFlags = 0; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option return true; } else { @@ -18777,124 +22886,176 @@ var ts; else { symbol.declarations.push(node); } - if (symbolFlags & 1952 && !symbol.exports) { + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 && !symbol.members) { + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 107455) { + if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 234 /* ModuleDeclaration */)) { + // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } } } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. function getDeclarationName(node) { + if (node.kind === 244 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 144) { + if (name.kind === 145 /* ComputedPropertyName */) { var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } return ts.getEscapedTextOfIdentifierOrLiteral(name); } switch (node.kind) { - case 152: - return "__constructor"; - case 160: - case 155: - return "__call"; - case 161: - case 156: - return "__new"; - case 157: - return "__index"; - case 244: - return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; - case 194: - if (ts.getSpecialPropertyAssignmentKind(node) === 2) { - return "export="; + case 153 /* Constructor */: + return "__constructor" /* Constructor */; + case 161 /* FunctionType */: + case 156 /* CallSignature */: + return "__call" /* Call */; + case 162 /* ConstructorType */: + case 157 /* ConstructSignature */: + return "__new" /* New */; + case 158 /* IndexSignature */: + return "__index" /* Index */; + case 245 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 195 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 228: - case 229: - return (ts.hasModifier(node, 512) ? "default" : undefined); - case 273: - return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); - case 146: - ts.Debug.assert(node.parent.kind === 273); + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); + case 277 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 147 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 283: - var name_11 = ts.getNameOfJSDocTypedef(node); - return typeof name_11 !== "undefined" ? name_11.escapedText : undefined; + case 288 /* JSDocTypedefTag */: + var name_2 = ts.getNameOfJSDocTypedef(node); + return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512); - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; if (name === undefined) { - symbol = createSymbol(0, "__missing"); + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); } else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. symbol = symbolTable.get(name); - if (includes & 788448) { + if (includes & 2885600 /* Classifiable */) { classifiableNames.set(name, true); } if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0, name)); + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); if (isReplaceableByMethod) symbol.isReplaceableByMethod = true; } else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. return symbol; } else if (symbol.flags & excludes) { if (symbol.isReplaceableByMethod) { - symbolTable.set(name, symbol = createSymbol(0, name)); + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } else { if (node.name) { node.name.parent = node; } - var message_1 = symbol.flags & 2 + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { + (isDefaultExport || (node.kind === 244 /* ExportAssignment */ && !node.isExportEquals))) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); } } } @@ -18903,85 +23064,127 @@ var ts; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; - if (symbolFlags & 2097152) { - if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 247 /* ExportSpecifier */ || (node.kind === 238 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } else { - if (node.kind === 283) - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var isJSDocTypedefInJSDocNamespace = node.kind === 283 && + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (node.kind === 288 /* JSDocTypedefTag */) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + var isJSDocTypedefInJSDocNamespace = node.kind === 288 /* JSDocTypedefTag */ && node.name && - node.name.kind === 71 && + node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 107455 ? 1048576 : 0; - var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { + var exportKind = symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; return local; } else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; - if (containerFlags & 1) { + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we proactively initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; - if (containerFlags & 32) { + if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createSymbolTable(); } addToContainerChain(container); } - else if (containerFlags & 2) { + else if (containerFlags & 2 /* IsBlockScopedContainer */) { blockScopeContainer = node; blockScopeContainer.locals = undefined; } - if (containerFlags & 4) { + if (containerFlags & 4 /* IsControlFlowContainer */) { var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: 2 }; - if (containerFlags & (16 | 128)) { + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async 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 */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } - currentReturnTarget = undefined; } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 153 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; bindChildren(node); - node.flags &= ~1408; - if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 128; + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; if (hasExplicitReturn) - node.flags |= 256; + node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 265) { + if (node.kind === 269 /* SourceFile */) { node.flags |= emitFlags; } - if (isIIFE) { + if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 153 /* Constructor */) { + node.returnFlowNode = currentFlow; + } } - else { + if (!isIIFE) { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; @@ -18990,10 +23193,10 @@ var ts; activeLabels = saveActiveLabels; hasExplicitReturn = saveHasExplicitReturn; } - else if (containerFlags & 64) { + else if (containerFlags & 64 /* IsInterface */) { seenThisKeyword = false; bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; } else { bindChildren(node); @@ -19005,7 +23208,7 @@ var ts; if (skipTransformFlagAggregation) { bindChildrenWorker(node); } - else if (node.transformFlags & 536870912) { + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { skipTransformFlagAggregation = true; bindChildrenWorker(node); skipTransformFlagAggregation = false; @@ -19027,14 +23230,14 @@ var ts; } else { var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var nodeArrayFlags = 0; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912; + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } - nodes.transformFlags = nodeArrayFlags | 536870912; + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; subtreeTransformFlags |= savedSubtreeTransformFlags; } } @@ -19042,6 +23245,9 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { + // Binding of JsDocComment should be done before the current block scope container changes. + // because the scope of JsDocComment should not be affected by whether the current node is a + // container or not. if (ts.hasJSDocNodes(node)) { if (ts.isInJavaScriptFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -19061,70 +23267,70 @@ var ts; return; } switch (node.kind) { - case 213: + case 214 /* WhileStatement */: bindWhileStatement(node); break; - case 212: + case 213 /* DoStatement */: bindDoStatement(node); break; - case 214: + case 215 /* ForStatement */: bindForStatement(node); break; - case 215: - case 216: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 211: + case 212 /* IfStatement */: bindIfStatement(node); break; - case 219: - case 223: + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 218: - case 217: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 224: + case 225 /* TryStatement */: bindTryStatement(node); break; - case 221: + case 222 /* SwitchStatement */: bindSwitchStatement(node); break; - case 235: + case 236 /* CaseBlock */: bindCaseBlock(node); break; - case 257: + case 261 /* CaseClause */: bindCaseClause(node); break; - case 222: + case 223 /* LabeledStatement */: bindLabeledStatement(node); break; - case 192: + case 193 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 193: + case 194 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 194: + case 195 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 188: + case 189 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 195: + case 196 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 226: + case 227 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 181: + case 182 /* CallExpression */: bindCallExpressionFlow(node); break; - case 275: + case 279 /* JSDocComment */: bindJSDocComment(node); break; - case 283: + case 288 /* JSDocTypedefTag */: bindJSDocTypedefTag(node); break; default: @@ -19134,26 +23340,26 @@ var ts; } function isNarrowingExpression(expr) { switch (expr.kind) { - case 71: - case 99: - case 179: + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 180 /* PropertyAccessExpression */: return isNarrowableReference(expr); - case 181: + case 182 /* CallExpression */: return hasNarrowableArgument(expr); - case 185: + case 186 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 194: + case 195 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 192: - return expr.operator === 51 && isNarrowingExpression(expr.operand); + case 193 /* PrefixUnaryExpression */: + return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 || - expr.kind === 99 || - expr.kind === 97 || - expr.kind === 179 && isNarrowableReference(expr.expression); + return expr.kind === 71 /* Identifier */ || + expr.kind === 99 /* ThisKeyword */ || + expr.kind === 97 /* SuperKeyword */ || + expr.kind === 180 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -19164,41 +23370,41 @@ var ts; } } } - if (expr.expression.kind === 179 && + if (expr.expression.kind === 180 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { - case 58: + case 58 /* EqualsToken */: return isNarrowableReference(expr.left); - case 32: - case 33: - case 34: - case 35: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93: + case 93 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); - case 26: + case 26 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 185: + case 186 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 194: + case 195 /* BinaryExpression */: switch (expr.operatorToken.kind) { - case 58: + case 58 /* EqualsToken */: return isNarrowableOperand(expr.left); - case 26: + case 26 /* CommaToken */: return isNarrowableOperand(expr.right); } } @@ -19206,34 +23412,35 @@ var ts; } function createBranchLabel() { return { - flags: 4, + flags: 4 /* BranchLabel */, antecedents: undefined }; } function createLoopLabel() { return { - flags: 8, + flags: 8 /* LoopLabel */, antecedents: undefined }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 512 ? 1024 : 512; + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; } function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { (label.antecedents || (label.antecedents = [])).push(antecedent); setFlowNodeReferenced(antecedent); } } function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1) { + if (antecedent.flags & 1 /* Unreachable */) { return antecedent; } if (!expression) { - return flags & 32 ? antecedent : unreachableFlow; + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; } - if (expression.kind === 101 && flags & 64 || - expression.kind === 86 && flags & 32) { + if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -19247,15 +23454,15 @@ var ts; return antecedent; } setFlowNodeReferenced(antecedent); - return { flags: 128, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; + return { flags: 128 /* SwitchClause */, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd, antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { setFlowNodeReferenced(antecedent); - return { flags: 16, antecedent: antecedent, node: node }; + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; } function createFlowArrayMutation(antecedent, node) { setFlowNodeReferenced(antecedent); - var res = { flags: 256, antecedent: antecedent, node: node }; + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; return res; } function finishFlowLabel(flow) { @@ -19271,34 +23478,34 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 211: - case 213: - case 212: + case 212 /* IfStatement */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: return parent.expression === node; - case 214: - case 195: + case 215 /* ForStatement */: + case 196 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 185) { + if (node.kind === 186 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 192 && node.operator === 51) { + else if (node.kind === 193 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 194 && (node.operatorToken.kind === 53 || - node.operatorToken.kind === 54); + return node.kind === 195 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 54 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 || - node.parent.kind === 192 && - node.parent.operator === 51) { + while (node.parent.kind === 186 /* ParenthesizedExpression */ || + node.parent.kind === 193 /* PrefixUnaryExpression */ && + node.parent.operator === 51 /* ExclamationToken */) { node = node.parent; } return !isStatementCondition(node) && !isLogicalExpression(node.parent); @@ -19312,8 +23519,8 @@ var ts; currentTrueTarget = saveTrueTarget; currentFalseTarget = saveFalseTarget; if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); } } function bindIterativeStatement(node, breakTarget, continueTarget) { @@ -19339,9 +23546,11 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 + var enclosingLabeledStatement = node.parent.kind === 223 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); addAntecedent(preDoLabel, currentFlow); @@ -19371,13 +23580,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 216) { + if (node.kind === 217 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 227) { + if (node.initializer.kind !== 228 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -19399,7 +23608,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 219) { + if (node.kind === 220 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -19419,7 +23628,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 ? breakTarget : continueTarget; + var flowLabel = node.kind === 219 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -19441,6 +23650,7 @@ var ts; function bindTryStatement(node) { var preFinallyLabel = createBranchLabel(); var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! bind(node.tryBlock); addAntecedent(preFinallyLabel, currentFlow); var flowAfterTry = currentFlow; @@ -19452,19 +23662,51 @@ var ts; flowAfterCatch = currentFlow; } if (node.finallyBlock) { - var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // 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: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); - if (!(currentFlow.flags & 1)) { - if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow ? reportedUnreachableFlow : unreachableFlow; } } - if (!(currentFlow.flags & 1)) { - var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; preFinallyFlow.lock = afterFinallyFlow; currentFlow = afterFinallyFlow; } @@ -19482,7 +23724,9 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 262 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -19509,11 +23753,11 @@ var ts; var clause = clauses[i]; bind(clause); fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } - clauses.transformFlags = subtreeTransformFlags | 536870912; + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; subtreeTransformFlags |= savedSubtreeTransformFlags; } function bindCaseClause(node) { @@ -19545,15 +23789,16 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - if (!node.statement || node.statement.kind !== 212) { + if (!node.statement || node.statement.kind !== 213 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 194 && node.operatorToken.kind === 58) { + if (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -19564,10 +23809,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 177) { + else if (node.kind === 178 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 198) { + if (e.kind === 199 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -19575,16 +23820,16 @@ var ts; } } } - else if (node.kind === 178) { + else if (node.kind === 179 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 261) { + if (p.kind === 265 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 262) { + else if (p.kind === 266 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 263) { + else if (p.kind === 267 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -19592,7 +23837,7 @@ var ts; } function bindLogicalExpression(node, trueTarget, falseTarget) { var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53) { + if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { bindCondition(node.left, preRightLabel, falseTarget); } else { @@ -19603,7 +23848,7 @@ var ts; bindCondition(node.right, trueTarget, falseTarget); } function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51) { + if (node.operator === 51 /* ExclamationToken */) { var saveTrueTarget = currentTrueTarget; currentTrueTarget = currentFalseTarget; currentFalseTarget = saveTrueTarget; @@ -19613,20 +23858,20 @@ var ts; } else { bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } } function bindPostfixUnaryExpressionFlow(node) { bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } function bindBinaryExpressionFlow(node) { var operator = node.operatorToken.kind; - if (operator === 53 || operator === 54) { + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { if (isTopLevelLogicalExpression(node)) { var postExpressionLabel = createBranchLabel(); bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); @@ -19640,7 +23885,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 180) { + if (operator === 58 /* EqualsToken */ && node.left.kind === 181 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -19651,7 +23896,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 179) { + if (node.expression.kind === 180 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -19690,25 +23935,31 @@ var ts; } function bindJSDocComment(node) { ts.forEachChild(node, function (n) { - if (n.kind !== 283) { + if (n.kind !== 288 /* JSDocTypedefTag */) { bind(n); } }); } function bindJSDocTypedefTag(node) { ts.forEachChild(node, function (n) { - if (node.fullName && n === node.name && node.fullName.kind !== 71) { + // if the node has a fullName "A.B.C", that means symbol "C" was already bound + // when we visit "fullName"; so when we visit the name "C" as the next child of + // the jsDocTypedefTag, we should skip binding it. + if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { return; } bind(n); }); } function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 185) { + while (expr.kind === 186 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 186 || expr.kind === 187) { + if (expr.kind === 187 /* FunctionExpression */ || expr.kind === 188 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -19716,7 +23967,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 179) { + if (node.expression.kind === 180 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -19725,55 +23976,72 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 199: - case 229: - case 232: - case 178: - case 163: - case 285: - case 254: - return 1; - case 230: - return 1 | 64; - case 233: - case 231: - case 172: - return 1 | 32; - case 265: - return 1 | 4 | 32; - case 151: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 179 /* ObjectLiteralExpression */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 258 /* JsxAttributes */: + return 1 /* IsContainer */; + case 231 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 173 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 269 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 152 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 | 4 | 32 | 8 | 128; - } - case 152: - case 228: - case 150: - case 153: - case 154: - case 155: - case 273: - case 160: - case 156: - case 157: - case 161: - return 1 | 4 | 32 | 8; - case 186: - case 187: - return 1 | 4 | 32 | 8 | 16; - case 234: - return 4; - case 149: - return node.initializer ? 4 : 0; - case 260: - case 214: - case 215: - case 216: - case 235: - return 2; - case 207: - return ts.isFunctionLike(node.parent) ? 0 : 2; - } - return 0; + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 156 /* CallSignature */: + case 277 /* JSDocFunctionType */: + case 161 /* FunctionType */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 162 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 235 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 150 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 264 /* CatchClause */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 236 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 208 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; } function addToContainerChain(next) { if (lastContainer) { @@ -19783,56 +24051,71 @@ var ts; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 233: + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 234 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265: + case 269 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199: - case 229: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 232: + case 233 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 285: - case 178: - case 230: - case 254: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 179 /* ObjectLiteralExpression */: + case 231 /* InterfaceDeclaration */: + case 258 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160: - case 161: - case 155: - case 156: - case 157: - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: - case 187: - case 273: - case 231: - case 172: - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 277 /* JSDocFunctionType */: + case 232 /* TypeAliasDeclaration */: + case 173 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32) + return ts.hasModifier(node, 32 /* Static */) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } function declareSourceFileMember(node, symbolFlags, symbolExcludes) { return ts.isExternalModule(file) ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 265 ? node : node.body; - if (body && (body.kind === 265 || body.kind === 234)) { + var body = node.kind === 269 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 269 /* SourceFile */ || body.kind === 235 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 244 || stat.kind === 243) { + if (stat.kind === 245 /* ExportDeclaration */ || stat.kind === 244 /* ExportAssignment */) { return true; } } @@ -19840,17 +24123,19 @@ var ts; return false; } function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 32; + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 2097152 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; } else { - node.flags &= ~32; + node.flags &= ~32 /* ExportContext */; } } function bindModuleDeclaration(node) { setExportContextFlag(node); if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (ts.isExternalModuleAugmentation(node)) { @@ -19858,7 +24143,7 @@ var ts; } else { var pattern = void 0; - if (node.name.kind === 9) { + if (node.name.kind === 9 /* StringLiteral */) { var text = node.name.text; if (ts.hasZeroOrOneAsteriskCharacter(text)) { pattern = ts.tryParsePattern(text); @@ -19867,7 +24152,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); if (pattern) { (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); } @@ -19875,33 +24160,34 @@ var ts; } else { var state = declareModuleSymbol(node); - if (state !== 0) { - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; } } } function declareModuleSymbol(node) { var state = getModuleInstanceState(node); - var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { - var symbol = createSymbol(131072, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072); - var typeLiteralSymbol = createSymbol(2048, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048); + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); typeLiteralSymbol.members = ts.createSymbolTable(); typeLiteralSymbol.members.set(symbol.escapedName, symbol); } @@ -19915,72 +24201,86 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 || prop.name.kind !== 71) { + if (prop.kind === 267 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 - ? 1 - : 2; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 265 /* PropertyAssignment */ || prop.kind === 266 /* ShorthandPropertyAssignment */ || prop.kind === 152 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); if (!existingKind) { seen.set(identifier.escapedText, currentKind); continue; } - if (currentKind === 1 && existingKind === 1) { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { var span_1 = ts.getErrorSpanForNode(file, identifier); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } } } - return bindAnonymousDeclaration(node, 4096, "__object"); + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); } function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); } function bindJsxAttribute(node, symbolFlags, symbolExcludes) { return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & 8) { + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { symbol.parent = container.symbol; } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 233: + case 234 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 265: + case 269 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; } + // falls through default: if (!blockScopeContainer.locals) { blockScopeContainer.locals = ts.createSymbolTable(); addToContainerChain(blockScopeContainer); } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. function checkStrictModeIdentifier(node) { if (inStrictMode && - node.originalKeywordKind >= 108 && - node.originalKeywordKind <= 116 && + node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { + !(node.flags & 2097152 /* Ambient */)) { + // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. if (ts.getContainingClass(node)) { return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; } @@ -19991,16 +24291,23 @@ var ts; } function checkStrictModeBinaryExpression(node) { if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) checkStrictModeEvalOrArguments(node, node.left); } } function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments if (inStrictMode && node.variableDeclaration) { checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); } } function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 71) { + // Grammar checking + if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name var span_2 = ts.getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } @@ -20009,15 +24316,19 @@ var ts; return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71) { + if (name && name.kind === 71 /* Identifier */) { var identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. if (ts.getContainingClass(node)) { return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } @@ -20028,10 +24339,13 @@ var ts; } function checkStrictModeFunctionName(node) { if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) checkStrictModeEvalOrArguments(node, node.name); } } function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. if (ts.getContainingClass(node)) { return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; } @@ -20041,33 +24355,42 @@ var ts; return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; } function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2) { - if (blockScopeContainer.kind !== 265 && - blockScopeContainer.kind !== 233 && + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 269 /* SourceFile */ && + blockScopeContainer.kind !== 234 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); } } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.operand); } } function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking if (inStrictMode) { - if (node.operator === 43 || node.operator === 44) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { checkStrictModeEvalOrArguments(node, node.operand); } } } function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement if (inStrictMode) { errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } @@ -20082,14 +24405,38 @@ var ts; } node.parent = parent; var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. if (ts.isInJavaScriptFile(node)) bindJSDocTypedefTagIfAny(node); + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. bindWorker(node); - if (node.kind > 142) { + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 143 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); - if (containerFlags === 0) { + if (containerFlags === 0 /* None */) { bindChildren(node); } else { @@ -20097,7 +24444,7 @@ var ts; } parent = saveParent; } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); } inStrictMode = saveInStrictMode; @@ -20113,7 +24460,7 @@ var ts; } for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; - if (tag.kind === 283) { + if (tag.kind === 288 /* JSDocTypedefTag */) { var savedParent = parent; parent = jsDoc; bind(tag); @@ -20136,191 +24483,213 @@ var ts; } } } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) function isUseStrictPrologueDirective(node) { var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). return nodeText === '"use strict"' || nodeText === "'use strict'"; } function bindWorker(node) { switch (node.kind) { - case 71: + /* Strict mode checks */ + case 71 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 283) { + while (parentNode && parentNode.kind !== 288 /* JSDocTypedefTag */) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 793064); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); break; } - case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { + // falls through + case 99 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 266 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 179: + case 180 /* PropertyAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } break; - case 194: + case 195 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { - case 1: + case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); break; - case 2: + case 2 /* ModuleExports */: bindModuleExportsAssignment(node); break; - case 3: + case 3 /* PrototypeProperty */: bindPrototypePropertyAssignment(node); break; - case 4: + case 4 /* ThisProperty */: bindThisPropertyAssignment(node); break; - case 5: + case 5 /* Property */: bindStaticPropertyAssignment(node); break; - case 0: + case 0 /* None */: + // Nothing to do break; default: ts.Debug.fail("Unknown special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 260: + case 264 /* CatchClause */: return checkStrictModeCatchClause(node); - case 188: + case 189 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); - case 8: + case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 193: + case 194 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 192: + case 193 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 220: + case 221 /* WithStatement */: return checkStrictModeWithStatement(node); - case 169: + case 170 /* ThisType */: seenThisKeyword = true; return; - case 158: + case 159 /* TypePredicate */: return checkTypePredicate(node); - case 145: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 146: + case 146 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + case 147 /* Parameter */: return bindParameter(node); - case 226: + case 227 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 176: + case 177 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 149: - case 148: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return bindPropertyWorker(node); - case 261: - case 262: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 264: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 155: - case 156: - case 157: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); - case 151: - case 150: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 228: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 268 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 229 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 152: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); - case 153: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); - case 154: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 160: - case 273: - case 161: + case 153 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 154 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 155 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 161 /* FunctionType */: + case 277 /* JSDocFunctionType */: + case 162 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 163: - case 285: - case 172: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 173 /* MappedType */: return bindAnonymousTypeWorker(node); - case 178: + case 179 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 186: - case 187: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return bindFunctionExpression(node); - case 181: + case 182 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 199: - case 229: + // Members of classes, interfaces, and modules + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 230: - return bindBlockScopedDeclaration(node, 64, 792968); - case 231: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 232: + case 231 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + case 232 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + case 233 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 233: + case 234 /* ModuleDeclaration */: return bindModuleDeclaration(node); - case 254: + // Jsx-attributes + case 258 /* JsxAttributes */: return bindJsxAttributes(node); - case 253: - return bindJsxAttribute(node, 4, 0); - case 237: - case 240: - case 242: - case 246: - return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); - case 236: + case 257 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 237 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 239: + case 240 /* ImportClause */: return bindImportClause(node); - case 244: + case 245 /* ExportDeclaration */: return bindExportDeclaration(node); - case 243: + case 244 /* ExportAssignment */: return bindExportAssignment(node); - case 265: + case 269 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 207: + case 208 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } - case 234: + // falls through + case 235 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 279: - if (node.parent.kind !== 285) { + case 284 /* JSDocParameterTag */: + if (node.parent.kind !== 280 /* JSDocTypeLiteral */) { break; } - case 284: + // falls through + case 289 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? - 4 | 16777216 : - 4; - return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 283: { + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 276 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 288 /* JSDocTypedefTag */: { var fullName = node.fullName; - if (!fullName || fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); + if (!fullName || fullName.kind === 71 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); } break; } } } function bindPropertyWorker(node) { - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 16777216 : 0), 0); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); } function bindAnonymousTypeWorker(node) { - return bindAnonymousDeclaration(node, 2048, "__type"); + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); } function checkTypePredicate(node) { var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71) { + if (parameterName && parameterName.kind === 71 /* Identifier */) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 169) { + if (parameterName && parameterName.kind === 170 /* ThisType */) { seenThisKeyword = true; } bind(type); @@ -20332,52 +24701,59 @@ var ts; } } function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) - ? 2097152 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 2097152 | 32 | 16); + var flags = node.kind === 244 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression exports all meanings of that identifier + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + if (node.parent.kind !== 269 /* SourceFile */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { - var parent_4 = node.parent; - if (!ts.isExternalModule(parent_4)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_4.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); } else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0); + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); } } function bindImportClause(node) { if (node.name) { - declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } } function setCommonJsModuleIndicator(node) { @@ -20389,124 +24765,201 @@ var ts; } } function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); } function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; } + // 'module.exports = expr' assignment setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 | 1048576 | 512, 0); + declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */, 0 /* None */); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, false); + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (container.kind) { - case 228: - case 186: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + // Declare a 'member' if the container is an ES5 class or ES6 constructor container.symbol.members = container.symbol.members || ts.createSymbolTable(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); break; - case 152: - case 149: - case 151: - case 153: - case 154: + case 153 /* Constructor */: + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class var containingClass = container.parent; - var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; - declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); + var symbolTable = ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; } } + function bindSpecialPropertyDeclaration(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (node.expression.kind === 99 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if ((node.expression.kind === 71 /* Identifier */ || node.expression.kind === 180 /* PropertyAccessExpression */) && + node.parent.parent.kind === 269 /* SourceFile */) { + bindStaticPropertyAssignment(node); + } + } function bindPrototypePropertyAssignment(node) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x is a function or class, or not declared. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration var leftSideOfAssignment = node.left; var classPrototype = leftSideOfAssignment.expression; var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them leftSideOfAssignment.parent = node; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ true); } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function or class, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.left; + // Look up the function in the local scope, since static assignments should + // follow the function declaration + var leftSideOfAssignment = node.kind === 180 /* PropertyAccessExpression */ ? node : node.left; var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + if (ts.isIdentifier(target)) { + // Fix up parent pointers since we're going to use these nodes before we bind into them + target.parent = leftSideOfAssignment; + if (node.kind === 195 /* BinaryExpression */) { + leftSideOfAssignment.parent = node; + } + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } } } function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { + var symbol = lookupSymbolForName(functionName); + var targetSymbol = symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol) ? + symbol.valueDeclaration.initializer.symbol : + symbol; + ts.Debug.assert(propertyAccess.parent.kind === 195 /* BinaryExpression */ || propertyAccess.parent.kind === 211 /* ExpressionStatement */); + var isLegalPosition; + if (propertyAccess.parent.kind === 195 /* BinaryExpression */) { + var initializerKind = propertyAccess.parent.right.kind; + isLegalPosition = (initializerKind === 200 /* ClassExpression */ || initializerKind === 187 /* FunctionExpression */) && + propertyAccess.parent.parent.parent.kind === 269 /* SourceFile */; + } + else { + isLegalPosition = propertyAccess.parent.parent.kind === 269 /* SourceFile */; + } + if (!isPrototypeProperty && (!targetSymbol || !(targetSymbol.flags & 1920 /* Namespace */)) && isLegalPosition) { + ts.Debug.assert(ts.isIdentifier(propertyAccess.expression)); + var identifier = propertyAccess.expression; + var flags = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags = 106639 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + if (targetSymbol) { + addDeclarationToSymbol(symbol, identifier, flags); + } + else { + targetSymbol = declareSymbol(container.locals, /*parent*/ undefined, identifier, flags, excludeFlags); + } } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { + if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */))) { return; } + // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); + // Declare the method/property + declareSymbol(symbolTable, targetSymbol, propertyAccess, 4 /* Property */, 0 /* PropertyExcludes */); } function bindCallExpression(node) { - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { setCommonJsModuleIndicator(node); } } function bindClassLikeDeclaration(node) { - if (node.kind === 229) { - bindBlockScopedDeclaration(node, 32, 899519); + if (node.kind === 230 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { - var bindingName = node.name ? node.name.escapedText : "__class"; - bindAnonymousDeclaration(node, 32, bindingName); + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier if (node.name) { classifiableNames.set(node.name.escapedText, true); } } var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 4194304, "prototype"); + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); if (symbolExport) { if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; } function bindEnumDeclaration(node) { return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128, 899967) - : bindBlockScopedDeclaration(node, 256, 899327); + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); } function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { @@ -20517,86 +24970,114 @@ var ts; bindBlockScopedVariableDeclaration(node); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 107455); + // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1, 107454); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); } } } function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { + if (inStrictMode && !(node.flags & 2097152 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 16777216 : 0), 0); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); } } function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; + emitFlags |= 1024 /* HasAsyncFunctions */; } } checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 106927); + bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16, 106927); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); } } function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; + emitFlags |= 1024 /* HasAsyncFunctions */; } } if (currentFlow) { node.flowNode = currentFlow; } checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.escapedText : "__function"; - return bindAnonymousDeclaration(node, 16, bindingName); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { - emitFlags |= 1024; + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { node.flowNode = currentFlow; } return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); } function checkUnreachable(node) { - if (!(currentFlow.flags & 1)) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || - node.kind === 229 || - (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 210 /* EmptyStatement */) || + // report error on class declarations + node.kind === 230 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 234 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 233 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || + !(node.flags & 2097152 /* Ambient */) && + (node.kind !== 209 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -20606,59 +25087,65 @@ var ts; return true; } } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 181: + case 182 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 182: + case 183 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 233: + case 234 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 185: + case 186 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 194: + case 195 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 210: + case 211 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 146: + case 147 /* Parameter */: return computeParameter(node, subtreeFlags); - case 187: + case 188 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 186: + case 187 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 228: + case 229 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 226: + case 227 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 227: + case 228 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 208: + case 209 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 222: + case 223 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 229: + case 230 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 199: + case 200 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 259: + case 263 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 260: + case 264 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 201: + case 202 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152: + case 153 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 149: + case 150 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 151: + case 152 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 237: + case 238 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 179: + case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -20670,618 +25157,765 @@ var ts; var expression = node.expression; var expressionKind = expression.kind; if (node.typeArguments) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 + if (subtreeFlags & 524288 /* ContainsSpread */ || isSuperOrSuperProperty(expression, expressionKind)) { - transformFlags |= 192; + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; } - if (expression.kind === 91) { - transformFlags |= 67108864; + if (expression.kind === 91 /* ImportKeyword */) { + transformFlags |= 67108864 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; } function isSuperOrSuperProperty(node, kind) { switch (kind) { - case 97: + case 97 /* SuperKeyword */: return true; - case 179: - case 180: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: var expression = node.expression; var expressionKind = expression.kind; - return expressionKind === 97; + return expressionKind === 97 /* SuperKeyword */; } return false; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288) { - transformFlags |= 192; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 178) { - transformFlags |= 8 | 192 | 3072; + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 179 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 && leftKind === 177) { - transformFlags |= 192 | 3072; + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 40 - || operatorTokenKind === 62) { - transformFlags |= 32; + else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ + || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; var name = node.name; var initializer = node.initializer; var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 + || subtreeFlags & 4096 /* ContainsDecorators */ || ts.isThisIdentifier(name)) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (ts.hasModifier(node, 92)) { - transformFlags |= 3 | 262144; + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 202 - || expressionKind === 184) { - transformFlags |= 3; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 203 /* AsExpression */ + || expressionKind === 185 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; } - if (expressionTransformFlags & 1024) { - transformFlags |= 1024; + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; - if (ts.hasModifier(node, 2)) { - transformFlags = 3; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) || node.typeParameters) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; } } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~539358529 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ || node.typeParameters) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~539358529 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { - case 85: - transformFlags |= 192; + case 85 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; break; - case 108: - transformFlags |= 3; + case 108 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 8; + transformFlags |= 8 /* AssertESNext */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192; + transformFlags |= 192 /* AssertES2015 */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537920833 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. if (node.decorators - || ts.hasModifier(node, 2270) + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768; + transformFlags |= 768 /* AssertGenerator */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. if (node.decorators - || ts.hasModifier(node, 2270) + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags | 3; + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // so that it handle the transformation. if (node.initializer) { - transformFlags |= 8192; + transformFlags |= 8192 /* ContainsPropertyInitializer */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; - if (!body || (modifierFlags & 2)) { - transformFlags = 3; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432; - if (modifierFlags & 2270 + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3; - } - if (modifierFlags & 256) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. if (node.asteriskToken) { - transformFlags |= 768; + transformFlags |= 768 /* AssertGenerator */; } } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601281857 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } - if (subtreeFlags & 163840) { - transformFlags |= 192; + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. if (node.asteriskToken) { - transformFlags |= 768; + transformFlags |= 768 /* AssertGenerator */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601281857 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (ts.hasModifier(node, 2270) + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - if (ts.hasModifier(node, 256)) { - transformFlags |= 16; + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } - if (subtreeFlags & 16384) { - transformFlags |= 32768; + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601249089 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionKind === 97 /* SuperKeyword */) { + transformFlags |= 16384 /* ContainsLexicalThis */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { - transformFlags |= 8; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; } + // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; - if (ts.hasModifier(node, 2)) { - transformFlags = 3; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { - transformFlags |= 192; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; } } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 - && ts.isIterationStatement(node, true)) { - transformFlags |= 192; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3; + transformFlags |= 3 /* AssertTypeScript */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 1024) { - transformFlags |= 192; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3; + var transformFlags = 3 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2) === 0) { + if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~574674241 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { - transformFlags |= 192; + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; } - if (node.flags & 3) { - transformFlags |= 192 | 4194304; + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257; + var excludeFlags = 536872257 /* NodeExcludes */; switch (kind) { - case 120: - case 191: - transformFlags |= 8 | 16; + case 120 /* AsyncKeyword */: + case 192 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 114: - case 112: - case 113: - case 117: - case 124: - case 76: - case 232: - case 264: - case 184: - case 202: - case 203: - case 131: - transformFlags |= 3; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 117 /* AbstractKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 204 /* NonNullExpression */: + case 131 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; break; - case 249: - case 250: - case 251: - case 10: - case 252: - case 253: - case 254: - case 255: - case 256: - transformFlags |= 4; + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 253 /* JsxClosingElement */: + case 254 /* JsxFragment */: + case 255 /* JsxOpeningFragment */: + case 256 /* JsxClosingFragment */: + case 257 /* JsxAttribute */: + case 258 /* JsxAttributes */: + case 259 /* JsxSpreadAttribute */: + case 260 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; break; - case 13: - case 14: - case 15: - case 16: - case 196: - case 183: - case 262: - case 115: - case 204: - transformFlags |= 192; + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 197 /* TemplateExpression */: + case 184 /* TaggedTemplateExpression */: + case 266 /* ShorthandPropertyAssignment */: + case 115 /* StaticKeyword */: + case 205 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; break; - case 9: + case 9 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192; + transformFlags |= 192 /* AssertES2015 */; } break; - case 8: - if (node.numericLiteralFlags & 48) { - transformFlags |= 192; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 216: + case 217 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 8; + transformFlags |= 8 /* AssertESNext */; } - transformFlags |= 192; + transformFlags |= 192 /* AssertES2015 */; break; - case 197: - transformFlags |= 8 | 192 | 16777216; + case 198 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; break; - case 119: - case 133: - case 130: - case 134: - case 136: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 158: - case 159: - case 160: - case 161: - case 162: - case 163: - case 164: - case 165: - case 166: - case 167: - case 168: - case 230: - case 231: - case 169: - case 170: - case 171: - case 172: - case 173: - case 236: - transformFlags = 3; - excludeFlags = -3; + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 134 /* ObjectKeyword */: + case 136 /* StringKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 146 /* TypeParameter */: + case 149 /* PropertySignature */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 159 /* TypePredicate */: + case 160 /* TypeReference */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 163 /* TypeQuery */: + case 164 /* TypeLiteral */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 170 /* ThisType */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 174 /* LiteralType */: + case 237 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; break; - case 144: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; + case 145 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 198: - transformFlags |= 192 | 524288; + case 199 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; break; - case 263: - transformFlags |= 8 | 1048576; + case 267 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; break; - case 97: - transformFlags |= 192; + case 97 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; break; - case 99: - transformFlags |= 16384; + case 99 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 16384 /* ContainsLexicalThis */; break; - case 174: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; + case 175 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545; + excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 175: - transformFlags |= 192 | 8388608; - excludeFlags = 537396545; + case 176 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 176: - transformFlags |= 192; + case 177 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288; + transformFlags |= 524288 /* ContainsRest */; } break; - case 147: - transformFlags |= 3 | 4096; + case 148 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; - case 178: - excludeFlags = 540087617; - if (subtreeFlags & 2097152) { - transformFlags |= 192; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; + case 179 /* ObjectLiteralExpression */: + excludeFlags = 540087617 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; } break; - case 177: - case 182: - excludeFlags = 537396545; - if (subtreeFlags & 524288) { - transformFlags |= 192; + case 178 /* ArrayLiteralExpression */: + case 183 /* NewExpression */: + excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; } break; - case 212: - case 213: - case 214: - case 215: - if (subtreeFlags & 4194304) { - transformFlags |= 192; + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 265: - if (subtreeFlags & 32768) { - transformFlags |= 192; + case 269 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; } break; - case 219: - case 217: - case 218: - transformFlags |= 33554432; + case 220 /* ReturnStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; break; } - node.transformFlags = transformFlags | 536870912; + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 && kind <= 173) { - return -3; + if (kind >= 159 /* FirstTypeNode */ && kind <= 174 /* LastTypeNode */) { + return -3 /* TypeExcludes */; } switch (kind) { - case 181: - case 182: - case 177: - return 537396545; - case 233: - return 574674241; - case 146: - return 536872257; - case 187: - return 601249089; - case 186: - case 228: - return 601281857; - case 227: - return 546309441; - case 229: - case 199: - return 539358529; - case 152: - return 601015617; - case 151: - case 153: - case 154: - return 601015617; - case 119: - case 133: - case 130: - case 136: - case 134: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 230: - case 231: - return -3; - case 178: - return 540087617; - case 260: - return 537920833; - case 174: - case 175: - return 537396545; + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 178 /* ArrayLiteralExpression */: + return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + case 234 /* ModuleDeclaration */: + return 574674241 /* ModuleExcludes */; + case 147 /* Parameter */: + return 536872257 /* ParameterExcludes */; + case 188 /* ArrowFunction */: + return 601249089 /* ArrowFunctionExcludes */; + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + return 601281857 /* FunctionExcludes */; + case 228 /* VariableDeclarationList */: + return 546309441 /* VariableDeclarationListExcludes */; + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + return 539358529 /* ClassExcludes */; + case 153 /* Constructor */: + return 601015617 /* ConstructorExcludes */; + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return 601015617 /* MethodOrAccessorExcludes */; + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 136 /* StringKeyword */: + case 134 /* ObjectKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 146 /* TypeParameter */: + case 149 /* PropertySignature */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 179 /* ObjectLiteralExpression */: + return 540087617 /* ObjectLiteralExcludes */; + case 264 /* CatchClause */: + return 537920833 /* CatchClauseExcludes */; + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: + return 537396545 /* BindingPatternExcludes */; default: - return 536872257; + return 536872257 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ function setParentPointers(parent, child) { child.parent = parent; ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); } })(ts || (ts = {})); +/** @internal */ var ts; (function (ts) { function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = []; - var visitedSymbols = []; + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol return { walkType: function (type) { try { @@ -21312,35 +25946,38 @@ var ts; return; } visitedTypes[type.id] = type; + // Reuse visitSymbol to visit the type's symbol, + // but be sure to bail on recuring into the type if accept declines the symbol. var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; - if (type.flags & 32768) { + // Visit the type's related types, if any + if (type.flags & 65536 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; - if (objectFlags & 4) { + if (objectFlags & 4 /* Reference */) { visitTypeReference(type); } - if (objectFlags & 32) { + if (objectFlags & 32 /* Mapped */) { visitMappedType(type); } - if (objectFlags & (1 | 2)) { + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { visitInterfaceType(type); } - if (objectFlags & (8 | 16)) { + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { visitObjectType(objectType); } } - if (type.flags & 16384) { + if (type.flags & 32768 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 196608) { + if (type.flags & 393216 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 262144) { + if (type.flags & 524288 /* Index */) { visitIndexType(type); } - if (type.flags & 524288) { + if (type.flags & 1048576 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -21387,10 +26024,11 @@ var ts; visitType(interfaceT.thisType); } function visitObjectType(type) { - var stringIndexType = getIndexTypeOfStructuredType(type, 0); + var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */); visitType(stringIndexType); - var numberIndexType = getIndexTypeOfStructuredType(type, 1); + var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */); visitType(numberIndexType); + // The two checks above *should* have already resolved the type (if needed), so this should be cached var resolved = resolveStructuredTypeMembers(type); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -21418,12 +26056,16 @@ var ts; return true; } var t = getTypeOfSymbol(symbol); - visitType(t); - if (symbol.flags & 1952) { + visitType(t); // Should handle members on classes and such + if (symbol.flags & 1952 /* HasExports */) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { - if (d.type && d.type.kind === 162) { + // Type queries are too far resolved when we just visit the symbol's type + // (their type resolved directly to the member deeply referenced) + // So to get the intervening symbols, we need to check if there's a type + // query node on any of the symbol's declarations and get symbols there + if (d.type && d.type.kind === 163 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -21434,6 +26076,10 @@ var ts; } ts.createGetSymbolWalker = createGetSymbolWalker; })(ts || (ts = {})); +/// +/// +/// +/* @internal */ var ts; (function (ts) { var ambientModuleSymbolRegex = /^".+"$/; @@ -21459,17 +26105,28 @@ var ts; ts.getSymbolId = getSymbolId; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); - return moduleState === 1 || - (preserveConstEnums && moduleState === 2); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; + // tslint:disable variable-name var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name var typeCount = 0; var symbolCount = 0; var enumCount = 0; @@ -21480,16 +26137,24 @@ var ts; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); - var undefinedSymbol = createSymbol(4, "undefined"); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4, "arguments"); + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; + // 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 + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -21598,12 +26263,12 @@ var ts; return parsed ? isImplementationOfOverload(parsed) : undefined; }, getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - links.immediateTarget = getTargetOfAliasDeclaration(node, true); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); } return links.immediateTarget; }, @@ -21625,18 +26290,39 @@ var ts; tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { - return tryFindAmbientModule(moduleName, false); + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, - getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -21644,42 +26330,57 @@ var ts; var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4, "unknown"); - var resolvingSymbol = createSymbol(0, "__resolving__"); - var anyType = createIntrinsicType(1, "any"); - var autoType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); - var stringType = createIntrinsicType(2, "string"); - var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); + var undefinedProperties = ts.createMap(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var undefinedType = createIntrinsicType(4096 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 /* Undefined */ | 4194304 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(8192 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 /* Null */ | 4194304 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(2 /* String */, "string"); + var numberType = createIntrinsicType(4 /* Number */, "number"); + var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); + var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); - var silentNeverType = createIntrinsicType(8192, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(2048 /* Void */, "void"); + var neverType = createIntrinsicType(16384 /* Never */, "never"); + var silentNeverType = createIntrinsicType(16384 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(16384 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(33554432 /* NonPrimitive */, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyGenericType.instantiations = ts.createMap(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 16777216 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); - var enumNumberIndexInfo = createIndexInfo(stringType, true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(32768 /* TypeParameter */); + var markerSubType = createType(32768 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(32768 /* TypeParameter */); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var ambientModulesCache; + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ var patternAmbientModules; var globalObjectType; var globalFunctionType; @@ -21693,6 +26394,9 @@ var ts; var anyArrayType; var autoArrayType; var anyReadonlyArrayType; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files var deferredGlobalESSymbolConstructorSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; @@ -21762,6 +26466,9 @@ var ts; TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; TypeFacts[TypeFacts["All"] = 8388607] = "All"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; @@ -21796,29 +26503,29 @@ var ts; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ - "string": 1, - "number": 2, - "boolean": 4, - "symbol": 8, - "undefined": 16384, - "object": 16, - "function": 32 + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + boolean: 4 /* TypeofEQBoolean */, + symbol: 8 /* TypeofEQSymbol */, + undefined: 16384 /* EQUndefined */, + object: 16 /* TypeofEQObject */, + function: 32 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128, - "number": 256, - "boolean": 512, - "symbol": 1024, - "undefined": 131072, - "object": 2048, - "function": 4096 + string: 128 /* TypeofNEString */, + number: 256 /* TypeofNENumber */, + boolean: 512 /* TypeofNEBoolean */, + symbol: 1024 /* TypeofNESymbol */, + undefined: 131072 /* NEUndefined */, + object: 2048 /* TypeofNEObject */, + function: 4096 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType + string: stringType, + number: numberType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType }); var typeofType = createTypeofType(); var _jsxNamespace; @@ -21827,22 +26534,14 @@ var ts; var _hasComputedJsxElementPropertiesName = false; var _jsxElementChildrenPropertyName; var _hasComputedJsxElementChildrenPropertyName = false; + /** Things we lazy load from the JSX namespace */ var jsxTypes = ts.createUnderscoreEscapedMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); + // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; (function (TypeSystemPropertyName) { @@ -21857,6 +26556,29 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["Readonly"] = 1] = "Readonly"; + MappedTypeModifiers[MappedTypeModifiers["Optional"] = 2] = "Optional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -21878,58 +26600,60 @@ var ts; return _jsxNamespace; } function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. getDiagnostics(sourceFile, cancellationToken); return emitResolver; } - function error(location, message, arg0, arg1, arg2) { + function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); } - function createSymbol(flags, name) { + function createSymbol(flags, name, checkFlags) { symbolCount++; - var symbol = (new Symbol(flags | 33554432, name)); - symbol.checkFlags = 0; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = checkFlags || 0; return symbol; } function isTransientSymbol(symbol) { - return (symbol.flags & 33554432) !== 0; + return (symbol.flags & 33554432 /* Transient */) !== 0; } function getExcludedSymbolFlags(flags) { var result = 0; - if (flags & 2) - result |= 107455; - if (flags & 1) - result |= 107454; - if (flags & 4) - result |= 0; - if (flags & 8) - result |= 900095; - if (flags & 16) - result |= 106927; - if (flags & 32) - result |= 899519; - if (flags & 64) - result |= 792968; - if (flags & 256) - result |= 899327; - if (flags & 128) - result |= 899967; - if (flags & 512) - result |= 106639; - if (flags & 8192) - result |= 99263; - if (flags & 32768) - result |= 41919; - if (flags & 65536) - result |= 74687; - if (flags & 262144) - result |= 530920; - if (flags & 524288) - result |= 793064; - if (flags & 2097152) - result |= 2097152; + if (flags & 2 /* BlockScopedVariable */) + result |= 107455 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 107454 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 900095 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 106927 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 899519 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 792968 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 106639 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 99263 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 41919 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 74687 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 530920 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 793064 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; return result; } function recordMergedSymbol(target, source) { @@ -21955,14 +26679,18 @@ var ts; return result; } function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { - if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + source.flags & 67108864 /* JSContainer */ || target.flags & 67108864 /* JSContainer */) { + // Javascript static-property-assignment declarations always merge, even though they are also values + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums target.constEnumOnlyModule = false; } target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { + (target.valueDeclaration.kind === 234 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 234 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -21978,11 +26706,11 @@ var ts; } recordMergedSymbol(target, source); } - else if (target.flags & 1024) { + else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { - var message_2 = target.flags & 2 || source.flags & 2 + var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); @@ -21992,6 +26720,16 @@ var ts; }); } } + function combineSymbolTables(first, second) { + if (!first || first.size === 0) + return second; + if (!second || second.size === 0) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); @@ -21999,7 +26737,7 @@ var ts; target.set(id, sourceSymbol); } else { - if (!(targetSymbol.flags & 33554432)) { + if (!(targetSymbol.flags & 33554432 /* Transient */)) { targetSymbol = cloneSymbol(targetSymbol); target.set(id, targetSymbol); } @@ -22010,6 +26748,9 @@ var ts; function mergeModuleAugmentation(moduleName) { var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); return; } @@ -22017,19 +26758,25 @@ var ts; mergeSymbolTable(globals, moduleAugmentation.symbol.exports); } else { - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152 /* Ambient */) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); if (!mainModule) { return; } + // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & 33554432 /* Transient */ ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } else { + // moduleName will be a StringLiteral since this is not `declare global`. error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); } } @@ -22038,6 +26785,7 @@ var ts; source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); if (targetSymbol) { + // Error on redeclarations ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); } else { @@ -22049,7 +26797,7 @@ var ts; } } function getSymbolLinks(symbol) { - if (symbol.flags & 33554432) + if (symbol.flags & 33554432 /* Transient */) return symbol; var id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); @@ -22058,34 +26806,39 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } - function getObjectFlags(type) { - return type.flags & 32768 ? type.objectFlags : 0; - } function isGlobalSourceFile(node) { - return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 269 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } - if (symbol.flags & 2097152) { + if (symbol.flags & 2097152 /* Alias */) { var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors if (target === unknownSymbol || target.flags & meaning) { return symbol; } } } } + // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -22098,9 +26851,12 @@ var ts; if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - ts.isInAmbientContext(declaration)) { + declaration.flags & 2097152 /* Ambient */) { + // nodes are in different files and order cannot be determined return true; } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { return true; } @@ -22108,23 +26864,37 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - if (declaration.kind === 176) { - var errorBindingElement = ts.getAncestor(usage, 176); + // declaration is before usage + if (declaration.kind === 177 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 177 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 227 /* VariableDeclaration */), usage); } - else if (declaration.kind === 226) { + else if (declaration.kind === 227 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return true; } - if (usage.parent.kind === 246 || (usage.parent.kind === 243 && usage.parent.isExportEquals)) { + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + if (usage.parent.kind === 247 /* ExportSpecifier */ || (usage.parent.kind === 244 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // export specifiers do not use the variable, they only make it available for use return true; } - if (usage.kind === 243 && usage.isExportEquals) { + // When resolving symbols for exports, the `usage` location passed in can be the export site directly + if (usage.kind === 244 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -22132,14 +26902,17 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 208: - case 214: - case 216: + case 209 /* VariableStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { return true; } break; } + // ForIn/ForOf case - use site should not be used in expression part return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { @@ -22151,16 +26924,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 149 && + current.parent.kind === 150 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { - if (ts.hasModifier(current.parent, 32)) { - if (declaration.kind === 151) { + if (ts.hasModifier(current.parent, 32 /* Static */)) { + if (declaration.kind === 152 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !ts.hasModifier(declaration, 32); + var isDeclarationInstanceProperty = declaration.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -22169,34 +26942,55 @@ var ts; }); } } + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { - var originalLocation = location; + var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; var isInExternalModule = false; loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 275) { - useResult = result.flags & 262144 + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 279 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 146 || - lastLocation.kind === 145 + lastLocation.kind === 147 /* Parameter */ || + lastLocation.kind === 146 /* TypeParameter */ + // local types not visible outside the function body : false; } - if (meaning & 107455 && result.flags & 1) { + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 146 || + lastLocation.kind === 147 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 146); + result.valueDeclaration.kind === 147 /* Parameter */); } } if (useResult) { @@ -22208,13 +27002,16 @@ var ts; } } switch (location.kind) { - case 265: + case 269 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 233: + // falls through + case 234 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 || ts.isAmbientModule(location)) { + if (location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. if (result = moduleExports.get("default")) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { @@ -22222,48 +27019,70 @@ var ts; } result = undefined; } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. var moduleExport = moduleExports.get(name); if (moduleExport && - moduleExport.flags === 2097152 && - ts.getDeclarationOfKind(moduleExport, 246)) { + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 247 /* ExportSpecifier */)) { break; } } - if (result = lookup(moduleExports, name, meaning & 2623475)) { + if (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */)) { break loop; } break; - case 232: - if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { + case 233 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 149: - case 148: - if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455)) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } } } break; - case 229: - case 199: - case 230: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container result = undefined; break; } - if (lastLocation && ts.hasModifier(lastLocation, 32)) { + if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } break loop; } - if (location.kind === 199 && meaning & 32) { + if (location.kind === 200 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -22271,10 +27090,11 @@ var ts; } } break; - case 201: - if (lastLocation === location.expression && location.parent.token === 85) { + case 202 /* ExpressionWithTypeArguments */: + // The type parameters of a class are not in scope in the base class expression. + if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 793064 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -22282,33 +27102,42 @@ var ts; } } break; - case 144: + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 145 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (ts.isClassLike(grandparent) || grandparent.kind === 231 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 187: - if (meaning & 3 && name === "arguments") { + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 186: - if (meaning & 3 && name === "arguments") { + case 187 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } - if (meaning & 16) { + if (meaning & 16 /* Function */) { var functionName = location.name; if (functionName && name === functionName.escapedText) { result = location.symbol; @@ -22316,24 +27145,44 @@ var ts; } } break; - case 147: - if (location.parent && location.parent.kind === 146) { + case 148 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 147 /* Parameter */) { location = location.parent; } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // if (location.parent && ts.isClassElement(location.parent)) { location = location.parent; } break; } + if (location.kind !== 208 /* Block */) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. + // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 265); + ts.Debug.assert(lastLocation.kind === 269 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -22352,7 +27201,7 @@ var ts; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); } } if (!suggestion) { @@ -22363,23 +27212,38 @@ var ts; } return undefined; } + // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. var propertyName = propertyWithInvalidInitializer.name; error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); return undefined; } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped if (errorLocation && - (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455))) { + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 107455) === 107455) { + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236) { + if (decls && decls.length === 1 && decls[0].kind === 237 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -22387,22 +27251,22 @@ var ts; return result; } function diagnosticName(nameArg) { - return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 145 && decl.parent === container) { + if (decl.kind === 146 /* TypeParameter */ && decl.parent === container) { return true; } } return false; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if ((errorLocation.kind === 71 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } - var container = ts.getThisContainer(errorLocation, true); + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); var location = container; while (location) { if (ts.isClassLike(location.parent)) { @@ -22410,12 +27274,15 @@ var ts; if (!classSymbol) { break; } + // Check to see if a static member exists. var constructorType = getTypeOfSymbol(classSymbol); if (getPropertyOfType(constructorType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); return true; } - if (location === container && !ts.hasModifier(location, 32)) { + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !ts.hasModifier(location, 32 /* Static */)) { var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); @@ -22429,35 +27296,41 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); + var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); if (isError) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); } return isError; } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ function getEntityNameForExtendingInterface(node) { switch (node.kind) { - case 71: - case 179: + case 71 /* Identifier */: + case 180 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; + case 202 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through default: return undefined; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); - var parent_5 = errorLocation.parent; + if (meaning === 1920 /* Namespace */) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~1920 /* Namespace */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var parent = errorLocation.parent; if (symbol) { - if (ts.isQualifiedName(parent_5)) { - ts.Debug.assert(parent_5.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); - var propName = parent_5.right.escapedText; + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); if (propType) { - error(parent_5, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); return true; } } @@ -22468,13 +27341,13 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024)) { + if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); - if (symbol && !(symbol.flags & 1024)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } @@ -22482,15 +27355,15 @@ var ts; return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined, false)); + if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined, false)); + else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -22499,33 +27372,38 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { - ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 233 /* EnumDeclaration */) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { - if (result.flags & 2) { + if (!(declaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + if (result.flags & 2 /* BlockScopedVariable */) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 32) { + else if (result.flags & 32 /* Class */) { error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } - else if (result.flags & 256) { + else if (result.flags & 256 /* RegularEnum */) { error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ function isSameScopeDescendentOf(initial, parent, stopAt) { return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { - case 237: + case 238 /* ImportEqualsDeclaration */: return node; - case 239: + case 240 /* ImportClause */: return node.parent; - case 240: + case 241 /* NamespaceImport */: return node.parent.parent; - case 242: + case 243 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -22535,7 +27413,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248) { + if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -22566,11 +27444,29 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (793064 | 1920)) { + if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -22585,12 +27481,12 @@ var ts; return result; } function getExportOfModule(symbol, name, dontResolveAlias) { - if (symbol.flags & 1536) { + if (symbol.flags & 1536 /* Module */) { return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); } } function getPropertyOfVariable(symbol, name) { - if (symbol.flags & 3) { + if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); @@ -22601,28 +27497,31 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { - var name_12 = specifier.propertyName || specifier.name; - if (name_12.escapedText) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_12.escapedText); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_12.escapedText); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); } + // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name_12.escapedText, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name_12.escapedText === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_12, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_12)); + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); } return symbol; } @@ -22637,39 +27536,42 @@ var ts; function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); + resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { - case 237: + case 238 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239: + case 240 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240: + case 241 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242: + case 243 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246: - return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); - case 243: + case 247 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 244 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236: + case 237 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); } } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 107455 | 793064 | 1920; } - return symbol && (symbol.flags & (2097152 | excludes)) === 2097152; + if (excludes === void 0) { excludes = 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */; } + return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; } function resolveSymbol(symbol, dontResolveAlias) { var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); return shouldResolve ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { - ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); var links = getSymbolLinks(symbol); if (!links.target) { links.target = resolvingSymbol; @@ -22693,76 +27595,102 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } } } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). function markAliasSymbolAsReferenced(symbol) { var links = getSymbolLinks(symbol); if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 243) { + if (node.kind === 244 /* ExportAssignment */) { + // export default checkExpressionCached(node.expression); } - else if (node.kind === 246) { + else if (node.kind === 247 /* ExportSpecifier */) { + // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = checkExpressionCached(node.moduleReference); } } } + // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 71 || entityName.parent.kind === 143) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); + // Check for case 1 and 3 in the above example + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 144 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 237); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 238 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); } + /** + * Resolves a qualified name and any involved aliases. + */ function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } var symbol; - if (name.kind === 71) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, true); + if (name.kind === 71 /* Identifier */) { + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, /*isUse*/ true); if (!symbol) { return undefined; } } - else if (name.kind === 143 || name.kind === 179) { + else if (name.kind === 144 /* QualifiedName */ || name.kind === 180 /* PropertyAccessExpression */) { var left = void 0; - if (name.kind === 143) { + if (name.kind === 144 /* QualifiedName */) { left = name.left; } - else if (name.kind === 179 && - (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { + else if (name.kind === 180 /* PropertyAccessExpression */ && + (name.expression.kind === 186 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { left = name.expression; } else { + // If the expression in property-access expression is not entity-name or parenthsizedExpression (e.g. it is a call expression), it won't be able to successfully resolve the name. + // This is the case when we are trying to do any language service operation in heritage clauses. By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression + // will attempt to checkPropertyAccessExpression to resolve symbol. + // i.e class C extends foo()./*do language service operation here*/B {} return undefined; } - var right = name.kind === 143 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); + var right = name.kind === 144 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } else if (namespace === unknownSymbol) { return namespace; } + if (ts.isInJavaScriptFile(name) && ts.isDeclarationOfFunctionOrClassExpression(namespace)) { + namespace = getSymbolOfNode(namespace.valueDeclaration.initializer); + } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { @@ -22771,7 +27699,11 @@ var ts; return undefined; } } - else if (name.kind === 185) { + else if (name.kind === 186 /* ParenthesizedExpression */) { + // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. + // This is the case when we are trying to do any language service operation in heritage clauses. + // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. + // i.e class C extends foo()./*do language service operation here*/B {} return ts.isEntityNameExpression(name.expression) ? resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : undefined; @@ -22779,7 +27711,7 @@ var ts; else { ts.Debug.assertNever(name, "Unknown entity name kind."); } - ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -22787,7 +27719,7 @@ var ts; } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } - if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { + if (moduleReferenceExpression.kind !== 9 /* StringLiteral */ && moduleReferenceExpression.kind !== 13 /* NoSubstitutionTemplateLiteral */) { return; } var moduleReferenceLiteral = moduleReferenceExpression; @@ -22803,7 +27735,7 @@ var ts; var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/"); error(errorNode, diag, withoutAtTypePrefix, moduleReference); } - var ambientModule = tryFindAmbientModule(moduleReference, true); + var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true); if (ambientModule) { return ambientModule; } @@ -22812,9 +27744,11 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { + // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); } if (moduleNotFoundError) { + // report errors only if it was requested error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; @@ -22825,19 +27759,22 @@ var ts; return getMergedSymbol(pattern.symbol); } } + // May be an untyped module. If so, ignore resolutionDiagnostic. if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. return undefined; } if (moduleNotFoundError) { + // report errors only if it was requested if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -22854,18 +27791,23 @@ var ts; } return undefined; } + // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, + // and an external module with no 'export =' declaration resolves to the module itself. function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias)) || moduleSymbol; } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { + if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); } return symbol; } function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -22886,23 +27828,33 @@ var ts; } function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); - if (!symbol) { - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); - } + if (symbol) { + return symbol; } - return symbol; + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 16382 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; } function getExportsOfModule(moduleSymbol) { var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { if (id === "default") return; var targetSymbol = target.get(id); @@ -22927,14 +27879,18 @@ var ts; } function getExportsOfModuleWorker(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.flags & 1952 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); - var exportStars = symbol.exports.get("__export"); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = ts.createMap(); @@ -22946,6 +27902,7 @@ var ts; } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { return; } @@ -22964,24 +27921,24 @@ var ts; return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; } function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); } function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576) !== 0 + return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) : symbol; } function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 107455); + return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 152 && ts.nodeIsPresent(member.body)) { + if (member.kind === 153 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -22999,12 +27956,12 @@ var ts; } function createBooleanType(trueFalseTypes) { var type = getUnionType(trueFalseTypes); - type.flags |= 8; + type.flags |= 8 /* Boolean */; type.intrinsicName = "boolean"; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(32768); + var type = createType(65536 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; return type; @@ -23012,11 +27969,15 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. function isReservedMemberName(name) { - return name.charCodeAt(0) === 95 && - name.charCodeAt(1) === 95 && - name.charCodeAt(2) !== 95 && - name.charCodeAt(2) !== 64; + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; } function getNamedMembers(members) { var result; @@ -23043,23 +28004,25 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - for (var location_1 = enclosingDeclaration; location_1; location_1 = location_1.parent) { - if (location_1.locals && !isGlobalSourceFile(location_1)) { - if (result = callback(location_1.locals)) { + for (var location = enclosingDeclaration; location; location = location.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { return result; } } - switch (location_1.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location_1)) { + switch (location.kind) { + case 269 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 233: - if (result = callback(getSymbolOfNode(location_1).exports)) { + // falls through + case 234 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { return result; } break; @@ -23068,7 +28031,8 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -23085,11 +28049,16 @@ var ts; return result; } function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); } @@ -23097,19 +28066,23 @@ var ts; return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName))) { return [symbol]; } + // Check if symbol is any of the alias return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 2097152 + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246) && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { return [symbolFromSymbolTable]; } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); @@ -23121,18 +28094,24 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); if (!symbolFromSymbolTable) { + // Continue to the next symbol table return false; } + // If the symbol with this name is present it should refer to the symbol if (symbolFromSymbolTable === symbol) { + // No need to qualify return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 247 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; } + // Continue to the next symbol table return false; }); return qualify; @@ -23142,10 +28121,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 149: - case 151: - case 153: - case 154: + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: continue; default: return false; @@ -23156,93 +28135,132 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); - return access.accessibility === 0; - } + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { - accessibility: 1, + accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, }; } return hasAccessibleDeclarations; } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification meaningToLook = getQualifiedLeftMeaning(meaning); symbol = getParentOfSymbol(symbol); } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible return { - accessibility: 2, + accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } } + // Just a local name that is not accessible return { - accessibility: 1, + accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), }; } - return { accessibility: 0 }; + return { accessibility: 0 /* Accessible */ }; function getExternalModuleContainer(declaration) { var node = ts.findAncestor(declaration, hasExternalModuleSymbol); return node && getSymbolOfNode(node); } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; } - return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; function getIsDeclarationVisible(declaration) { if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !ts.hasModifier(anyImportSyntax, 1) && + !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); } return true; } + // Declaration is not visible return false; } return true; } } function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning = 107455 | 1048576; - } - else if (entityName.kind === 143 || entityName.kind === 179 || - entityName.parent.kind === 237) { - meaning = 1920; + if (entityName.parent.kind === 163 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 145 /* ComputedPropertyName */) { + // Typeof value + meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 144 /* QualifiedName */ || entityName.kind === 180 /* PropertyAccessExpression */ || + entityName.parent.kind === 238 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; } else { - meaning = 793064; + // Type Reference or TypeAlias entity = Identifier + meaning = 793064 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); - return (symbol && hasVisibleDeclarations(symbol, true)) || { - accessibility: 1, + 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)) || { + accessibility: 1 /* NotAccessible */, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier }; @@ -23273,9 +28291,9 @@ var ts; var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4, typeNode, sourceFile, writer); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; + var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -23285,19 +28303,19 @@ var ts; if (!flags) { return result; } - if (flags & 8) { + if (flags & 8 /* NoTruncation */) { result |= ts.NodeBuilderFlags.NoTruncation; } - if (flags & 256) { + if (flags & 256 /* UseFullyQualifiedType */) { result |= ts.NodeBuilderFlags.UseFullyQualifiedType; } - if (flags & 4096) { + if (flags & 4096 /* SuppressAnyReturnType */) { result |= ts.NodeBuilderFlags.SuppressAnyReturnType; } - if (flags & 1) { + if (flags & 1 /* WriteArrayAsGenericType */) { result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; } - if (flags & 64) { + if (flags & 64 /* WriteTypeArgumentsOfSignature */) { result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; } return result; @@ -23306,18 +28324,21 @@ var ts; function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; @@ -23339,56 +28360,59 @@ var ts; context.encounteredError = true; return undefined; } - if (type.flags & 1) { - return ts.createKeywordTypeNode(119); + if (type.flags & 1 /* Any */) { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); } - if (type.flags & 2) { - return ts.createKeywordTypeNode(136); + if (type.flags & 2 /* String */) { + return ts.createKeywordTypeNode(136 /* StringKeyword */); } - if (type.flags & 4) { - return ts.createKeywordTypeNode(133); + if (type.flags & 4 /* Number */) { + return ts.createKeywordTypeNode(133 /* NumberKeyword */); } - if (type.flags & 8) { - return ts.createKeywordTypeNode(122); + if (type.flags & 8 /* Boolean */) { + return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 256 && !(type.flags & 65536)) { + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 793064, false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); - return ts.createTypeReferenceNode(enumLiteralName, undefined); + var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } - if (type.flags & 272) { - var name_13 = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name_13, undefined); + if (type.flags & 272 /* EnumLike */) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (32)) { - return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); + if (type.flags & (32 /* StringLiteral */)) { + return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (64)) { + if (type.flags & (64 /* NumberLiteral */)) { return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 128) { + if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 1024) { - return ts.createKeywordTypeNode(105); + if (type.flags & 1024 /* UniqueESSymbol */) { + return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); + } + if (type.flags & 2048 /* Void */) { + return ts.createKeywordTypeNode(105 /* VoidKeyword */); } - if (type.flags & 2048) { - return ts.createKeywordTypeNode(139); + if (type.flags & 4096 /* Undefined */) { + return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); } - if (type.flags & 4096) { - return ts.createKeywordTypeNode(95); + if (type.flags & 8192 /* Null */) { + return ts.createKeywordTypeNode(95 /* NullKeyword */); } - if (type.flags & 8192) { - return ts.createKeywordTypeNode(130); + if (type.flags & 16384 /* Never */) { + return ts.createKeywordTypeNode(130 /* NeverKeyword */); } - if (type.flags & 512) { - return ts.createKeywordTypeNode(137); + if (type.flags & 512 /* ESSymbol */) { + return ts.createKeywordTypeNode(137 /* SymbolKeyword */); } - if (type.flags & 16777216) { - return ts.createKeywordTypeNode(134); + if (type.flags & 33554432 /* NonPrimitive */) { + return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } - if (type.flags & 16384 && type.isThisType) { + if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; @@ -23396,25 +28420,26 @@ var ts; } return ts.createThis(); } - var objectFlags = getObjectFlags(type); - if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 32768)); + var objectFlags = ts.getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 16384 || objectFlags & 3) { - var name_14 = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name_14, undefined); + if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = type.symbol ? symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); + // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. + return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { - var name_15 = symbolToTypeReferenceName(type.aliasSymbol); + var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name_15, typeArgumentNodes); + return ts.createTypeReferenceNode(name, typeArgumentNodes); } - if (type.flags & (65536 | 131072)) { - var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; + if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { + var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; var typeNodes = mapToTypeNodes(types, context); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 ? 166 : 167, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 /* Union */ ? 167 /* UnionType */ : 168 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -23424,49 +28449,55 @@ var ts; return undefined; } } - if (objectFlags & (16 | 32)) { - ts.Debug.assert(!!(type.flags & 32768)); + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 262144) { + if (type.flags & 524288 /* Index */) { var indexedType = type.type; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 524288) { + if (type.flags & 1048576 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768)); - var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; - var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; + var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); - return ts.setEmitFlags(mappedTypeNode, 1); + return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512) || + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455); + return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); } else if (ts.contains(context.symbolStack, symbol)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - var entityName = symbolToName(typeAlias, context, 793064, false); - return ts.createTypeReferenceNode(entityName, undefined); + // The specified symbol flags need to be reinterpreted as type flags + var entityName = symbolToName(typeAlias, context, 793064 /* Type */, /*expectsIdentifier*/ false); + return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); } else { - return ts.createKeywordTypeNode(119); + return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type if (!context.symbolStack) { context.symbolStack = []; } @@ -23477,18 +28508,20 @@ var ts; } } else { + // Anonymous types without a symbol are never circular. return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192) && - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; + return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); + // typeof is allowed only for static/non local functions + return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively } } } @@ -23499,16 +28532,16 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 162 /* ConstructorType */, context); return signatureNode; } } @@ -23517,14 +28550,15 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { - var entityName = symbolToName(symbol, context, symbolFlags, false); + var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); return ts.createTypeQueryNode(entityName); } function symbolToTypeReferenceName(symbol) { - var entityName = symbol.flags & 32 || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); return entityName; } function typeReferenceToTypeNode(type) { @@ -23537,7 +28571,7 @@ var ts; var elementType = typeToTypeNodeHelper(typeArguments[0], context); return ts.createArrayTypeNode(elementType); } - else if (type.target.objectFlags & 8) { + else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { @@ -23557,23 +28591,26 @@ var ts; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent_6); - (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; + var namePart = symbolToTypeReferenceName(parent); + (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, undefined); + qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); } else { - qualifiedName = ts.createQualifiedName(namePart, undefined); + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); } } } @@ -23594,7 +28631,7 @@ var ts; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 ? entityName : entityName.right; + var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; lastIdentifier.typeArguments = undefined; } return ts.createTypeReferenceNode(entityName, typeArgumentNodes); @@ -23602,12 +28639,12 @@ var ts; } function addToQualifiedNameMissingRightIdentifier(left, right) { ts.Debug.assert(left.right === undefined); - if (right.kind === 71) { + if (right.kind === 71 /* Identifier */) { left.right = right; return left; } var rightPart = right; - while (rightPart.left.kind !== 71) { + while (rightPart.left.kind !== 71 /* Identifier */) { rightPart = rightPart.left; } left.right = rightPart.left; @@ -23618,17 +28655,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); } var properties = resolvedType.properties; if (!properties) { @@ -23639,23 +28676,24 @@ var ts; var propertyType = getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - var propertyName = symbolToName(propertySymbol, context, 107455, true); + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; - if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0); + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 151 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); } } else { - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined; + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); typeElements.push(propertySignature); } } @@ -23665,8 +28703,8 @@ var ts; function mapToTypeNodes(types, context) { if (ts.some(types)) { var result = []; - for (var i = 0; i < types.length; ++i) { - var type = types[i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -23677,10 +28715,16 @@ var ts; } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; - var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 136 /* StringKeyword */ : 133 /* NumberKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); var typeNode = typeToTypeNodeHelper(indexInfo.type, context); - return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); @@ -23692,8 +28736,8 @@ var ts; var returnTypeNode; if (signature.typePredicate) { var typePredicate = signature.typePredicate; - var parameterName = typePredicate.kind === 1 ? - ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : + var parameterName = typePredicate.kind === 1 /* Identifier */ ? + ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : ts.createThisTypeNode(); var typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode); @@ -23703,17 +28747,17 @@ var ts; returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { - if (returnTypeNode && returnTypeNode.kind === 119) { + if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } } else if (!returnTypeNode) { - returnTypeNode = ts.createKeywordTypeNode(119); + returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); } function typeParameterToDeclaration(type, context) { - var name = symbolToName(type.symbol, context, 793064, true); + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); @@ -23721,42 +28765,45 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); - if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { - return ts.createParameter(undefined, undefined, parameterSymbol.isRestParameter ? ts.createToken(24) : undefined, "args", undefined, typeToTypeNodeHelper(anyArrayType, context), undefined); - } - var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; - var name = parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : - cloneBindingName(parameterDeclaration.name) : - ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); - var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 147 /* Parameter */); + ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); var parameterType = getTypeOfSymbol(parameterSymbol); - if (isRequiredInitializedParameter(parameterDeclaration)) { - parameterType = getNullableType(parameterType, 2048); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); + var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var parameterNode = ts.createParameter( + /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + /*initializer*/ undefined); return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 176) { + if (clone.kind === 177 /* BindingElement */) { clone.initializer = undefined; } - return ts.setEmitFlags(clone, 1 | 16777216); + return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } function symbolToName(symbol, context, meaning, expectsIdentifier) { + // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; - var isTypeParameter = symbol.flags & 262144; + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { - chain = getSymbolChain(symbol, meaning, true); + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { @@ -23775,31 +28822,32 @@ var ts; if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { var parentSymbol = chain[index - 1]; var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); } else { var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); } } typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol, context); - var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - var parentChain = getSymbolChain(parent_7, getQualifiedLeftMeaning(meaning), false); + // Go up and add our parent. + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { - parentSymbol = parent_7; + parentSymbol = parent; accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); } } @@ -23807,9 +28855,13 @@ var ts; if (accessibleSymbolChain) { return accessibleSymbolChain; } - if (endOfChain || + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { return [symbol]; } } @@ -23826,10 +28878,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 65536) { + if (!(t.flags & 12288 /* Nullable */)) { + if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { + var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 131072 /* Union */) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -23841,25 +28893,25 @@ var ts; result.push(t); } } - if (flags & 4096) + if (flags & 8192 /* Null */) result.push(nullType); - if (flags & 2048) + if (flags & 4096 /* Undefined */) result.push(undefinedType); return result || types; } function visibilityToString(flags) { - if (flags === 8) { + if (flags === 8 /* Private */) { return "private"; } - if (flags === 16) { + if (flags === 16 /* Protected */) { return "protected"; } return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); - if (node.kind === 231) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 169 /* ParenthesizedType */; }); + if (node.kind === 232 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -23867,71 +28919,96 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 234 && + node.parent.kind === 235 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } - function getNameOfSymbol(symbol, context) { + return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; + } + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name_16 = ts.getNameOfDeclaration(declaration); - if (name_16) { - return ts.declarationNameToString(name_16); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 226) { + if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { context.encounteredError = true; } switch (declaration.kind) { - case 199: + case 200 /* ClassExpression */: return "(Anonymous class)"; - case 186: - case 187: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return "(Anonymous function)"; } } if (symbol.syntheticLiteralTypeOrigin) { var stringValue = symbol.syntheticLiteralTypeOrigin.value; if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { - return "\"" + ts.escapeString(stringValue, 34) + "\""; + return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; } } - return ts.unescapeLeadingUnderscores(symbol.escapedName); + return ts.symbolName(symbol); } function getSymbolDisplayBuilder() { + /** + * Writes only the name of the symbol out to the writer. Uses the original source text + * for the name of the symbol if it is available to match how the user wrote the name. + */ function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); + writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); } + /** + * Writes a property access or element access with the name of the symbol out to the writer. + * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, + * ensuring that any names written with literals use element accesses. + */ function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); + var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 21); + if (firstChar !== 91 /* openBracket */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + } if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 22); + if (firstChar !== 91 /* openBracket */) { + writePunctuation(writer, 22 /* CloseBracketToken */); + } } else { - writePunctuation(writer, 23); + writePunctuation(writer, 23 /* DotToken */); writer.writeSymbol(symbolName, symbol); } } + /** + * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope + * Meaning needs to be specified if the enclosing declaration is given + */ function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { var parentSymbol; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + // Write type arguments of instantiated class/interface here + if (flags & 1 /* WriteTypeParametersOrArguments */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); } else { @@ -23945,14 +29022,23 @@ var ts; } parentSymbol = symbol; } + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // this to determine if an import it has previously seen (and not written out) needs + // to be written to the file once the walk of the tree is complete. + // + // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree + // up front (for example, during checking) could determine if we need to emit the imports + // and we could then access that data during declaration emit. writer.trackSymbol(symbol, enclosingDeclaration, meaning); + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_8) { - walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); + // Go up and add our parent. + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23961,151 +29047,182 @@ var ts; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } - else if (endOfChain || + else if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { appendParentTypeArgumentsAndSymbolName(symbol); } } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 256 & typeFlags; + // Get qualified name if the symbol is not a type parameter + // and there is an enclosing declaration or we specifically + // asked for it + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); + walkSymbol(symbol, meaning, /*endOfChain*/ true); } else { appendParentTypeArgumentsAndSymbolName(symbol); } } function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 | 16384); + var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - var nextFlags = flags & ~1024; - if (type.flags & 16793231) { - writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) + var nextFlags = flags & ~1024 /* InTypeAlias */; + // Write undefined/null type as any + if (type.flags & 33585807 /* Intrinsic */) { + // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving + writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 16384 && type.isThisType) { + else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (getObjectFlags(type) & 4) { + else if (ts.getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 && !(type.flags & 65536)) { - var parent_9 = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent_9, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent_9) !== type) { - writePunctuation(writer, 23); + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { + var parent = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + // In a literal enum type with a single member E { A }, E and E.A denote the + // same type. We always display this type simply as E. + if (getDeclaredTypeOfSymbol(parent) !== type) { + writePunctuation(writer, 23 /* DotToken */); appendSymbolNameOnly(type.symbol, writer); } } - else if (getObjectFlags(type) & 3 || type.flags & (272 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 1024) && type.aliasSymbol && - ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { + else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && + ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } - else if (type.flags & 196608) { + else if (type.flags & 393216 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); } - else if (getObjectFlags(type) & (16 | 32)) { + else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { writeAnonymousType(type, nextFlags); } - else if (type.flags & 96) { + else if (type.flags & 1024 /* UniqueESSymbol */) { + if (flags & 131072 /* AllowUniqueESSymbolType */) { + writeKeyword(writer, 140 /* UniqueKeyword */); + writeSpace(writer); + } + else { + writer.reportInaccessibleUniqueSymbolError(); + } + writeKeyword(writer, 137 /* SymbolKeyword */); + } + else if (type.flags & 96 /* StringOrNumberLiteral */) { writer.writeStringLiteral(literalTypeToString(type)); } - else if (type.flags & 262144) { - if (flags & 128) { - writePunctuation(writer, 19); + else if (type.flags & 524288 /* Index */) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); } writer.writeKeyword("keyof"); writeSpace(writer); - writeType(type.type, 128); - if (flags & 128) { - writePunctuation(writer, 20); + writeType(type.type, 128 /* InElementType */); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); } } - else if (type.flags & 524288) { - writeType(type.objectType, 128); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); + else if (type.flags & 1048576 /* IndexedAccess */) { + writeType(type.objectType, 128 /* InElementType */); + writePunctuation(writer, 21 /* OpenBracketToken */); + writeType(type.indexType, 0 /* None */); + writePunctuation(writer, 22 /* CloseBracketToken */); } else { - writePunctuation(writer, 17); + // Should never get here + // { ... } + writePunctuation(writer, 17 /* OpenBraceToken */); writeSpace(writer); - writePunctuation(writer, 24); + writePunctuation(writer, 24 /* DotDotDotToken */); writeSpace(writer); - writePunctuation(writer, 18); + writePunctuation(writer, 18 /* CloseBraceToken */); } } function writeTypeList(types, delimiter) { for (var i = 0; i < types.length; i++) { if (i > 0) { - if (delimiter !== 26) { + if (delimiter !== 26 /* CommaToken */) { writeSpace(writer); } writePunctuation(writer, delimiter); writeSpace(writer); } - writeType(types[i], delimiter === 26 ? 0 : 128); + writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); } } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 512); + writePunctuation(writer, 27 /* LessThanToken */); + writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); pos++; while (pos < end) { - writePunctuation(writer, 26); + writePunctuation(writer, 26 /* CommaToken */); writeSpace(writer); - writeType(typeArguments[pos], 0); + writeType(typeArguments[pos], 0 /* None */); pos++; } - writePunctuation(writer, 29); + writePunctuation(writer, 29 /* GreaterThanToken */); } } function writeTypeReference(type, flags) { var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 128 | 32768); - writePunctuation(writer, 21); - writePunctuation(writer, 22); + if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { + writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); + writePunctuation(writer, 21 /* OpenBracketToken */); + writePunctuation(writer, 22 /* CloseBracketToken */); } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); + else if (type.target.objectFlags & 8 /* Tuple */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); + writePunctuation(writer, 22 /* CloseBracketToken */); } - else if (flags & 16384 && + else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 199) { - writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + writeAnonymousType(type, flags); } else { + // Write the type reference in the format f.g.C where A and B are type arguments + // for outer type parameters, and f and g are the respective declaring containers of those + // type parameters. var outerTypeParameters = type.target.outerTypeParameters; var i = 0; if (outerTypeParameters) { var length_2 = outerTypeParameters.length; while (i < length_2) { + // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_10 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_10); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_10, typeArguments, start, i, flags); - writePunctuation(writer, 23); + writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writePunctuation(writer, 23 /* DotToken */); } } } @@ -24114,45 +29231,54 @@ var ts; } } function writeUnionOrIntersectionType(type, flags) { - if (flags & 128) { - writePunctuation(writer, 19); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); } - if (type.flags & 65536) { - writeTypeList(formatUnionTypes(type.types), 49); + if (type.flags & 131072 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); } else { - writeTypeList(type.types, 48); + writeTypeList(type.types, 48 /* AmpersandToken */); } - if (flags & 128) { - writePunctuation(writer, 20); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); } } function writeAnonymousType(type, flags) { var symbol = type.symbol; if (symbol) { - if (symbol.flags & 32 && + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 199 && flags & 16384) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type, flags); + !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { + writeTypeOfSymbol(type.symbol, flags); } else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (ts.contains(symbolStack, symbol)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); } else { - writeKeyword(writer, 119); + // Recursive usage, use any + writeKeyword(writer, 119 /* AnyKeyword */); } } else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + // However, in case of class expressions, we want to write both the static side and the instance side. + // We skip adding the static side so that the instance side has a chance to be written + // before checking for circular references. if (!symbolStack) { symbolStack = []; } - var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; + var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; if (isConstructorObject) { writeLiteralType(type, flags); } @@ -24164,49 +29290,59 @@ var ts; } } else { + // Anonymous types with no symbol are never circular writeLiteralType(type, flags); } function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192) && - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || // is exported function symbol ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; + return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 4) || - ts.contains(symbolStack, symbol); + // typeof is allowed only for static/non local functions + return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it + ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively } } } - function writeTypeOfSymbol(type, typeFormatFlags) { - if (typeFormatFlags & 32768) { - writePunctuation(writer, 19); + function writeTypeOfSymbol(symbol, typeFormatFlags) { + if (typeFormatFlags & 32768 /* InArrayType */) { + writePunctuation(writer, 19 /* OpenParenToken */); } - writeKeyword(writer, 103); + writeKeyword(writer, 103 /* TypeOfKeyword */); writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - if (typeFormatFlags & 32768) { - writePunctuation(writer, 20); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); + if (typeFormatFlags & 32768 /* InArrayType */) { + writePunctuation(writer, 20 /* CloseParenToken */); } } function writePropertyWithModifiers(prop) { if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); + writeKeyword(writer, 131 /* ReadonlyKeyword */); writeSpace(writer); } + if (ts.getCheckFlags(prop) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(prop.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name) { + writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); + } + } buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216) { - writePunctuation(writer, 55); + if (prop.flags & 16777216 /* Optional */) { + writePunctuation(writer, 55 /* QuestionToken */); } } function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128) { + if (flags & 128 /* InElementType */) { return true; } - else if (flags & 512) { - var typeParameters = callSignature.target && (flags & 64) ? + else if (flags & 512 /* InFirstTypeArgument */) { + // Add parenthesis around function type for the first type argument to avoid ambiguity + var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? callSignature.target.typeParameters : callSignature.typeParameters; return typeParameters && typeParameters.length !== 0; } @@ -24220,120 +29356,120 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); + writePunctuation(writer, 17 /* OpenBraceToken */); + writePunctuation(writer, 18 /* CloseBraceToken */); return; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); if (parenthesizeSignature) { - writePunctuation(writer, 19); + writePunctuation(writer, 19 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (parenthesizeSignature) { - writePunctuation(writer, 20); + writePunctuation(writer, 20 /* CloseParenToken */); } return; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128) { - writePunctuation(writer, 19); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); } - writeKeyword(writer, 94); + writeKeyword(writer, 94 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (flags & 128) { - writePunctuation(writer, 20); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); } return; } } var saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; - writePunctuation(writer, 17); + writePunctuation(writer, 17 /* OpenBraceToken */); writer.writeLine(); writer.increaseIndent(); writeObjectLiteralType(resolved); writer.decreaseIndent(); - writePunctuation(writer, 18); + writePunctuation(writer, 18 /* CloseBraceToken */); inObjectTypeLiteral = saveInObjectTypeLiteral; } function writeObjectLiteralType(resolved) { for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); writer.writeLine(); } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; - if (globalFlags & 16384) { - if (p.flags & 4194304) { + if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { + if (p.flags & 4194304 /* Prototype */) { continue; } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { + writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); } } var t = getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); + if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0 /* Call */); for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { var signature = signatures_2[_f]; writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); writer.writeLine(); } } else { writePropertyWithModifiers(p); - writePunctuation(writer, 56); + writePunctuation(writer, 56 /* ColonToken */); writeSpace(writer); - writeType(t, globalFlags & 16384); - writePunctuation(writer, 25); + writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); + writePunctuation(writer, 25 /* SemicolonToken */); writer.writeLine(); } } } function writeMappedType(type) { - writePunctuation(writer, 17); + writePunctuation(writer, 17 /* OpenBraceToken */); writer.writeLine(); writer.increaseIndent(); if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); + writeKeyword(writer, 131 /* ReadonlyKeyword */); writeSpace(writer); } - writePunctuation(writer, 21); + writePunctuation(writer, 21 /* OpenBracketToken */); appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); writeSpace(writer); - writeKeyword(writer, 92); + writeKeyword(writer, 92 /* InKeyword */); writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); + writeType(getConstraintTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 22 /* CloseBracketToken */); if (type.declaration.questionToken) { - writePunctuation(writer, 55); + writePunctuation(writer, 55 /* QuestionToken */); } - writePunctuation(writer, 56); + writePunctuation(writer, 56 /* ColonToken */); writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); + writeType(getTemplateTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 25 /* SemicolonToken */); writer.writeLine(); writer.decreaseIndent(); - writePunctuation(writer, 18); + writePunctuation(writer, 18 /* CloseBraceToken */); } } function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { + if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } @@ -24342,14 +29478,14 @@ var ts; var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); - writeKeyword(writer, 85); + writeKeyword(writer, 85 /* ExtendsKeyword */); writeSpace(writer); buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } var defaultType = getDefaultFromTypeParameter(tp); if (defaultType) { writeSpace(writer); - writePunctuation(writer, 58); + writePunctuation(writer, 58 /* EqualsToken */); writeSpace(writer); buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); } @@ -24357,7 +29493,7 @@ var ts; function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { var parameterNode = p.valueDeclaration; if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); + writePunctuation(writer, 24 /* DotDotDotToken */); } if (parameterNode && ts.isBindingPattern(parameterNode.name)) { buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); @@ -24366,40 +29502,41 @@ var ts; appendSymbolNameOnly(p, writer); } if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); + writePunctuation(writer, 55 /* QuestionToken */); } - writePunctuation(writer, 56); + writePunctuation(writer, 56 /* ColonToken */); writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048); + type = getOptionalType(type); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 174) { - writePunctuation(writer, 17); + // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. + if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { + writePunctuation(writer, 17 /* OpenBraceToken */); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); + writePunctuation(writer, 18 /* CloseBraceToken */); } - else if (bindingPattern.kind === 175) { - writePunctuation(writer, 21); + else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { + writePunctuation(writer, 21 /* OpenBracketToken */); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); + writePunctuation(writer, 26 /* CommaToken */); } - writePunctuation(writer, 22); + writePunctuation(writer, 22 /* CloseBracketToken */); } } function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 176); + ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); if (bindingElement.propertyName) { writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); + writePunctuation(writer, 56 /* ColonToken */); writeSpace(writer); } if (ts.isBindingPattern(bindingElement.name)) { @@ -24407,22 +29544,22 @@ var ts; } else { if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); + writePunctuation(writer, 24 /* DotDotDotToken */); } appendSymbolNameOnly(bindingElement.symbol, writer); } } function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); + writePunctuation(writer, 27 /* LessThanToken */); buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); + writePunctuation(writer, 29 /* GreaterThanToken */); } } function buildDisplayForCommaSeparatedList(list, writer, action) { for (var i = 0; i < list.length; i++) { if (i > 0) { - writePunctuation(writer, 26); + writePunctuation(writer, 26 /* CommaToken */); writeSpace(writer); } action(list[i]); @@ -24430,56 +29567,56 @@ var ts; } function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 512; + writePunctuation(writer, 27 /* LessThanToken */); + var flags = 512 /* InFirstTypeArgument */; for (var i = 0; i < typeParameters.length; i++) { if (i > 0) { - writePunctuation(writer, 26); + writePunctuation(writer, 26 /* CommaToken */); writeSpace(writer); - flags = 0; + flags = 0 /* None */; } buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); } - writePunctuation(writer, 29); + writePunctuation(writer, 29 /* GreaterThanToken */); } } function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); + writePunctuation(writer, 19 /* OpenParenToken */); if (thisParameter) { buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (var i = 0; i < parameters.length; i++) { if (i > 0 || thisParameter) { - writePunctuation(writer, 26); + writePunctuation(writer, 26 /* CommaToken */); writeSpace(writer); } buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } - writePunctuation(writer, 20); + writePunctuation(writer, 20 /* CloseParenToken */); } function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { if (ts.isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } else { - writeKeyword(writer, 99); + writeKeyword(writer, 99 /* ThisKeyword */); } writeSpace(writer); - writeKeyword(writer, 126); + writeKeyword(writer, 126 /* IsKeyword */); writeSpace(writer); buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 && isTypeAny(returnType)) { + if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { return; } - if (flags & 16) { + if (flags & 16 /* WriteArrowStyleSignature */) { writeSpace(writer); - writePunctuation(writer, 36); + writePunctuation(writer, 36 /* EqualsGreaterThanToken */); } else { - writePunctuation(writer, 56); + writePunctuation(writer, 56 /* ColonToken */); } writeSpace(writer); if (signature.typePredicate) { @@ -24490,11 +29627,13 @@ var ts; } } function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); + if (kind === 1 /* Construct */) { + writeKeyword(writer, 94 /* NewKeyword */); writeSpace(writer); } - if (signature.target && (flags & 64)) { + if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { + // Instantiated signature, write type arguments instead + // This is achieved by passing in the mapper separately buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } else { @@ -24506,26 +29645,26 @@ var ts; function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { if (info) { if (info.isReadonly) { - writeKeyword(writer, 131); + writeKeyword(writer, 131 /* ReadonlyKeyword */); writeSpace(writer); } - writePunctuation(writer, 21); + writePunctuation(writer, 21 /* OpenBracketToken */); writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); + writePunctuation(writer, 56 /* ColonToken */); writeSpace(writer); switch (kind) { - case 1: - writeKeyword(writer, 133); + case 1 /* Number */: + writeKeyword(writer, 133 /* NumberKeyword */); break; - case 0: - writeKeyword(writer, 136); + case 0 /* String */: + writeKeyword(writer, 136 /* StringKeyword */); break; } - writePunctuation(writer, 22); - writePunctuation(writer, 56); + writePunctuation(writer, 22 /* CloseBracketToken */); + writePunctuation(writer, 56 /* ColonToken */); writeSpace(writer); buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25); + writePunctuation(writer, 25 /* SemicolonToken */); writer.writeLine(); } } @@ -24554,91 +29693,110 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 176: + case 177 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 226: + case 227 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible return false; } - case 233: - case 229: - case 230: - case 231: - case 228: - case 232: - case 237: + // falls through + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 233 /* EnumDeclaration */: + case 238 /* ImportEqualsDeclaration */: + // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_11 = getDeclarationContainer(node); - if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent_11.kind !== 265 && ts.isInAmbientContext(parent_11))) { - return isGlobalSourceFile(parent_11); - } - return isDeclarationVisible(parent_11); - case 149: - case 148: - case 153: - case 154: - case 151: - case 150: - if (ts.hasModifier(node, 8 | 16)) { + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible return false; } - case 152: - case 156: - case 155: - case 157: - case 146: - case 234: - case 160: - case 161: - case 163: - case 159: - case 164: - case 165: - case 166: - case 167: - case 168: + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 153 /* Constructor */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: + case 147 /* Parameter */: + case 235 /* ModuleBlock */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 160 /* TypeReference */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: return isDeclarationVisible(node.parent); - case 239: - case 240: - case 242: + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: return false; - case 145: - case 265: - case 236: + // Type parameters are always visible + case 146 /* TypeParameter */: + // Source file and namespace export are always visible + case 269 /* SourceFile */: + case 237 /* NamespaceExportDeclaration */: return true; - case 243: + // Export assignments do not create name bindings outside the module + case 244 /* ExportAssignment */: return false; default: return false; } } } - function collectLinkedAliases(node) { + function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node, false); + if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 246) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); + else if (node.parent.kind === 247 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } - var result = []; + var result; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } return result; function buildVisibleNodeList(declarations) { ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - ts.pushIfUnique(result, resultNode); + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined, false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -24646,9 +29804,21 @@ var ts; }); } } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { + // A cycle was found var length_3 = resolutionTargets.length; for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; @@ -24656,7 +29826,7 @@ var ts; return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -24672,20 +29842,22 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0) { + if (propertyName === 0 /* Type */) { return getSymbolLinks(target).type; } - if (propertyName === 2) { + if (propertyName === 2 /* DeclaredType */) { return getSymbolLinks(target).declaredType; } - if (propertyName === 1) { + if (propertyName === 1 /* ResolvedBaseConstructorType */) { return target.resolvedBaseConstructorType; } - if (propertyName === 3) { + if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. function popTypeResolution() { resolutionTargets.pop(); resolutionPropertyNames.pop(); @@ -24694,12 +29866,12 @@ var ts; function getDeclarationContainer(node) { node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 226: - case 227: - case 242: - case 241: - case 240: - case 239: + case 227 /* VariableDeclaration */: + case 228 /* VariableDeclarationList */: + case 243 /* ImportSpecifier */: + case 242 /* NamedImports */: + case 241 /* NamespaceImport */: + case 240 /* ImportClause */: return false; default: return true; @@ -24708,64 +29880,76 @@ var ts; return node && node.parent; } function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; } + // Return the type of the given property in the given type, or undefined if no such property exists function getTypeOfPropertyOfType(type, name) { var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } function isTypeAny(type) { - return type && (type.flags & 1) !== 0; + return type && (type.flags & 1 /* Any */) !== 0; } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 145 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144); }); - if (source.flags & 8192) { + source = filterType(source, function (t) { return !(t.flags & 12288 /* Nullable */); }); + if (source.flags & 16384 /* Never */) { return emptyObjectType; } - if (source.flags & 65536) { + if (source.flags & 131072 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); var names = ts.createUnderscoreEscapedMap(); for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { - var name_17 = properties_2[_i]; - names.set(ts.getTextOfPropertyName(name_17), true); + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); - var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); + var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { members.set(prop.escapedName, prop); } } - var stringIndexInfo = getIndexInfoOfType(source, 0); - var numberIndexInfo = getIndexInfoOfType(source, 1); + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element if (parentType === unknownType) { return unknownType; } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; - if (pattern.kind === 174) { + if (pattern.kind === 175 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (!isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -24781,30 +29965,40 @@ var ts; type = getRestType(parentType, literalMembers, declaration.symbol); } else { - var name_18 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_18)) { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + // computed properties with non-literal names are treated as 'any' return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + var text = ts.getTextOfPropertyName(name); + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); } - var text = ts.getTextOfPropertyName(name_18); var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || + getIndexTypeOfType(parentType, 0 /* String */); if (!type) { - error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18)); + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); return unknownType; } } } else { - var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); if (declaration.dotDotDotToken) { + // Rest element has an array type with the same element type as the parent type type = createArrayType(elementType); } else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array var propName = "" + ts.indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) @@ -24820,11 +30014,13 @@ var ts; } } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { - type = getTypeWithFacts(type, 131072); + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096 /* Undefined */)) { + type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -24836,56 +30032,73 @@ var ts; } function isNullOrUndefined(node) { var expr = ts.skipParentheses(node); - return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 177 && expr.elements.length === 0; + return expr.kind === 178 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048) : type; + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; } + // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.parent.parent.kind === 215) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (declaration.parent.parent.kind === 216 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 | 262144) ? indexType : stringType; + return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 216) { + if (declaration.parent.parent.kind === 217 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } + // Use type from type annotation if one is present var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, declaration.questionToken && includeOptionality); + return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { - if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + declaration.kind === 227 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 2097152 /* Ambient */)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { return autoType; } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { return autoArrayType; } } - if (declaration.kind === 146) { + if (declaration.kind === 147 /* Parameter */) { var func = declaration.parent; - if (func.kind === 154 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 155 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 154 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* ts.Debug.assert(!thisParameter.type); return getTypeOfSymbol(getterSignature.thisParameter); } return getReturnTypeOfSignature(getterSignature); } } + // Use contextual parameter type if one is available var type = void 0; if (declaration.symbol.escapedName === "this") { type = getContextualThisParameterType(func); @@ -24894,22 +30107,28 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, declaration.questionToken && includeOptionality); + return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); } } + // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, declaration.questionToken && includeOptionality); + return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); } if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for return trueType; } - if (declaration.kind === 262) { + // If it is a short-hand property assignment, use the type of the identifier + if (declaration.kind === 266 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); } + // No type specified and nothing can be inferred return undefined; } function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { @@ -24919,38 +30138,44 @@ var ts; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = declaration.kind === 194 ? declaration : - declaration.kind === 179 ? ts.getAncestor(declaration, 194) : + var expression = declaration.kind === 195 /* BinaryExpression */ ? declaration : + declaration.kind === 180 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 195 /* BinaryExpression */) : undefined; if (!expression) { return unknownType; } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 152) { + if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { + if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 153 /* Constructor */) { definedInConstructor = true; } else { definedInMethod = true; } } + // If there is a JSDoc type, use it var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); if (type_1) { var declarationType = getWidenedType(type_1); if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { - var name_19 = ts.getNameOfDeclaration(declaration); - error(name_19, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name_19), typeToString(jsDocType), typeToString(declarationType)); + else if (jsDocType !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(jsDocType, declarationType) && + !(symbol.flags & 67108864 /* JSContainer */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } } - var type = jsDocType || getUnionType(types, true); + var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { return checkDeclarationInitializer(element); @@ -24963,6 +30188,7 @@ var ts; } return anyType; } + // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; @@ -24970,15 +30196,16 @@ var ts; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type hasComputedProperties = true; return; } if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo(anyType, false); + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); return; } var text = ts.getTextOfPropertyName(name); - var flags = 4 | (e.initializer ? 16777216 : 0); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; @@ -24989,16 +30216,18 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.objectFlags |= 512; + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } return result; } + // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } + // If the pattern has at least one element, and no rest element, then it should imply a tuple type. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); var result = createTupleType(elementTypes); if (includePatternInType) { @@ -25007,23 +30236,48 @@ var ts; } return result; } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 + return pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, true); + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (declaration.kind === 261) { + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 1024 /* UniqueESSymbol */ && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } + // During a normal type check we'll never get to here with a property assignment (the check of the containing + // object literal uses a different path). We exclude widening only so that language services and type verification + // tools see the actual type. + if (declaration.kind === 265 /* PropertyAssignment */) { return type; } return getWidenedType(type); } + // Rest parameters default to type any[], other parameters default to type any type = declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && noImplicitAny) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { reportImplicitAnyError(declaration, type); @@ -25033,35 +30287,44 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 ? root.parent : root; + var memberDeclaration = root.kind === 147 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.flags & 4194304) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } + // Handle catch clause variables var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } - if (declaration.kind === 243) { + // Handle export default expressions + if (declaration.kind === 244 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } - if (!pushTypeResolution(symbol, 0)) { + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } var type = void 0; - if (declaration.kind === 194 || - declaration.kind === 179 && declaration.parent.kind === 194) { + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + if (declaration.kind === 195 /* BinaryExpression */ || + declaration.kind === 180 /* PropertyAccessExpression */ && declaration.parent.kind === 195 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -25072,7 +30335,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 153) { + if (accessor.kind === 154 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -25093,28 +30356,31 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153); - var setter = ts.getDeclarationOfKind(symbol, 154); + var getter = ts.getDeclarationOfKind(symbol, 154 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 155 /* SetAccessor */); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; } } - if (!pushTypeResolution(symbol, 0)) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } var type = void 0; + // First try to see if the user specified a return type on the get-accessor. var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { type = getterReturnType; } else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. var setterParameterType = getAnnotatedAccessorType(setter); if (setterParameterType) { type = setterParameterType; } else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. if (getter && getter.body) { type = getReturnTypeFromBody(getter); } @@ -25135,7 +30401,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153); + var getter_1 = ts.getDeclarationOfKind(symbol, 154 /* GetAccessor */); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -25145,22 +30411,22 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; + return baseConstructorType.flags & 1081344 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } else { - var type = createObjectType(16, symbol); - if (symbol.flags & 32) { + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { var baseTypeVariable = getBaseTypeVariableOfClass(symbol); links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 16777216 ? getNullableType(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; } } } @@ -25177,7 +30443,12 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 107455 + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 107455 /* Value */ ? getTypeOfSymbol(targetSymbol) : unknownType; } @@ -25191,7 +30462,7 @@ var ts; links.type = unknownType; } else { - if (!pushTypeResolution(symbol, 0)) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } symbolInstantiationDepth++; @@ -25206,32 +30477,34 @@ var ts; return links.type; } function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); return unknownType; } + // Otherwise variable has initializer that circularly references the variable itself if (noImplicitAny) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } return anyType; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (symbol.flags & (3 | 4)) { + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { return getTypeOfVariableOrParameterOrProperty(symbol); } - if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); } - if (symbol.flags & 8) { + if (symbol.flags & 8 /* EnumMember */) { return getTypeOfEnumMember(symbol); } - if (symbol.flags & 98304) { + if (symbol.flags & 98304 /* Accessor */) { return getTypeOfAccessors(symbol); } - if (symbol.flags & 2097152) { + if (symbol.flags & 2097152 /* Alias */) { return getTypeOfAlias(symbol); } return unknownType; @@ -25239,24 +30512,27 @@ var ts; function isReferenceToType(type, target) { return type !== undefined && target !== undefined - && (getObjectFlags(type) & 4) !== 0 + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target; } function getTargetType(type) { - return getObjectFlags(type) & 4 ? type.target : type; + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); function check(type) { - if (getObjectFlags(type) & (3 | 4)) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); return target === checkBase || ts.forEach(getBaseTypes(target), check); } - else if (type.flags & 131072) { + else if (type.flags & 262144 /* Intersection */) { return ts.forEach(type.types, check); } } } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. function appendTypeParameters(typeParameters, declarations) { for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; @@ -25265,6 +30541,7 @@ var ts; } return typeParameters; } + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. function getOuterTypeParameters(node, includeThisTypes) { while (true) { node = node.parent; @@ -25272,44 +30549,47 @@ var ts; return undefined; } switch (node.kind) { - case 229: - case 199: - case 230: - case 155: - case 156: - case 150: - case 160: - case 161: - case 273: - case 228: - case 151: - case 186: - case 187: - case 231: - case 282: - case 172: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 232 /* TypeAliasDeclaration */: + case 287 /* JSDocTemplateTag */: + case 173 /* MappedType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 172) { + if (node.kind === 173 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); var thisType = includeThisTypes && - (node.kind === 229 || node.kind === 199 || node.kind === 230) && + (node.kind === 230 /* ClassDeclaration */ || node.kind === 200 /* ClassExpression */ || node.kind === 231 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 231 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 230 || node.kind === 229 || - node.kind === 199 || node.kind === 231) { + if (node.kind === 231 /* InterfaceDeclaration */ || node.kind === 230 /* ClassDeclaration */ || + node.kind === 200 /* ClassExpression */ || node.kind === 232 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -25318,11 +30598,15 @@ var ts; } return result; } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. function getTypeParametersOfClassOrInterface(symbol) { return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. function isMixinConstructorType(type) { - var signatures = getSignaturesOfType(type, 1); + var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; @@ -25330,46 +30614,70 @@ var ts; return false; } function isConstructorType(type) { - if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 540672) { + if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + var decl = type.symbol.valueDeclaration; + if (ts.isInJavaScriptFile(decl)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(decl); + if (tag) { + return tag.class; + } + } + return ts.getClassExtendsHeritageClauseElement(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getClassExtendsHeritageClauseElement(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; } - if (!pushTypeResolution(type, 1)) { + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 | 131072)) { + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); return type.resolvedBaseConstructorType = unknownType; } - if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); return type.resolvedBaseConstructorType = unknownType; } @@ -25379,14 +30687,14 @@ var ts; } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { - if (type.objectFlags & 8) { + if (type.objectFlags & 8 /* Tuple */) { type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { resolveBaseTypesOfClass(type); } - if (type.symbol.flags & 64) { + if (type.symbol.flags & 64 /* Interface */) { resolveBaseTypesOfInterface(type); } } @@ -25399,21 +30707,27 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { + if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; - if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); } - else if (baseConstructorType.flags & 1) { + else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); @@ -25421,13 +30735,6 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag && augTag.typeExpression && augTag.typeExpression.type) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } if (baseType === unknownType) { return; } @@ -25436,29 +30743,33 @@ var ts; return; } if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. var outerTypeParameters = type.outerTypeParameters; if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; + var last_1 = outerTypeParameters.length - 1; var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; } return true; } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. function isValidBaseType(type) { - return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || - type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return type.flags & (65536 /* Object */ | 33554432 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 231 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -25473,7 +30784,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); } } else { @@ -25484,11 +30795,18 @@ var ts; } } } - function isIndependentInterface(symbol) { + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230) { - if (declaration.flags & 64) { + if (declaration.kind === 231 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); @@ -25496,8 +30814,8 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); - if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } } @@ -25510,12 +30828,17 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1 : 2; + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { - type.objectFlags |= 4; + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; @@ -25523,7 +30846,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384); + type.thisType = createType(32768 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -25534,17 +30857,22 @@ var ts; function getDeclaredTypeOfTypeAlias(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - if (!pushTypeResolution(symbol, 2)) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 283 || d.kind === 231; + return d.kind === 288 /* JSDocTypedefTag */ || d.kind === 232 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 283 ? declaration.typeExpression : declaration.type; + var typeNode = declaration.kind === 288 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. links.typeParameters = typeParameters; links.instantiations = ts.createMap(); links.instantiations.set(getTypeListId(typeParameters), type); @@ -25561,16 +30889,16 @@ var ts; function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !ts.isInAmbientContext(member); + return !(member.flags & 2097152 /* Ambient */); } switch (expr.kind) { - case 9: - case 8: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: return true; - case 192: - return expr.operator === 38 && - expr.operand.kind === 8; - case 71: + case 193 /* PrefixUnaryExpression */: + return expr.operator === 38 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 71 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); default: return false; @@ -25584,11 +30912,11 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232) { + if (declaration.kind === 233 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - if (member.initializer && member.initializer.kind === 9) { - return links.enumKind = 1; + if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; } if (!isLiteralEnumMember(member)) { hasNonLiteralMember = true; @@ -25596,22 +30924,22 @@ var ts; } } } - return links.enumKind = hasNonLiteralMember ? 0 : 1; + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 && !(type.flags & 65536) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (links.declaredType) { return links.declaredType; } - if (getEnumKind(symbol) === 1) { + if (getEnumKind(symbol) === 1 /* Literal */) { enumCount++; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232) { + if (declaration.kind === 233 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); @@ -25621,15 +30949,15 @@ var ts; } } if (memberTypeList.length) { - var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); - if (enumType_1.flags & 65536) { - enumType_1.flags |= 256; + var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + if (enumType_1.flags & 131072 /* Union */) { + enumType_1.flags |= 256 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; } } - var enumType = createType(16); + var enumType = createType(16 /* Enum */); enumType.symbol = symbol; return links.declaredType = enumType; } @@ -25646,7 +30974,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384); + var type = createType(32768 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -25660,99 +30988,109 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { - if (symbol.flags & (32 | 64)) { + return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { return getDeclaredTypeOfClassOrInterface(symbol); } - if (symbol.flags & 524288) { + if (symbol.flags & 524288 /* TypeAlias */) { return getDeclaredTypeOfTypeAlias(symbol); } - if (symbol.flags & 262144) { + if (symbol.flags & 262144 /* TypeParameter */) { return getDeclaredTypeOfTypeParameter(symbol); } - if (symbol.flags & 384) { + if (symbol.flags & 384 /* Enum */) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 8) { + if (symbol.flags & 8 /* EnumMember */) { return getDeclaredTypeOfEnumMember(symbol); } - if (symbol.flags & 2097152) { + if (symbol.flags & 2097152 /* Alias */) { return getDeclaredTypeOfAlias(symbol); } - return unknownType; - } - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; + return undefined; } - function isIndependentType(node) { + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { switch (node.kind) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 134: - case 105: - case 139: - case 95: - case 130: - case 173: + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 134 /* ObjectKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 130 /* NeverKeyword */: + case 174 /* LiteralType */: return true; - case 164: - return isIndependentType(node.elementType); - case 159: - return isIndependentTypeReference(node); + case 165 /* ArrayType */: + return isThislessType(node.elementType); + case 160 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; } - function isIndependentVariableLikeDeclaration(node) { - var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isIndependentType(typeNode) : !node.initializer; + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + return !node.constraint || isThislessType(node.constraint); } - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152) { - var typeNode = ts.getEffectiveReturnTypeNode(node); - if (!typeNode || !isIndependentType(typeNode)) { - return false; - } - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; - } - function isIndependentMember(symbol) { + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !node.initializer; + } + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + return (node.kind === 153 /* Constructor */ || (returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 149: - case 148: - return isIndependentVariableLikeDeclaration(declaration); - case 151: - case 150: - case 152: - return isIndependentFunctionLikeDeclaration(declaration); + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); } } } return false; } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { var result = ts.createSymbolTable(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; - result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; } @@ -25767,23 +31105,219 @@ var ts; function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); - type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); } return type; } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 1120 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 1024 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & 96 /* StringOrNumberLiteral */) { + return ts.escapeLeadingUnderscores("" + type.value); + } + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + lateSymbol.parent = parent; + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { + var member = members_3[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); } } - else if (type.flags & 131072) { + else if (type.flags & 262144 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); } return type; @@ -25797,7 +31331,7 @@ var ts; var numberIndexInfo; if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = identityMapper; - members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); callSignatures = source.declaredCallSignatures; constructSignatures = source.declaredConstructSignatures; stringIndexInfo = source.declaredStringIndexInfo; @@ -25805,7 +31339,7 @@ var ts; } else { mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); @@ -25813,7 +31347,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -25821,14 +31355,14 @@ var ts; var baseType = baseTypes_1[_i]; var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); - constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); if (!stringIndexInfo) { stringIndexInfo = instantiatedBaseType === anyType ? - createIndexInfo(anyType, false) : - getIndexInfoOfType(instantiatedBaseType, 0); + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); } - numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); } } setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -25861,9 +31395,9 @@ var ts; } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); - var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); 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, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -25874,7 +31408,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -25893,11 +31427,13 @@ var ts; } function findMatchingSignatures(signatureLists, signature, listIndex) { if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. if (listIndex > 0) { return undefined; } for (var i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { return undefined; } } @@ -25905,7 +31441,8 @@ var ts; } var result = undefined; for (var i = 0; i < signatureLists.length; i++) { - var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); if (!match) { return undefined; } @@ -25913,22 +31450,29 @@ var ts; } return result; } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. function getUnionSignatures(types, kind) { var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); var result = undefined; for (var i = 0; i < signatureLists.length; i++) { for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; - if (!result || !findMatchingSignature(result, signature, false, true, true)) { + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { var unionSignatures = findMatchingSignatures(signatureLists, signature, i); if (unionSignatures) { var s = signature; + // Union the result types when more than one signature matches if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); } + // Clear resolved return type we possibly got from cloneSignature s.resolvedReturnType = undefined; s.unionSignatures = unionSignatures; } @@ -25942,8 +31486,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type = types_1[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -25951,13 +31495,15 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); } function resolveUnionTypeMembers(type) { - var callSignatures = getUnionSignatures(type.types, 0); - var constructSignatures = getUnionSignatures(type.types, 1); - var stringIndexInfo = getUnionIndexInfo(type.types, 0); - var numberIndexInfo = getUnionIndexInfo(type.types, 1); + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(type.types, 0 /* Call */); + var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { @@ -25976,12 +31522,14 @@ var ts; mixedTypes.push(type); } else if (isMixinConstructorType(types[i])) { - mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); } } return getIntersectionType(mixedTypes); } function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). var callSignatures = ts.emptyArray; var constructSignatures = ts.emptyArray; var stringIndexInfo; @@ -25990,8 +31538,13 @@ var ts; var mixinCount = ts.countWhere(types, isMixinConstructorType); var _loop_4 = function (i) { var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { - var signatures = getSignaturesOfType(t, 1); + var signatures = getSignaturesOfType(t, 1 /* Construct */); if (signatures.length && mixinCount > 0) { signatures = ts.map(signatures, function (s) { var clone = cloneSignature(s); @@ -26001,58 +31554,67 @@ var ts; } constructSignatures = ts.concatenate(constructSignatures, signatures); } - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); - stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); - numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } + /** + * Converts an AnonymousType to a ResolvedType. + */ function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { - var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); - var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); - var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); - var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } - else if (symbol.flags & 2048) { - var members = symbol.members; - var callSignatures = getSignaturesOfSymbol(members.get("__call")); - var constructSignatures = getSignaturesOfSymbol(members.get("__new")); - var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + else if (symbol.flags & 2048 /* TypeLiteral */) { + var members = getMembersOfSymbol(symbol); + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { + // Combinations of function, class, enum and module var members = emptySymbols; var stringIndexInfo = undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & 32) { + if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 | 131072 | 540672)) { + if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1081344 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, false); + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); } } - var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - if (symbol.flags & (16 | 8192)) { + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); } - if (symbol.flags & 32) { + // And likewise for construct signatures for classes + if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); - var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + var constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } @@ -26060,45 +31622,63 @@ var ts; } } } + /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); var stringIndexInfo; + // Resolve upfront such that recursive references see an empty object type. setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. var typeParameter = getTypeParameterFromMappedType(type); var constraintType = getConstraintTypeFromMappedType(type); var templateType = getTemplateTypeFromMappedType(type); - var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 171 /* TypeOperator */ && + constraintDeclaration.operator === 127 /* KeyOfKeyword */) { + // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var propertySymbol = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); } - if (getIndexInfoOfType(modifiersType, 0)) { + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); } } else { - var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + // First, if the constraint type is a type parameter, obtain the base constraint. Then, + // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Finally, iterate over the constituents of the resulting iteration type. + var keyType = constraintType.flags & 1081344 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 524288 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); function addMemberForKeyType(t, propertySymbolOrIndex) { var propertySymbol; + // forEachType delegates to forEach, which calls with a numeric second argument + // the type system currently doesn't catch this incompatibility, so we annotate + // the function ourselves to indicate the runtime behavior and deal with it here if (typeof propertySymbolOrIndex === "object") { propertySymbol = propertySymbolOrIndex; } + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. var iterationMapper = createTypeMapper([typeParameter], [t]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); - if (t.flags & 32) { + // If the current iteration type constituent is a string literal type, create a property. + // Otherwise, for type string create a string index signature. + if (t.flags & 32 /* StringLiteral */) { var propName = ts.escapeLeadingUnderscores(t.value); var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216); - var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, checkFlags); prop.type = propType; if (propertySymbol) { prop.syntheticOrigin = propertySymbol; @@ -26107,7 +31687,7 @@ var ts; prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } - else if (t.flags & 2) { + else if (t.flags & (1 /* Any */ | 2 /* String */)) { stringIndexInfo = createIndexInfo(propType, templateReadonly); } } @@ -26129,57 +31709,77 @@ var ts; function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170) { + if (constraintDeclaration.kind === 171 /* TypeOperator */ && + constraintDeclaration.operator === 127 /* KeyOfKeyword */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); } else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } + function getMappedTypeModifiers(type) { + return (type.declaration.readonlyToken ? 1 /* Readonly */ : 0) | + (type.declaration.questionToken ? 2 /* Optional */ : 0); + } + function getCombinedMappedTypeModifiers(type) { + var modifiersType = getModifiersTypeFromMappedType(type); + return getMappedTypeModifiers(type) | + (isGenericMappedType(modifiersType) ? getMappedTypeModifiers(modifiersType) : 0); + } function isPartialMappedType(type) { - return getObjectFlags(type) & 32 && !!type.declaration.questionToken; + return ts.getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 32768) { - if (type.objectFlags & 4) { + if (type.flags & 65536 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } - else if (type.objectFlags & 3) { + else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 16) { + else if (type.objectFlags & 16 /* Anonymous */) { resolveAnonymousTypeMembers(type); } - else if (type.objectFlags & 32) { + else if (type.objectFlags & 32 /* Mapped */) { resolveMappedTypeMembers(type); } } - else if (type.flags & 65536) { + else if (type.flags & 131072 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 131072) { + else if (type.flags & 262144 /* Intersection */) { resolveIntersectionTypeMembers(type); } } return type; } + /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 32768) { + if (type.flags & 65536 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ function getPropertyOfObjectType(type, name) { - if (type.flags & 32768) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -26201,7 +31801,9 @@ var ts; } } } - if (type.flags & 65536) { + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 131072 /* Union */) { break; } } @@ -26211,19 +31813,19 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 196608 ? + return type.flags & 393216 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 65536)) { - return getPropertiesOfType(unionType); + if (!(unionType.flags & 131072 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var memberType = types_2[_i]; - for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); @@ -26233,8 +31835,8 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 16384 ? getConstraintOfTypeParameter(type) : - type.flags & 524288 ? getConstraintOfIndexedAccess(type) : + return type.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 1048576 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { @@ -26250,13 +31852,13 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (540672 | 196608)) { + if (type.flags & (1081344 /* TypeVariable */ | 393216 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 262144) { + else if (type.flags & 524288 /* Index */) { return stringType; } return undefined; @@ -26264,6 +31866,11 @@ var ts; function hasNonCircularBaseConstraint(type) { return getResolvedBaseConstraint(type) !== circularConstraintType; } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ function getResolvedBaseConstraint(type) { var typeStack; var circular; @@ -26284,29 +31891,29 @@ var ts; return result; } function computeBaseConstraint(t) { - if (t.flags & 16384) { + if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType ? constraint : constraint ? getBaseConstraint(constraint) : undefined; } - if (t.flags & 196608) { + if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_2 = types_4[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 131072 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 262144 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 262144) { + if (t.flags & 524288 /* Index */) { return stringType; } - if (t.flags & 524288) { + if (t.flags & 1048576 /* IndexedAccess */) { var transformed = getTransformedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); @@ -26325,39 +31932,75 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ function getApparentType(type) { - var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 ? globalStringType : - t.flags & 84 ? globalNumberType : - t.flags & 136 ? globalBooleanType : - t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : + var t = type.flags & 1081344 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 262144 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 524322 /* StringLike */ ? globalStringType : + t.flags & 84 /* NumberLike */ ? globalNumberType : + t.flags & 136 /* BooleanLike */ ? globalBooleanType : + t.flags & 1536 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 33554432 /* NonPrimitive */ ? emptyObjectType : t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var types = containingType.types; - var isUnion = containingType.flags & 65536; - var excludeModifiers = isUnion ? 24 : 0; - var commonFlags = isUnion ? 0 : 16777216; - var syntheticFlag = 4; + var isUnion = containingType.flags & 131072 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var current = types_5[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -26365,24 +32008,24 @@ var ts; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); - checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | - (!(modifiers & 24) ? 64 : 0) | - (modifiers & 16 ? 128 : 0) | - (modifiers & 8 ? 256 : 0) | - (modifiers & 32 ? 512 : 0); + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); if (!isMethodLike(prop)) { - syntheticFlag = 2; + syntheticFlag = 2 /* SyntheticProperty */; } } else if (isUnion) { - checkFlags |= 16; + checkFlags |= 16 /* Partial */; } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { return props[0]; } var propTypes = []; @@ -26398,17 +32041,21 @@ var ts; commonType = type; } else if (type !== commonType) { - checkFlags |= 32; + checkFlags |= 32 /* HasNonUniformType */; } propTypes.push(type); } - var result = createSymbol(4 | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; result.declarations = declarations; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. function getUnionOrIntersectionProperty(type, name) { var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); var property = properties.get(name); @@ -26422,11 +32069,20 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; - } + // We need to filter out partial properties in union types + return property && !(ts.getCheckFlags(property) & 16 /* Partial */) ? property : undefined; + } + /** + * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @param type a type to look up property from + * @param name a name of property to look up in a given type + */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 32768) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -26440,52 +32096,62 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 196608) { + if (type.flags & 393216 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376) { + if (type.flags & 458752 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } return ts.emptyArray; } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376) { + if (type.flags & 458752 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } function getIndexTypeOfStructuredType(type, kind) { var info = getIndexInfoOfStructuredType(type, kind); return info && info.type; } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { return getIndexInfoOfStructuredType(getApparentType(type), kind); } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { propTypes.push(getTypeOfSymbol(prop)); } } if (propTypes.length) { - return getUnionType(propTypes, true); + return getUnionType(propTypes, /*subtypeReduction*/ true); } } return undefined; } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). function getTypeParametersFromDeclaration(declaration) { var result; ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { @@ -26505,7 +32171,7 @@ var ts; } function isJSDocOptionalParameter(node) { if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 272) { + if (node.type && node.type.kind === 276 /* JSDocOptionalType */) { return true; } var paramTags = ts.getJSDocParameterTags(node); @@ -26516,7 +32182,7 @@ var ts; return true; } if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 272; + return paramTag.typeExpression.type.kind === 276 /* JSDocOptionalType */; } } } @@ -26526,7 +32192,8 @@ var ts; if (ts.isExternalModuleNameRelative(moduleName)) { return undefined; } - var symbol = getSymbol(globals, '"' + moduleName + '"', 512); + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { @@ -26550,9 +32217,9 @@ var ts; } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; - if (parameterName.kind === 71) { + if (parameterName.kind === 71 /* Identifier */) { return { - kind: 1, + kind: 1 /* Identifier */, parameterName: parameterName ? parameterName.escapedText : undefined, parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, type: getTypeFromTypeNode(node.type) @@ -26560,38 +32227,57 @@ var ts; } else { return { - kind: 0, + kind: 0 /* This */, type: getTypeFromTypeNode(node.type) }; } } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ function getMinTypeArgumentCount(typeParameters) { var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } } return minTypeArgumentCount; } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { + /** + * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined + * when a default type is supplied, a new array will be created and returned. + * + * @param typeArguments The supplied type arguments. + * @param typeParameters The requested type parameters. + * @param minTypeArgumentCount The minimum number of required type arguments. + */ + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { if (!typeArguments) { typeArguments = []; } + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); } for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + defaultType = anyType; + } + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); } + typeArguments.length = typeParameters.length; } } return typeArguments; @@ -26607,11 +32293,15 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; - if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined, false); + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -26621,9 +32311,10 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 173) { + if (param.type && param.type.kind === 174 /* LiteralType */) { hasLiteralTypes = true; } + // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || isJSDocOptionalParameter(param) || @@ -26632,35 +32323,51 @@ var ts; minArgumentCount = parameters.length; } } - if ((declaration.kind === 153 || declaration.kind === 154) && - !ts.hasDynamicName(declaration) && + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 154 /* GetAccessor */ || declaration.kind === 155 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 ? 154 : 153; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + var otherKind = declaration.kind === 154 /* GetAccessor */ ? 155 /* SetAccessor */ : 154 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 152 ? + var classType = declaration.kind === 153 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 ? + var typePredicate = declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - var hasRestLikeParameter = ts.hasRestParameter(declaration); - if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { - hasRestLikeParameter = true; - var syntheticArgsSymbol = createSymbol(3, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - parameters.push(syntheticArgsSymbol); - } + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + // JS functions get a free rest parameter if: + // a) The last parameter has `...` preceding its type + // b) It references `arguments` somewhere + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { + return false; + } + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); @@ -26672,8 +32379,10 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154); + // TypeScript 1.0 spec (April 2014): + // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. + if (declaration.kind === 154 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 155 /* SetAccessor */); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -26683,7 +32392,7 @@ var ts; function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); if (links.containsArgumentsReference === undefined) { - if (links.flags & 8192) { + if (links.flags & 8192 /* CaptureArguments */) { links.containsArgumentsReference = true; } else { @@ -26695,13 +32404,13 @@ var ts; if (!node) return false; switch (node.kind) { - case 71: - return node.escapedText === "arguments" && ts.isPartOfExpression(node); - case 149: - case 151: - case 153: - case 154: - return node.name.kind === 144 + case 71 /* Identifier */: + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return node.name.kind === 145 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); @@ -26715,20 +32424,23 @@ var ts; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 273: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 277 /* JSDocFunctionType */: + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -26757,7 +32469,7 @@ var ts; } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature, 3)) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return unknownType; } var type = void 0; @@ -26765,7 +32477,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } else { type = getReturnTypeFromBody(signature.declaration); @@ -26774,9 +32486,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - var name_20 = ts.getNameOfDeclaration(declaration); - if (name_20) { - error(name_20, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name_20)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -26788,12 +32500,12 @@ var ts; return signature.resolvedReturnType; } function isResolvingReturnTypeOfSignature(signature) { - return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3) >= 0; + return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 && type.target === globalArrayType) { + if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -26810,7 +32522,7 @@ var ts; return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { return signature.typeParameters ? @@ -26818,7 +32530,8 @@ var ts; signature; } function createErasedSignature(signature) { - return instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } function getCanonicalSignature(signature) { return signature.typeParameters ? @@ -26826,12 +32539,31 @@ var ts; signature; } function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; - var type = createObjectType(16); + var isConstructor = signature.declaration.kind === 153 /* Constructor */ || signature.declaration.kind === 157 /* ConstructSignature */; + var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; @@ -26841,10 +32573,10 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index"); + return symbol.members.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 133 : 136; + var syntaxKind = kind === 1 /* Number */ ? 133 /* NumberKeyword */ : 136 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -26866,12 +32598,12 @@ var ts; function getIndexInfoOfSymbol(symbol, kind) { var declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64), declaration); + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration); } return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145).constraint; + return type.symbol && ts.getDeclarationOfKind(type.symbol, 146 /* TypeParameter */).constraint; } function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { @@ -26887,7 +32619,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 146 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -26912,23 +32644,27 @@ var ts; } return result; } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } } - return result & 14680064; + return result & 29360128 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations.get(id); if (!type) { - type = createObjectType(4, target.symbol); + type = createObjectType(4 /* Reference */, target.symbol); target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; type.typeArguments = typeArguments; } @@ -26945,20 +32681,37 @@ var ts; function getTypeReferenceArity(type) { return ts.length(type.target.typeParameters); } + /** + * Get type from type-reference that reference to class or interface + */ function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJavascript = ts.isInJavaScriptFile(node); - if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); - return unknownType; + var isJs = ts.isInJavaScriptFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && node.parent.kind !== 282 /* JSDocAugmentsTag */; + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return unknownType; + } } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -26978,6 +32731,11 @@ var ts; } return instantiation; } + /** + * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + * declared type. Instantiations are cached using the type identities of the type arguments as the key. + */ function getTypeFromTypeAliasReference(node, symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = getSymbolLinks(symbol).typeParameters; @@ -26998,18 +32756,13 @@ var ts; } return type; } - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } function getTypeReferenceName(node) { switch (node.kind) { - case 159: + case 160 /* TypeReference */: return node.typeName; - case 201: + case 202 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -27024,7 +32777,7 @@ var ts; return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; } function getTypeReferenceType(node, symbol) { - var typeArguments = typeArgumentsFromTypeReferenceNode(node); + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { return unknownType; } @@ -27032,45 +32785,56 @@ var ts; if (type) { return type; } - if (symbol.flags & 107455 && isJSDocTypeReference(node)) { - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res !== undefined) { + if (typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; } - resolveTypeReferenceName(getTypeReferenceName(node), 793064); - return valueType; + return res; + } + if (!(symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node))) { + return unknownType; } - return getTypeFromNonGenericTypeReference(node, symbol); + // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + // the symbol is a constructor function, return the inferred class type; otherwise, + // the type of this reference is just the type of the value we resolved to. + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; + } + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { - if (symbol.flags & (32 | 64)) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } - if (symbol.flags & 524288) { + if (symbol.flags & 524288 /* TypeAlias */) { return getTypeFromTypeAliasReference(node, symbol, typeArguments); } - if (symbol.flags & 16 && + if (symbol.flags & 16 /* Function */ && isJSDocTypeReference(node) && (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { return getInferredClassType(symbol); } } function isJSDocTypeReference(node) { - return node.flags & 1048576 && node.kind === 159; + return node.flags & 1048576 /* JSDoc */ && node.kind === 160 /* TypeReference */; } function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); - var index = createIndexInfo(target, false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + var index = createIndexInfo(target, /*isReadonly*/ false); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -27101,22 +32865,24 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; + return strictNullChecks ? getNullableType(type, 8192 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 793064; + var meaning = 793064 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 107455; + meaning |= 107455 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // type reference in checkTypeReferenceOrExpressionWithTypeArguments. links.resolvedSymbol = symbol; links.resolvedType = type; } @@ -27128,6 +32894,10 @@ var ts; function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. links.resolvedType = getWidenedType(checkExpression(node.exprName)); } return links.resolvedType; @@ -27138,9 +32908,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 229: - case 230: - case 232: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: return declaration; } } @@ -27149,78 +32919,86 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + if (!(type.flags & 65536 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name, false); + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; } function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; } function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; } function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } function getGlobalESSymbolType(reportErrors) { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; } function getGlobalPromiseType(reportErrors) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } function getGlobalPromiseConstructorLikeType(reportErrors) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; } function getGlobalAsyncIterableType(reportErrors) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalAsyncIteratorType(reportErrors) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalAsyncIterableIteratorType(reportErrors) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalIterableType(reportErrors) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalIteratorType(reportErrors) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalIterableIteratorType(reportErrors) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064, undefined); + var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } + /** + * Returns a type that is inside a namespace at the global scope, e.g. + * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type + */ function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; } @@ -27228,16 +33006,16 @@ var ts; return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); } function createAsyncIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); } function createAsyncIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); } function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); } function createIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); } function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); @@ -27249,17 +33027,27 @@ var ts; } return links.resolvedType; } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. function createTupleTypeOfArity(arity) { var typeParameters = []; var properties = []; for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); + var typeParameter = createType(32768 /* TypeParameter */); typeParameters.push(typeParameter); - var property = createSymbol(4, "" + i); + var property = createSymbol(4 /* Property */, "" + i); property.type = typeParameter; properties.push(property); } - var type = createObjectType(8 | 4); + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = getLiteralType(arity); + properties.push(lengthSymbol); + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; @@ -27267,7 +33055,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384); + type.thisType = createType(32768 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -27290,37 +33078,23 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; + function getTypeId(type) { + return type.id; } function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + // Return true if the given intersection type contains (a) more than one unit type or (b) an object + // type and a nullable type (null or undefined). function isEmptyIntersectionType(type) { var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6368 && combined & 6368) { + if (t.flags & 13536 /* Unit */ && combined & 13536 /* Unit */) { return true; } combined |= t.flags; - if (combined & 6144 && combined & (32768 | 16777216)) { + if (combined & 12288 /* Nullable */ && combined & (65536 /* Object */ | 33554432 /* NonPrimitive */)) { return true; } } @@ -27328,56 +33102,66 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 65536) { + if (flags & 131072 /* Union */) { addTypesToUnion(typeSet, type.types); } - else if (flags & 1) { + else if (flags & 1 /* Any */) { typeSet.containsAny = true; } - else if (!strictNullChecks && flags & 6144) { - if (flags & 2048) + else if (!strictNullChecks && flags & 12288 /* Nullable */) { + if (flags & 4096 /* Undefined */) typeSet.containsUndefined = true; - if (flags & 4096) + if (flags & 8192 /* Null */) typeSet.containsNull = true; - if (!(flags & 2097152)) + if (!(flags & 4194304 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 || flags & 131072 && isEmptyIntersectionType(type))) { - if (flags & 2) + else if (!(flags & 16384 /* Never */ || flags & 262144 /* Intersection */ && isEmptyIntersectionType(type))) { + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (flags & 2 /* String */) typeSet.containsString = true; - if (flags & 4) + if (flags & 4 /* Number */) typeSet.containsNumber = true; - if (flags & 96) - typeSet.containsStringOrNumberLiteral = true; + if (flags & 512 /* ESSymbol */) + typeSet.containsESSymbol = true; + if (flags & 1120 /* StringOrNumberLiteralOrUnique */) + typeSet.containsLiteralOrUniqueESSymbol = true; var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } } } } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; if (isTypeIdenticalTo(t, type)) { return true; } } return false; } - function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - if (candidate !== type && isTypeSubtypeOf(candidate, type)) { + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { return true; } } @@ -27385,11 +33169,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 256) { + if (first.flags & 256 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -27414,14 +33198,22 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 32 && types.containsString || - t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); + var remove = t.flags & 32 /* StringLiteral */ && types.containsString || + t.flags & 64 /* NumberLiteral */ && types.containsNumber || + t.flags & 1024 /* UniqueESSymbol */ && types.containsESSymbol || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 2097152 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } } } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; @@ -27437,7 +33229,7 @@ var ts; if (subtypeReduction) { removeSubtypes(typeSet); } - else if (typeSet.containsStringOrNumberLiteral) { + else if (typeSet.containsLiteralOrUniqueESSymbol) { removeRedundantLiteralTypes(typeSet); } if (typeSet.length === 0) { @@ -27447,6 +33239,7 @@ var ts; } return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + // This function assumes the constituent type list is sorted and deduplicated. function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; @@ -27457,10 +33250,16 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = createType(65536 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); + type = createType(131072 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } @@ -27469,42 +33268,54 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072) { + if (type.flags & 262144 /* Intersection */) { addTypesToIntersection(typeSet, type.types); } - else if (type.flags & 1) { + else if (type.flags & 1 /* Any */) { typeSet.containsAny = true; } - else if (type.flags & 8192) { + else if (type.flags & 16384 /* Never */) { typeSet.containsNever = true; } - else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { + else if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { typeSet.containsEmptyObject = true; } - else if ((strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768) { + else if ((strictNullChecks || !(type.flags & 12288 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 /* Object */) { typeSet.containsObjectType = true; } - if (type.flags & 65536 && typeSet.unionIndex === undefined) { + if (type.flags & 131072 /* Union */ && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - if (!(type.flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.push(type); } } } + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { var type = types_9[_i]; - addTypeToIntersection(typeSet, type); - } - } + addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); + } + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return emptyObjectType; @@ -27525,17 +33336,20 @@ var ts; } var unionIndex = typeSet.unionIndex; if (unionIndex !== undefined) { + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), + /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = createType(131072 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 12288 /* Nullable */); + type = createType(262144 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; - type.aliasSymbol = aliasSymbol; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. type.aliasTypeArguments = aliasTypeArguments; } return type; @@ -27549,48 +33363,56 @@ var ts; } function getIndexTypeForGenericType(type) { if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144); + type.resolvedIndexType = createType(524288 /* Index */); type.resolvedIndexType.type = type; } return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? neverType : - getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + getLiteralType(ts.symbolName(prop)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : - type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + return maybeTypeOfKind(type, 1081344 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; + return indexType.flags & 16384 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + switch (node.operator) { + case 127 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 140 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 137 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : unknownType; + break; + } } return links.resolvedType; } function createIndexedAccessType(objectType, indexType) { - var type = createType(524288); + var type = createType(1048576 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & 96 ? - ts.escapeLeadingUnderscores("" + indexType.value) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + var accessExpression = accessNode && accessNode.kind === 181 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); @@ -27607,12 +33429,12 @@ var ts; return getTypeOfSymbol(prop); } } - if (!(indexType.flags & 6144) && isTypeAssignableToKind(indexType, 262178 | 84 | 512)) { + if (!(indexType.flags & 12288 /* Nullable */) && isTypeAssignableToKind(indexType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */)) { if (isTypeAny(objectType)) { return anyType; } - var indexInfo = isTypeAssignableToKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || - getIndexInfoOfType(objectType, 0) || + var indexInfo = isTypeAssignableToKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -27622,7 +33444,7 @@ var ts; } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1)) { + if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { @@ -27633,11 +33455,11 @@ var ts; } } if (accessNode) { - var indexNode = accessNode.kind === 180 ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (32 | 64)) { + var indexNode = accessNode.kind === 181 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } - else if (indexType.flags & (2 | 4)) { + else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); } else { @@ -27648,18 +33470,20 @@ var ts; return anyType; } function isGenericObjectType(type) { - return type.flags & 540672 ? true : - getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : - type.flags & 196608 ? ts.forEach(type.types, isGenericObjectType) : + return type.flags & 1081344 /* TypeVariable */ ? true : + ts.getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 393216 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : false; } function isGenericIndexType(type) { - return type.flags & (540672 | 262144) ? true : - type.flags & 196608 ? ts.forEach(type.types, isGenericIndexType) : + return type.flags & (1081344 /* TypeVariable */ | 524288 /* Index */) ? true : + type.flags & 393216 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : false; } + // Return true if the given type is a non-generic object type with a string index signature and no + // other members. function isStringIndexOnlyType(type) { - if (type.flags & 32768 && !isGenericMappedType(type)) { + if (type.flags & 65536 /* Object */ && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && @@ -27667,15 +33491,21 @@ var ts; } return false; } + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // undefined if no transformation is possible. function getTransformedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 131072 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); } else { regularTypes.push(t); @@ -27686,6 +33516,9 @@ var ts; getIntersectionType(stringIndexTypes) ]); } + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. if (isGenericMappedType(objectType)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); var objectTypeMapper = objectType.mapper; @@ -27695,10 +33528,16 @@ var ts; return undefined; } function getIndexedAccessType(objectType, indexType, accessNode) { - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { - if (objectType.flags & 1) { + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (objectType.flags & 1 /* Any */) { return objectType; } + // Defer the operation by creating an indexed access type. var id = objectType.id + "," + indexType.id; var type = indexedAccessTypes.get(id); if (!type) { @@ -27706,12 +33545,15 @@ var ts; } return type; } + // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8)) { + if (indexType.flags & 131072 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); if (propType === unknownType) { return unknownType; } @@ -27719,7 +33561,7 @@ var ts; } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -27731,11 +33573,13 @@ var ts; function getTypeFromMappedTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(32, node.symbol); + var type = createObjectType(32 /* Mapped */, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. getConstraintTypeFromMappedType(type); } return links.resolvedType; @@ -27743,12 +33587,13 @@ var ts; function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { links.resolvedType = emptyTypeLiteralType; } else { - var type = createObjectType(16, node.symbol); + var type = createObjectType(16 /* Anonymous */, node.symbol); type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { @@ -27760,32 +33605,37 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; + return node.parent.kind === 232 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; } function getAliasTypeArgumentsForTypeNode(node) { var symbol = getAliasSymbolForTypeNode(node); return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } - function getSpreadType(left, right) { - if (left.flags & 1 || right.flags & 1) { + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right, symbol, propagatedFlags) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } - if (left.flags & 8192) { + if (left.flags & 16384 /* Never */) { return right; } - if (right.flags & 8192) { + if (right.flags & 16384 /* Never */) { return left; } - if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + if (left.flags & 131072 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } - if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + if (right.flags & 131072 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 16777216) { + if (right.flags & 33554432 /* NonPrimitive */) { return nonPrimitiveType; } - if (right.flags & (136 | 84 | 262178 | 272)) { + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */)) { return left; } var members = ts.createSymbolTable(); @@ -27793,17 +33643,19 @@ var ts; var stringIndexInfo; var numberIndexInfo; if (left === emptyObjectType) { - stringIndexInfo = getIndexInfoOfType(right, 0); - numberIndexInfo = getIndexInfoOfType(right, 1); + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); } else { - stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); - numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + // we approximate own properties as non-methods plus methods that are inside the object literal + var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.escapedName, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { @@ -27812,7 +33664,7 @@ var ts; } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) || skippedPrivateMembers.has(leftProp.escapedName) || isClassMethod(leftProp)) { continue; @@ -27820,11 +33672,11 @@ var ts; if (members.has(leftProp.escapedName)) { var rightProp = members.get(leftProp.escapedName); var rightType = getTypeOfSymbol(rightProp); - if (rightProp.flags & 16777216) { + if (rightProp.flags & 16777216 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); - var flags = 4 | (leftProp.flags & 16777216); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -27835,21 +33687,31 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= propagatedFlags; + spread.flags |= 2097152 /* FreshLiteral */ | 8388608 /* ContainsObjectLiteral */; + spread.objectFlags |= (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; } - var flags = 4 | (prop.flags & 16777216); + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); var result = createSymbol(flags, prop.escapedName); result.type = getTypeOfSymbol(prop); result.declarations = prop.declarations; result.syntheticOrigin = prop; return result; } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } function isClassMethod(prop) { - return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); + return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } function createLiteralType(flags, value, symbol) { var type = createType(flags); @@ -27858,9 +33720,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 && !(type.flags & 1048576)) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 2097152 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 2097152 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -27869,14 +33731,18 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? type.regularType : type; } function getLiteralType(value, enumId, symbol) { + // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', + // where NNN is the text representation of a numeric literal and SSS are the characters + // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where + // EEE is a unique id for the containing enum type. var qualifier = typeof value === "number" ? "#" : "@"; var key = enumId ? enumId + qualifier + value : qualifier + value; var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; @@ -27888,20 +33754,25 @@ var ts; } return links.resolvedType; } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; + function createUniqueESSymbolType(symbol) { + var type = createType(1024 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.type || (links.type = createUniqueESSymbolType(symbol)); } - return links.resolvedType; + return esSymbolType; } function getThisType(node) { - var container = ts.getThisContainer(node, false); + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!ts.hasModifier(container, 32) && - (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { + if (parent && (ts.isClassLike(parent) || parent.kind === 231 /* InterfaceDeclaration */)) { + if (!ts.hasModifier(container, 32 /* Static */) && + (container.kind !== 153 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -27917,74 +33788,76 @@ var ts; } function getTypeFromTypeNode(node) { switch (node.kind) { - case 119: - case 268: - case 269: + case 119 /* AnyKeyword */: + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: return anyType; - case 136: + case 136 /* StringKeyword */: return stringType; - case 133: + case 133 /* NumberKeyword */: return numberType; - case 122: + case 122 /* BooleanKeyword */: return booleanType; - case 137: + case 137 /* SymbolKeyword */: return esSymbolType; - case 105: + case 105 /* VoidKeyword */: return voidType; - case 139: + case 139 /* UndefinedKeyword */: return undefinedType; - case 95: + case 95 /* NullKeyword */: return nullType; - case 130: + case 130 /* NeverKeyword */: return neverType; - case 134: - return node.flags & 65536 ? anyType : nonPrimitiveType; - case 169: - case 99: + case 134 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 170 /* ThisType */: + case 99 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 173: + case 174 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 159: + case 160 /* TypeReference */: return getTypeFromTypeReference(node); - case 158: + case 159 /* TypePredicate */: return booleanType; - case 201: + case 202 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 162: + case 163 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 164: + case 165 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 165: + case 166 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 166: + case 167 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 167: + case 168 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 270: + case 274 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 168: - case 271: - case 272: - case 267: + case 169 /* ParenthesizedType */: + case 275 /* JSDocNonNullableType */: + case 276 /* JSDocOptionalType */: + case 271 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 160: - case 161: - case 163: - case 285: - case 273: + case 278 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 277 /* JSDocFunctionType */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170: + case 171 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 171: + case 172 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 172: + case 173 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 71: - case 143: + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 71 /* Identifier */: + case 144 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 274: - return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -28029,8 +33902,12 @@ var ts; makeArrayTypeMapper(sources, targets); } function createTypeEraser(sources) { - return createTypeMapper(sources, undefined); + return createTypeMapper(sources, /*targets*/ undefined); } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ function createBackreferenceMapper(typeParameters, index) { return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; } @@ -28039,7 +33916,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -28049,7 +33926,7 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { - var result = createType(16384); + var result = createType(32768 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -28057,7 +33934,7 @@ var ts; function cloneTypePredicate(predicate, mapper) { if (ts.isIdentifierTypePredicate(predicate)) { return { - kind: 1, + kind: 1 /* Identifier */, parameterName: predicate.parameterName, parameterIndex: predicate.parameterIndex, type: instantiateType(predicate.type, mapper) @@ -28065,7 +33942,7 @@ var ts; } else { return { - kind: 0, + kind: 0 /* This */, type: instantiateType(predicate.type, mapper) }; } @@ -28074,6 +33951,9 @@ var ts; var freshTypeParameters; var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { @@ -28084,19 +33964,24 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; } function instantiateSymbol(symbol, mapper) { - if (ts.getCheckFlags(symbol) & 1) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { var links = getSymbolLinks(symbol); + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(symbol.flags, symbol.escapedName); - result.checkFlags = 1; + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -28110,15 +33995,19 @@ var ts; return result; } function getAnonymousTypeInstantiation(type, mapper) { - var target = type.objectFlags & 64 ? type.target : type; + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; var symbol = target.symbol; var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; - typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -28127,33 +34016,55 @@ var ts; } } if (typeParameters.length) { - var combinedMapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; var typeArguments = ts.map(typeParameters, combinedMapper); var id = getTypeListId(typeArguments); var result = links.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 32 ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); links.instantiations.set(id, result); } return result; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 208 /* Block */ ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 170 /* ThisType */: + return tp.isThisType; + case 71 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 163 /* TypeQuery */: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { + // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some + // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated + // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for + // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a + // union type A | undefined, we produce { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144) { + if (constraintType.flags & 524288 /* Index */) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384) { + if (typeVariable_1.flags & 32768 /* TypeParameter */) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -28168,11 +34079,11 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (16384 | 32768 | 131072 | 524288); + return type.flags & (1 /* Any */ | 32768 /* TypeParameter */ | 65536 /* Object */ | 262144 /* Intersection */ | 1048576 /* IndexedAccess */); } function instantiateAnonymousType(type, mapper) { - var result = createObjectType(type.objectFlags | 64, type.symbol); - if (type.objectFlags & 32) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; } result.target = type; @@ -28183,31 +34094,34 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { + if (type.flags & 32768 /* TypeParameter */) { return mapper(type); } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + if (type.flags & 65536 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.objectFlags & 32) { + if (type.objectFlags & 32 /* Mapped */) { return getAnonymousTypeInstantiation(type, mapper); } - if (type.objectFlags & 4) { + if (type.objectFlags & 4 /* Reference */) { return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 131072) { + if (type.flags & 262144 /* Intersection */) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 262144) { + if (type.flags & 524288 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 524288) { + if (type.flags & 1048576 /* IndexedAccess */) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } @@ -28216,59 +34130,68 @@ var ts; function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 186: - case 187: - case 151: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 178: + case 179 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 177: + case 178 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 195: + case 196 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 194: - return node.operatorToken.kind === 54 && + case 195 /* BinaryExpression */: + return node.operatorToken.kind === 54 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261: + case 265 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 185: + case 186 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 254: + case 258 /* JsxAttributes */: return ts.forEach(node.properties, isContextSensitive); - case 253: + case 257 /* JsxAttribute */: + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. return node.initializer && isContextSensitive(node.initializer); - case 256: + case 260 /* JsxExpression */: + // It is possible to that node.expression is undefined (e.g
) return node.expression && isContextSensitive(node.expression); } return false; } function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. if (node.typeParameters) { return false; } + // Functions with any parameters that lack type annotations are context sensitive. if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 187) { + if (node.kind !== 188 /* ArrowFunction */) { + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); if (!(parameter && ts.parameterIsThisKeyword(parameter))) { return true; } } - return node.body.kind === 207 ? false : isContextSensitive(node.body); + // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. + return node.body.kind === 208 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 32768) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(16, type.symbol); + var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = ts.emptyArray; @@ -28276,19 +34199,20 @@ var ts; return result; } } - else if (type.flags & 131072) { + else if (type.flags & 262144 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; } + // TYPE CHECKING function isTypeIdenticalTo(source, target) { return isTypeRelatedTo(source, target, identityRelation); } function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; } function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); @@ -28296,9 +34220,31 @@ var ts; function isTypeAssignableTo(source, target) { return isTypeRelatedTo(source, target, assignableRelation); } - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); - } + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 131072 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 131072 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 1081344 /* TypeVariable */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + hasBaseType(source, getTargetType(target)); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); } @@ -28308,35 +34254,48 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; - } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { - return -1; + return -1 /* True */; } if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0; + return 0 /* False */; } if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); - source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); + source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } - var result = -1; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 152 /* MethodDeclaration */ && + kind !== 151 /* MethodSignature */ && kind !== 153 /* Constructor */; + var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { var targetThisType = getThisTypeOfSignature(target); if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType, false) + // void sources are assignable to anything. + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) || compareTypes(targetThisType, sourceThisType, reportErrors); if (!related) { if (reportErrors) { errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); } - return 0; + return 0 /* False */; } result &= related; } @@ -28349,18 +34308,26 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we know we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); + (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); } - return 0; + return 0 /* False */; } result &= related; } @@ -28370,6 +34337,7 @@ var ts; return result; } var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions if (target.typePredicate) { if (source.typePredicate) { result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); @@ -28378,11 +34346,14 @@ var ts; if (reportErrors) { errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } - return 0; + return 0 /* False */; } } else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -28394,9 +34365,9 @@ var ts; errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } - return 0; + return 0 /* False */; } - if (source.kind === 1) { + if (source.kind === 1 /* Identifier */) { var sourcePredicate = source; var targetPredicate = target; var sourceIndex = sourcePredicate.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); @@ -28406,11 +34377,11 @@ var ts; errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } - return 0; + return 0 /* False */; } } var related = compareTypes(source.type, target.type, reportErrors); - if (related === 0 && reportErrors) { + if (related === 0 /* False */ && reportErrors) { errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return related; @@ -28418,12 +34389,13 @@ var ts; function isImplementationCompatibleWithOverload(implementation, overload) { var erasedSource = getErasedSignature(implementation); var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo(erasedSource, erasedTarget, true); + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); } return false; } @@ -28436,6 +34408,8 @@ var ts; function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { if (source.hasRestParameter === target.hasRestParameter) { if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; } else { @@ -28443,6 +34417,7 @@ var ts; } } else { + // Return the count for whichever signature doesn't have rest parameters. return source.hasRestParameter ? targetNonRestParamCount : sourceNonRestParamCount; @@ -28456,10 +34431,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 ? true : - type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 33554432 /* NonPrimitive */ ? true : + type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -28471,18 +34446,18 @@ var ts; if (relation !== undefined) { return relation; } - if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { enumRelation.set(id, false); return false; } var targetEnumType = getTypeOfSymbol(targetSymbol); for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) { var property = _a[_i]; - if (property.flags & 8) { + if (property.flags & 8 /* EnumMember */) { var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); - if (!targetProperty || !(targetProperty.flags & 8)) { + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -28495,69 +34470,88 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 8192) - return false; - if (t & 1 || s & 8192) + if (t & 1 /* Any */ || s & 16384 /* Never */) return true; - if (s & 262178 && t & 2) + if (t & 16384 /* Never */) + return false; + if (s & 524322 /* StringLike */ && t & 2 /* String */) return true; - if (s & 32 && s & 256 && - t & 32 && !(t & 256) && + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 84 && t & 4) + if (s & 84 /* NumberLike */ && t & 4 /* Number */) return true; - if (s & 64 && s & 256 && - t & 64 && !(t & 256) && + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 136 && t & 8) + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) + return true; + if (s & 1536 /* ESSymbolLike */ && t & 512 /* ESSymbol */) return true; - if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 256 && t & 256) { - if (s & 65536 && t & 65536 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { + if (s & 131072 /* Union */ && t & 131072 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 224 && t & 224 && + if (s & 224 /* Literal */ && t & 224 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 2048 && (!strictNullChecks || t & (2048 | 1024))) + if (s & 4096 /* Undefined */ && (!strictNullChecks || t & (4096 /* Undefined */ | 2048 /* Void */))) return true; - if (s & 4096 && (!strictNullChecks || t & 4096)) + if (s & 8192 /* Null */ && (!strictNullChecks || t & 8192 /* Null */)) return true; - if (s & 32768 && t & 16777216) + if (s & 65536 /* Object */ && t & 33554432 /* NonPrimitive */) return true; + if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) + return false; if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1) + if (s & 1 /* Any */) return true; - if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) + // Type number or any numeric literal type is assignable to any numeric enum type or any + // numeric enum literal type. This rule exists for backwards compatibility reasons because + // bit-flag enum types sometimes look like literal enum types with numeric literal values. + if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 1048576) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 2097152 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 && target.flags & 1048576) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 2097152 /* FreshLiteral */) { target = target.regularType; } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + if (source === target || + relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 32768 && target.flags & 32768) { + if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { - return related === 1; + return related === 1 /* Succeeded */; } } - if (source.flags & 1032192 || target.flags & 1032192) { - return checkTypeRelatedTo(source, target, relation, undefined); + if (source.flags & 2064384 /* StructuredOrTypeVariable */ || target.flags & 2064384 /* StructuredOrTypeVariable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var maybeKeys; @@ -28565,18 +34559,11 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var ExpandingFlags; - (function (ExpandingFlags) { - ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; - ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; - ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; - ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; - })(ExpandingFlags || (ExpandingFlags = {})); - var expandingFlags = 0; + var expandingFlags = 0 /* None */; var overflow = false; var isIntersectionConstituent = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, !!errorNode, headMessage); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } @@ -28586,7 +34573,7 @@ var ts; } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } - return result !== 0; + return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); @@ -28595,8 +34582,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 256); - targetType = typeToString(target, undefined, 256); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -28617,18 +34604,20 @@ var ts; if ((globalStringType === source && stringType === target) || (globalNumberType === source && numberType === target) || (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType(false) === source && esSymbolType === target)) { + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608)) { + if (!(type.flags & 393216 /* UnionOrIntersection */)) { return false; } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6144) { + if (t.flags & 12288 /* Nullable */) { continue; } if (seenNonNullable) { @@ -28638,75 +34627,101 @@ var ts; } return false; } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 && source.flags & 1048576) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 2097152 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 && target.flags & 1048576) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 2097152 /* FreshLiteral */) { target = target.regularType; } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) - return -1; + return -1 /* True */; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (getObjectFlags(source) & 128 && source.flags & 1048576) { + if (relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + if (isObjectLiteralType(source) && source.flags & 2097152 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } - return 0; + return 0 /* False */; } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } if (relation !== comparableRelation && - !(source.flags & 196608) && - !(target.flags & 65536) && + !(source.flags & 393216 /* UnionOrIntersection */) && + !(target.flags & 131072 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && - (getPropertiesOfType(source).length > 0 || - getSignaturesOfType(source, 0).length > 0 || - getSignaturesOfType(source, 1).length > 0) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { - var calls = getSignaturesOfType(source, 0); - var constructs = getSignaturesOfType(source, 1); - if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, false) || - constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, false)) { + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) { reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target)); } else { reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); } } - return 0; + return 0 /* False */; } - var result = 0; + var result = 0 /* False */; var saveErrorInfo = errorInfo; var saveIsIntersectionConstituent = isIntersectionConstituent; isIntersectionConstituent = false; - if (source.flags & 65536) { + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 131072 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)); } else { - if (target.flags & 65536) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190)); + if (target.flags & 131072 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */) && !(target.flags & 16382 /* Primitive */)); } - else if (target.flags & 131072) { + else if (target.flags & 262144 /* Intersection */) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 131072) { - result = someTypeRelatedToType(source, target, false); - } - if (!result && (source.flags & 1032192 || target.flags & 1032192)) { + else if (source.flags & 262144 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 2064384 /* StructuredOrTypeVariable */ || target.flags & 2064384 /* StructuredOrTypeVariable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } @@ -28714,10 +34729,10 @@ var ts; } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 32768 && target.flags & 8190) { + if (source.flags & 65536 /* Object */ && target.flags & 16382 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 32768 && globalObjectType === source) { + else if (source.symbol && source.flags & 65536 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -28726,34 +34741,47 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 32768 && target.flags & 32768) { - return recursiveTypeRelatedTo(source, target, false); + if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } - if (source.flags & 65536 && target.flags & 65536 || - source.flags & 131072 && target.flags & 131072) { + if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ || + source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - return 0; + return 0 /* False */; } function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { - var isComparingJsxAttributes = !!(source.flags & 33554432); + if (maybeTypeOfKind(target, 65536 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(source.flags & 67108864 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 131072 /* Union */) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. ts.Debug.assert(!!errorNode); if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { + // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { @@ -28765,7 +34793,7 @@ var ts; } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); } else { reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); @@ -28785,13 +34813,13 @@ var ts; return false; } function eachTypeRelatedToSomeType(source, target) { - var result = -1; + var result = -1 /* True */; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { - return 0; + return 0 /* False */; } result &= related; } @@ -28799,48 +34827,57 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 65536 && containsType(targetTypes, source)) { - return -1; + if (target.flags & 131072 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; - var related = isRelatedTo(source, type, false); + var related = isRelatedTo(source, type, /*reportErrors*/ false); if (related) { return related; } } if (reportErrors) { var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } - return 0; + return 0 /* False */; } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { + var sourceProperty = sourcePropertiesFiltered_1[_i]; var sourceType = getTypeOfSymbol(sourceProperty); for (var _a = 0, _b = target.types; _a < _b.length; _a++) { var type = _b[_a]; var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); if (targetType && isRelatedTo(sourceType, targetType)) { - return type; + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + if (match) { + return undefined; + } + match = type; } } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { - var result = -1; + var result = -1 /* True */; var targetTypes = target.types; for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { var targetType = targetTypes_2[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { - return 0; + return 0 /* False */; } result &= related; } @@ -28848,8 +34885,8 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 65536 && containsType(sourceTypes, target)) { - return -1; + if (source.flags & 131072 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; } var len = sourceTypes.length; for (var i = 0; i < len; i++) { @@ -28858,50 +34895,91 @@ var ts; return related; } } - return 0; + return 0 /* False */; } function eachTypeRelatedToType(source, target, reportErrors) { - var result = -1; + var result = -1 /* True */; var sourceTypes = source.types; for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { - return 0; + return 0 /* False */; } result &= related; } return result; } - function typeArgumentsRelatedTo(source, target, reportErrors) { + function typeArgumentsRelatedTo(source, target, variances, reportErrors) { var sources = source.typeArguments || ts.emptyArray; var targets = target.typeArguments || ts.emptyArray; if (sources.length !== targets.length && relation === identityRelation) { - return 0; + return 0 /* False */; } var length = sources.length <= targets.length ? sources.length : targets.length; - var result = -1; + var result = -1 /* True */; for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0; + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; } - result &= related; } return result; } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. function recursiveTypeRelatedTo(source, target, reportErrors) { if (overflow) { - return 0; + return 0 /* False */; } var id = getRelationKey(source, target, relation); var related = relation.get(id); if (related !== undefined) { - if (reportErrors && related === 2) { - relation.set(id, 3); + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation.set(id, 3 /* FailedAndReported */); } else { - return related === 1 ? -1 : 0; + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } if (!maybeKeys) { @@ -28911,13 +34989,14 @@ var ts; } else { for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i]) { - return 1; + return 1 /* Maybe */; } } if (depth === 100) { overflow = true; - return 0; + return 0 /* False */; } } var maybeStart = maybeCount; @@ -28927,32 +35006,37 @@ var ts; targetStack[depth] = target; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { - if (result === -1 || depth === 0) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded for (var i = maybeStart; i < maybeCount; i++) { - relation.set(maybeKeys[i], 1); + relation.set(maybeKeys[i], 1 /* Succeeded */); } maybeCount = maybeStart; } } else { - relation.set(id, reportErrors ? 3 : 2); + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); maybeCount = maybeStart; } return result; } function structuredTypeRelatedTo(source, target, reportErrors) { var result; + var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 16384) { - if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (target.flags & 32768 /* TypeParameter */) { + // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. + if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -28962,12 +35046,15 @@ var ts; } } } - else if (target.flags & 262144) { - if (source.flags & 262144) { - if (result = isRelatedTo(target.type, source.type, false)) { + else if (target.flags & 524288 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 524288 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // constraint of T. var constraint = getConstraintOfType(target.type); if (constraint) { if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { @@ -28975,7 +35062,9 @@ var ts; } } } - else if (target.flags & 524288) { + else if (target.flags & 1048576 /* IndexedAccess */) { + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -28984,31 +35073,33 @@ var ts; } } } - if (source.flags & 16384) { - if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + else if (isGenericMappedType(target) && !isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + if (source.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(source); + // A type parameter with no constraint is not related to the non-primitive object type. + if (constraint || !(target.flags & 33554432 /* NonPrimitive */)) { + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; } } - else { - var constraint = getConstraintOfTypeParameter(source); - if (constraint || !(target.flags & 16777216)) { - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; - } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } } - else if (source.flags & 524288) { + else if (source.flags & 1048576 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -29016,158 +35107,224 @@ var ts; return result; } } - else if (target.flags & 524288 && source.indexType === target.indexType) { + else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { + // if we have indexed access types with identical index types, see if relationship holds for + // the two object types. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } else { - if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(source.flags & 134217728 /* MarkerType */ || target.flags & 134217728 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { return result; } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } } - var sourceIsPrimitive = !!(source.flags & 8190); + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + var sourceIsPrimitive = !!(source.flags & 16382 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); } - if (source.flags & (32768 | 131072) && target.flags & 32768) { + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (65536 /* Object */ | 262144 /* Intersection */) && target.flags & 65536 /* Object */) { + // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + // An empty object type is related to any mapped type that includes a '?' modifier. if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1; + result = -1 /* True */; } else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; } else { result = propertiesRelatedTo(source, target, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } } } if (result) { - errorInfo = saveErrorInfo; - return result; + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; } } } - return 0; + return 0 /* False */; } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. function mappedTypeRelatedTo(source, target, reportErrors) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + !(getCombinedMappedTypeModifiers(source) & 2 /* Optional */) || + getCombinedMappedTypeModifiers(target) & 2 /* Optional */); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_1; + if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } - return 0; + return 0 /* False */; } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); } - return 0; + return 0 /* False */; + } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } } - var result = -1; + var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; - if (!(targetProp.flags & 4194304)) { + for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { + var targetProp = properties_3[_b]; + if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 || targetPropFlags & 8) { - if (ts.getCheckFlags(sourceProp) & 256) { + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } - return 0; + return 0 /* False */; } if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 8 && targetPropFlags & 8) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); } } - return 0; + return 0 /* False */; } } - else if (targetPropFlags & 16) { + else if (targetPropFlags & 16 /* Protected */) { if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } - return 0; + return 0 /* False */; } } - else if (sourcePropFlags & 16) { + else if (sourcePropFlags & 16 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } - return 0; + return 0 /* False */; } var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); } - return 0; + return 0 /* False */; } result &= related; - if (relation !== comparableRelation && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } - return 0; + return 0 /* False */; } } } } return result; } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ function isWeakType(type) { - if (type.flags & 32768) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); } - if (type.flags & 131072) { + if (type.flags & 262144 /* Intersection */) { return ts.every(type.types, isWeakType); } return false; } function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(source.flags & 33554432); + var isComparingJsxAttributes = !!(source.flags & 67108864 /* JsxAttributes */); for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { @@ -29177,24 +35334,24 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 && target.flags & 32768)) { - return 0; + if (!(source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */)) { + return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); var targetProperties = getPropertiesOfObjectType(target); if (sourceProperties.length !== targetProperties.length) { - return 0; + return 0 /* False */; } - var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + var result = -1 /* True */; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { - return 0; + return 0 /* False */; } var related = compareProperties(sourceProp, targetProp, isRelatedTo); if (!related) { - return 0; + return 0 /* False */; } result &= related; } @@ -29205,43 +35362,57 @@ var ts; return signaturesIdenticalTo(source, target, kind); } if (target === anyFunctionType || source === anyFunctionType) { - return -1; + return -1 /* True */; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); - if (kind === 1 && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. if (reportErrors) { reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); } - return 0; + return 0 /* False */; } if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { - return 0; + return 0 /* False */; } } - var result = -1; + var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have instantiations of the same anonymous type (which typically will be the type of a + // method). Simply do a pairwise comparison of the signatures in the two signature lists instead + // of the much more expensive N * M comparison matrix we explore below. We erase type parameters + // as they are known to always be the same. for (var i = 0; i < targetSignatures.length; i++) { - var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], true, reportErrors); + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); if (!related) { - return 0; + return 0 /* False */; } result &= related; } } else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure var shouldElaborateErrors = reportErrors; for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, true, shouldElaborateErrors); + var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors); if (related) { result &= related; errorInfo = saveErrorInfo; @@ -29250,43 +35421,46 @@ var ts; shouldElaborateErrors = false; } if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); } - return 0; + return 0 /* False */; } } return result; } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); if (sourceSignatures.length !== targetSignatures.length) { - return 0; + return 0 /* False */; } - var result = -1; + var result = -1 /* True */; for (var i = 0; i < sourceSignatures.length; i++) { - var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { - return 0; + return 0 /* False */; } result &= related; } return result; } function eachPropertyRelatedTo(source, target, kind, reportErrors) { - var result = -1; + var result = -1 /* True */; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); } - return 0; + return 0 /* False */; } result &= related; } @@ -29305,21 +35479,24 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { - return -1; + if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; } var sourceInfo = getIndexInfoOfType(source, kind) || - kind === 1 && getIndexInfoOfType(source, 0); + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); if (sourceInfo) { return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); } if (isGenericMappedType(source)) { - return kind === 0 && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); - } - if (isObjectLiteralType(source)) { - var related = -1; - if (kind === 0) { - var sourceNumberInfo = getIndexInfoOfType(source, 1); + // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } + // if T is related to U. + return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + } + if (isObjectTypeWithInferableIndex(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); if (sourceNumberInfo) { related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); } @@ -29332,32 +35509,35 @@ var ts; if (reportErrors) { reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } - return 0; + return 0 /* False */; } function indexTypesIdenticalTo(source, target, indexKind) { var targetInfo = getIndexInfoOfType(target, indexKind); var sourceInfo = getIndexInfoOfType(source, indexKind); if (!sourceInfo && !targetInfo) { - return -1; + return -1 /* True */; } if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { return isRelatedTo(sourceInfo.type, targetInfo.type); } - return 0; + return 0 /* False */; } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; } - var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24); - var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24); - if (targetAccessibility === 8) { + var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { return true; } - if (targetAccessibility === 16 && sourceAccessibility !== 8) { + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { return true; } - if (targetAccessibility !== 16 && !sourceAccessibility) { + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { return true; } if (reportErrors) { @@ -29366,12 +35546,77 @@ var ts; return false; } } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.flags |= 134217728 /* MarkerType */; + return result; + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + var typeParameters = type.typeParameters || ts.emptyArray; + var variances = type.variances; + if (!variances) { + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this + variances = [1 /* Covariant */]; + } + else { + // The emptyArray singleton is used to signal a recursive invocation. + type.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); + var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + } + type.variances = variances; + } + return variances; + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 2048 /* Void */) { + return true; + } + } + return false; + } function isUnconstrainedTypeParameter(type) { - return type.flags & 16384 && !getConstraintFromTypeParameter(type); + return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } + /** + * getTypeReferenceId(A) returns "111=0-12=1" + * where A.id=111 and number.id=12 + */ function getTypeReferenceId(type, typeParameters, depth) { if (depth === void 0) { depth = 0; } var result = "" + type.target.id; @@ -29394,6 +35639,10 @@ var ts; } return result; } + /** + * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. + * For other cases, the types ids are used. + */ function getRelationKey(source, target, relation) { if (relation === identityRelation && source.id > target.id) { var temp = source; @@ -29406,8 +35655,10 @@ var ts; } return source.id + "," + target.id; } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. function forEachProperty(prop, callback) { - if (ts.getCheckFlags(prop) & 6) { + if (ts.getCheckFlags(prop) & 6 /* Synthetic */) { for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { var t = _a[_i]; var p = getPropertyOfType(t, prop.escapedName); @@ -29420,43 +35671,43 @@ var ts; } return callback(prop); } + // Return the declaring class type of a property or undefined if property not declared in class function getDeclaringClass(prop) { - return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. function isPropertyInClassDerivedFrom(prop, baseClass) { return forEachProperty(prop, function (sp) { var sourceClass = getDeclaringClass(sp); return sourceClass ? hasBaseType(sourceClass, baseClass) : false; }); } + // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.hasModifier(declaration, 128)) { - return true; - } - } - } - return false; - } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 32768) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 65536 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 32768 && t.symbol === symbol) { + if (t.flags & 65536 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -29467,38 +35718,46 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types if (sourceProp === targetProp) { - return -1; + return -1 /* True */; } - var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { - return 0; + return 0 /* False */; } if (sourcePropAccessibility) { if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { - return 0; + return 0 /* False */; } } else { - if ((sourceProp.flags & 16777216) !== (targetProp.flags & 16777216)) { - return 0; + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; } } if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { - return 0; + return 0 /* False */; } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } function isMatchingSignature(source, target, partialMatch) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. if (source.parameters.length === target.parameters.length && source.minArgumentCount === target.minArgumentCount && source.hasRestParameter === target.hasRestParameter) { return true; } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). var sourceRestCount = source.hasRestParameter ? 1 : 0; var targetRestCount = target.hasRestParameter ? 1 : 0; if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || @@ -29507,19 +35766,30 @@ var ts; } return false; } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { - return -1; + return -1 /* True */; } if (!(isMatchingSignature(source, target, partialMatch))) { - return 0; + return 0 /* False */; } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { - return 0; + return 0 /* False */; } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); - var result = -1; + var result = -1 /* True */; if (!ignoreThisTypes) { var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType) { @@ -29527,7 +35797,7 @@ var ts; if (targetThisType) { var related = compareTypes(sourceThisType, targetThisType); if (!related) { - return 0; + return 0 /* False */; } result &= related; } @@ -29539,7 +35809,7 @@ var ts; var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); var related = compareTypes(s, t); if (!related) { - return 0; + return 0 /* False */; } result &= related; } @@ -29565,6 +35835,9 @@ var ts; } return true; } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. function getSupertypeOrUnion(types) { return literalTypesWithSameBaseType(types) ? getUnionType(types) : @@ -29574,47 +35847,72 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : - getUnionType(types, true); + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : + getUnionType(types, /*subtypeReduction*/ true); + } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return getObjectFlags(type) & 4 && type.target === globalArrayType; + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { - return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 12288 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return !!(type.flags & 6368); + return !!(type.flags & 13536 /* Unit */); } function isLiteralType(type) { - return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + return type.flags & 8 /* Boolean */ ? true : + type.flags & 131072 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 256 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 && type.flags & 1048576 ? stringType : - type.flags & 64 && type.flags & 1048576 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 65536 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 32 /* StringLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? numberType : + type.flags & 128 /* BooleanLiteral */ ? booleanType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 1024 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ function isTupleType(type) { - return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -29624,44 +35922,59 @@ var ts; } return result; } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type.value === "" ? 32 : 0 : - type.flags & 64 ? type.value === 0 ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; + return type.flags & 131072 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : + type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : + type.flags & 14574 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : + return getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 14560 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); } function getDefinitelyFalsyPartOfType(type) { - return type.flags & 2 ? emptyStringType : - type.flags & 4 ? zeroType : - type.flags & 8 || type === falseType ? falseType : - type.flags & (1024 | 2048 | 4096) || - type.flags & 32 && type.value === "" || - type.flags & 64 && type.value === 0 ? type : + return type.flags & 2 /* String */ ? emptyStringType : + type.flags & 4 /* Number */ ? zeroType : + type.flags & 8 /* Boolean */ || type === falseType ? falseType : + type.flags & (2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */) || + type.flags & 32 /* StringLiteral */ && type.value === "" || + type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : neverType; } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (2048 | 4096); + var missing = (flags & ~type.flags) & (4096 /* Undefined */ | 8192 /* Null */); return missing === 0 ? type : - missing === 2048 ? getUnionType([type, undefinedType]) : - missing === 4096 ? getUnionType([type, nullType]) : + missing === 4096 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 8192 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } function getNonNullableType(type) { - return strictNullChecks ? getTypeWithFacts(type, 524288) : type; + return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && - getSignaturesOfType(type, 0).length === 0 && - getSignaturesOfType(type, 1).length === 0; + /** + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module + * with no call or construct signatures. + */ + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName); @@ -29684,8 +35997,13 @@ var ts; } return members; } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { + if (!(isObjectLiteralType(type) && type.flags & 2097152 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -29695,39 +36013,102 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; - regularNew.objectFlags |= 128; + regularNew.flags = resolved.flags & ~2097152 /* FreshLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } - function getWidenedProperty(prop) { + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertyNamesOfContext(context) { + if (!context.resolvedPropertyNames) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, true); + } + } + } + context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + } + return context.resolvedPropertyNames; + } + function getWidenedProperty(prop, context) { var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getWidenedTypeOfObjectLiteral(type) { + function getUndefinedProperty(name) { + var cached = undefinedProperties.get(name); + if (cached) { + return cached; + } + var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); + result.type = undefinedType; + undefinedProperties.set(name, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; - members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop) : prop); + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop, context) : prop); } - var stringIndexInfo = getIndexInfoOfType(type, 0); - var numberIndexInfo = getIndexInfoOfType(type, 1); + if (context) { + for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { + var name = _c[_b]; + if (!members.has(name)) { + members.set(name, getUndefinedProperty(name)); + } + } + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } - function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); - } function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 6144) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 12582912 /* RequiresWidening */) { + if (type.flags & 12288 /* Nullable */) { return anyType; } - if (getObjectFlags(type) & 128) { - return getWidenedTypeOfObjectLiteral(type); + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 65536) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + if (type.flags & 131072 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -29735,33 +36116,51 @@ var ts; } return type; } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 65536) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { + if (type.flags & 4194304 /* ContainsWideningType */) { + if (type.flags & 131072 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } } } - } - if (getObjectFlags(type) & 128) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 4194304 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.symbolName(p), typeToString(getWidenedType(t))); + } + errorReported = true; } - errorReported = true; } } } @@ -29771,25 +36170,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 149: - case 148: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 146: + case 147 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 176: + case 177 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 228: - case 151: - case 150: - case 153: - case 154: - case 186: - case 187: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -29802,7 +36201,8 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { + if (produceDiagnostics && noImplicitAny && type.flags & 4194304 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -29866,13 +36266,16 @@ var ts; isFixed: inference.isFixed }; } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & (540672 | 262144) || - objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || - objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || - objectFlags & 32 || - type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & (1081344 /* TypeVariable */ | 524288 /* Index */) || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 393216 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -29881,11 +36284,36 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `{}` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 32 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = emptyObjectType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 2 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } - function inferTypeForHomomorphicMappedType(source, target) { + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0); + var indexInfo = getIndexInfoOfType(source, 0 /* String */); if (properties.length === 0 && !indexInfo) { return undefined; } @@ -29894,39 +36322,37 @@ var ts; var inferences = [inference]; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 16777216; + var optionalMask = target.declaration.questionToken ? 0 : 16777216 /* Optional */; var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); - if (!inferredPropType) { + var propType = getTypeOfSymbol(prop); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + if (propType.flags & 16777216 /* ContainsAnyFunctionType */) { return undefined; } - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; + inferredProp.type = inferTargetType(propType); members.set(prop.escapedName, inferredProp); } if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); } return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); function inferTargetType(sourceType) { inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType); - return inference.candidates && getUnionType(inference.candidates, true); + inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); + return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; } } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = getPropertiesOfObjectType(target); + var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; - if (requireOptionalProperties || !(targetProp.flags & 16777216)) { + if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { return targetProp; @@ -29935,7 +36361,7 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; @@ -29945,6 +36371,8 @@ var ts; return; } if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. var sourceTypes = source.aliasTypeArguments; var targetTypes = target.aliasTypeArguments; for (var i = 0; i < sourceTypes.length; i++) { @@ -29952,8 +36380,10 @@ var ts; } return; } - if (source.flags & 65536 && target.flags & 65536 && !(source.flags & 256 && target.flags & 256) || - source.flags & 131072 && target.flags & 131072) { + if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || + source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { + // Source and target are both unions or both intersections. If source and target + // are the same type, just relate each constituent type to itself. if (source === target) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -29961,6 +36391,12 @@ var ts; } return; } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. var matchingTypes = void 0; for (var _b = 0, _c = source.types; _b < _c.length; _b++) { var t = _c[_b]; @@ -29968,58 +36404,88 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (64 | 32)) { + else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); } } } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. if (matchingTypes) { source = removeTypesFromUnionOrIntersection(source, matchingTypes); target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 540672) { - if (source.flags & 8388608 || source === silentNeverType) { + if (target.flags & 1081344 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 16777216 /* ContainsAnyFunctionType */ || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - if (!inference.candidates || priority < inference.priority) { + // We give lowest priority to inferences of implicitNeverType (which is used as the + // element type for empty array literals). Thus, inferences from empty array literals + // only matter when no other inferences are made. + var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); + if (!inference.candidates || p < inference.priority) { inference.candidates = [source]; - inference.priority = priority; + inference.priority = p; } - else if (priority === inference.priority) { + else if (p === inference.priority) { inference.candidates.push(source); } - if (!(priority & 4) && target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + else if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } } } - else if (source.flags & 262144 && target.flags & 262144) { + else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { + priority ^= 1 /* Contravariant */; inferFromTypes(source.type, target.type); + priority ^= 1 /* Contravariant */; } - else if (source.flags & 524288 && target.flags & 524288) { + else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + priority ^= 1 /* Contravariant */; + inferFromTypes(empty, target.type); + priority ^= 1 /* Contravariant */; + } + else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (target.flags & 196608) { + else if (target.flags & 393216 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { var t = targetTypes_3[_d]; if (getInferenceInfoForType(t)) { @@ -30030,14 +36496,18 @@ var ts; inferFromTypes(source, t); } } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 1; + priority |= 2 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } } - else if (source.flags & 65536) { + else if (source.flags & 131072 /* Union */) { + // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -30046,14 +36516,18 @@ var ts; } else { source = getApparentType(source); - if (source.flags & (32768 | 131072)) { + if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; } (visited || (visited = ts.createMap())).set(key, true); - var isNonConstructorObject = target.flags & 32768 && - !(getObjectFlags(target) & 16 && target.symbol && target.symbol.flags & 32); + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + var isNonConstructorObject = target.flags & 65536 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (ts.contains(symbolStack, symbol)) { @@ -30069,8 +36543,18 @@ var ts; } } } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes) { + priority ^= 1 /* Contravariant */; + inferFromTypes(source, target); + priority ^= 1 /* Contravariant */; + } + else { + inferFromTypes(source, target); + } + } function getInferenceInfoForType(type) { - if (type.flags & 540672) { + if (type.flags & 1081344 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -30082,34 +36566,50 @@ var ts; } function inferFromObjectTypes(source, target) { if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); } - if (getObjectFlags(target) & 32) { + if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144) { + if (constraintType.flags & 524288 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); + var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); + if (ts.contains(mappedTypeStack, key)) { + return; + } + (mappedTypeStack || (mappedTypeStack = [])).push(key); + var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); + mappedTypeStack.pop(); if (inferredType) { var savePriority = priority; - priority |= 2; + priority |= 4 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } } return; } - if (constraintType.flags & 16384) { + if (constraintType.flags & 32768 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. inferFromTypes(getIndexType(source), constraintType); inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); return; } } - if (!getUnmatchedProperty(source, target, false) || !getUnmatchedProperty(target, source, false)) { + // Infer from the members of source and target only if the two types are possibly related. We check + // in both directions because we may be inferring for a co-variant or a contra-variant position. + if (!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) || !getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false)) { inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); inferFromIndexTypes(source, target); } } @@ -30130,11 +36630,11 @@ var ts; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); } } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromContravariantTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -30143,19 +36643,19 @@ var ts; } } function inferFromIndexTypes(source, target) { - var targetStringIndexType = getIndexTypeOfType(target, 0); + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); if (targetStringIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 0); + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); if (sourceIndexType) { inferFromTypes(sourceIndexType, targetStringIndexType); } } - var targetNumberIndexType = getIndexTypeOfType(target, 1); + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); if (targetNumberIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 1) || - getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 1); + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); if (sourceIndexType) { inferFromTypes(sourceIndexType, targetNumberIndexType); } @@ -30171,6 +36671,10 @@ var ts; } return false; } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ function removeTypesFromUnionOrIntersection(type, typesToRemove) { var reducedTypes = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { @@ -30179,44 +36683,76 @@ var ts; reducedTypes.push(t); } } - return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 131072 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 | 262144); + return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; } function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; if (!inferredType) { if (inference.candidates) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); + // We widen inferred literal types if + // all inferences were made to top-level ocurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. var signature = context.signature; var widenLiteralTypes = inference.topLevel && !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; - var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? - getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unionOrSuperType); - } - else if (context.flags & 2) { + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if + // union types were requested or if all inferences were made from the return type position, infer a + // union type. Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : + context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : + getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unwidenedType); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. var defaultType = getDefaultFromTypeParameter(inference.typeParameter); if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); } } + inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); } } } @@ -30232,32 +36768,42 @@ var ts; } return result; } + // EXPRESSION TYPE CHECKING function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); - } + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 163 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 144 /* QualifiedName */ ? false : "quit"; }); + } + // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. We prefix nodes + // occurring in an apparent type position with '@' because the control flow type + // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; } - if (node.kind === 99) { + if (node.kind === 99 /* ThisKeyword */) { return "0"; } - if (node.kind === 179) { + if (node.kind === 180 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + return key && key + "." + ts.idText(node.name); } - if (node.kind === 176) { + if (node.kind === 177 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 176 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 177 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -30265,17 +36811,18 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 174) { - var name_21 = element.propertyName || element.name; - switch (name_21.kind) { - case 71: - return ts.unescapeLeadingUnderscores(name_21.escapedText); - case 144: - return ts.isStringOrNumericLiteral(name_21.expression) ? name_21.expression.text : undefined; - case 9: - case 8: - return name_21.text; + if (element.parent.kind === 175 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 71 /* Identifier */: + return ts.idText(name); + case 145 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined ts.Debug.fail("Unexpected name kind for binding element name"); } } @@ -30285,28 +36832,28 @@ var ts; } function isMatchingReference(source, target) { switch (source.kind) { - case 71: - return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 || target.kind === 176) && + case 71 /* Identifier */: + return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 227 /* VariableDeclaration */ || target.kind === 177 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99: - return target.kind === 99; - case 97: - return target.kind === 97; - case 179: - return target.kind === 179 && + case 99 /* ThisKeyword */: + return target.kind === 99 /* ThisKeyword */; + case 97 /* SuperKeyword */: + return target.kind === 97 /* SuperKeyword */; + case 180 /* PropertyAccessExpression */: + return target.kind === 180 /* PropertyAccessExpression */ && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 176: - if (target.kind !== 179) + case 177 /* BindingElement */: + if (target.kind !== 180 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 176 && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 177 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 226) { + if (source.parent.parent.kind === 227 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return maybeId && isMatchingReference(maybeId, t.expression); } @@ -30314,7 +36861,7 @@ var ts; return false; } function containsMatchingReference(source, target) { - while (source.kind === 179) { + while (source.kind === 180 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -30322,33 +36869,51 @@ var ts; } 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 + // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 && + return target.kind === 180 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71) { + if (expr.kind === 71 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 179) { + if (expr.kind === 180 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536) { + if (type && type.flags & 131072 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2) { + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } } return false; } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -30361,7 +36926,7 @@ var ts; } } } - if (callExpression.expression.kind === 179 && + if (callExpression.expression.kind === 180 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -30375,7 +36940,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536)) { + if (!(source.flags & 131072 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -30386,20 +36951,23 @@ var ts; } return false; } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 8192) { + if (assignedType.flags & 16384 /* Never */) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192)) { + if (!(reducedType.flags & 16384 /* Never */)) { return reducedType; } } return declaredType; } function getTypeFactsOfTypes(types) { - var result = 0; + var result = 0 /* None */; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; result |= getTypeFacts(t); @@ -30407,98 +36975,110 @@ var ts; return result; } function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. var resolved = resolveStructuredTypeMembers(type); return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2) { - return strictNullChecks ? 4079361 : 4194049; + if (flags & 2 /* String */) { + return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 32) { + if (flags & 32 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? - isEmpty ? 3030785 : 1982209 : - isEmpty ? 3145473 : 4194049; + isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } - if (flags & (4 | 16)) { - return strictNullChecks ? 4079234 : 4193922; + if (flags & (4 /* Number */ | 16 /* Enum */)) { + return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & 64) { + if (flags & 64 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; + isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : + isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; } - if (flags & 8) { - return strictNullChecks ? 4078980 : 4193668; + if (flags & 8 /* Boolean */) { + return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 136) { + if (flags & 136 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 32768) { + if (flags & 65536 /* Object */) { return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; + strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : + strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; } - if (flags & (1024 | 2048)) { - return 2457472; + if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { + return 2457472 /* UndefinedFacts */; } - if (flags & 4096) { - return 2340752; + if (flags & 8192 /* Null */) { + return 2340752 /* NullFacts */; } - if (flags & 512) { - return strictNullChecks ? 1981320 : 4193160; + if (flags & 1536 /* ESSymbolLike */) { + return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 16777216) { - return strictNullChecks ? 6166480 : 8378320; + if (flags & 33554432 /* NonPrimitive */) { + return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; } - if (flags & 540672) { + if (flags & 1081344 /* TypeVariable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 196608) { + if (flags & 393216 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } - return 8388607; + return 8388607 /* All */; } function getTypeWithFacts(type, include) { + if (type.flags & 1048576 /* IndexedAccess */) { + // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to + // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072), defaultType]); + return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); } return type; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); return getTypeOfPropertyOfType(type, text) || - isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || - getIndexTypeOfType(type, 0) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || unknownType; } function getTypeOfDestructuredArrayElement(type, index) { return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || - checkIteratedTypeOrElementType(type, undefined, false, false) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; } function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 178 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 265 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 && parent.parent.left === parent || - parent.parent.kind === 216 && parent.parent.initializer === parent; + return parent.parent.kind === 195 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); @@ -30515,21 +37095,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 215: + case 216 /* ForInStatement */: return stringType; - case 216: + case 217 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194: + case 195 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 188: + case 189 /* DeleteExpression */: return undefinedType; - case 177: + case 178 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198: + case 199 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 261: + case 265 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 262: + case 266 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -30537,7 +37117,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 ? + var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : @@ -30545,6 +37125,9 @@ var ts; return getTypeWithDefault(type, node.initializer); } function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. var links = getNodeLinks(node); return links.resolvedType || getTypeOfExpression(node); } @@ -30552,39 +37135,39 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 215) { + if (node.parent.parent.kind === 216 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 216) { + if (node.parent.parent.kind === 217 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 226 ? + return node.kind === 227 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 226 || node.kind === 176 ? + return node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 226 && node.initializer && + return node.kind === 227 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 && node.parent.kind === 194 && + node.kind !== 177 /* BindingElement */ && node.parent.kind === 195 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 185: + case 186 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 194: + case 195 /* BinaryExpression */: switch (node.operatorToken.kind) { - case 58: + case 58 /* EqualsToken */: return getReferenceCandidate(node.left); - case 26: + case 26 /* CommaToken */: return getReferenceCandidate(node.right); } } @@ -30592,13 +37175,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 185 || - parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? + return parent.kind === 186 /* ParenthesizedExpression */ || + parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 257) { + if (clause.kind === 261 /* CaseClause */) { var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } @@ -30607,6 +37190,8 @@ var ts; function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. links.switchTypes = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; @@ -30620,13 +37205,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 131072 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 131072 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536) { + if (source.flags & 131072 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -30635,24 +37220,27 @@ var ts; } return true; } - if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + return type.flags & 131072 /* Union */ ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 65536) { + if (type.flags & 131072 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); } return f(type) ? type : neverType; } + // Apply a mapping function to a type and return the resulting type. If the source type + // is a union type, the mapping function is applied to each constituent type and a union + // of the resulting types is returned. function mapType(type, mapper) { - if (!(type.flags & 65536)) { + if (!(type.flags & 131072 /* Union */)) { return mapper(type); } var types = type.types; @@ -30678,12 +37266,15 @@ var ts; function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : - t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : t; }); } @@ -30698,40 +37289,48 @@ var ts; function createFlowType(type, incomplete) { return incomplete ? { flags: 0, type: type } : type; } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. function createEvolvingArrayType(elementType) { - var result = createObjectType(256); + var result = createObjectType(256 /* EvolvingArray */); result.elementType = elementType; return result; } function getEvolvingArrayType(elementType) { return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. function addEvolvingArrayElementType(evolvingArrayType, node) { var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 8192 ? + return elementType.flags & 16384 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 65536 ? - getUnionType(elementType.types, true) : + createArrayType(elementType.flags & 131072 /* Union */ ? + getUnionType(elementType.types, /*subtypeReduction*/ true) : elementType); } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. function getFinalArrayType(evolvingArrayType) { return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); } function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; } function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? type.elementType : neverType; + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var t = types_15[_i]; - if (!(t.flags & 8192)) { - if (!(getObjectFlags(t) & 256)) { + if (!(t.flags & 16384 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } hasEvolvingArrayType = true; @@ -30739,23 +37338,28 @@ var ts; } return hasEvolvingArrayType; } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. function getUnionOrEvolvingArrayType(types, subtypeReduction) { return isEvolvingArrayTypeList(types) ? getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.escapedText === "length" || - parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 && + var isLengthPushOrUnshift = parent.kind === 180 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 182 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 181 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 194 && - parent.parent.operatorToken.kind === 58 && + parent.parent.kind === 195 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -30766,12 +37370,12 @@ var ts; return links.maybeTypePredicate; } function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97) { + if (node.expression.kind !== 97 /* SuperKeyword */) { var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0); + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); } } @@ -30791,19 +37395,25 @@ var ts; if (flowAnalysisDisabled) { return unknownType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 35620607 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); sharedFlowCount = sharedFlowStart; - var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 204 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 16384 /* Never */) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { if (flowDepth === 2500) { + // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); return unknownType; @@ -30811,7 +37421,10 @@ var ts; flowDepth++; while (true) { var flags = flow.flags; - if (flags & 1024) { + if (flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. for (var i = sharedFlowStart; i < sharedFlowCount; i++) { if (sharedFlowNodes[i] === flow) { flowDepth--; @@ -30820,56 +37433,64 @@ var ts; } } var type = void 0; - if (flags & 4096) { + if (flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement flow.locked = true; type = getTypeAtFlowNode(flow.antecedent); flow.locked = false; } - else if (flags & 2048) { + else if (flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent flow = flow.antecedent; continue; } - else if (flags & 16) { + else if (flags & 16 /* Assignment */) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flags & 96) { + else if (flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } - else if (flags & 128) { + else if (flags & 128 /* SwitchClause */) { type = getTypeAtSwitchClause(flow); } - else if (flags & 12) { + else if (flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; continue; } - type = flags & 4 ? + type = flags & 4 /* BranchLabel */ ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } - else if (flags & 256) { + else if (flags & 256 /* ArrayMutation */) { type = getTypeAtFlowArrayMutation(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flags & 2) { + else if (flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { + if (container && container !== flowContainer && reference.kind !== 180 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } + // At the top of the flow we have the initial type. type = initialType; } else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. type = convertAutoToAny(declaredType); } - if (flags & 1024) { + if (flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. sharedFlowNodes[sharedFlowCount] = flow; sharedFlowTypes[sharedFlowCount] = type; sharedFlowCount++; @@ -30880,8 +37501,10 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - if (ts.getAssignmentTargetKind(node) === 2) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { var flowType = getTypeAtFlowNode(flow.antecedent); return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); } @@ -30892,28 +37515,33 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 65536) { + if (declaredType.flags & 131072 /* Union */) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. if (containsMatchingReference(reference, node)) { return declaredType; } + // Assignment doesn't affect reference return undefined; } function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 181 ? + var expr = node.kind === 182 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 181) { + if (node.kind === 182 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -30921,7 +37549,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84)) { + if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -30935,17 +37563,24 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 8192) { + if (type.flags & 16384 /* Never */) { return flowType; } - var assumeTrue = (flow.flags & 32) !== 0; + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; var nonEvolvingType = finalizeEvolvingArrayType(type); var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); if (narrowedType === nonEvolvingType) { return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 16384 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -30966,15 +37601,25 @@ var ts; var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - if (antecedent.flags & 2048 && antecedent.lock.locked) { + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. continue; } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. if (type === declaredType && declaredType === initialType) { return type; } ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -30985,10 +37630,13 @@ var ts; return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. var id = getFlowNodeId(flow); var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); if (!key) { key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations if (!key) { return declaredType; } @@ -30997,11 +37645,21 @@ var ts; if (cached) { return cached; } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); } } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. var antecedentTypes = []; var subtypeReduction = false; var firstAntecedentType; @@ -31017,28 +37675,39 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. var cached_1 = cache.get(key); if (cached_1) { return cached_1; } ts.pushIfUnique(antecedentTypes, type); + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. if (type === declaredType) { break; } } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); + return createFlowType(result, /*incomplete*/ true); } cache.set(key, result); return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 179 && - computedType.flags & 65536 && + return expr.kind === 180 /* PropertyAccessExpression */ && + computedType.flags & 131072 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -31050,10 +37719,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); } if (isMatchingReferenceDiscriminant(expr, declaredType)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); } if (containsMatchingReferenceDiscriminant(reference, expr)) { return declaredType; @@ -31062,19 +37731,19 @@ var ts; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { - case 58: + case 58 /* EqualsToken */: return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32: - case 33: - case 34: - case 35: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 && right_1.kind === 9) { + if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 189 && left_1.kind === 9) { + if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -31093,39 +37762,39 @@ var ts; return declaredType; } break; - case 93: + case 93 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); - case 26: + case 26 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } return type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { + if (type.flags & 1 /* Any */) { return type; } - if (operator === 33 || operator === 35) { + if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144) { + if (valueType.flags & 12288 /* Nullable */) { if (!strictNullChecks) { return type; } - var doubleEquals = operator === 32 || operator === 33; + var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 95 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + value.kind === 95 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16810497) { + if (type.flags & 33620481 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 16384 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -31134,23 +37803,29 @@ var ts; return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the + // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (operator === 33 || operator === 35) { + if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 65536)) { + if (assumeTrue && !(type.flags & 131072 /* Union */)) { + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. var targetType = typeofTypesByName.get(literal.text); if (targetType) { if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 540672) { + if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -31159,11 +37834,12 @@ var ts; } } var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; @@ -31171,22 +37847,25 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : + var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 16384 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the + // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, left)) { return declaredType; } return type; } + // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -31194,28 +37873,31 @@ var ts; var targetType; var prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { + // Target type is type of the prototype property var prototypePropertyType = getTypeOfSymbol(prototypeProperty); if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { return type; } if (!targetType) { + // Target type is type of construct signature var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2) { + if (ts.getObjectFlags(rightType) & 2 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); + else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { + constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } return type; } @@ -31223,12 +37905,19 @@ var ts; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 65536) { + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 131072 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192)) { + if (!(assignableType.flags & 16384 /* Never */)) { return assignableType; } } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : isTypeAssignableTo(candidate, type) ? candidate : @@ -31243,6 +37932,7 @@ var ts; if (!predicate) { return 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; } @@ -31259,7 +37949,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { + if (invokedExpression.kind === 181 /* ElementAccessExpression */ || invokedExpression.kind === 180 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -31272,21 +37962,23 @@ var ts; } 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) { switch (expr.kind) { - case 71: - case 99: - case 97: - case 179: + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 180 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181: + case 182 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185: + case 186 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 194: + case 195 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192: - if (expr.operator === 51) { + case 193 /* PrefixUnaryExpression */: + if (expr.operator === 51 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; @@ -31296,32 +37988,42 @@ var ts; } function getTypeOfSymbolAtLocation(symbol, location) { symbol = symbol.exportSymbol || symbol; - if (location.kind === 71) { + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 71 /* Identifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. return getTypeOfSymbol(symbol); } function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 || - node.kind === 265 || - node.kind === 149; + node.kind === 235 /* ModuleBlock */ || + node.kind === 269 /* SourceFile */ || + node.kind === 150 /* PropertyDeclaration */; }); } + // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; + if (!(links.flags & 4194304 /* AssignmentsMarked */)) { + links.flags |= 4194304 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -31329,13 +38031,13 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 147 /* Parameter */) { symbol.isAssigned = true; } } @@ -31345,26 +38047,31 @@ var ts; } } function isConstVariable(symbol) { - return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 && + declaration.kind === 147 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 2048 && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072) : declaredType; + getFalsyFlags(declaredType) & 4096 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } function isApparentTypePosition(node) { var parent = node.parent; - return parent.kind === 179 || - parent.kind === 181 && parent.expression === node || - parent.kind === 180 && parent.expression === node; + return parent.kind === 180 /* PropertyAccessExpression */ || + parent.kind === 182 /* CallExpression */ && parent.expression === node || + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; } function typeHasNullableConstraint(type) { - return type.flags & 540672 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144); + return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } function getDeclaredOrApparentType(symbol, node) { + // When a node is the left hand expression of a property access, element access, or call expression, + // and the type of the node includes type variables with constraints that are nullable, we fetch the + // apparent type of the node *before* performing control flow analysis such that narrowings apply to + // the constraint type. var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); @@ -31376,48 +38083,62 @@ var ts; if (symbol === unknownSymbol) { return unknownType; } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (languageVersion < 2) { - if (container.kind === 187) { + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 188 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } - else if (ts.hasModifier(container, 256)) { + else if (ts.hasModifier(container, 256 /* Async */)) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); } } - getNodeLinks(container).flags |= 8192; + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; return getTypeOfSymbol(symbol); } - if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32) { - if (declaration.kind === 229 + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 230 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); } } - else if (declaration.kind === 199) { - var container = ts.getThisContainer(node, false); + else if (declaration.kind === 200 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); while (container !== undefined) { if (container.parent === declaration) { - if (container.kind === 149 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + if (container.kind === 150 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } break; } - container = ts.getThisContainer(container, false); + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); } } } @@ -31428,7 +38149,7 @@ var ts; var type = getDeclaredOrApparentType(localOrExportSymbol, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3)) { + if (!(localOrExportSymbol.flags & 3 /* Variable */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return unknownType; } @@ -31437,9 +38158,11 @@ var ts; return unknownType; } } - var isAlias = localOrExportSymbol.flags & 2097152; - if (localOrExportSymbol.flags & 3) { - if (assignmentKind === 1) { + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { return type; } } @@ -31452,23 +38175,37 @@ var ts; if (!declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 146; + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 147 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || - flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 187 /* FunctionExpression */ || + flowContainer.kind === 188 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || - node.parent.kind === 203 || - ts.isInAmbientContext(declaration); + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || + node.parent.kind === 204 /* NonNullExpression */ || + declaration.kind === 227 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 2097152 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048); + getOptionalType(type); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + // A variable is considered uninitialized when it is possible to analyze the entire control flow graph + // from declaration to use, and when the variable's declared type doesn't include undefined but the + // control flow based type does include undefined. if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { @@ -31478,8 +38215,9 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; @@ -31488,17 +38226,21 @@ var ts; return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 || - (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 260) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 264 /* CatchClause */) { return; } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); var usedInFunction = isInsideFunction(node.parent, container); var current = container; var containedInIterationStatement = false; while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, false)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { containedInIterationStatement = true; break; } @@ -31506,45 +38248,53 @@ var ts; } if (containedInIterationStatement) { if (usedInFunction) { - getNodeLinks(current).flags |= 65536; + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; } - if (container.kind === 214 && - ts.getAncestor(symbol.valueDeclaration, 227).parent === container && + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 215 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 228 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; + getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; } } function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes var current = node; - while (current.parent.kind === 185) { + while (current.parent.kind === 186 /* ParenthesizedExpression */) { current = current.parent; } + // check if node is used as LHS in some assignment expression var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 192 || current.parent.kind === 193)) { + else if ((current.parent.kind === 193 /* PrefixUnaryExpression */ || current.parent.kind === 194 /* PostfixUnaryExpression */)) { var expr = current.parent; - isAssigned = expr.operator === 43 || expr.operator === 44; + isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; } if (!isAssigned) { return false; } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); } function captureLexicalThis(node, container) { - getNodeLinks(node).flags |= 2; - if (container.kind === 149 || container.kind === 152) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 150 /* PropertyDeclaration */ || container.kind === 153 /* Constructor */) { var classNode = container.parent; - getNodeLinks(classNode).flags |= 4; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } else { - getNodeLinks(container).flags |= 4; + getNodeLinks(container).flags |= 4 /* CaptureThis */; } } function findFirstSuperCall(n) { @@ -31556,14 +38306,26 @@ var ts; } return ts.forEachChild(n, findFirstSuperCall); } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ function getSuperCallInConstructor(constructor) { var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result if (links.hasSuperCall === undefined) { links.superCall = findFirstSuperCall(constructor.body); links.hasSuperCall = links.superCall ? true : false; } return links.superCall; } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ function classDeclarationExtendsNull(classDecl) { var classSymbol = getSymbolOfNode(classDecl); var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); @@ -31573,42 +38335,60 @@ var ts; function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing error(node, diagnosticMessage); } } } function checkThisExpression(node) { - var container = ts.getThisContainer(node, true); + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 152) { + if (container.kind === 153 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 187) { - container = ts.getThisContainer(container, false); - needToCaptureLexicalThis = (languageVersion < 2); + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 188 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code + needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 233: + case 234 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 232: + case 233 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 152: + case 153 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 149: - case 148: - if (ts.hasModifier(container, 32)) { + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 144: + case 145 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -31617,15 +38397,19 @@ var ts; } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 186 && - container.parent.kind === 194 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === 187 /* FunctionExpression */ && + container.parent.kind === 195 /* BinaryExpression */ && + ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.prototype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x var classSymbol = checkExpression(className).symbol; - if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { return getInferredClassType(classSymbol); } } @@ -31636,7 +38420,7 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } if (ts.isInJavaScriptFile(node)) { @@ -31646,13 +38430,14 @@ var ts; } } if (noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 273) { + if (jsdocType && jsdocType.kind === 277 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -31662,29 +38447,35 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 147 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; - var container = ts.getSuperContainer(node, true); + var isCallExpression = node.parent.kind === 182 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 187) { - container = ts.getSuperContainer(container, true); - needToCaptureLexicalThis = languageVersion < 2; + while (container && container.kind === 188 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); - if (current && current.kind === 144) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 145 /* ComputedPropertyName */; }); + if (current && current.kind === 145 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 179 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -31692,50 +38483,113 @@ var ts; } return unknownType; } - if (!isCallExpression && container.kind === 152) { + if (!isCallExpression && container.kind === 153 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - if (ts.hasModifier(container, 32) || isCallExpression) { - nodeCheckFlag = 512; + if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; } else { - nodeCheckFlag = 256; + nodeCheckFlag = 256 /* SuperInstance */; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.hasModifier(container, 256)) { + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === 152 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096; + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } else { - getNodeLinks(container).flags |= 2048; + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; } } if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 178) { - if (languageVersion < 2) { + if (container.parent.kind === 179 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; } else { + // for object literal assume that type of 'super' is 'any' return anyType; } } + // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return unknownType; + } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } return unknownType; } - if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 153 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } - return nodeCheckFlag === 512 + return nodeCheckFlag === 512 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container) { @@ -31743,24 +38597,31 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 152; + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 153 /* Constructor */; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.hasModifier(container, 32)) { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154; + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 179 /* ObjectLiteralExpression */) { + if (ts.hasModifier(container, 32 /* Static */)) { + return container.kind === 152 /* MethodDeclaration */ || + container.kind === 151 /* MethodSignature */ || + container.kind === 154 /* GetAccessor */ || + container.kind === 155 /* SetAccessor */; } else { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154 || - container.kind === 149 || - container.kind === 148 || - container.kind === 152; + return container.kind === 152 /* MethodDeclaration */ || + container.kind === 151 /* MethodSignature */ || + container.kind === 154 /* GetAccessor */ || + container.kind === 155 /* SetAccessor */ || + container.kind === 150 /* PropertyDeclaration */ || + container.kind === 149 /* PropertySignature */ || + container.kind === 153 /* Constructor */; } } } @@ -31768,22 +38629,22 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 151 || - func.kind === 153 || - func.kind === 154) && func.parent.kind === 178 ? func.parent : - func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : + return (func.kind === 152 /* MethodDeclaration */ || + func.kind === 154 /* GetAccessor */ || + func.kind === 155 /* SetAccessor */) && func.parent.kind === 179 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 187 /* FunctionExpression */ && func.parent.kind === 265 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 262144 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 187) { + if (func.kind === 188 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -31799,6 +38660,9 @@ var ts; if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. var contextualType = getApparentTypeOfContextualType(containingLiteral); var literal = containingLiteral; var type = contextualType; @@ -31807,21 +38671,27 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 261) { + if (literal.parent.kind !== 265 /* PropertyAssignment */) { break; } literal = literal.parent.parent; type = getApparentTypeOfContextualType(literal); } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } - var parent_12 = func.parent; - if (parent_12.kind === 194 && parent_12.operatorToken.kind === 58) { - var target = parent_12.left; - if (target.kind === 179 || target.kind === 180) { + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + var parent = func.parent; + if (parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + var target = parent.left; + if (target.kind === 180 /* PropertyAccessExpression */ || target.kind === 181 /* ElementAccessExpression */) { var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { - var sourceFile = ts.getSourceFileOfNode(parent_12); + var sourceFile = ts.getSourceFileOfNode(parent); if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { return undefined; } @@ -31832,6 +38702,7 @@ var ts; } return undefined; } + // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -31859,9 +38730,14 @@ var ts; var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. + indexOfParameter -= 1; + } if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } + // If last parameter is contextually rest parameter get its type if (funcHasRestParameters && indexOfParameter === (func.parameters.length - 1) && isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { @@ -31871,29 +38747,37 @@ var ts; } return undefined; } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer) { + if (node === declaration.initializer || node.kind === 58 /* EqualsToken */) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 146) { + if (declaration.kind === 147 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_22 = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176) { + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 177 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name_22)) { - var text = ts.getTextOfPropertyName(name_22); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); } @@ -31907,13 +38791,13 @@ var ts; var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { + if (functionFlags & 1 /* Generator */) { return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; + return functionFlags & 2 /* Async */ + ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function + : contextualReturnType; // Regular function } return undefined; } @@ -31925,87 +38809,122 @@ var ts; if (contextualReturnType) { return node.asteriskToken ? contextualReturnType - : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); } } return undefined; } function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 && node.parent.initializer === node) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { return true; } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } node = node.parent; } return false; } function getContextualReturnType(functionDecl) { - if (functionDecl.kind === 152 || + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + if (functionDecl.kind === 153 /* Constructor */ || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } 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) { var args = getEffectiveCallArguments(callTarget); var argIndex = ts.indexOf(args, arg); if (argIndex >= 0) { + // 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); return getTypeAtPosition(signature, argIndex); } return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183) { + if (template.parent.kind === 184 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (ts.isAssignmentOperator(operator)) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 58 /* EqualsToken */: + return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + case 54 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand. + var type = getContextualType(binaryExpression); + return !type && node === right ? getTypeOfExpression(left, /*cache*/ true) : type; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + // For completions after `x === ` + return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; + default: return undefined; - } - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } } - else if (operator === 54) { - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left, true); - } - return type; - } - else if (operator === 53 || operator === 26) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for special property assignments to avoid circularity. + function isContextSensitiveAssignment(binaryExpression) { + var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + return !binaryExpression.left.symbol; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + return false; + default: + ts.Debug.assertNever(kind); } - return undefined; } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } + // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 131072 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } return getContextualTypeForObjectLiteralElement(node); @@ -32014,47 +38933,70 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { - if (!ts.hasDynamicName(element)) { - var symbolName = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (!hasNonBindableDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName_1 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); if (propertyType) { return propertyType; } } - return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || - getIndexTypeOfContextualType(type, 0); + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. function getContextualTypeForElementExpression(arrayContextualType, index) { return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) - || getIndexTypeOfContextualType(arrayContextualType, 1) - || getIteratedTypeOrElementType(arrayContextualType, undefined, false, false, false)); + || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node) { var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } function getContextualTypeForJsxExpression(node) { + // JSX expression can appear in two position : JSX Element's children or JSX attribute var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? node.parent.parent : - node.parent.openingElement.attributes; + ts.isJsxElement(node.parent) ? + node.parent.openingElement.attributes : + undefined; // node.parent is JsxFragment with no attributes + if (!jsxAttributes) { + return undefined; // don't check children of a fragment + } + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName var attributesType = getContextualType(jsxAttributes); if (!attributesType || isTypeAny(attributesType)) { return undefined; } if (ts.isJsxAttribute(node.parent)) { + // JSX expression is in JSX attribute return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } - else if (node.parent.kind === 249) { + else if (node.parent.kind === 250 /* JsxElement */) { + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; } else { + // JSX expression is in JSX spread attribute return attributesType; } } function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName var attributesType = getContextualType(attribute.parent); if (ts.isJsxAttribute(attribute)) { if (!attributesType || isTypeAny(attributesType)) { @@ -32066,12 +39008,61 @@ var ts; return attributesType; } } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); - } + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (!(contextualType && contextualType.flags & 131072 /* Union */ && ts.isObjectLiteralExpression(node))) { + return contextualType; + } + // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` + var match; + propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (!prop.symbol) + continue; + if (prop.kind !== 265 /* PropertyAssignment */) + continue; + if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = getTypeOfNode(prop.initializer); + for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); + if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + match = undefined; + break propLoop; + } + match = type; + } + } + } + } + return match || contextualType; + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ function getContextualType(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (node.contextualType) { @@ -32079,52 +39070,63 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 176: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 177 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 187: - case 219: + case 188 /* ArrowFunction */: + case 220 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 197: + case 198 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 181: - case 182: + case 183 /* NewExpression */: + if (node.kind === 94 /* NewKeyword */) { + return getContextualType(parent); + } + // falls through + case 182 /* CallExpression */: return getContextualTypeForArgument(parent, node); - case 184: - case 202: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 194: + case 195 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 261: - case 262: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 263: + case 267 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 177: { + case 178 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 195: + case 196 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 205: - ts.Debug.assert(parent.parent.kind === 196); + case 206 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 197 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: { + case 186 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 256: + case 260 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 253: - case 255: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 251: - case 250: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: return getAttributesTypeFromJsxOpeningLikeElement(parent); + case 261 /* CaseClause */: { + if (node.kind === 73 /* CaseKeyword */) { + var switchStatement = parent.parent.parent; + return getTypeOfExpression(switchStatement.expression); + } + } } return undefined; } @@ -32132,8 +39134,10 @@ var ts; node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); return node ? node.contextualMapper : identityMapper; } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); + var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -32141,6 +39145,7 @@ var ts; } } } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ function isAritySmaller(signature, target) { var targetParameterCount = 0; for (; targetParameterCount < target.parameters.length; targetParameterCount++) { @@ -32156,9 +39161,10 @@ var ts; return sourceLength < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 || node.kind === 187; + return node.kind === 187 /* FunctionExpression */ || node.kind === 188 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) ? getContextualSignature(node) : undefined; @@ -32168,13 +39174,18 @@ var ts; getContextualTypeForObjectLiteralMethod(node) : getApparentTypeOfContextualType(node); } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 65536)) { + if (!(type.flags & 131072 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; @@ -32184,34 +39195,39 @@ var ts; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { + // This signature will contribute to contextual union signature signatureList = [signature]; } - else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use return undefined; } else { + // Use this signature for contextual union signature signatureList.push(signature); } } } + // Result is union of signatures collected (return type is union of return types of this signature set) var result; if (signatureList) { result = cloneSignature(signatureList[0]); + // Clear resolved return type we possibly got from cloneSignature result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; } function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 1536); + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); } var arrayOrIterableType = checkExpression(node.expression, checkMode); - return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 176 && !!node.initializer) || - (node.kind === 194 && node.operatorToken.kind === 58); + return (node.kind === 177 /* BindingElement */ && !!node.initializer) || + (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; @@ -32221,10 +39237,22 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elements.length; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 198) { + if (inDestructuringPattern && e.kind === 199 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. var restArrayType = checkExpression(e.expression, checkMode); - var restElementType = getIndexTypeOfType(restArrayType, 1) || - getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { elementTypes.push(restElementType); } @@ -32234,26 +39262,29 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 198; + hasSpreadElement = hasSpreadElement || e.kind === 199 /* SpreadElement */; } if (!hasSpreadElement) { + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } - var contextualType_1 = getApparentTypeOfContextualType(node); - if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { - var pattern = contextualType_1.pattern; - if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (pattern && (pattern.kind === 176 /* ArrayBindingPattern */ || pattern.kind === 178 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType_1.typeArguments[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 200) { + if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -32266,42 +39297,67 @@ var ts; } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); + getUnionType(elementTypes, /*subtypeReduction*/ true) : + strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 144: + case 145 /* ComputedPropertyName */: return isNumericComputedName(name); - case 71: + case 71 /* Identifier */: return isNumericLiteralName(name.escapedText); - case 8: - case 9: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: return isNumericLiteralName(name.text); default: return false; } } function isNumericComputedName(name) { - return isTypeAssignableToKind(checkComputedPropertyName(name), 84); + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAssignableToKind(checkComputedPropertyName(name), 84 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; } function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. return (+name).toString() === name; } function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (links.resolvedType.flags & 6144 || - !isTypeAssignableToKind(links.resolvedType, 262178 | 84 | 512) && + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (links.resolvedType.flags & 12288 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); } } return links.resolvedType; @@ -32309,15 +39365,16 @@ var ts; function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; - return createIndexInfo(unionType, false); + var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, checkMode) { var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; @@ -32325,7 +39382,7 @@ var ts; var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); + (contextualType.pattern.kind === 175 /* ObjectBindingPattern */ || contextualType.pattern.kind === 179 /* ObjectLiteralExpression */); var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); var typeFlags = 0; var patternWithComputedProperties = false; @@ -32335,30 +39392,30 @@ var ts; var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; - var member = memberDecl.symbol; + var member = getSymbolOfNode(memberDecl); var literalName = void 0; - if (memberDecl.kind === 261 || - memberDecl.kind === 262 || + if (memberDecl.kind === 265 /* PropertyAssignment */ || + memberDecl.kind === 266 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var jsdocType = void 0; if (isInJSFile) { jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); } var type = void 0; - if (memberDecl.kind === 261) { - if (memberDecl.name.kind === 144) { + if (memberDecl.kind === 265 /* PropertyAssignment */) { + if (memberDecl.name.kind === 145 /* ComputedPropertyName */) { var t = checkComputedPropertyName(memberDecl.name); - if (t.flags & 224) { + if (t.flags & 224 /* Literal */) { literalName = ts.escapeLeadingUnderscores("" + t.value); } } type = checkPropertyAssignment(memberDecl, checkMode); } - else if (memberDecl.kind === 151) { + else if (memberDecl.kind === 152 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, checkMode); } else { - ts.Debug.assert(memberDecl.kind === 262); + ts.Debug.assert(memberDecl.kind === 266 /* ShorthandPropertyAssignment */); type = checkExpressionForMutableLocation(memberDecl.name, checkMode); } if (jsdocType) { @@ -32366,23 +39423,30 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, literalName || member.escapedName); + var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; + var prop = nameType && isTypeUsableAsLateBoundName(nameType) + ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) + : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 265 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 266 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { - prop.flags |= 16777216; + prop.flags |= 16777216 /* Optional */; } if (!literalName && ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.escapedName); if (impliedProp) { - prop.flags |= impliedProp.flags & 16777216; + prop.flags |= impliedProp.flags & 16777216 /* Optional */; } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -32395,12 +39459,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 263) { - if (languageVersion < 2) { - checkExternalEmitHelpers(memberDecl, 2); + else if (memberDecl.kind === 267 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -32412,15 +39476,20 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } else { - ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 154 /* GetAccessor */ || memberDecl.kind === 155 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (!literalName && ts.hasDynamicName(memberDecl)) { + if (!literalName && hasNonBindableDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -32433,11 +39502,13 @@ var ts; } propertiesArray.push(member); } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. if (contextualTypeHasPattern) { for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; - if (!propertiesTable.get(prop.escapedName)) { - if (!(prop.flags & 16777216)) { + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + if (!(prop.flags & 16777216 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.escapedName, prop); @@ -32447,48 +39518,44 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); - result.objectFlags |= 128; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 2097152 /* FreshLiteral */; + result.flags |= 8388608 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 29360128 /* PropagatingFlags */); + result.objectFlags |= 128 /* ObjectLiteral */; if (patternWithComputedProperties) { - result.objectFlags |= 512; + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 6144)) { - propagatedFlags |= (result.flags & 14680064); + if (!(result.flags & 12288 /* Nullable */)) { + propagatedFlags |= (result.flags & 29360128 /* PropagatingFlags */); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 | 16777216) || - getFalsyFlags(type) & 7392 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 32768 && !isGenericMappedType(type) || - type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (1 /* Any */ | 33554432 /* NonPrimitive */) || + getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 65536 /* Object */ && !isGenericMappedType(type) || + type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); + checkJsxOpeningLikeElementOrOpeningFragment(node); return getJsxGlobalElementType() || anyType; } function checkJsxElement(node) { - checkJsxOpeningLikeElement(node.openingElement); + // Check attributes + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); } @@ -32497,20 +39564,44 @@ var ts; } return getJsxGlobalElementType() || anyType; } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { + error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + } + return getJsxGlobalElementType() || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return !ts.stringContains(name, "-"); } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ function isJsxIntrinsicIdentifier(tagName) { + // TODO (yuisu): comment switch (tagName.kind) { - case 179: - case 99: + case 180 /* PropertyAccessExpression */: + case 99 /* ThisKeyword */: return false; - case 71: + case 71 /* Identifier */: return ts.isIntrinsicJsxName(tagName.escapedText); default: ts.Debug.fail(); } } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); @@ -32526,8 +39617,8 @@ var ts; if (ts.isJsxAttribute(attributeDecl)) { var exprType = attributeDecl.initializer ? checkExpression(attributeDecl.initializer, checkMode) : - trueType; - var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); + trueType; // is sugar for + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; if (member.valueDeclaration) { @@ -32542,9 +39633,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 255); + ts.Debug.assert(attributeDecl.kind === 259 /* JsxSpreadAttribute */); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -32553,7 +39644,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -32563,7 +39654,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); } attributesArray = getPropertiesOfType(spread); } @@ -32575,28 +39666,23 @@ var ts; } } } - var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; + // Handle children attribute + var parent = openingLikeElement.parent.kind === 250 /* JsxElement */ ? openingLikeElement.parent : undefined; + // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { - var childrenTypes = []; - for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - if (child.kind === 10) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } + var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); + // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, false)); + createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } @@ -32606,15 +39692,42 @@ var ts; var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : typeToIntersect ? typeToIntersect : attributeType; + /** + * Create anonymous type from given attributes symbol table. + * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable + * @param attributesTable a symbol table of attributes property + */ function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 33554432 | 4194304; - result.objectFlags |= 128; + var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 67108864 /* JsxAttributes */ | 8388608 /* ContainsObjectLiteral */; + result.objectFlags |= 128 /* ObjectLiteral */; return result; } } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 10 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + return childrenTypes; + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); } function getJsxType(name) { var jsxType = jsxTypes.get(name); @@ -32623,24 +39736,33 @@ var ts; } return jsxType; } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { + // Property case if (!ts.isIdentifier(node.tagName)) throw ts.Debug.fail(); var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { - links.jsxFlags |= 1; + links.jsxFlags |= 1 /* IntrinsicNamedElement */; return links.resolvedSymbol = intrinsicProp; } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); if (indexSignatureType) { - links.jsxFlags |= 2; + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; return links.resolvedSymbol = intrinsicElementsType.symbol; } - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { @@ -32652,15 +39774,24 @@ var ts; } return links.resolvedSymbol; } + /** + * Given a JSX element that is a class element, finds the Element Instance Type. If the + * element is not a class element, or the class element type cannot be determined, returns 'undefined'. + * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). + */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536)); + ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' return anyType; } - var signatures = getSignaturesOfType(valueType, 1); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); if (signatures.length === 0) { - signatures = getSignaturesOfType(valueType, 0); + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); if (signatures.length === 0) { + // We found no signatures at all, which is an error error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return unknownType; } @@ -32670,21 +39801,33 @@ var ts; var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0, isJavascript); + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { instantiatedSignatures.push(signature); } } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } + /** + * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); + // JSX + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type if (propertiesOfJsxElementAttribPropInterface.length === 0) { return ""; } @@ -32692,11 +39835,17 @@ var ts; return propertiesOfJsxElementAttribPropInterface[0].escapedName; } else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } } return undefined; } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { if (!_hasComputedJsxElementPropertiesName) { _hasComputedJsxElementPropertiesName = true; @@ -32715,7 +39864,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 131072) { + if (propsType.flags & 262144 /* Intersection */) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -32725,17 +39874,29 @@ var ts; } return getApparentType(propsType); } + /** + * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. + * Return only attributes type of successfully resolved call signature. + * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) + * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. + * @param openingLikeElement a JSX opening-like element to find attributes type + * @param elementType a type of the opening-like element. This elementType can't be an union type + * @param elemInstanceType an element instance type (the result of newing or invoking this tag) + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global + */ function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); + // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { + // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { paramType = intersectTypes(intrinsicAttributes, paramType); @@ -32747,11 +39908,23 @@ var ts; } return undefined; } + /** + * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. + * Return all attributes type of resolved call signature including candidate signatures. + * This function assumes that the caller handled other possible element type of the JSX element. + * This function is a behavior used by language service when looking up completion in JSX element. + * @param openingLikeElement a JSX opening-like element to find attributes type + * @param elementType a type of the opening-like element. This elementType can't be an union type + * @param elemInstanceType an element instance type (the result of newing or invoking this tag) + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global + */ function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { + // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); var result = void 0; @@ -32778,9 +39951,11 @@ var ts; allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); } } + // If we can't find any matching, just return everything. if (!result) { result = allMatchingAttributesType; } + // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { result = intersectTypes(intrinsicAttributes, result); @@ -32790,40 +39965,67 @@ var ts; } return undefined; } + /** + * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. + * For instance: + * declare function Foo(attr: { p1: string}): JSX.Element; + * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" + * + * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. + * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component + * + * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement + * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) + * @return attributes type if able to resolve the type of node + * anyType if there is no type ElementAttributesProperty or there is an error + * emptyObjectType if there is no "prop" in the element instance type + */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } - if (elementType.flags & 65536) { + if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), true); + }), /*subtypeReduction*/ true); } - if (elementType.flags & 2) { + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (elementType.flags & 2 /* String */) { return anyType; } - else if (elementType.flags & 32) { + else if (elementType.flags & 32 /* StringLiteral */) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + var stringLiteralTypeName = elementType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream return anyType; } + // Get the element instance type (the result of newing or invoking this tag) var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. + // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); if (statelessAttributesType) { return statelessAttributesType; } + // Issue an error if this return type isn't assignable to JSX.ElementClass if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } @@ -32832,20 +40034,25 @@ var ts; } var propsName = getJsxElementPropertiesName(); if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' return anyType; } else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead return elemInstanceType; } else { var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); if (!attributesType) { + // There is no property named 'props' on this instance type return emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown return attributesType; } else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements var apparentAttributesType = attributesType; var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); if (intrinsicClassAttribs !== unknownType) { @@ -32867,16 +40074,21 @@ var ts; } } } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); var links = getNodeLinks(node); if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); - if (links.jsxFlags & 1) { + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); } - else if (links.jsxFlags & 2) { - return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; } else { return links.resolvedJsxElementAttributesType = unknownType; @@ -32884,31 +40096,54 @@ var ts; } return links.resolvedJsxElementAttributesType; } + /** + * Get attributes type of the given custom opening-like JSX element. + * This function is intended to be called from a caller that handles intrinsic JSX element already. + * @param node a custom JSX opening-like element + * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component + */ function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { var links = getNodeLinks(node); var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; if (!links[linkLocation]) { var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); } return links[linkLocation]; } + /** + * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. + * This function is called by language service (see: completions-tryGetGlobalSymbols). + * @param node a JSX opening-like element to get attributes type for + */ function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, true); + // Because in language service, the given JSX opening-like element may be incomplete and therefore, + // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); } } + /** + * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. + * @param node a JSXOpeningLikeElement node + * @return an attributes type of the given node + */ function getAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, false); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); } } + /** + * Given a JSX attribute, returns the symbol for the corresponds property + * of the element attributes type. Will return unknownSymbol for attributes + * that have no matching element attributes type property. + */ function getJsxAttributePropertySymbol(attrib) { var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); var prop = getPropertyOfType(attributesType, attrib.name.escapedText); @@ -32935,12 +40170,16 @@ var ts; } return deferredJsxStatelessElementType; } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ function getJsxIntrinsicTagNames() { var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; } function checkJsxPreconditions(errorNode) { - if ((compilerOptions.jsx || 0) === 0) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); } if (getJsxGlobalElementType() === undefined) { @@ -32949,31 +40188,59 @@ var ts; } } } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } checkJsxPreconditions(node); - var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace, true); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted reactSym.isReferenced = true; - if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { markAliasSymbolAsReferenced(reactSym); } } - checkJsxAttributesAssignableToTagNameAttributes(node); - } + if (isNodeOpeningLikeElement) { + checkJsxAttributesAssignableToTagNameAttributes(node); + } + else { + checkJsxChildren(node.parent); + } + } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. In a union or intersection type, + * a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 32768) { + if (targetType.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || getPropertyOfObjectType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. return true; } } - else if (targetType.flags & 196608) { + else if (targetType.flags & 393216 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -32983,23 +40250,44 @@ var ts; } return false; } + /** + * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. + * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" + * Check assignablity between given attributes property, "source attributes", and the "target attributes" + * @param openingLikeElement an opening-like JSX element to check its JSXAttributes + */ function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + // The function involves following steps: + // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. + // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) + // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. + // 3. Check if the two are assignable to each other + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, false); + getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); + // sourceAttributesType is a type of an attributes properties. + // i.e
+ // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); }); + // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. + // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); } else { + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; - if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); + // We break here so that errors won't be cascading break; } } @@ -33010,7 +40298,7 @@ var ts; if (node.expression) { var type = checkExpression(node.expression, checkMode); if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); } return type; } @@ -33018,86 +40306,128 @@ var ts; return unknownType; } } + // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized + // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149; + return s.valueDeclaration ? s.valueDeclaration.kind : 150 /* PropertyDeclaration */; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); - } + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param left The left hand side of the property access (e.g.: the super in `super.foo`). + * @param type The type of left. + * @param prop The symbol for the right hand side of the property access. + */ function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 || node.kind === 226 ? + var errorNode = node.kind === 180 /* PropertyAccessExpression */ || node.kind === 227 /* VariableDeclaration */ ? node.name : node.right; - if (ts.getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97) { - if (languageVersion < 2) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 && propKind !== 150; - }); - if (hasNonMethodDeclaration) { + if (left.kind === 97 /* SuperKeyword */) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } } - if (flags & 128) { + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } - if (!(flags & 24)) { + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { return true; } - if (flags & 8) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; } - if (left.kind === 97) { + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (left.kind === 97 /* SuperKeyword */) { return true; } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; }); + // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); return false; } - if (flags & 32) { + // No further restrictions for static properties + if (flags & 32 /* Static */) { return true; } - if (type.flags & 16384 && type.isThisType) { - type = getConstraintOfTypeParameter(type); + if (type.flags & 32768 /* TypeParameter */) { + // get the original type -- represented as the type constraint of the 'this' type + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } - if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { + if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; } + function symbolHasNonMethodDeclaration(symbol) { + return forEachProperty(symbol, function (prop) { + var propKind = getDeclarationKindFromSymbol(prop); + return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; + }); + } function checkNonNullExpression(node) { return checkNonNullType(checkExpression(node), node); } function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 2048 ? kind & 4096 ? + error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); var t = getNonNullableType(type); - return t.flags & (6144 | 8192) ? unknownType : t; + return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } return type; } @@ -33108,46 +40438,76 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + var propType; + var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; + var leftType = checkNonNullExpression(left); + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { return apparentType; } + var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { - var indexInfo = getIndexInfoOfType(apparentType, 0); - if (indexInfo && indexInfo.type) { - if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { - error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); + if (!(indexInfo && indexInfo.type)) { + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 32768 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } - return indexInfo.type; + return unknownType; } - if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); } - return unknownType; + propType = indexInfo.type; } - checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); - return unknownType; + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module + leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && + !(isNonLocalAlias(leftSymbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { + getSymbolLinks(leftSymbol).referenced = undefined; + } + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + return unknownType; + } } + propType = getDeclaredOrApparentType(prop, node); } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 180 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 131072 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 153 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + // Return the declared type to reduce follow-on errors return propType; } - var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { @@ -33158,27 +40518,32 @@ var ts; if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); } - else if (valueDeclaration.kind === 229 && - node.parent.kind !== 159 && - !ts.isInAmbientContext(valueDeclaration) && + else if (valueDeclaration.kind === 230 /* ClassDeclaration */ && + node.parent.kind !== 160 /* TypeReference */ && + !(valueDeclaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 149: + case 150 /* PropertyDeclaration */: return true; - case 261: + case 265 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: - return ts.isPartOfExpression(node) ? false : "quit"; + return ts.isExpressionNode(node) ? false : "quit"; } }); } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ function isPropertyDeclaredInAncestorClass(prop) { var classType = getTypeOfSymbol(prop.parent); while (true) { @@ -33202,7 +40567,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 65536 && !(containingType.flags & 8190)) { + if (containingType.flags & 131072 /* Union */ && !(containingType.flags & 16382 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -33213,7 +40578,7 @@ var ts; } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -33221,77 +40586,129 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455); - return suggestion && suggestion.escapedName; + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455 /* Value */); + return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, undefined, name, false, function (symbols, name, meaning) { + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); - if (symbol) { - return symbol; - } - return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - if (result) { - return result.escapedName; - } - } + return result && ts.symbolName(result); + } + /** + * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose meaning doesn't match the `meaning` parameter. + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ function getSpellingSuggestionForName(name, symbols, meaning) { - var worstDistance = name.length * 0.4; - var maximumLengthDifference = Math.min(3, name.length * 0.34); - var bestDistance = Number.MAX_VALUE; - var bestCandidate = undefined; + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; var justCheckExactMatches = false; - if (name.length > 30) { - return undefined; - } - name = name.toLowerCase(); + var nameLowerCase = name.toLowerCase(); for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; - var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); - if (candidate.flags & meaning && - candidateName && - Math.abs(candidateName.length - name.length) < maximumLengthDifference) { - candidateName = candidateName.toLowerCase(); - if (candidateName === name) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3 || - name.length < 3 || - candidateName === "eval" || - candidateName === "intl" || - candidateName === "undefined" || - candidateName === "map" || - candidateName === "nan" || - candidateName === "set") { - continue; - } - var distance = ts.levenshtein(name, candidateName); - if (distance > worstDistance) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else if (distance < bestDistance) { - bestDistance = distance; - bestCandidate = candidate; - } + var candidateName = ts.symbolName(candidate); + if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + continue; + } + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; } } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && - (prop.flags & 106500) && - prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) + (prop.flags & 106500 /* ClassMember */) && + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { - if (ts.getCheckFlags(prop) & 1) { + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -33300,7 +40717,7 @@ var ts; } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 179 + var left = node.kind === 180 /* PropertyAccessExpression */ ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); @@ -33311,7 +40728,8 @@ var ts; if (prop) { return checkPropertyAccessibility(node, left, type, prop); } - if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + // In js files properties of unions are allowed in completion + if (ts.isInJavaScriptFile(left) && (type.flags & 131072 /* Union */)) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var elementType = _a[_i]; if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { @@ -33323,31 +40741,41 @@ var ts; } return true; } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 227) { + if (initializer.kind === 228 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } - else if (initializer.kind === 71) { + else if (initializer.kind === 71 /* Identifier */) { return getResolvedSymbol(initializer); } return undefined; } + /** + * Return true if the given type is considered to have numeric property names. + */ function hasNumericPropertyNames(type) { - return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ function isForInVariableForNumericPropertyNames(expr) { var e = ts.skipParentheses(expr); - if (e.kind === 71) { + if (e.kind === 71 /* Identifier */) { var symbol = getResolvedSymbol(e); - if (symbol.flags & 3) { + if (symbol.flags & 3 /* Variable */) { var child = expr; var node = expr.parent; while (node) { - if (node.kind === 215 && + if (node.kind === 216 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -33365,7 +40793,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 && node.parent.expression === node) { + if (node.parent.kind === 183 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -33381,7 +40809,7 @@ var ts; if (objectType === unknownType || objectType === silentNeverType) { return objectType; } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return unknownType; } @@ -33389,24 +40817,29 @@ var ts; } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === unknownType) { + // There is already an error, so no need to report one. return false; } if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 512) === 0) { + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 1536 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } return false; } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object var leftHandSide = expression.expression; var leftHandSideSymbol = getResolvedSymbol(leftHandSide); if (!leftHandSideSymbol) { return false; } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); if (!globalESSymbol) { + // Already errored when we tried to look up the symbol return false; } if (leftHandSideSymbol !== globalESSymbol) { @@ -33418,16 +40851,19 @@ var ts; return true; } function callLikeExpressionMayHaveTypeArguments(node) { + // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) return ts.isCallOrNewExpression(node); } function resolveUntypedCall(node) { if (callLikeExpressionMayHaveTypeArguments(node)) { + // Check type arguments even though we will give an error that untyped calls may not accept type arguments. + // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 183) { + if (node.kind === 184 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 147) { + else if (node.kind !== 148 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -33438,6 +40874,14 @@ var ts; resolveUntypedCall(node); return unknownSignature; } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures, result) { var lastParent; var lastSymbol; @@ -33449,24 +40893,31 @@ var ts; for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_13 = signature.declaration && signature.declaration.parent; + var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_13 === lastParent) { + if (lastParent && parent === lastParent) { index++; } else { - lastParent = parent_13; + lastParent = parent; index = cutoffIndex; } } else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_13; + lastParent = parent; } lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. cutoffIndex++; } else { @@ -33478,7 +40929,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 198) { + if (arg && arg.kind === 199 /* SpreadElement */) { return i; } } @@ -33486,44 +40937,56 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var typeArguments; - var callIsIncomplete; + var argCount; // Apparent number of arguments we will have in this call + var typeArguments; // Type arguments (undefined if none) + var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { + // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } - if (node.kind === 183) { + if (node.kind === 184 /* TaggedTemplateExpression */) { var tagExpression = node; + // Even if the call is incomplete, we'll have a missing expression as our last argument, + // so we can say the count is just the arg list length argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 196) { + if (tagExpression.template.kind === 197 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); - ts.Debug.assert(lastSpan !== undefined); + ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 13); + ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 147) { + else if (node.kind === 148 /* Decorator */) { typeArguments = undefined; - argCount = getEffectiveArgumentCount(node, undefined, signature); + argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 182); + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(callExpression.kind === 183 /* NewExpression */); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = callExpression.arguments.end === callExpression.end; typeArguments = callExpression.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); var hasRightNumberOfTypeArgs = !typeArguments || @@ -33531,17 +40994,22 @@ var ts; if (!hasRightNumberOfTypeArgs) { return false; } + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + return isRestParameterIndex(signature, spreadArgIndex) || + signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; } + // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { return false; } + // If the call is incomplete, we should skip the lower bound check. var hasEnoughArguments = argCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 32768) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -33550,33 +41018,55 @@ var ts; } return undefined; } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature, 1, compareTypes); + var context = createInferenceContext(signature, 1 /* InferUnionTypes */, compareTypes); forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. if (!inference.isFixed) { inference.inferredType = undefined; } } - if (node.kind !== 147) { + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (node.kind !== 148 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -33585,21 +41075,34 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } + // We perform two passes over the arguments. In the first pass we infer from all arguments, but use + // wildcards for all context sensitive function expressions. var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 201 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. if (argType === undefined) { + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; argType = checkExpressionWithContextualType(arg, paramType, mapper); } inferTypes(context.inferences, argType, paramType); } } + // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this + // time treating function expressions normally (which may cause previously inferred type arguments to be fixed + // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { for (var i = 0; i < argCount; i++) { + // No need to check for omitted args and template expressions, their exclusion value is always undefined if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); @@ -33609,38 +41112,51 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (!constraint) + continue; + var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return false; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - var callIsIncomplete = node.attributes.end === node.end; + // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: + // 1. callIsIncomplete + // 2. attributes property has same number of properties as the parameter object type. + // We can figure that out by resolving attributes property and check number of properties in the resolved type + // If the call has correct arity, we will then check if the argument type and parameter type is assignable + var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete if (callIsIncomplete) { return true; } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); var argProperties = getPropertiesOfType(attributesType); for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { var arg = argProperties_1[_i]; @@ -33648,14 +41164,17 @@ var ts; return false; } } - return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); + return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182) { + if (thisType && thisType !== voidType && node.kind !== 183 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // 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 errorNode = reportErrors ? (thisArgumentNode || node) : undefined; @@ -33668,11 +41187,19 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 201 /* OmittedExpression */) { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. var argType = getEffectiveArgumentType(node, i) || checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + // Use argument expression as error location when reporting errors var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { return false; @@ -33681,29 +41208,44 @@ var ts; } return true; } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ function getThisArgumentOfCall(node) { - if (node.kind === 181) { + if (node.kind === 182 /* CallExpression */) { var callee = node.expression; - if (callee.kind === 179) { + if (callee.kind === 180 /* PropertyAccessExpression */) { return callee.expression; } - else if (callee.kind === 180) { + else if (callee.kind === 181 /* ElementAccessExpression */) { return callee.expression; } } } + /** + * Returns the effective arguments for an expression that works like a function invocation. + * + * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. + * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. + */ function getEffectiveCallArguments(node) { - if (node.kind === 183) { + if (node.kind === 184 /* TaggedTemplateExpression */) { var template = node.template; var args_4 = [undefined]; - if (template.kind === 196) { + if (template.kind === 197 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 147) { + else if (node.kind === 148 /* Decorator */) { + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. return undefined; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -33713,22 +41255,45 @@ var ts; return node.arguments || ts.emptyArray; } } + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147) { + if (node.kind === 148 /* Decorator */) { switch (node.parent.kind) { - case 229: - case 199: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 149: + case 150 /* PropertyDeclaration */: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) return 2; - case 151: - case 153: - case 154: - if (languageVersion === 0) { + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If we are emitting decorators for ES3, we will only pass two arguments. + if (languageVersion === 0 /* ES3 */) { return 2; } + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 146: + case 147 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) return 3; } } @@ -33736,52 +41301,96 @@ var ts; return args.length; } } + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 229) { + // The first argument to a decorator is its `target`. + if (node.kind === 230 /* ClassDeclaration */) { + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 146) { + if (node.kind === 147 /* Parameter */) { + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. node = node.parent; - if (node.kind === 152) { + if (node.kind === 153 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 229) { + // The second argument to a decorator is its `propertyKey` + if (node.kind === 230 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 146) { + if (node.kind === 147 /* Parameter */) { node = node.parent; - if (node.kind === 152) { + if (node.kind === 153 /* Constructor */) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + } + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. var element = node; switch (element.name.kind) { - case 71: - return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); - case 8: - case 9: + case 71 /* Identifier */: + return getLiteralType(ts.idText(element.name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: return getLiteralType(element.name.text); - case 144: + case 145 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 512)) { + if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { return nameType; } else { @@ -33795,27 +41404,42 @@ var ts; ts.Debug.fail("Unsupported decorator target."); return unknownType; } + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 229) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a parameter decorator + if (node.kind === 230 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 146) { + if (node.kind === 147 /* Parameter */) { + // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 149) { + if (node.kind === 150 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 151 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } + /** + * Returns the effective argument type for the provided argument to a decorator. + */ function getEffectiveDecoratorArgumentType(node, argIndex) { if (argIndex === 0) { return getEffectiveDecoratorFirstArgumentType(node.parent); @@ -33829,27 +41453,44 @@ var ts; ts.Debug.fail("Decorators should not have a fourth synthetic argument."); return unknownType; } + /** + * Gets the effective argument type for an argument in a call expression. + */ function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 147) { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === 148 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 183) { + else if (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. return undefined; } + /** + * Gets the effective argument expression for an argument in a call expression. + */ function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 147 || - (argIndex === 0 && node.kind === 183)) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === 148 /* Decorator */ || + (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; } + /** + * Gets the error node to use when reporting errors for an effective argument. + */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147) { + if (node.kind === 148 /* Decorator */) { + // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 183) { + else if (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } else { @@ -33857,27 +41498,45 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183; - var isDecorator = node.kind === 147; + var isTaggedTemplate = node.kind === 184 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 148 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { typeArguments = node.typeArguments; - if (node.expression.kind !== 97) { + // We already perform checking on the type arguments on the class declaration itself. + if (node.expression.kind !== 97 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); + // The following applies to any value of 'excludeArgument[i]': + // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. + // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. + // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for each of those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary + // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; var excludeArgument; var excludeCount = 0; if (!isDecorator && !isSingleNonGenericCandidate) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { @@ -33888,10 +41547,43 @@ var ts; } } } + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // var candidateForArgumentError; var candidateForTypeArgumentError; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 182 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -33901,15 +41593,24 @@ var ts; if (result) { return result; } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. if (candidateForArgumentError) { if (isJsxOpeningOrSelfClosingElement) { + // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". return candidateForArgumentError; } - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -33935,30 +41636,41 @@ var ts; var paramCount = hasRestParameter_1 ? min : min < max ? min + "-" + max : min; - var argCount = args.length - (hasSpreadArgument ? 1 : 0); - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + var argCount = args.length; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1; diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); + ts.Debug.assert(candidates.length > 0); // Else would have exited above. var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -33974,7 +41686,7 @@ var ts; if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; return undefined; } @@ -33987,16 +41699,18 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -34004,9 +41718,10 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; break; } @@ -34016,7 +41731,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, true)] = false; + excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; } else { excludeArgument = undefined; @@ -34042,9 +41757,11 @@ var ts; return maxParamsIndex; } function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 97) { + if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); @@ -34059,16 +41776,29 @@ var ts; } var apparentType = getApparentType(funcType); if (apparentType === unknownType) { + // Another error has already been reported return resolveErrorCall(node); } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. if (!callSignatures.length) { if (constructSignatures.length) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); @@ -34080,23 +41810,18 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 65536) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 /* Union */ | 16384 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 1) { + if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); @@ -34106,29 +41831,50 @@ var ts; if (expressionType === silentNeverType) { return silentNeverSignature; } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. expressionType = getApparentType(expressionType); if (expressionType === unknownType) { + // Another error has already been reported return resolveErrorCall(node); } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. if (isTypeAny(expressionType)) { if (node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } - var constructSignatures = getSignaturesOfType(expressionType, 1); + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); if (constructSignatures.length) { if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasModifier(valueDecl, 128)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } return resolveCall(node, constructSignatures, candidatesOutArray); } - var callSignatures = getSignaturesOfType(expressionType, 0); + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray); if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { @@ -34147,12 +41893,14 @@ var ts; return true; } var declaration = signature.declaration; - var modifiers = ts.getSelectedModifierFlags(declaration, 24); + var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); + // Public constructor is accessible. if (!modifiers) { return true; } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); if (containingClass) { @@ -34160,17 +41908,17 @@ var ts; var baseTypes = getBaseTypes(containingType); while (baseTypes.length) { var baseType = baseTypes[0]; - if (modifiers & 16 && + if (modifiers & 16 /* Protected */ && baseType.symbol === declaration.parent.symbol) { return true; } baseTypes = getBaseTypes(baseType); } } - if (modifiers & 8) { + if (modifiers & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (modifiers & 16) { + if (modifiers & 16 /* Protected */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -34181,10 +41929,11 @@ var ts; var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === unknownType) { + // Another error has already been reported return resolveErrorCall(node); } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } @@ -34194,32 +41943,43 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 229: - case 199: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146: + case 147 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149: + case 150 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151: - case 153: - case 154: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } + /** + * Resolves a decorator as if it were a call expression. + */ function resolveDecorator(node, candidatesOutArray) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === unknownType) { return resolveErrorCall(node); } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -34230,13 +41990,44 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + }); } + /** + * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. + * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName + * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) + * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. + * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function + * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + */ + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); + } + /** + * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. + * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible + * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. + * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures + */ function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 65536) { + // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) + if (elementType.flags & 131072 /* Union */) { var types = elementType.types; var result = void 0; for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { @@ -34245,7 +42036,7 @@ var ts; } return result; } - var callSignatures = elementType && getSignaturesOfType(elementType, 0); + var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); } @@ -34253,35 +42044,56 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 181: + case 182 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 182: + case 183 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 183: + case 184 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147: + case 148 /* Decorator */: return resolveDecorator(node, candidatesOutArray); - case 251: - case 250: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + // This code-path is called by language service + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. var cached = links.resolvedSignature; if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } links.resolvedSignature = resolvingSignature; var result = resolveSignature(node, candidatesOutArray); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ function isJavaScriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { + // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; + // If the symbol of the node has members, treat it like a constructor. var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; @@ -34296,7 +42108,7 @@ var ts; if (isJavaScriptConstructor(symbol.valueDeclaration)) { return getInferredClassType(symbol); } - if (symbol.flags & 3) { + if (symbol.flags & 3 /* Variable */) { var valueType = getTypeOfSymbol(symbol); if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { return getInferredClassType(valueType.symbol); @@ -34306,31 +42118,43 @@ var ts; function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } function isInferredClassType(type) { return type.symbol - && getObjectFlags(type) & 16 + && ts.getObjectFlags(type) & 16 /* Anonymous */ && getSymbolLinks(type.symbol).inferredClassType === type; } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); - if (node.expression.kind === 97) { + if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; } - if (node.kind === 182) { + if (node.kind === 183 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 152 && - declaration.kind !== 156 && - declaration.kind !== 161 && + declaration.kind !== 153 /* Constructor */ && + declaration.kind !== 157 /* ConstructSignature */ && + declaration.kind !== 162 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 71 ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { return type; @@ -34341,27 +42165,55 @@ var ts; return anyType; } } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } - return getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 1536 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + return returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { - checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); + // Check grammar of dynamic import + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } var specifier = node.arguments[0]; var specifierType = checkExpressionCached(specifier); + // Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 2048 || specifierType.flags & 4096 || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 4096 /* Undefined */ || specifierType.flags & 8192 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal var moduleSymbol = resolveExternalModuleName(node, specifier); if (moduleSymbol) { - var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); } @@ -34372,13 +42224,13 @@ var ts; if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default")) { + if (!getPropertyOfType(type, "default" /* Default */)) { var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152, "default"); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); - memberTable.set("default", newSymbol); - var anonymousSymbol = createSymbol(2048, "__type"); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + memberTable.set("default" /* Default */, newSymbol); + var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); } @@ -34391,30 +42243,37 @@ var ts; return type; } function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, true)) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { return false; } + // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (!resolvedRequire) { + // project does not contain symbol named 'require' - assume commonjs require return true; } - if (resolvedRequire.flags & 2097152) { + // project includes symbol named 'require' - make sure that it it ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { return false; } - var targetDeclarationKind = resolvedRequire.flags & 16 - ? 228 - : resolvedRequire.flags & 3 - ? 226 - : 0; - if (targetDeclarationKind !== 0) { + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 229 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 227 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return ts.isInAmbientContext(decl); + // function/variable declaration should be ambient + return !!decl && !!(decl.flags & 2097152 /* Ambient */); } return false; } function checkTaggedTemplateExpression(node) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { @@ -34442,7 +42301,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return unknownType; } - else if (container.kind === 152) { + else if (container.kind === 153 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -34456,7 +42315,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return getNullableType(type, 2048); + return getOptionalType(type); } } return type; @@ -34487,7 +42346,7 @@ var ts; var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); } assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } @@ -34501,6 +42360,7 @@ var ts; } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.lastOrUndefined(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); @@ -34508,11 +42368,13 @@ var ts; } } } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. function assignBindingElementTypes(pattern) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { + if (element.name.kind === 71 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } else { @@ -34526,7 +42388,8 @@ var ts; if (!links.type) { links.type = contextualType; var decl = parameter.valueDeclaration; - if (decl.name.kind !== 71) { + if (decl.name.kind !== 71 /* Identifier */) { + // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType) { links.type = getTypeFromBindingPattern(decl.name); } @@ -34535,8 +42398,10 @@ var ts; } } function createPromiseType(promisedType) { - var globalPromiseType = getGlobalPromiseType(true); + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type promisedType = getAwaitedType(promisedType) || emptyObjectType; return createTypeReference(globalPromiseType, [promisedType]); } @@ -34550,7 +42415,7 @@ var ts; ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return unknownType; } - else if (!getGlobalPromiseConstructorSymbol(true)) { + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { error(func, ts.isImportCall(func) ? ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); @@ -34564,20 +42429,24 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 207) { + if (func.body.kind !== 208 /* Block */) { type = checkExpressionCached(func.body, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } } else { var types = void 0; - if (functionFlags & 1) { + if (functionFlags & 1 /* Generator */) { types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); if (!types || types.length === 0) { - var iterableIteratorAny = functionFlags & 2 - ? createAsyncIterableIteratorType(anyType) - : createIterableIteratorType(anyType); + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function if (noImplicitAny) { error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); } @@ -34587,35 +42456,57 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { - return functionFlags & 2 - ? createPromiseReturnType(func, neverType) - : neverType; + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function } if (types.length === 0) { - return functionFlags & 2 - ? createPromiseReturnType(func, voidType) - : voidType; + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function } } - type = getUnionType(types, true); - if (functionFlags & 1) { - type = functionFlags & 2 - ? createAsyncIterableIteratorType(type) - : createIterableIteratorType(type); - } + // Return a union of the return expression types. + type = getUnionType(types, /*subtypeReduction*/ true); } if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); } var widenedType = getWidenedType(type); - return (functionFlags & 3) === 2 - ? createPromiseReturnType(func, widenedType) - : widenedType; + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; @@ -34625,9 +42516,10 @@ var ts; if (expr) { var type = checkExpressionCached(expr, checkMode); if (yieldExpression.asteriskToken) { - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); + // A yield* expression effectively yields everything that its operand yields + type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); } - if (functionFlags & 2) { + if (functionFlags & 2 /* Async */) { type = checkAwaitedType(type, expr, yieldExpression.asteriskToken ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -34652,11 +42544,10 @@ var ts; return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); } function functionHasImplicitReturn(func) { - if (!(func.flags & 128)) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 222 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -34670,10 +42561,14 @@ var ts; var expr = returnStatement.expression; if (expr) { var type = checkExpressionCached(expr, checkMode); - if (functionFlags & 2) { + if (functionFlags & 2 /* Async */) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 8192) { + if (type.flags & 16384 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -34683,7 +42578,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 || func.kind === 187)) { + func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -34691,21 +42586,36 @@ var ts; } return aggregatedTypes; } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 2048 /* Void */)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 208 /* Block */ || !functionHasImplicitReturn(func)) { return; } - var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 8192) { + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 16384 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { @@ -34713,6 +42623,9 @@ var ts; } else if (compilerOptions.noImplicitReturns) { if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype if (!hasExplicitReturn) { return; } @@ -34725,26 +42638,32 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - if (checkMode === 1 && isContextSensitive(node)) { + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { checkNodeDeferred(node); return anyFunctionType; } + // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { + if (!hasGrammarError && node.kind === 187 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); - if (!(links.flags & 1024)) { + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { var contextualSignature = getContextualSignature(node); - if (!(links.flags & 1024)) { - links.flags |= 1024; + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; if (contextualSignature) { - var signature = getSignaturesOfType(type, 0)[0]; + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; if (isContextSensitive(node)) { var contextualMapper = getContextualMapper(node); - if (checkMode === 2) { + if (checkMode === 2 /* Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); } var instantiatedContextualSignature = contextualMapper === identityMapper ? @@ -34762,7 +42681,7 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 151) { + if (produceDiagnostics && node.kind !== 152 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -34770,27 +42689,38 @@ var ts; return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3) === 2 ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(returnTypeNode)); - if ((functionFlags & 1) === 0) { + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? + checkAsyncFunctionReturnType(node) : // Async function + getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + if ((functionFlags & 1 /* Generator */) === 0) { + // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!returnTypeNode) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 207) { + if (node.body.kind === 208 /* Block */) { checkSourceElement(node.body); } else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3) === 2) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -34803,28 +42733,39 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 84)) { + if (!isTypeAssignableToKind(type, 84 /* NumberLike */)) { error(operand, diagnostic); return false; } return true; } function isReadonlySymbol(symbol) { - return !!(ts.getCheckFlags(symbol) & 8 || - symbol.flags & 4 && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 || - symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || - symbol.flags & 98304 && !(symbol.flags & 65536) || - symbol.flags & 8); + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ || + symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + symbol.flags & 8 /* EnumMember */); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { - if (symbol.flags & 4 && - (expr.kind === 179 || expr.kind === 180) && - expr.expression.kind === 99) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 180 /* PropertyAccessExpression */ || expr.kind === 181 /* ElementAccessExpression */) && + expr.expression.kind === 99 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152)) { + if (!(func && func.kind === 153 /* Constructor */)) { return true; } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; @@ -34832,21 +42773,22 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 || expr.kind === 180) { + if (expr.kind === 180 /* PropertyAccessExpression */ || expr.kind === 181 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol.flags & 2097152) { + if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240; + return declaration && declaration.kind === 241 /* NamespaceImport */; } } } return false; } function checkReferenceExpression(expr, invalidReferenceMessage) { - var node = ts.skipOuterExpressions(expr, 2 | 1); - if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 71 /* Identifier */ && node.kind !== 180 /* PropertyAccessExpression */ && node.kind !== 181 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -34855,7 +42797,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 && expr.kind !== 180) { + if (expr.kind !== 180 /* PropertyAccessExpression */ && expr.kind !== 181 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -34875,8 +42817,9 @@ var ts; return undefinedWideningType; } function checkAwaitExpression(node) { + // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 16384)) { + if (!(node.flags & 16384 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -34891,32 +42834,33 @@ var ts; if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === 8) { - if (node.operator === 38) { + if (node.operand.kind === 8 /* NumericLiteral */) { + if (node.operator === 38 /* MinusToken */) { return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); } - else if (node.operator === 37) { + else if (node.operator === 37 /* PlusToken */) { return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text)); } } switch (node.operator) { - case 37: - case 38: - case 52: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512)) { + if (maybeTypeOfKind(operandType, 1536 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; - case 51: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : + case 51 /* ExclamationToken */: + var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); + return facts === 1048576 /* Truthy */ ? falseType : + facts === 2097152 /* Falsy */ ? trueType : booleanType; - case 43: - case 44: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; @@ -34930,15 +42874,18 @@ var ts; } var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } return numberType; } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. function maybeTypeOfKind(type, kind) { if (type.flags & kind) { return true; } - if (type.flags & 196608) { + if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { var t = types_18[_i]; @@ -34953,36 +42900,45 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 | 1024 | 2048 | 4096)) { + if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { return false; } - return (kind & 84 && isTypeAssignableTo(source, numberType)) || - (kind & 262178 && isTypeAssignableTo(source, stringType)) || - (kind & 136 && isTypeAssignableTo(source, booleanType)) || - (kind & 1024 && isTypeAssignableTo(source, voidType)) || - (kind & 8192 && isTypeAssignableTo(source, neverType)) || - (kind & 4096 && isTypeAssignableTo(source, nullType)) || - (kind & 2048 && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 && isTypeAssignableTo(source, esSymbolType)) || - (kind & 16777216 && isTypeAssignableTo(source, nonPrimitiveType)); + return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || + (kind & 524322 /* StringLike */ && isTypeAssignableTo(source, stringType)) || + (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || + (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || + (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || + (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || + (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || + (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || + (kind & 33554432 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 131072 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { - return (symbol.flags & 128) !== 0; + return (symbol.flags & 128 /* ConstEnum */) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190)) { + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 16382 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0).length || - getSignaturesOfType(rightType, 1).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); } return booleanType; @@ -34993,10 +42949,14 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 | 512))) { + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { + if (!isTypeAssignableToKind(rightType, 33554432 /* NonPrimitive */ | 1081344 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -35009,36 +42969,38 @@ var ts; } return sourceType; } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 || property.kind === 262) { - var name_23 = property.name; - if (name_23.kind === 144) { - checkComputedPropertyName(name_23); + if (property.kind === 265 /* PropertyAssignment */ || property.kind === 266 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 145 /* ComputedPropertyName */) { + checkComputedPropertyName(name); } - if (isComputedNonLiteralName(name_23)) { + if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name_23); + var text = ts.getTextOfPropertyName(name); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || - getIndexTypeOfType(objectLiteralType, 0); + isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || + getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 262) { + if (property.kind === 266 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { + // non-shorthand property assignments should always have initializers return checkDestructuringAssignment(property.initializer, type); } } else { - error(name_23, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_23)); + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 263) { - if (languageVersion < 5) { - checkExternalEmitHelpers(property, 4); + else if (property.kind === 267 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); } var nonRestNames = []; if (allProperties) { @@ -35054,10 +43016,13 @@ var ts; } } function checkArrayLiteralAssignment(node, sourceType, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); } - var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; var elements = node.elements; for (var i = 0; i < elements.length; i++) { checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); @@ -35067,8 +43032,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 200) { - if (element.kind !== 198) { + if (element.kind !== 201 /* OmittedExpression */) { + if (element.kind !== 199 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -35079,6 +43044,8 @@ var ts; return checkDestructuringAssignment(element, type, checkMode); } else { + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. checkExpression(element); if (isTupleType(sourceType)) { error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); @@ -35094,7 +43061,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { + if (restExpression.kind === 195 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -35107,12 +43074,14 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 262) { + if (exprOrAssignment.kind === 266 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { - sourceType = getTypeWithFacts(sourceType, 131072); + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } @@ -35121,133 +43090,140 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 194 && target.operatorToken.kind === 58) { + if (target.kind === 195 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 178) { + if (target.kind === 179 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 177) { + if (target.kind === 178 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 ? + var error = target.parent.kind === 267 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, undefined); + checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ function isSideEffectFree(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 71: - case 9: - case 12: - case 183: - case 196: - case 13: - case 8: - case 101: - case 86: - case 95: - case 139: - case 186: - case 199: - case 187: - case 177: - case 178: - case 189: - case 203: - case 250: - case 249: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 184 /* TaggedTemplateExpression */: + case 197 /* TemplateExpression */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 139 /* UndefinedKeyword */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 190 /* TypeOfExpression */: + case 204 /* NonNullExpression */: + case 251 /* JsxSelfClosingElement */: + case 250 /* JsxElement */: return true; - case 195: + case 196 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 194: + case 195 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 192: - case 193: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. switch (node.operator) { - case 51: - case 37: - case 38: - case 52: + case 51 /* ExclamationToken */: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: return true; } return false; - case 190: - case 184: - case 202: + // Some forms listed here for clarity + case 191 /* VoidExpression */: // Explicit opt-out + case 185 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 203 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); + return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 178 || left.kind === 177)) { + if (operator === 58 /* EqualsToken */ && (left.kind === 179 /* ObjectLiteralExpression */ || left.kind === 178 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { - case 39: - case 40: - case 61: - case 62: - case 41: - case 63: - case 42: - case 64: - case 38: - case 60: - case 45: - case 65: - case 46: - case 66: - case 47: - case 67: - case 49: - case 69: - case 50: - case 70: - case 48: - case 68: + case 39 /* AsteriskToken */: + case 40 /* AsteriskAsteriskToken */: + case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + case 42 /* PercentToken */: + case 64 /* PercentEqualsToken */: + case 38 /* MinusToken */: + case 60 /* MinusEqualsToken */: + case 45 /* LessThanLessThanToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 49 /* BarToken */: + case 69 /* BarEqualsToken */: + case 50 /* CaretToken */: + case 70 /* CaretEqualsToken */: + case 48 /* AmpersandToken */: + case 68 /* AmpersandEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 136 /* BooleanLike */) && + (rightType.flags & 136 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } else { + // otherwise just check each operand separately and report errors as normal var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); if (leftOk && rightOk) { @@ -35255,25 +43231,31 @@ var ts; } } return numberType; - case 37: - case 59: + case 37 /* PlusToken */: + case 59 /* PlusEqualsToken */: if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 262178) && !isTypeAssignableToKind(rightType, 262178)) { + if (!isTypeAssignableToKind(leftType, 524322 /* StringLike */) && !isTypeAssignableToKind(rightType, 524322 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 84, true) && isTypeAssignableToKind(rightType, 84, true)) { + if (isTypeAssignableToKind(leftType, 84 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 84 /* NumberLike */, /*strict*/ true)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } - else if (isTypeAssignableToKind(leftType, 262178, true) || isTypeAssignableToKind(rightType, 262178, true)) { + else if (isTypeAssignableToKind(leftType, 524322 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 524322 /* StringLike */, /*strict*/ true)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; } + // Symbols are not allowed at all in arithmetic expressions if (resultType && !checkForDisallowedESSymbolOperand(operator)) { return resultType; } @@ -35281,14 +43263,14 @@ var ts; reportOperatorError(); return anyType; } - if (operator === 59) { + if (operator === 59 /* PlusEqualsToken */) { checkAssignmentOperator(resultType); } return resultType; - case 27: - case 29: - case 30: - case 31: + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); @@ -35297,10 +43279,10 @@ var ts; } } return booleanType; - case 32: - case 33: - case 34: - case 35: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: var leftIsLiteral = isLiteralType(leftType); var rightIsLiteral = isLiteralType(rightType); if (!leftIsLiteral || !rightIsLiteral) { @@ -35311,33 +43293,34 @@ var ts; reportOperatorError(); } return booleanType; - case 93: + case 93 /* InstanceOfKeyword */: return checkInstanceOfExpression(left, right, leftType, rightType); - case 92: + case 92 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); - case 53: - return getTypeFacts(leftType) & 1048576 ? + case 53 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 1048576 /* Truthy */ ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - case 54: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + case 54 /* BarBarToken */: + return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : leftType; - case 58: + case 58 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); - case 26: + case 26 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; } function isEvalNode(node) { - return node.kind === 71 && node.escapedText === "eval"; + return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; } + // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 1536 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -35347,23 +43330,30 @@ var ts; } function getSuggestedBooleanOperator(operator) { switch (operator) { - case 49: - case 69: - return 54; - case 50: - case 70: - return 35; - case 48: - case 68: - return 53; + case 49 /* BarToken */: + case 69 /* BarEqualsToken */: + return 54 /* BarBarToken */; + case 50 /* CaretToken */: + case 70 /* CaretEqualsToken */: + return 35 /* ExclamationEqualsEqualsToken */; + case 48 /* AmpersandToken */: + case 68 /* AmpersandEqualsToken */: + return 53 /* AmpersandAmpersandToken */; default: return undefined; } } function checkAssignmentOperator(valueType) { if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non - compound operation to be assignable to the type of VarExpr. if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { - checkTypeAssignableTo(valueType, leftType, left, undefined); + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); } } } @@ -35387,8 +43377,9 @@ var ts; return false; } function checkYieldExpression(node) { + // Grammar checking if (produceDiagnostics) { - if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -35397,49 +43388,65 @@ var ts; } if (node.expression) { var func = ts.getContainingFunction(node); + // If the user's code is syntactically correct, the func should always have a star. After all, + // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if ((functionFlags & 3) === 3 && - languageVersion < 5) { - checkExternalEmitHelpers(node, 26624); + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - if ((functionFlags & 3) === 1 && - languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256); + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); } } - if (functionFlags & 1) { + if (functionFlags & 1 /* Generator */) { var expressionType = checkExpressionCached(node.expression); var expressionElementType = void 0; var nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); + expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); } + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. var returnType = ts.getEffectiveReturnTypeNode(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2) !== 0) || anyType; + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2 /* Async */) !== 0) || anyType; if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 + checkTypeAssignableTo(functionFlags & 2 /* Async */ ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionElementType, signatureElementType, node.expression, undefined); + : expressionElementType, signatureElementType, node.expression, + /*headMessage*/ undefined); } else { - checkTypeAssignableTo(functionFlags & 2 + checkTypeAssignableTo(functionFlags & 2 /* Async */ ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionType, signatureElementType, node.expression, undefined); + : expressionType, signatureElementType, node.expression, + /*headMessage*/ undefined); } } } } + // Both yield and yield* expressions have type 'any' return anyType; } function checkConditionalExpression(node, checkMode) { checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2], /*subtypeReduction*/ true); } function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { checkExpression(templateSpan.expression); }); @@ -35450,8 +43457,8 @@ var ts; var saveContextualMapper = node.contextualMapper; node.contextualType = contextualType; node.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 : - contextualMapper ? 2 : 0; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; var result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -35460,6 +43467,9 @@ var ts; function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. var saveFlowLoopStart = flowLoopStart; flowLoopStart = flowLoopCount; links.resolvedType = checkExpression(node, checkMode); @@ -35469,24 +43479,42 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 184 || node.kind === 202; + return node.kind === 185 /* TypeAssertionExpression */ || node.kind === 203 /* AsExpression */; } function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, true); - return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || + var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); + return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } - function isLiteralContextualType(contextualType) { + function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 540672) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - if (constraint.flags & (2 | 4 | 8 | 16)) { - return true; - } - contextualType = constraint; + if (contextualType.flags & 131072 /* Union */ && !(contextualType.flags & 8 /* Boolean */)) { + // If the contextual type is a union containing both of the 'true' and 'false' types we + // don't consider it a literal context for boolean literals. + var types_19 = contextualType.types; + return ts.some(types_19, function (t) { + return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_19, trueType) && containsType(types_19, falseType)) && + isLiteralOfContextualType(candidateType, t); + }); } - return maybeTypeOfKind(contextualType, (224 | 262144)); + if (contextualType.flags & 1081344 /* TypeVariable */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || + constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || + contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); } return false; } @@ -35495,25 +43523,32 @@ var ts; contextualType = getContextualType(node); } var type = checkExpression(node, checkMode); - var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); - return shouldWiden ? type : getWidenedLiteralType(type); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); } function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 144) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking checkGrammarMethod(node); - if (node.name.kind === 144) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2) { + if (checkMode === 2 /* Inferential */) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { var contextualType = getApparentTypeOfContextualType(node); @@ -35527,16 +43562,34 @@ var ts; } return type; } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ function getTypeOfExpression(node, cache) { - if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { + // 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 (node.kind === 182 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. return cache ? checkExpressionCached(node) : checkExpression(node); } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ function getContextFreeTypeOfExpression(node) { var saveContextualType = node.contextualType; node.contextualType = anyType; @@ -35544,9 +43597,16 @@ var ts; node.contextualType = saveContextualType; return type; } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, checkMode) { var type; - if (node.kind === 143) { + if (node.kind === 144 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -35554,9 +43614,13 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 179 && node.parent.expression === node) || - (node.parent.kind === 180 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -35572,94 +43636,99 @@ var ts; } function checkExpressionWorker(node, checkMode) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return checkIdentifier(node); - case 99: + case 99 /* ThisKeyword */: return checkThisExpression(node); - case 97: + case 97 /* SuperKeyword */: return checkSuperExpression(node); - case 95: + case 95 /* NullKeyword */: return nullWideningType; - case 13: - case 9: + case 13 /* NoSubstitutionTemplateLiteral */: + case 9 /* StringLiteral */: return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: + case 8 /* NumericLiteral */: checkGrammarNumericLiteral(node); return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: + case 101 /* TrueKeyword */: return trueType; - case 86: + case 86 /* FalseKeyword */: return falseType; - case 196: + case 197 /* TemplateExpression */: return checkTemplateExpression(node); - case 12: + case 12 /* RegularExpressionLiteral */: return globalRegExpType; - case 177: + case 178 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode); - case 178: + case 179 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 179: + case 180 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 180: + case 181 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 181: - if (node.expression.kind === 91) { + case 182 /* CallExpression */: + if (node.expression.kind === 91 /* ImportKeyword */) { return checkImportCallExpression(node); } - case 182: + /* falls through */ + case 183 /* NewExpression */: return checkCallExpression(node); - case 183: + case 184 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 185: + case 186 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 199: + case 200 /* ClassExpression */: return checkClassExpression(node); - case 186: - case 187: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189: + case 190 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 184: - case 202: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return checkAssertion(node); - case 203: + case 204 /* NonNullExpression */: return checkNonNullAssertion(node); - case 204: + case 205 /* MetaProperty */: return checkMetaProperty(node); - case 188: + case 189 /* DeleteExpression */: return checkDeleteExpression(node); - case 190: + case 191 /* VoidExpression */: return checkVoidExpression(node); - case 191: + case 192 /* AwaitExpression */: return checkAwaitExpression(node); - case 192: + case 193 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 193: + case 194 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 194: + case 195 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 195: + case 196 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 198: + case 199 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 200: + case 201 /* OmittedExpression */: return undefinedWideningType; - case 197: + case 198 /* YieldExpression */: return checkYieldExpression(node); - case 256: + case 260 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 249: + case 250 /* JsxElement */: return checkJsxElement(node); - case 250: + case 251 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 254: + case 254 /* JsxFragment */: + return checkJsxFragment(node); + case 258 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 251: + case 252 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; } + // DECLARATION AND STATEMENT TYPE CHECKING function checkTypeParameter(node) { + // Grammar Checking if (node.expression) { grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } @@ -35669,6 +43738,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -35679,12 +43751,15 @@ var ts; } } function checkParameter(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasModifier(node, 92)) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!(func.kind === 153 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -35695,10 +43770,12 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 152 || func.kind === 156 || func.kind === 161) { + if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } @@ -35707,7 +43784,7 @@ var ts; if (parameterList) { for (var i = 0; i < parameterList.length; i++) { var param = parameterList[i]; - if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { return i; } } @@ -35717,6 +43794,7 @@ var ts; function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { + // The parent must not be valid. error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } @@ -35735,16 +43813,17 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); + var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); } } else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_24 = _a[_i].name; - if (ts.isBindingPattern(name_24) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_24, parameterName, typePredicate.parameterName)) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -35757,16 +43836,16 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 187: - case 155: - case 228: - case 186: - case 160: - case 151: - case 150: - var parent_14 = node.parent; - if (node === parent_14.type) { - return parent_14; + case 188 /* ArrowFunction */: + case 156 /* CallSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 161 /* FunctionType */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; } } } @@ -35776,41 +43855,47 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_25 = element.name; - if (name_25.kind === 71 && name_25.escapedText === predicateVariableName) { + var name = element.name; + if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_25.kind === 175 || name_25.kind === 174) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_25, predicateVariableNode, predicateVariableName)) { + else if (name.kind === 176 /* ArrayBindingPattern */ || name.kind === 175 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } } } } function checkSignatureDeclaration(node) { - if (node.kind === 157) { + // Grammar checking + if (node.kind === 158 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || - node.kind === 155 || node.kind === 152 || - node.kind === 156) { + else if (node.kind === 161 /* FunctionType */ || node.kind === 229 /* FunctionDeclaration */ || node.kind === 162 /* ConstructorType */ || + node.kind === 156 /* CallSignature */ || node.kind === 153 /* Constructor */ || + node.kind === 157 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if (!(functionFlags & 4)) { - if ((functionFlags & 3) === 3 && languageVersion < 5) { - checkExternalEmitHelpers(node, 6144); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - if ((functionFlags & 3) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - if ((functionFlags & 3) !== 0 && languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 128 /* Generator */); } } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? if (node.type) { checkSourceElement(node.type); } @@ -35819,30 +43904,36 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 156: + case 157 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 155: + case 156 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } if (returnTypeNode) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & (4 | 1)) === 1) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(returnTypeNode); if (returnType === voidType) { error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { - var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; - var iterableIteratorInstantiation = functionFlags_1 & 2 - ? createAsyncIterableIteratorType(generatorElementType) - : createIterableIteratorType(generatorElementType); + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); } } - else if ((functionFlags_1 & 3) === 2) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -35863,31 +43954,31 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152) { + if (member.kind === 153 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { - addName(instanceNames, param.name, param.name.escapedText, 3); + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); } } } else { - var isStatic = ts.hasModifier(member, 32); + var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 153: - addName(names, member.name, memberName, 1); + case 154 /* GetAccessor */: + addName(names, member.name, memberName, 1 /* Getter */); break; - case 154: - addName(names, member.name, memberName, 2); + case 155 /* SetAccessor */: + addName(names, member.name, memberName, 2 /* Setter */); break; - case 149: - addName(names, member.name, memberName, 3); + case 150 /* PropertyDeclaration */: + addName(names, member.name, memberName, 3 /* Property */); break; - case 151: - addName(names, member.name, memberName, 4); + case 152 /* MethodDeclaration */: + addName(names, member.name, memberName, 4 /* Method */); break; } } @@ -35896,8 +43987,8 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 4) { - if (meaning !== 4) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } } @@ -35913,11 +44004,22 @@ var ts; } } } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ function checkClassForStaticPropertyNameConflicts(node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; var memberNameNode = member.name; - var isStatic = ts.hasModifier(member, 32); + var isStatic = ts.hasModifier(member, 32 /* Static */); if (isStatic && memberNameNode) { var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); switch (memberName) { @@ -35927,7 +44029,7 @@ var ts; case "arguments": case "prototype": var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); error(memberNameNode, message, memberName, className); break; } @@ -35938,15 +44040,15 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148) { + if (member.kind === 149 /* PropertySignature */) { var memberName = void 0; switch (member.name.kind) { - case 9: - case 8: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: memberName = member.name.text; break; - case 71: - memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + case 71 /* Identifier */: + memberName = ts.idText(member.name); break; default: continue; @@ -35962,12 +44064,17 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230) { + if (node.kind === 231 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol) { var seenNumericIndexer = false; @@ -35977,7 +44084,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 136: + case 136 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -35985,7 +44092,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 133: + case 133 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -35999,26 +44106,38 @@ var ts; } } function checkPropertyDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); } function checkMethodDeclaration(node) { - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + // Grammar checking + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); - if (ts.hasModifier(node, 128) && node.body) { + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.hasModifier(node, 128 /* Abstract */) && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + // Grammar check for checking only related to constructorDeclaration + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(symbol); } + // exit early in the case of signature - super checks are not relevant to them if (ts.nodeIsMissing(node.body)) { return; } @@ -36042,10 +44161,13 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function isInstancePropertyWithInitializer(n) { - return n.kind === 149 && - !ts.hasModifier(n, 32) && + return n.kind === 150 /* PropertyDeclaration */ && + !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); @@ -36055,14 +44177,21 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializer) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); }); + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -36082,37 +44211,46 @@ var ts; } function checkAccessorDeclaration(node) { if (produceDiagnostics) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + // Grammar checking accessors + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 153) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { - if (!(node.flags & 256)) { + if (node.kind === 154 /* GetAccessor */) { + if (!(node.flags & 2097152 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 144) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 153 ? 154 : 153; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (!hasNonBindableDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 154 /* GetAccessor */ ? 155 /* SetAccessor */ : 154 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); var otherFlags = ts.getModifierFlags(otherAccessor); - if ((nodeFlags & 28) !== (otherFlags & 28)) { + if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if ((nodeFlags & 128) !== (otherFlags & 128)) { + if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153) { + if (node.kind === 154 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -36142,34 +44280,41 @@ var ts; mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, instantiateType(constraint, mapper), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 160 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); if (type !== unknownType) { if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved ts.forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; if (!symbol) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + // There is no resolved symbol cached if the type resolved to a builtin + // via JSDoc type reference resolution (eg, Boolean became boolean), none + // of which are generic when they have no associated symbol + // (additionally, JSDoc's index signature syntax, Object actually uses generic syntax without being generic) + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } - var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; - if (!typeParameters && getObjectFlags(type) & 4) { + var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && ts.getObjectFlags(type) & 4 /* Reference */) { typeParameters = type.target.localTypeParameters; } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && getNodeLinks(node).resolvedSymbol.flags & 8) { + if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -36190,6 +44335,7 @@ var ts; checkSourceElement(node.elementType); } function checkTupleType(node) { + // Grammar checking var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); @@ -36200,19 +44346,22 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288)) { + if (!(type.flags & 1048576 /* IndexedAccess */)) { return type; } + // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { + if (accessNode.kind === 181 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; } - if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { + // Check if we're indexing with a numeric type and if either object or index types + // is a generic type with a constraint that has a numeric index signature. + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -36230,19 +44379,26 @@ var ts; var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 2097152 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 230 && - n.parent.kind !== 229 && - n.parent.kind !== 199 && - ts.isInAmbientContext(n)) { - if (!(flags & 2)) { - flags |= 1; - } - flags |= 2; + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 231 /* InterfaceDeclaration */ && + n.parent.kind !== 230 /* ClassDeclaration */ && + n.parent.kind !== 200 /* ClassExpression */ && + n.flags & 2097152 /* Ambient */) { + if (!(flags & 2 /* Ambient */)) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; } return flags & flagsToCheck; } @@ -36251,25 +44407,32 @@ var ts; return; } function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; } function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; - if (deviation & 1) { + if (deviation & 1 /* Export */) { error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } - else if (deviation & 2) { + else if (deviation & 2 /* Ambient */) { error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (8 | 16)) { + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 128) { + else if (deviation & 128 /* Abstract */) { error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); @@ -36286,8 +44449,8 @@ var ts; }); } } - var flagsToCheck = 1 | 2 | 8 | 16 | 128; - var someNodeFlags = 0; + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; var allHaveQuestionToken = true; @@ -36296,7 +44459,7 @@ var ts; var lastSeenNonAmbientDeclaration; var previousDeclaration; var declarations = symbol.declarations; - var isConstructor = (symbol.flags & 16384) !== 0; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; function reportImplementationExpectedError(node) { if (node.name && ts.nodeIsMissing(node.name)) { return; @@ -36310,17 +44473,24 @@ var ts; seen = c === node; } }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) var subsequentName = subsequentNode.name; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 151 || node.kind === 150) && - ts.hasModifier(node, 32) !== ts.hasModifier(subsequentNode, 32); + var reportError = (node.kind === 152 /* MethodDeclaration */ || node.kind === 151 /* MethodSignature */) && + ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder if (reportError) { - var diagnostic = ts.hasModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -36336,7 +44506,9 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (ts.hasModifier(node, 128)) { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.hasModifier(node, 128 /* Abstract */)) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -36349,12 +44521,19 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; + var inAmbientContext = node.flags & 2097152 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 231 /* InterfaceDeclaration */ || node.parent.kind === 164 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { + if (node.kind === 229 /* FunctionDeclaration */ || node.kind === 152 /* MethodDeclaration */ || node.kind === 151 /* MethodSignature */ || node.kind === 153 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -36395,8 +44574,9 @@ var ts; error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } + // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !ts.hasModifier(lastSeenNonAmbientDeclaration, 128) && !lastSeenNonAmbientDeclaration.questionToken) { + !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -36419,25 +44599,30 @@ var ts; if (!produceDiagnostics) { return; } + // if localSymbol is defined on node then node itself is exported - check is required var symbol = node.localSymbol; if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported symbol = getSymbolOfNode(node); if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything return; } } + // run the check only for the first declaration in the list if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { return; } - var exportedDeclarationSpaces = 0; - var nonExportedDeclarationSpaces = 0; - var defaultExportedDeclarationSpaces = 0; + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); - if (effectiveDeclarationFlags & 1) { - if (effectiveDeclarationFlags & 512) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -36448,19 +44633,22 @@ var ts; nonExportedDeclarationSpaces |= declarationSpaces; } } + // Spaces for anything not declared a 'default export'. var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); - var name_26 = ts.getNameOfDeclaration(d); + var name = ts.getNameOfDeclaration(d); + // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(name_26, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name_26)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(name_26, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name_26)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -36473,29 +44661,31 @@ var ts; })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(d) { switch (d.kind) { - case 230: - case 231: - case 283: - return 2; - case 233: - return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 - ? 4 | 1 - : 4; - case 229: - case 232: - return 2 | 1; - case 237: - case 240: - case 239: - var result_3 = 0; + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + // A jsdoc typedef is, by definition, a type alias + case 288 /* JSDocTypedefTag */: + return 2 /* ExportType */; + case 234 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + // The below options all declare an Alias, which is allowed to merge with other values within the importing module + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 240 /* ImportClause */: + var result_2 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 226: - case 176: - case 228: - case 242: - return 1; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 229 /* FunctionDeclaration */: + case 243 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; default: ts.Debug.fail(ts.SyntaxKind[d.kind]); } @@ -36505,7 +44695,21 @@ var ts; var promisedType = getPromisedTypeOfPromise(type, errorNode); return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // if (isTypeAny(promise)) { return undefined; } @@ -36513,33 +44717,40 @@ var ts; if (typeAsPromise.promisedTypeOfPromise) { return typeAsPromise.promisedTypeOfPromise; } - if (isReferenceToType(promise, getGlobalPromiseType(false))) { + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); if (isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : ts.emptyArray; + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; if (thenSignatures.length === 0) { if (errorNode) { error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } - var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); if (onfulfilledParameterSignatures.length === 0) { if (errorNode) { error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); } return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ function checkAwaitedType(type, errorNode, diagnosticMessage) { return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; } @@ -36551,7 +44762,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 65536) { + if (type.flags & 131072 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -36560,16 +44771,50 @@ var ts; if (!types) { return undefined; } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // if (errorNode) { error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); } return undefined; } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. awaitedTypeStack.push(type.id); var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); awaitedTypeStack.pop(); @@ -36578,8 +44823,23 @@ var ts; } return typeAsAwaitable.awaitedTypeOfType = awaitedType; } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { if (errorNode) { ts.Debug.assert(!!diagnosticMessage); error(errorNode, diagnosticMessage); @@ -36588,20 +44848,60 @@ var ts; } return typeAsAwaitable.awaitedTypeOfType = type; } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + * + * @param node The signature to check + */ function checkAsyncFunctionReturnType(node) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnType = getTypeFromTypeNode(returnTypeNode); - if (languageVersion >= 2) { + if (languageVersion >= 2 /* ES2015 */) { if (returnType === unknownType) { return unknownType; } - var globalPromiseType = getGlobalPromiseType(true); + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); return unknownType; } } else { + // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); if (returnType === unknownType) { return unknownType; @@ -36611,10 +44911,10 @@ var ts; error(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, typeToString(returnType)); return unknownType; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { + if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -36622,49 +44922,54 @@ var ts; } return unknownType; } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. error(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, ts.entityNameToString(promiseConstructorName)); return unknownType; } 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 unknownType; } + // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455 /* Value */); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; } } + // Get and return the awaited type of the return type. return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** Check a decorator */ function checkDecorator(node) { var signature = getResolvedSignature(node); var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 1) { + if (returnType.flags & 1 /* Any */) { return; } var expectedReturnType; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 229: + case 230 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 146: + case 147 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 149: + case 150 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 151: - case 153: - case 154: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -36672,6 +44977,10 @@ var ts; } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ function markTypeNodeAsReferenced(node) { markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); } @@ -36679,15 +44988,22 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 793064 : 1920) | 2097152; - var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); + var meaning = (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol - && rootSymbol.flags & 2097152 + && rootSymbol.flags & 2097152 /* Alias */ && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { markAliasSymbolAsReferenced(rootSymbol); } } + /** + * This function marks the type used for metadata decorator as referenced if it is import + * from external module. + * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in + * union and intersection type + * @param node + */ function markDecoratorMedataDataTypeNodeAsReferenced(node) { var entityName = getEntityNameForDecoratorMetadata(node); if (entityName && ts.isEntityName(entityName)) { @@ -36697,16 +45013,32 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 167: - case 166: + case 168 /* IntersectionType */: + case 167 /* UnionType */: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) { + // Individual is something like string number + // So it would be serialized to either that type or object + // Safe to return here return undefined; } if (commonEntityName) { + // Note this is in sync with the transformation that happens for type node. + // Keep this in sync with serializeUnionOrIntersectionType + // Verify if they refer to same entity and is identifier + // return undefined if they dont match because we would emit object if (!ts.isIdentifier(commonEntityName) || !ts.isIdentifier(individualEntityName) || commonEntityName.escapedText !== individualEntityName.escapedText) { @@ -36718,9 +45050,9 @@ var ts; } } return commonEntityName; - case 168: + case 169 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 159: + case 160 /* TypeReference */: return node.typeName; } } @@ -36729,25 +45061,29 @@ var ts; var typeNode = ts.getEffectiveTypeAnnotationNode(node); return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; } + /** Check the decorators of a node */ function checkDecorators(node) { if (!node.decorators) { return; } - if (!ts.nodeCanBeDecorated(node)) { + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } var firstDecorator = node.decorators[0]; - checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 146) { - checkExternalEmitHelpers(firstDecorator, 32); + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 147 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16); + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 229: + case 230 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -36756,20 +45092,25 @@ var ts; } } break; - case 151: - case 153: - case 154: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 149: + case 150 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 146: + case 147 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } break; } } @@ -36788,42 +45129,100 @@ var ts; } function checkJSDocTypedefTag(node) { if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 144 /* QualifiedName */ ? node.name.right : node.name)); + } + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 282 /* JSDocAugmentsTag */); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 71 /* Identifier */: + return node; + case 180 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 144) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 145 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536); }); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 65536 /* JavaScriptFile */); }); + // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } if (symbol.parent) { + // run check once for the first declaration if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations checkFunctionOrConstructorSymbol(symbol); } } } checkSourceElement(node.body); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - if ((functionFlags & 1) === 0) { - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 - ? checkAsyncFunctionReturnType(node) - : getTypeFromTypeNode(returnTypeNode)); + if ((functionFlags & 1 /* Generator */) === 0) { + var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ + ? checkAsyncFunctionReturnType(node) // Async function + : getTypeFromTypeNode(returnTypeNode)); // normal function checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !returnTypeNode) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { reportImplicitAnyError(node, anyType); } - if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(node.body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } @@ -36839,68 +45238,67 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 265: - case 233: + case 269 /* SourceFile */: + case 234 /* ModuleDeclaration */: checkUnusedModuleMembers(node); break; - case 229: - case 199: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 230: + case 231 /* InterfaceDeclaration */: checkUnusedTypeParameters(node); break; - case 207: - case 235: - case 214: - case 215: - case 216: + case 208 /* Block */: + case 236 /* CaseBlock */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: checkUnusedLocalsAndParameters(node); break; - case 152: - case 186: - case 228: - case 187: - case 151: - case 153: - case 154: + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 150: - case 155: - case 156: - case 157: - case 160: - case 161: - checkUnusedTypeParameters(node); - break; - case 231: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 232 /* TypeAliasDeclaration */: checkUnusedTypeParameters(node); break; + default: + ts.Debug.fail("Node should not have been registered for unused identifiers check"); } } } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + if (noUnusedIdentifiers && !(node.flags & 2097152 /* Ambient */)) { node.locals.forEach(function (local) { if (!local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 147 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name_27 = ts.getNameOfDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(name_27)) { - error(name_27, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); } } }); @@ -36917,12 +45315,12 @@ var ts; var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 226 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 145) { + if ((declaration_2.kind === 227 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 146 /* TypeParameter */) { return; } } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { + if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); } } @@ -36930,23 +45328,23 @@ var ts; return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95; + return node.kind === 71 /* Identifier */ && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + if (member.kind === 152 /* MethodDeclaration */ || member.kind === 150 /* PropertyDeclaration */) { + if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); } } - else if (member.kind === 152) { + else if (member.kind === 153 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } } @@ -36955,8 +45353,10 @@ var ts; } } function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { if (node.typeParameters) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. var symbol = getSymbolOfNode(node); var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); if (lastDeclaration !== node) { @@ -36965,20 +45365,20 @@ var ts; for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); } } } } } function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { node.locals.forEach(function (local) { if (!local.isReferenced && !local.exportSymbol) { for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.symbolName(local)); } } } @@ -36986,7 +45386,8 @@ var ts; } } function checkBlock(node) { - if (node.kind === 207) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 208 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -37002,7 +45403,8 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -37015,19 +45417,22 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 149 || - node.kind === 148 || - node.kind === 151 || - node.kind === 150 || - node.kind === 153 || - node.kind === 154) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 149 /* PropertySignature */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 151 /* MethodSignature */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152 /* Ambient */) { + // ambient context - no codegen impact return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 147 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact return false; } return true; @@ -37042,10 +45447,11 @@ var ts; potentialNewTargetCollisions.push(node); } } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 71; + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -37058,8 +45464,8 @@ var ts; } function checkIfNewTargetIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 8) { - var isDeclaration_2 = node.kind !== 71; + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } @@ -37074,12 +45480,14 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } + // bubble up and find containing type var enclosingClass = ts.getContainingClass(node); - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + // if containing type was not found or it is ambient - exit (no codegen) + if (!enclosingClass || enclosingClass.flags & 2097152 /* Ambient */) { return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71; + var isDeclaration_3 = node.kind !== 71 /* Identifier */; if (isDeclaration_3) { error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -37089,80 +45497,125 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later if (modulekind >= ts.ModuleKind.ES2015) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + // Uninstantiated modules shouldnt do this check + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + if (parent.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 226 && !node.initializer) { + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 227 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); - if (symbol.flags & 1) { + if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!ts.isIdentifier(node.name)) throw ts.Debug.fail(); - var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & 2) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); - var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 228 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 209 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 207 && ts.isFunctionLike(container.parent) || - container.kind === 234 || - container.kind === 233 || - container.kind === 265); + (container.kind === 208 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 235 /* ModuleBlock */ || + container.kind === 234 /* ModuleDeclaration */ || + container.kind === 269 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - var name_28 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_28, name_28); + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); } } } } } + // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146) { + if (ts.getRootDeclaration(node).kind !== 147 /* Parameter */) { return; } var func = ts.getContainingFunction(node); visit(node.initializer); function visit(n) { if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 179) { + if (n.kind === 180 /* PropertyAccessExpression */) { + // skip property names in property access expression return visit(n.expression); } - else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined, false); + else if (n.kind === 71 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -37170,24 +45623,32 @@ var ts; error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 || - symbol.valueDeclaration.kind === 176) { + if (symbol.valueDeclaration.kind === 147 /* Parameter */ || + symbol.valueDeclaration.kind === 177 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { return; } + // - parameter is wrapped in function-like entity if (ts.findAncestor(n, function (current) { if (current === node.initializer) { return "quit"; } return ts.isFunctionLike(current.parent) || - (current.parent.kind === 149 && - !(ts.hasModifier(current.parent, 32)) && + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 150 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { return; } + // fall through to report error } error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); } @@ -37200,47 +45661,59 @@ var ts; function convertAutoToAny(type) { return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; } + // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); + // JSDoc `function(string, string): string` syntax results in parameters with no name if (!node.name) { return; } - if (node.name.kind === 144) { + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 176) { - if (node.parent.kind === 174 && languageVersion < 5) { - checkExternalEmitHelpers(node, 4); + if (node.kind === 177 /* BindingElement */) { + if (node.parent.kind === 175 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); } - if (node.propertyName && node.propertyName.kind === 144) { + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } - var parent_15 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_15); - var name_29 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_29)); - markPropertyAsReferenced(property, undefined); - if (parent_15.initializer && property) { - checkPropertyAccessibility(parent_15, parent_15.initializer, parentType, property); + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } + // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); + if (node.name.kind === 176 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 147 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } + // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } return; @@ -37248,27 +45721,34 @@ var ts; var symbol = getSymbolOfNode(node); var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } } else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); + if (type !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* JSContainer */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 149 && node.kind !== 148) { + if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 226 || node.kind === 176) { + if (node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -37278,20 +45758,28 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 150 /* PropertyDeclaration */ || nextDeclaration.kind === 149 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 && right.kind === 226) || - (left.kind === 226 && right.kind === 146)) { + if ((left.kind === 147 /* Parameter */ && right.kind === 227 /* VariableDeclaration */) || + (left.kind === 227 /* VariableDeclaration */ && right.kind === 147 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { return false; } - var interestingFlags = 8 | - 16 | - 256 | - 128 | - 64 | - 32; + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { @@ -37303,12 +45791,15 @@ var ts; return checkVariableLikeDeclaration(node); } function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 178) { - if (ts.getFunctionFlags(node) & 2) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && node.parent.kind === 179 /* ObjectLiteralExpression */) { + if (ts.getFunctionFlags(node) & 2 /* Async */) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } @@ -37319,36 +45810,41 @@ var ts; } } function checkExpressionStatement(node) { + // Grammar checking checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); } function checkIfStatement(node) { + // Grammar checking checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209) { + if (node.thenStatement.kind === 210 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } function checkDoStatement(node) { + // Grammar checking checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); checkExpression(node.expression); } function checkWhileStatement(node) { + // Grammar checking checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.statement); } function checkForStatement(node) { + // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227) { + if (node.initializer && node.initializer.kind === 228 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 227) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -37366,31 +45862,46 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 216) { + if (node.kind === 217 /* ForOfStatement */) { if (node.awaitModifier) { var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { - checkExternalEmitHelpers(node, 16384); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (compilerOptions.downlevelIteration && languageVersion < 2) { - checkExternalEmitHelpers(node, 256); + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } - if (node.initializer.kind === 227) { + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 228 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 177 || varExpr.kind === 178) { + // There may be a destructuring assignment on the left side + if (varExpr.kind === 178 /* ArrayLiteralExpression */ || varExpr.kind === 179 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { var leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); + checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); } } } @@ -37400,9 +45911,15 @@ var ts; } } function checkForInStatement(node) { + // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 227) { + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 228 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -37410,19 +45927,26 @@ var ts; checkForInOrForOfVariableDeclaration(node); } else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 || varExpr.kind === 178) { + if (varExpr.kind === 178 /* ArrayLiteralExpression */ || varExpr.kind === 179 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { + // run check only former check succeeded to avoid cascading errors checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); } } - if (!isTypeAssignableToKind(rightType, 16777216 | 540672)) { + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (!isTypeAssignableToKind(rightType, 33554432 /* NonPrimitive */ | 1081344 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -37432,6 +45956,7 @@ var ts; } function checkForInOrForOfVariableDeclaration(iterationStatement) { var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. if (variableDeclarationList.declarations.length >= 1) { var decl = variableDeclarationList.declarations[0]; checkVariableDeclaration(decl); @@ -37439,19 +45964,28 @@ var ts; } function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { var expressionType = checkNonNullExpression(rhsExpression); - return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); } function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { if (isTypeAny(inputType)) { return inputType; } - return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, true) || anyType; + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { - var uplevelIteration = languageVersion >= 2; + var uplevelIteration = languageVersion >= 2 /* ES2015 */; var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. if (uplevelIteration || downlevelIteration || allowAsyncIterables) { - var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, true, checkAssignability); + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); if (iteratedType || uplevelIteration) { return iteratedType; } @@ -37459,32 +45993,44 @@ var ts; var arrayType = inputType; var reportedError = false; var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. if (allowStringInput) { - if (arrayType.flags & 65536) { + if (arrayType.flags & 131072 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, true); + arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); } } - else if (arrayType.flags & 262178) { + else if (arrayType.flags & 524322 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; if (hasStringConstituent) { - if (languageVersion < 1) { + if (languageVersion < 1 /* ES5 */) { if (errorNode) { error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); reportedError = true; } } - if (arrayType.flags & 8192) { + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 16384 /* Never */) { return stringType; } } } if (!isArrayLikeType(arrayType)) { if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. var diagnostic = !allowStringInput || hasStringConstituent ? downlevelIteration ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator @@ -37496,15 +46042,54 @@ var ts; } return hasStringConstituent ? stringType : undefined; } - var arrayElementType = getIndexTypeOfType(arrayType, 1); + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 262178) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 524322 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType], true); + return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); } return arrayElementType; } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { if (isTypeAny(type)) { return undefined; @@ -37516,8 +46101,10 @@ var ts; if (typeAsIterable.iteratedTypeOfAsyncIterable) { return typeAsIterable.iteratedTypeOfAsyncIterable; } - if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || - isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; } } @@ -37525,8 +46112,10 @@ var ts; if (typeAsIterable.iteratedTypeOfIterable) { return typeAsIterable.iteratedTypeOfIterable; } - if (isReferenceToType(type, getGlobalIterableType(false)) || - isReferenceToType(type, getGlobalIterableIteratorType(false))) { + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } @@ -37535,19 +46124,23 @@ var ts; if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0); + var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); if (!ts.some(signatures)) { if (errorNode) { error(errorNode, allowAsyncIterables ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + // only report on the first error errorNode = undefined; } return undefined; } - var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); - var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. checkTypeAssignableTo(type, asyncMethodType ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); @@ -37557,6 +46150,28 @@ var ts; : typeAsIterable.iteratedTypeOfIterable = iteratedType; } } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { if (isTypeAny(type)) { return undefined; @@ -37565,17 +46180,21 @@ var ts; if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; - if (isReferenceToType(type, getIteratorType(false))) { + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; } + // Both async and non-async iterators must have a `next` method. var nextMethod = getTypeOfPropertyOfType(type, "next"); if (isTypeAny(nextMethod)) { return undefined; } - var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : ts.emptyArray; + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; if (nextMethodSignatures.length === 0) { if (errorNode) { error(errorNode, isAsyncIterator @@ -37584,10 +46203,11 @@ var ts; } return undefined; } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); if (isTypeAny(nextResult)) { return undefined; } + // For an async iterator, we must get the awaited type of the return type. if (isAsyncIterator) { nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); if (isTypeAny(nextResult)) { @@ -37607,27 +46227,37 @@ var ts; ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue : typeAsIterator.iteratedTypeOfIterator = nextValue; } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { if (isTypeAny(returnType)) { return undefined; } - return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, !isAsyncGenerator, false) - || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); } function checkBreakOrContinueStatement(node) { - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 153 - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154)) !== undefined; + return node.kind === 154 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 155 /* SetAccessor */)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 - ? getPromisedTypeOfPromise(returnType) - : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ + ? getPromisedTypeOfPromise(returnType) // Async function + : returnType; // AsyncGenerator function, Generator function, or normal function + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { + // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { var functionBlock = ts.getContainingFunction(node); if (!functionBlock) { @@ -37638,27 +46268,34 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return expressions of generators when return type tracking is added + // for generators. + return; + } + if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return; - } - if (func.kind === 154) { + if (func.kind === 155 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 152) { + else if (func.kind === 153 /* Constructor */) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2) { + if (functionFlags & 2 /* Async */) { var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. checkTypeAssignableTo(awaitedType, promisedType, node); } } @@ -37667,14 +46304,16 @@ var ts; } } } - else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } } function checkWithStatement(node) { + // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 16384) { + if (node.flags & 16384 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -37687,13 +46326,15 @@ var ts; } } function checkSwitchStatement(node) { + // Grammar checking checkGrammarStatementInAmbientContext(node); var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 258 && !hasDuplicateDefaultClause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 262 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -37705,8 +46346,11 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 257) { + if (produceDiagnostics && clause.kind === 261 /* CaseClause */) { var caseClause = clause; + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. var caseType = checkExpression(caseClause.expression); var caseIsLiteral = isLiteralType(caseType); var comparedExpressionType = expressionType; @@ -37715,7 +46359,8 @@ var ts; comparedExpressionType = getBaseTypeOfLiteralType(expressionType); } if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); } } ts.forEach(clause.statements, checkSourceElement); @@ -37725,21 +46370,24 @@ var ts; } } function checkLabeledStatement(node) { + // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { ts.findAncestor(node.parent, function (current) { if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 222 && current.label.escapedText === node.label.escapedText) { + if (current.kind === 223 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); return true; } }); } + // ensure that label is unique checkSourceElement(node.statement); } function checkThrowStatement(node) { + // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { if (node.expression === undefined) { grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); @@ -37750,10 +46398,12 @@ var ts; } } function checkTryStatement(node) { + // Grammar checking checkGrammarStatementInAmbientContext(node); checkBlock(node.tryBlock); var catchClause = node.catchClause; if (catchClause) { + // Grammar checking if (catchClause.variableDeclaration) { if (catchClause.variableDeclaration.type) { grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); @@ -37766,7 +46416,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2) !== 0) { + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -37780,24 +46430,28 @@ var ts; } } function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); - var stringIndexType = getIndexTypeOfType(type, 0); - var numberIndexType = getIndexTypeOfType(type, 1); + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!ts.hasModifier(member, 32) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); } } } @@ -37805,8 +46459,9 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (getObjectFlags(type) & 2)) { - var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } @@ -37818,25 +46473,31 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { return; } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && - (propDeclaration.kind === 194 || - ts.getNameOfDeclaration(propDeclaration).kind === 144 || + (propDeclaration.kind === 195 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 145 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (getObjectFlags(containingType) & 2) { + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 + var errorMessage = indexKind === 0 /* String */ ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); @@ -37844,6 +46505,8 @@ var ts; } } function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. switch (name.escapedText) { case "any": case "number": @@ -37855,6 +46518,9 @@ var ts; error(name, message, name.escapedText); } } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ function checkTypeParameters(typeParameterDeclarations) { if (typeParameterDeclarations) { var seenDefault = false; @@ -37877,6 +46543,7 @@ var ts; } } } + /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { return; @@ -37890,10 +46557,11 @@ var ts; } var type = getDeclaredTypeOfSymbol(symbol); if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - var name_30 = symbolToString(symbol); + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name_30); + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } } @@ -37903,6 +46571,7 @@ var ts; var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { var declaration = declarations_6[_i]; + // If this declaration has too few or too many type parameters, we report an error var numTypeParameters = ts.length(declaration.typeParameters); if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; @@ -37910,15 +46579,21 @@ var ts; for (var i = 0; i < numTypeParameters; i++) { var source = declaration.typeParameters[i]; var target = typeParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. if (source.name.escapedText !== target.symbol.escapedName) { return false; } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); var targetConstraint = getConstraintFromTypeParameter(target); if ((sourceConstraint || targetConstraint) && (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { return false; } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. var sourceDefault = source.default && getTypeFromTypeNode(source.default); var targetDefault = getDefaultFromTypeParameter(target); if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { @@ -37938,7 +46613,7 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (!node.name && !ts.hasModifier(node, 512)) { + if (!node.name && !ts.hasModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -37963,13 +46638,14 @@ var ts; var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); - if (!ts.isInAmbientContext(node)) { + // Only check for reserved static identifiers on non-ambient context. + if (!(node.flags & 2097152 /* Ambient */)) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (languageVersion < 2) { - checkExternalEmitHelpers(baseTypeNode.parent, 1); + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); } var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { @@ -37989,10 +46665,14 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 1081344 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); @@ -38025,14 +46705,15 @@ var ts; if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); } } function checkBaseTypeAccessibility(type, node) { - var signatures = getSignaturesOfType(type, 1); + var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { var declaration = signatures[0].declaration; - if (declaration && ts.hasModifier(declaration, 8)) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } @@ -38040,32 +46721,52 @@ var ts; } } function getTargetSymbol(s) { - return ts.getCheckFlags(s) & 1 ? s.target : s; - } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 || d.kind === 230; + return d.kind === 230 /* ClassDeclaration */ || d.kind === 231 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; var base = getTargetSymbol(baseProperty); - if (base.flags & 4194304) { + if (base.flags & 4194304 /* Prototype */) { continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { + // In order to resolve whether the inherited method was overridden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. if (derived === base) { - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128))) { - if (derivedClassDecl.kind === 199) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { + if (derivedClassDecl.kind === 200 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -38074,23 +46775,26 @@ var ts; } } else { + // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { + if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) { + // either base or derived property is private - not override, skip it continue; } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { + if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; } var errorMessage = void 0; if (isMethodLike(base)) { - if (derived.flags & 98304) { + 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; } } - else if (base.flags & 4) { + else if (base.flags & 4 /* Property */) { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; } else { @@ -38124,7 +46828,7 @@ var ts; ok = false; var typeName1 = typeToString(existing.containingType); var typeName2 = typeToString(base); - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); } @@ -38133,18 +46837,54 @@ var ts; } return ok; } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 1 /* Any */ || getFalsyFlags(type) & 4096 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 150 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 4096 /* Undefined */); + } function checkInterfaceDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 231 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded if (checkInheritedPropertiesAreIdentical(type, node.name)) { for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { var baseType = _a[_i]; @@ -38168,7 +46908,8 @@ var ts; } } function checkTypeAliasDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); checkTypeParameters(node.typeParameters); checkSourceElement(node.type); @@ -38176,8 +46917,8 @@ var ts; } function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 16384)) { - nodeLinks.flags |= 16384; + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; var autoValue = 0; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -38200,9 +46941,15 @@ var ts; if (member.initializer) { return computeConstantValue(member); } - if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + // In ambient enum declarations that specify no const modifier, enum member declarations that omit + // a value are considered computed members (as opposed to having auto-incremented values). + if (member.parent.flags & 2097152 /* Ambient */ && !ts.isConst(member.parent)) { return undefined; } + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error + // occurs if the immediately preceding member is not a constant enum member. if (autoValue !== undefined) { return autoValue; } @@ -38213,7 +46960,7 @@ var ts; var enumKind = getEnumKind(getSymbolOfNode(member.parent)); var isConstEnum = ts.isConst(member.parent); var initializer = member.initializer; - var value = enumKind === 1 && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); + var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); if (value !== undefined) { if (isConstEnum && typeof value === "number" && !isFinite(value)) { error(initializer, isNaN(value) ? @@ -38221,76 +46968,77 @@ var ts; ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); } } - else if (enumKind === 1) { + else if (enumKind === 1 /* Literal */) { error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members); return 0; } else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (ts.isInAmbientContext(member.parent)) { + else if (member.parent.flags & 2097152 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); } return value; function evaluate(expr) { switch (expr.kind) { - case 192: + case 193 /* PrefixUnaryExpression */: var value_1 = evaluate(expr.operand); if (typeof value_1 === "number") { switch (expr.operator) { - case 37: return value_1; - case 38: return -value_1; - case 52: return ~value_1; + case 37 /* PlusToken */: return value_1; + case 38 /* MinusToken */: return -value_1; + case 52 /* TildeToken */: return ~value_1; } } break; - case 194: + case 195 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { switch (expr.operatorToken.kind) { - case 49: return left | right; - case 48: return left & right; - case 46: return left >> right; - case 47: return left >>> right; - case 45: return left << right; - case 50: return left ^ right; - case 39: return left * right; - case 41: return left / right; - case 37: return left + right; - case 38: return left - right; - case 42: return left % right; + case 49 /* BarToken */: return left | right; + case 48 /* AmpersandToken */: return left & right; + case 46 /* GreaterThanGreaterThanToken */: return left >> right; + case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 45 /* LessThanLessThanToken */: return left << right; + case 50 /* CaretToken */: return left ^ right; + case 39 /* AsteriskToken */: return left * right; + case 41 /* SlashToken */: return left / right; + case 37 /* PlusToken */: return left + right; + case 38 /* MinusToken */: return left - right; + case 42 /* PercentToken */: return left % right; } } break; - case 9: + case 9 /* StringLiteral */: return expr.text; - case 8: + case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 185: + case 186 /* ParenthesizedExpression */: return evaluate(expr.expression); - case 71: + case 71 /* Identifier */: return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); - case 180: - case 179: + case 181 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); - if (type.symbol && type.symbol.flags & 384) { - var name_31; - if (ex.kind === 179) { - name_31 = ex.name.escapedText; + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 180 /* PropertyAccessExpression */) { + name = ex.name.escapedText; } else { var argument = ex.argumentExpression; ts.Debug.assert(ts.isLiteralExpression(argument)); - name_31 = ts.escapeLeadingUnderscores(argument.text); + name = ts.escapeLeadingUnderscores(argument.text); } - return evaluateEnumMember(expr, type.symbol, name_31); + return evaluateEnumMember(expr, type.symbol, name); } } break; @@ -38303,7 +47051,7 @@ var ts; var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { - return getNodeLinks(declaration).enumMemberValue; + return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; @@ -38313,16 +47061,17 @@ var ts; } } function isConstantMemberAccess(node) { - return node.kind === 71 || - node.kind === 179 && isConstantMemberAccess(node.expression) || - node.kind === 180 && isConstantMemberAccess(node.expression) && - node.argumentExpression.kind === 9; + return node.kind === 71 /* Identifier */ || + node.kind === 180 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 181 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.argumentExpression.kind === 9 /* StringLiteral */; } function checkEnumDeclaration(node) { if (!produceDiagnostics) { return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + // Grammar checking + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -38331,13 +47080,20 @@ var ts; checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152 /* Ambient */) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); @@ -38346,7 +47102,8 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 232) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 233 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -38369,9 +47126,9 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { var declaration = declarations_7[_i]; - if ((declaration.kind === 229 || - (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 230 /* ClassDeclaration */ || + (declaration.kind === 229 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 2097152 /* Ambient */)) { return declaration; } } @@ -38392,8 +47149,9 @@ var ts; } function checkModuleDeclaration(node) { if (produceDiagnostics) { + // Grammar checking var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContext = node.flags & 2097152 /* Ambient */; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -38402,10 +47160,11 @@ var ts; ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9) { + if (!checkGrammarDecoratorsAndModifiers(node)) { + if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } @@ -38416,7 +47175,8 @@ var ts; } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - if (symbol.flags & 512 + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !inAmbientContext && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { @@ -38429,16 +47189,24 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 229); + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 230 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { - getNodeLinks(node).flags |= 32768; + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; } } if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); if (checkBody && node.body) { + // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -38458,6 +47226,8 @@ var ts; error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); } else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); } } @@ -38472,43 +47242,51 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 208: + case 209 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 243: - case 244: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 237: - case 238: + case 238 /* ImportEqualsDeclaration */: + case 239 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 176: - case 226: - var name_32 = node.name; - if (ts.isBindingPattern(name_32)) { - for (var _b = 0, _c = name_32.elements; _b < _c.length; _b++) { + case 177 /* BindingElement */: + case 227 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { var el = _c[_b]; + // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } - case 229: - case 232: - case 228: - case 230: - case 233: - case 231: + // falls through + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 229 /* FunctionDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } var symbol = getSymbolOfNode(node); if (symbol) { - var reportError = !(symbol.flags & 33554432); + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { + // symbol should not originate in augmentation reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } @@ -38517,35 +47295,41 @@ var ts; } function getFirstIdentifier(node) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return node; - case 143: + case 144 /* QualifiedName */: do { node = node.left; - } while (node.kind !== 71); + } while (node.kind !== 71 /* Identifier */); return node; - case 179: + case 180 /* PropertyAccessExpression */: do { node = node.expression; - } while (node.kind !== 71); + } while (node.kind !== 71 /* Identifier */); return node; } } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 ? + var inAmbientExternalModule = node.parent.kind === 235 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 269 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 245 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); return false; } @@ -38556,19 +47340,26 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | + (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 246 ? + var message = node.kind === 247 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } + // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 246 - && !(target.flags & 107455) - && !ts.isInAmbientContext(node)) { + && node.kind === 247 /* ExportSpecifier */ + && !(target.flags & 107455 /* Value */) + && !(node.flags & 2097152 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } @@ -38581,9 +47372,10 @@ var ts; } function checkImportDeclaration(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -38593,7 +47385,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { + if (importClause.namedBindings.kind === 241 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -38605,30 +47397,33 @@ var ts; } function checkImportEqualsDeclaration(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.moduleReference.kind !== 249 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 107455) { + if (target.flags & 107455 /* 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); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 107455 /* 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)); } } - if (target.flags & 793064) { + if (target.flags & 793064 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152 /* Ambient */)) { + // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } @@ -38636,34 +47431,38 @@ var ts; } function checkExportDeclaration(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 235 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 235 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 2097152 /* Ambient */; + if (node.parent.kind !== 269 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { + // export * from "foo" var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { - checkExternalEmitHelpers(node, 32768); + checkExternalEmitHelpers(node, 32768 /* ExportStar */); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; + var isInAppropriateContext = node.parent.kind === 269 /* SourceFile */ || node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 234 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -38671,11 +47470,16 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { markExportAsReferenced(node); @@ -38684,10 +47488,11 @@ var ts; } function checkExportAssignment(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 234 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -38696,24 +47501,30 @@ var ts; } return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + // Grammar checking + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } - if (node.expression.kind === 71) { + if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } } else { checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 2097152 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (node.isExportEquals && !(node.flags & 2097152 /* Ambient */)) { if (modulekind >= ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { + // system modules does not support export assignment grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } } @@ -38732,36 +47543,44 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } + // Checks for export * conflicts var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - if (flags & (1920 | 64 | 384)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); - if (flags & 524288 && exportedDeclarationsCount <= 2) { - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (exports) { + exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } - } - }); + }); + } links.exportsChecked = true; } } function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || + return (declaration.kind !== 229 /* FunctionDeclaration */ && declaration.kind !== 152 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { @@ -38776,144 +47595,212 @@ var ts; } var kind = node.kind; if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. switch (kind) { - case 233: - case 229: - case 230: - case 228: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 145: + case 146 /* TypeParameter */: return checkTypeParameter(node); - case 146: + case 147 /* Parameter */: return checkParameter(node); - case 149: - case 148: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return checkPropertyDeclaration(node); - case 160: - case 161: - case 155: - case 156: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 157: + case 158 /* IndexSignature */: return checkSignatureDeclaration(node); - case 151: - case 150: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return checkMethodDeclaration(node); - case 152: + case 153 /* Constructor */: return checkConstructorDeclaration(node); - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return checkAccessorDeclaration(node); - case 159: + case 160 /* TypeReference */: return checkTypeReferenceNode(node); - case 158: + case 159 /* TypePredicate */: return checkTypePredicate(node); - case 162: + case 163 /* TypeQuery */: return checkTypeQuery(node); - case 163: + case 164 /* TypeLiteral */: return checkTypeLiteral(node); - case 164: + case 165 /* ArrayType */: return checkArrayType(node); - case 165: + case 166 /* TupleType */: return checkTupleType(node); - case 166: - case 167: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 168: - case 170: + case 169 /* ParenthesizedType */: return checkSourceElement(node.type); - case 283: + case 171 /* TypeOperator */: + return checkTypeOperator(node); + case 282 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 288 /* JSDocTypedefTag */: return checkJSDocTypedefTag(node); - case 279: - return checkSourceElement(node.typeExpression); - case 273: + case 284 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 277 /* JSDocFunctionType */: checkSignatureDeclaration(node); - case 274: - case 271: - case 270: - case 268: - case 269: - if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); - } + // falls through + case 275 /* JSDocNonNullableType */: + case 274 /* JSDocNullableType */: + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); return; - case 267: + case 278 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 271 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 171: + case 172 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 172: + case 173 /* MappedType */: return checkMappedType(node); - case 228: + case 229 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 207: - case 234: + case 208 /* Block */: + case 235 /* ModuleBlock */: return checkBlock(node); - case 208: + case 209 /* VariableStatement */: return checkVariableStatement(node); - case 210: + case 211 /* ExpressionStatement */: return checkExpressionStatement(node); - case 211: + case 212 /* IfStatement */: return checkIfStatement(node); - case 212: + case 213 /* DoStatement */: return checkDoStatement(node); - case 213: + case 214 /* WhileStatement */: return checkWhileStatement(node); - case 214: + case 215 /* ForStatement */: return checkForStatement(node); - case 215: + case 216 /* ForInStatement */: return checkForInStatement(node); - case 216: + case 217 /* ForOfStatement */: return checkForOfStatement(node); - case 217: - case 218: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 219: + case 220 /* ReturnStatement */: return checkReturnStatement(node); - case 220: + case 221 /* WithStatement */: return checkWithStatement(node); - case 221: + case 222 /* SwitchStatement */: return checkSwitchStatement(node); - case 222: + case 223 /* LabeledStatement */: return checkLabeledStatement(node); - case 223: + case 224 /* ThrowStatement */: return checkThrowStatement(node); - case 224: + case 225 /* TryStatement */: return checkTryStatement(node); - case 226: + case 227 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 176: + case 177 /* BindingElement */: return checkBindingElement(node); - case 229: + case 230 /* ClassDeclaration */: return checkClassDeclaration(node); - case 230: + case 231 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 231: + case 232 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 232: + case 233 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 233: + case 234 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 238: + case 239 /* ImportDeclaration */: return checkImportDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 244: + case 245 /* ExportDeclaration */: return checkExportDeclaration(node); - case 243: + case 244 /* ExportAssignment */: return checkExportAssignment(node); - case 209: + case 210 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 225: + case 226 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 247: + case 248 /* MissingDeclaration */: return checkMissingDeclaration(node); } } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJavaScriptFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag. + var parent = node.parent; + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = parent.parent; + if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (param) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + /* + Only return an array type if the corresponding parameter is marked as a rest parameter. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = host_1 && ts.last(host_1.parameters); + if (lastParamDeclaration.symbol === param && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + return addOptionality(type); + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { if (deferredNodes) { deferredNodes.push(node); @@ -38923,17 +47810,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 186: - case 187: - case 151: - case 150: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 199: + case 200 /* ClassExpression */: checkClassExpressionDeferred(node); break; } @@ -38945,12 +47832,17 @@ var ts; ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); } + // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { var links = getNodeLinks(node); - if (!(links.flags & 1)) { + if (!(links.flags & 1 /* TypeChecked */)) { + // If skipLibCheck is enabled, skip type checking if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip type checking if file contains a + // '/// ' directive. if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { return; } + // Grammar checking checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); @@ -38959,7 +47851,7 @@ var ts; flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); - if (ts.isExternalModule(node)) { + if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile) { @@ -38978,11 +47870,14 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - links.flags |= 1; + links.flags |= 1 /* TypeChecked */; } } function getDiagnostics(sourceFile, ct) { try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. cancellationToken = ct; return getDiagnosticsWorker(sourceFile); } @@ -38993,20 +47888,29 @@ var ts; function getDiagnosticsWorker(sourceFile) { throwIfNonDiagnosticsProducing(); if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; checkSourceFile(sourceFile); var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); } else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); } return semanticDiagnostics; } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics ts.forEach(host.getSourceFiles(), checkSourceFile); return diagnostics.getDiagnostics(); } @@ -39019,19 +47923,10 @@ var ts; throw new Error("Trying to get diagnostics from a type checker that does not produce them."); } } - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } + // Language service support function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { + if (location.flags & 4194304 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further return []; } var symbols = ts.createSymbolTable(); @@ -39044,24 +47939,31 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 233: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + case 234 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 232: - copySymbols(getSymbolOfNode(location).exports, meaning & 8); + case 233 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 199: + case 200 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 229: - case 230: + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064 /* Type */); } break; - case 186: + case 187 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -39071,14 +47973,24 @@ var ts; if (ts.introducesArgumentsExoticObject(location)) { copySymbol(argumentsSymbol, meaning); } - isStatic = ts.hasModifier(location, 32); + isStatic = ts.hasModifier(location, 32 /* Static */); location = location.parent; } copySymbols(globals, meaning); } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ function copySymbol(symbol, meaning) { if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array if (!symbols.has(id)) { symbols.set(id, symbol); } @@ -39093,33 +48005,34 @@ var ts; } } function isTypeDeclarationName(name) { - return name.kind === 71 && + return name.kind === 71 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 145: - case 229: - case 230: - case 231: - case 232: + case 146 /* TypeParameter */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: return true; } } + // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 143) { + while (node.parent && node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 159; + return node.parent && node.parent.kind === 160 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 179) { + while (node.parent && node.parent.kind === 180 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 201; + return node.parent && node.parent.kind === 202 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -39132,17 +48045,28 @@ var ts; } return result; } + function isNodeWithinConstructorOfClass(node, classDeclaration) { + return ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + return true; + } + else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } function isNodeWithinClass(node, classDeclaration) { return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143) { + while (nodeOnRightSide.parent.kind === 144 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 237) { + if (nodeOnRightSide.parent.kind === 238 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 243) { + if (nodeOnRightSide.parent.kind === 244 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -39153,12 +48077,12 @@ var ts; function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { - case 1: - case 3: + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: return getSymbolOfNode(entityName.parent); - case 4: - case 2: - case 5: + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: return getSymbolOfNode(entityName.parent.parent); } } @@ -39167,65 +48091,71 @@ var ts; return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 && + entityName.parent.kind === 180 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); if (specialPropertyAssignmentSymbol) { return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); + if (entityName.parent.kind === 244 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, + /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } - if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 237); + if (entityName.kind !== 180 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 238 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = 0; - if (entityName.parent.kind === 201) { - meaning = 793064; + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 202 /* ExpressionWithTypeArguments */) { + meaning = 793064 /* Type */; + // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455; + meaning |= 107455 /* Value */; } } else { - meaning = 1920; + meaning = 1920 /* Namespace */; } - meaning |= 2097152; + meaning |= 2097152 /* Alias */; var entityNameSymbol = resolveEntityName(entityName, meaning); if (entityNameSymbol) { return entityNameSymbol; } } - if (entityName.parent.kind === 279) { + if (entityName.parent.kind === 284 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 145 && entityName.parent.parent.kind === 282) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + if (entityName.parent.kind === 146 /* TypeParameter */ && entityName.parent.parent.kind === 287 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } - if (ts.isPartOfExpression(entityName)) { + if (ts.isExpressionNode(entityName)) { if (ts.nodeIsMissing(entityName)) { + // Missing entity name. return undefined; } - if (entityName.kind === 71) { + if (entityName.kind === 71 /* Identifier */) { if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { return getIntrinsicTagSymbol(entityName.parent); } - return resolveEntityName(entityName, 107455, false, true); + return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 179 || entityName.kind === 143) { + else if (entityName.kind === 180 /* PropertyAccessExpression */ || entityName.kind === 144 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 179) { + if (entityName.kind === 180 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -39235,36 +48165,39 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 159 ? 793064 : 1920; - return resolveEntityName(entityName, meaning, false, true); + var meaning = entityName.parent.kind === 160 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 253) { + else if (entityName.parent.kind === 257 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 158) { - return resolveEntityName(entityName, 1); + if (entityName.parent.kind === 159 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } + // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 265) { + if (node.kind === 269 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode return getSymbolOfNode(node.parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { return getSymbolOfNode(node.parent.parent); } - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 176 && - node.parent.parent.kind === 174 && + else if (node.parent.kind === 177 /* BindingElement */ && + node.parent.parent.kind === 175 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); @@ -39274,12 +48207,12 @@ var ts; } } switch (node.kind) { - case 71: - case 179: - case 143: + case 71 /* Identifier */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99: - var container = ts.getThisContainer(node, false); + case 99 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { var sig = getSignatureFromDeclaration(container); if (sig.thisParameter) { @@ -39289,48 +48222,62 @@ var ts; if (ts.isInExpressionContext(node)) { return checkExpression(node).symbol; } - case 169: + // falls through + case 170 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; - case 97: + case 97 /* SuperKeyword */: return checkExpression(node).symbol; - case 123: + case 123 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152) { + if (constructorDeclaration && constructorDeclaration.kind === 153 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; - case 9: + case 9 /* StringLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { + ((node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } - case 8: + // falls through + case 8 /* NumericLiteral */: + // index access var objectType = ts.isElementAccessExpression(node.parent) ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) ? getTypeFromTypeNode(node.parent.parent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); - case 79: + case 79 /* DefaultKeyword */: + case 89 /* FunctionKeyword */: + case 36 /* EqualsGreaterThanToken */: return getSymbolOfNode(node.parent); default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 262) { - return resolveEntityName(location.name, 107455 | 2097152); + // The function returns a value symbol of an identifier in the short-hand property assignment. + // This is necessary as an identifier in short-hand property assignment can contains two meaning: + // property name and property value. + if (location && location.kind === 266 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); } return undefined; } + /** Returns the target of an export specifier without following aliases */ function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 2097152); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { + // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } if (ts.isPartOfTypeNode(node)) { @@ -39342,16 +48289,19 @@ var ts; } return typeFromTypeNode; } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = getBaseTypes(classType)[0]; return baseType && getTypeWithThisArgument(baseType, classType.thisType); } if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); } @@ -39360,6 +48310,7 @@ var ts; return symbol && getDeclaredTypeOfSymbol(symbol); } if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } @@ -39368,7 +48319,7 @@ var ts; return symbol && getTypeOfSymbol(symbol); } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -39377,26 +48328,48 @@ var ts; } return unknownType; } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 || expr.kind === 177); - if (expr.parent.kind === 216) { + ts.Debug.assert(expr.kind === 179 /* ObjectLiteralExpression */ || expr.kind === 178 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 217 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 194) { + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 195 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } - if (expr.parent.kind === 261) { + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 265 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } - ts.Debug.assert(expr.parent.kind === 177); + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 178 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); } @@ -39406,16 +48379,22 @@ var ts; } return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return ts.hasModifier(node, 32) + return ts.hasModifier(node, 32 /* Static */) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { + if (typeHasCallOrConstructSignatures(type)) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); @@ -39424,19 +48403,22 @@ var ts; } return getNamedMembers(propsByName); } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } function getRootSymbols(symbol) { - if (ts.getCheckFlags(symbol) & 6) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { var symbols_4 = []; - var name_33 = symbol.escapedName; + var name_4 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_33); + var symbol = getPropertyOfType(t, name_4); if (symbol) { symbols_4.push(symbol); } }); return symbols_4; } - else if (symbol.flags & 33554432) { + else if (symbol.flags & 33554432 /* Transient */) { var transient = symbol; if (transient.leftSpread) { return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); @@ -39455,11 +48437,12 @@ var ts; } return [symbol]; } + // Emitter support function isArgumentsLocalBinding(node) { if (!ts.isGeneratedIdentifier(node)) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -39468,43 +48451,58 @@ var ts; function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455) + ? !!(moduleSymbol.flags & 107455 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 107455); + return s && !!(s.flags & 107455 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { var parent = node.parent; return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(node, prefixLocals) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { - var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); if (symbol) { - if (symbol.flags & 1048576) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944) { + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { return undefined; } symbol = exportSymbol; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 269 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. var symbolIsUmdExport = symbolFile !== referenceFile; return symbolIsUmdExport ? undefined : symbolFile; } @@ -39513,30 +48511,50 @@ var ts; } } } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. function getReferencedImportDeclaration(node) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 107455)) { + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418) { + if (symbol.flags & 418 /* BlockScoped */) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined, false)) { + if (resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; - var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); + else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 208 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -39548,6 +48566,9 @@ var ts; } return false; } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. function getReferencedDeclarationWithCollidingName(node) { if (!ts.isGeneratedIdentifier(node)) { node = ts.getParseTreeNode(node, ts.isIdentifier); @@ -39560,6 +48581,8 @@ var ts; } return undefined; } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel function isDeclarationWithCollidingName(node) { node = ts.getParseTreeNode(node, ts.isDeclaration); if (node) { @@ -39572,18 +48595,18 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 237: - case 239: - case 240: - case 242: - case 246: + case 238 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244: + case 245 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243: + case 244 /* ExportAssignment */: return node.expression - && node.expression.kind === 71 + && node.expression.kind === 71 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -39591,7 +48614,8 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 269 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -39602,7 +48626,9 @@ var ts; if (target === unknownSymbol) { return true; } - return target.flags & 107455 && + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return target.flags & 107455 /* Value */ && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -39614,6 +48640,11 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } + var target = getSymbolLinks(symbol).target; + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 107455 /* Value */) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } } if (checkChildren) { return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); @@ -39624,7 +48655,18 @@ var ts; if (ts.nodeIsPresent(node.body)) { var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); } return false; @@ -39633,13 +48675,13 @@ var ts; return strictNullChecks && !isOptionalParameter(parameter) && parameter.initializer && - !ts.hasModifier(parameter, 92); + !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasModifier(parameter, 92); + ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; @@ -39650,19 +48692,20 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 264: - case 179: - case 180: + case 268 /* EnumMember */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 264) { + if (node.kind === 268 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol && (symbol.flags & 8)) { + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { return getEnumMemberValue(symbol.valueDeclaration); } @@ -39670,9 +48713,10 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { + // ensure both `typeName` and `location` are parse tree nodes. typeName = ts.getParseTreeNode(typeName, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; @@ -39681,10 +48725,12 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); - var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { - var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { return ts.TypeReferenceSerializationKind.Promise; } @@ -39693,6 +48739,7 @@ var ts; return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -39700,25 +48747,25 @@ var ts; if (type === unknownType) { return ts.TypeReferenceSerializationKind.Unknown; } - else if (type.flags & 1) { + else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 1024 | 6144 | 8192)) { + else if (isTypeAssignableToKind(type, 2048 /* Void */ | 12288 /* Nullable */ | 16384 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 136)) { + else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 84)) { + else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 262178)) { + else if (isTypeAssignableToKind(type, 524322 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 512)) { + else if (isTypeAssignableToKind(type, 1536 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -39732,12 +48779,17 @@ var ts; } } function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (2048 | 131072)) + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; - if (flags & 8192) { - type = getNullableType(type, 2048); + if (type.flags & 1024 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 131072 /* AllowUniqueESSymbolType */; + } + if (flags & 8192 /* AddUndefined */) { + type = getOptionalType(type); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -39759,12 +48811,14 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_16 = reference.parent; - if (ts.isDeclaration(parent_16) && reference === parent_16.name) { - location = getDeclarationContainer(parent_16); + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -39781,7 +48835,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 1048576); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 2097152 /* FreshLiteral */); } return false; } @@ -39790,9 +48844,12 @@ var ts; writer.writeStringLiteral(literalTypeToString(type)); } function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); var fileToDirective; if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createMap(); resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { if (!resolvedDirective) { @@ -39809,11 +48866,13 @@ var ts; isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: function (node) { node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. return node ? isValueAliasDeclaration(node) : true; }, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: function (node, checkChildren) { node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. return node ? isReferencedAliasDeclaration(node, checkChildren) : true; }, getNodeCheckFlags: function (node) { @@ -39844,29 +48903,43 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, writeLiteralConstValue: writeLiteralConstValue, getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; + // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out if (!fileToDirective) { return undefined; } - var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) - ? 107455 | 1048576 - : 793064 | 1920; - var symbol = resolveEntityName(node, meaning, true); + // property access can only be used as values + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = (node.kind === 180 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) + ? 107455 /* Value */ | 1048576 /* ExportValue */ + : 793064 /* Type */ | 1920 /* Namespace */; + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } + // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out if (!fileToDirective) { return undefined; } if (!isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } + // check what declarations in the symbol can contribute to the target meaning var typeReferenceDirectives; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further if (decl.symbol && decl.symbol.flags & meaning) { var file = ts.getSourceFileOfNode(decl); var typeReferenceDirective = fileToDirective.get(file.path); @@ -39874,6 +48947,7 @@ var ts; (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); } else { + // found at least one entry that does not originate from type reference directive return undefined; } } @@ -39881,22 +48955,26 @@ var ts; return typeReferenceDirectives; } function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) if (!symbol.declarations) { return false; } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_17 = getParentOfSymbol(current); - if (parent_17) { - current = parent_17; + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; } else { break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 269 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } + // check that at least one declaration of top level symbol originates from type declaration file for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var file = ts.getSourceFileOfNode(decl); @@ -39909,17 +48987,19 @@ var ts; } function getExternalModuleFileFromDeclaration(declaration) { var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 265); + return ts.getDeclarationOfKind(moduleSymbol, 269 /* SourceFile */); } function initializeTypeChecker() { + // Bind all source files and propagate errors for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); } + // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; @@ -39933,6 +49013,7 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) var source = file.symbol.globalExports; source.forEach(function (sourceSymbol, id) { if (!globals.has(id)) { @@ -39942,6 +49023,8 @@ var ts; } } if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { var list = augmentations_1[_d]; for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { @@ -39950,36 +49033,42 @@ var ts; } } } + // Setup global builtins addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); getSymbolLinks(unknownSymbol).type = unknownType; - globalArrayType = getGlobalType("Array", 1, true); - globalObjectType = getGlobalType("Object", 0, true); - globalFunctionType = getGlobalType("Function", 0, true); - globalStringType = getGlobalType("String", 0, true); - globalNumberType = getGlobalType("Number", 0, true); - globalBooleanType = getGlobalType("Boolean", 0, true); - globalRegExpType = getGlobalType("RegExp", 0, true); + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152 /* Ambient */)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 32768; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { - var name_34 = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name_34), 107455); + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455 /* Value */); if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name_34); + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } } } @@ -39990,22 +49079,23 @@ var ts; } function getHelperName(helper) { switch (helper) { - case 1: return "__extends"; - case 2: return "__assign"; - case 4: return "__rest"; - case 8: return "__decorate"; - case 16: return "__metadata"; - case 32: return "__param"; - case 64: return "__awaiter"; - case 128: return "__generator"; - case 256: return "__values"; - case 512: return "__read"; - case 1024: return "__spread"; - case 2048: return "__await"; - case 4096: return "__asyncGenerator"; - case 8192: return "__asyncDelegator"; - case 16384: return "__asyncValues"; - case 32768: return "__exportStar"; + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; default: ts.Debug.fail("Unrecognized helper"); } } @@ -40015,19 +49105,23 @@ var ts; } return externalHelpersModule; } + // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } function checkGrammarDecorators(node) { if (!node.decorators) { return false; } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 152 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 153 || node.kind === 154) { + else if (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -40041,44 +49135,44 @@ var ts; return quickResult; } var lastStatic, lastDeclare, lastAsync, lastReadonly; - var flags = 0; + var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 131) { - if (node.kind === 148 || node.kind === 150) { + if (modifier.kind !== 131 /* ReadonlyKeyword */) { + if (node.kind === 149 /* PropertySignature */ || node.kind === 151 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 157) { + if (node.kind === 158 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { - case 76: - if (node.kind !== 232 && node.parent.kind === 229) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); + case 76 /* ConstKeyword */: + if (node.kind !== 233 /* EnumDeclaration */ && node.parent.kind === 230 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); } break; - case 114: - case 113: - case 112: + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (flags & 28) { + if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 32) { + else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & 64) { + else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); } - else if (flags & 256) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 234 || node.parent.kind === 265) { + else if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } - else if (flags & 128) { - if (modifier.kind === 112) { + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 112 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } else { @@ -40087,151 +49181,156 @@ var ts; } flags |= ts.modifierToFlag(modifier.kind); break; - case 115: - if (flags & 32) { + case 115 /* StaticKeyword */: + if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & 64) { + else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (flags & 256) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 234 || node.parent.kind === 265) { + else if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 146) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 128) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 32; + flags |= 32 /* Static */; lastStatic = modifier; break; - case 131: - if (flags & 64) { + case 131 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { + else if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */ && node.kind !== 158 /* IndexSignature */ && node.kind !== 147 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } - flags |= 64; + flags |= 64 /* Readonly */; lastReadonly = modifier; break; - case 84: - if (flags & 1) { + case 84 /* ExportKeyword */: + if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 2) { + else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 128) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 256) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 146) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 1; + flags |= 1 /* Export */; break; - case 79: - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { + case 79 /* DefaultKeyword */: + var container = node.parent.kind === 269 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 234 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } - flags |= 512; + flags |= 512 /* Default */; break; - case 124: - if (flags & 2) { + case 124 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 256) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 146) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { + else if ((node.parent.flags & 2097152 /* Ambient */) && node.parent.kind === 235 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 2; + flags |= 2 /* Ambient */; lastDeclare = modifier; break; - case 117: - if (flags & 128) { + case 117 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 229) { - if (node.kind !== 151 && - node.kind !== 149 && - node.kind !== 153 && - node.kind !== 154) { + if (node.kind !== 230 /* ClassDeclaration */) { + if (node.kind !== 152 /* MethodDeclaration */ && + node.kind !== 150 /* PropertyDeclaration */ && + node.kind !== 154 /* GetAccessor */ && + node.kind !== 155 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 && ts.hasModifier(node.parent, 128))) { + if (!(node.parent.kind === 230 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 32) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 8) { + if (flags & 8 /* Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= 128; + flags |= 128 /* Abstract */; break; - case 120: - if (flags & 256) { + case 120 /* AsyncKeyword */: + if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 /* Ambient */ || node.parent.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 146) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= 256; + flags |= 256 /* Async */; lastAsync = modifier; break; } } - if (node.kind === 152) { - if (flags & 32) { + if (node.kind === 153 /* Constructor */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 128) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 256) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } - else if (flags & 64) { + else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } return; } - else if ((node.kind === 238 || node.kind === 237) && flags & 2) { + else if ((node.kind === 239 /* ImportDeclaration */ || node.kind === 238 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { + else if (node.kind === 147 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { + else if (node.kind === 147 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } - if (flags & 256) { + if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ function reportObviousModifierErrors(node) { return !node.modifiers ? false @@ -40241,38 +49340,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 153: - case 154: - case 152: - case 149: - case 148: - case 151: - case 150: - case 157: - case 233: - case 238: - case 237: - case 244: - case 243: - case 186: - case 187: - case 146: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 234 /* ModuleDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 147 /* Parameter */: return false; default: - if (node.parent.kind === 234 || node.parent.kind === 265) { + if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return false; } switch (node.kind) { - case 228: - return nodeHasAnyModifiersExcept(node, 120); - case 229: - return nodeHasAnyModifiersExcept(node, 117); - case 230: - case 208: - case 231: + case 229 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); + case 230 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); + case 231 /* InterfaceDeclaration */: + case 209 /* VariableStatement */: + case 232 /* TypeAliasDeclaration */: return true; - case 232: - return nodeHasAnyModifiersExcept(node, 76); + case 233 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); default: ts.Debug.fail(); return false; @@ -40284,10 +49383,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 151: - case 228: - case 186: - case 187: + case 152 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -40340,8 +49439,9 @@ var ts; } } function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarClassLikeDeclaration(node) { @@ -40349,7 +49449,7 @@ var ts; return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 187) { + if (node.kind === 188 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -40384,7 +49484,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -40392,7 +49492,8 @@ var ts; } } function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + // Prevent cascading error by short-circuit + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -40410,7 +49511,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 200) { + if (arg.kind === 201 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -40436,10 +49537,10 @@ var ts; function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85) { + if (heritageClause.token === 85 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } @@ -40452,12 +49553,13 @@ var ts; seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108); + ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); if (seenImplementsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); } seenImplementsClause = true; } + // Grammar checking heritageClause inside class declaration checkGrammarHeritageClause(heritageClause); } } @@ -40467,36 +49569,38 @@ var ts; if (node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; - if (heritageClause.token === 85) { + if (heritageClause.token === 85 /* ExtendsKeyword */) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); } seenExtendsClause = true; } else { - ts.Debug.assert(heritageClause.token === 108); + ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); } + // Grammar checking heritageClause inside class declaration checkGrammarHeritageClause(heritageClause); } } return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 144) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 145 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { + if (computedPropertyName.expression.kind === 195 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 || - node.kind === 186 || - node.kind === 151); - if (ts.isInAmbientContext(node)) { + ts.Debug.assert(node.kind === 229 /* FunctionDeclaration */ || + node.kind === 187 /* FunctionExpression */ || + node.kind === 152 /* MethodDeclaration */); + if (node.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -40510,52 +49614,69 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); var seen = ts.createUnderscoreEscapedMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263) { + if (prop.kind === 267 /* SpreadAssignment */) { continue; } - var name_35 = prop.name; - if (name_35.kind === 144) { - checkGrammarComputedPropertyName(name_35); + var name = prop.name; + if (name.kind === 145 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); } - if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 266 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } + // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 151) { + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 152 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 261 || prop.kind === 262) { - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_35.kind === 8) { - checkGrammarNumericLiteral(name_35); - } - currentKind = Property; - } - else if (prop.kind === 151) { - currentKind = Property; - } - else if (prop.kind === 153) { - currentKind = GetAccessor; - } - else if (prop.kind === 154) { - currentKind = SetAccessor; - } - else { - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + switch (prop.kind) { + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 152 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 154 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 155 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_35); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { continue; } @@ -40564,19 +49685,19 @@ var ts; seen.set(effectiveName, currentKind); } else { - if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_35, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_35)); + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { - return grammarErrorOnNode(name_35, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_35, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -40585,19 +49706,19 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 255) { + if (attr.kind === 259 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_36 = jsxAttr.name; - if (!seen.get(name_36.escapedText)) { - seen.set(name_36.escapedText, true); + var name = jsxAttr.name; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); } else { - return grammarErrorOnNode(name_36, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 && !initializer.expression) { + if (initializer && initializer.kind === 260 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -40606,33 +49727,40 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 16384) === 0) { + if (forInOrOfStatement.kind === 217 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 227) { + if (forInOrOfStatement.initializer.kind === 228 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration if (!declarations.length) { return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -40643,27 +49771,27 @@ var ts; } function checkGrammarAccessor(accessor) { var kind = accessor.kind; - if (languageVersion < 1) { + if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (ts.isInAmbientContext(accessor)) { + else if (accessor.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !ts.hasModifier(accessor, 128)) { + else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } - else if (accessor.body && ts.hasModifier(accessor, 128)) { + else if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) { return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 ? + return grammarErrorOnNode(accessor.name, kind === 154 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 154) { + else if (kind === 155 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -40681,16 +49809,55 @@ var ts; } } } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 154 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 154 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 140 /* UniqueKeyword */) { + if (node.type.kind !== 137 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(137 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 227 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 71 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 150 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 149 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -40700,7 +49867,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 178) { + if (node.parent.kind === 179 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } @@ -40709,18 +49876,23 @@ var ts; } } if (ts.isClassLike(node.parent)) { - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (node.flags & 2097152 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 230) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 231 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 163) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 164 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } function checkGrammarBreakOrContinueStatement(node) { @@ -40730,23 +49902,27 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 222: + case 223 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { - var isMisplacedContinueLabel = node.kind === 217 - && !ts.isIterationStatement(current.statement, true); + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 218 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); } return false; } break; - case 221: - if (node.kind === 218 && !node.label) { + case 222 /* SwitchStatement */: + if (node.kind === 219 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok return false; } break; default: - if (ts.isIterationStatement(current, false) && !node.label) { + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok return false; } break; @@ -40754,13 +49930,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 218 + var message = node.kind === 219 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 218 + var message = node.kind === 219 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -40772,22 +49948,23 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 175 || node.name.kind === 174) { + if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { + // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } } function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8; + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 193 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { - if (ts.isInAmbientContext(node)) { + if (node.parent.parent.kind !== 216 /* ForInStatement */ && node.parent.parent.kind !== 217 /* ForOfStatement */) { + if (node.flags & 2097152 /* Ambient */) { if (node.initializer) { if (ts.isConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { @@ -40795,11 +49972,13 @@ var ts; } } else { + // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -40813,16 +49992,25 @@ var ts; } } } + if (node.exclamationToken && (node.parent.parent.kind !== 209 /* VariableStatement */ || !node.type || node.initializer || node.flags & 2097152 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + !(node.parent.parent.flags & 2097152 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkESModuleMarker(name) { - if (name.kind === 71) { - if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + if (name.kind === 71 /* Identifier */) { + if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } } @@ -40837,8 +50025,8 @@ var ts; } } function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71) { - if (name.originalKeywordKind === 110) { + if (name.kind === 71 /* Identifier */) { + if (name.originalKeywordKind === 110 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -40863,15 +50051,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 211: - case 212: - case 213: - case 220: - case 214: - case 215: - case 216: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return false; - case 222: + case 223 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -40887,7 +50075,7 @@ var ts; } } function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94) { + if (node.keywordToken === 94 /* NewKeyword */) { if (node.name.escapedText !== "target") { return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); } @@ -40919,50 +50107,69 @@ var ts; } } function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } } function checkGrammarProperty(node) { if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } } - else if (node.parent.kind === 230) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 231 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 163) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 164 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (ts.isInAmbientContext(node) && node.initializer) { + if (node.flags & 2097152 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } + if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 230 || - node.kind === 231 || - node.kind === 238 || - node.kind === 237 || - node.kind === 244 || - node.kind === 243 || - node.kind === 236 || - ts.hasModifier(node, 2 | 1 | 512)) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 231 /* InterfaceDeclaration */ || + node.kind === 232 /* TypeAliasDeclaration */ || + node.kind === 239 /* ImportDeclaration */ || + node.kind === 238 /* ImportEqualsDeclaration */ || + node.kind === 245 /* ExportDeclaration */ || + node.kind === 244 /* ExportAssignment */ || + node.kind === 237 /* NamespaceExportDeclaration */ || + ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -40970,7 +50177,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208) { + if (ts.isDeclaration(decl) || decl.kind === 209 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -40978,41 +50185,53 @@ var ts; } } function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 2097152 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152 /* Ambient */) { + // An accessors is already reported about the ambient context if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; } + // Find containing block which is either Block, ModuleBlock, SourceFile var links = getNodeLinks(node); if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 208 /* Block */ || node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); + // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); } } } function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 4) { + // Grammar checking + if (node.numericLiteralFlags & 32 /* Octal */) { var diagnosticMessage = void 0; - if (languageVersion >= 1) { + if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 173)) { + else if (ts.isChildOfNodeWithKind(node, 174 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 264)) { + else if (ts.isChildOfNodeWithKind(node, 268 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; var literal = (withMinus ? "-" : "") + "0o" + node.text; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } @@ -41022,18 +50241,21 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); return true; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -41046,16 +50268,19 @@ var ts; if (nodeArguments.length !== 1) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } } } ts.createTypeChecker = createTypeChecker; + /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 242: - case 246: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return true; default: return ts.isDeclarationName(name); @@ -41063,37 +50288,54 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 239: - case 237: - case 240: - case 242: + case 240 /* ImportClause */: // For default import + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */:// For rename import `x as y` return true; - case 71: - return decl.parent.kind === 242; + case 71 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 243 /* ImportSpecifier */; default: return false; } } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); })(ts || (ts = {})); +/// +/// var ts; (function (ts) { function createSynthesizedNode(kind) { var node = ts.createNode(kind, -1, -1); - node.flags |= 8; + node.flags |= 8 /* Synthesized */; return node; } + /* @internal */ function updateNode(updated, original) { if (updated !== original) { setOriginalNode(updated, original); setTextRange(updated, original); - if (original.startsOnNewLine) { - updated.startsOnNewLine = true; - } ts.aggregateTransformFlags(updated); } return updated; } ts.updateNode = updateNode; + /** + * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + */ function createNodeArray(elements, hasTrailingComma) { if (elements) { if (ts.isNodeArray(elements)) { @@ -41110,7 +50352,17 @@ var ts; return array; } ts.createNodeArray = createNodeArray; + /** + * Creates a shallow, memberwise clone of a node with no source map location. + */ + /* @internal */ function getSynthesizedClone(node) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -41130,21 +50382,21 @@ var ts; if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } - if (typeof value === "string") { + if (ts.isString(value)) { return createStringLiteral(value); } return createLiteralFromNode(value); } ts.createLiteral = createLiteral; function createNumericLiteral(value) { - var node = createSynthesizedNode(8); + var node = createSynthesizedNode(8 /* NumericLiteral */); node.text = value; node.numericLiteralFlags = 0; return node; } ts.createNumericLiteral = createNumericLiteral; function createStringLiteral(text) { - var node = createSynthesizedNode(9); + var node = createSynthesizedNode(9 /* StringLiteral */); node.text = text; return node; } @@ -41154,10 +50406,10 @@ var ts; return node; } function createIdentifier(text, typeArguments) { - var node = createSynthesizedNode(71); + var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.originalKeywordKind = text ? ts.stringToToken(text) : 0; - node.autoGenerateKind = 0; + node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; + node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -41167,14 +50419,15 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; + /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable) { var name = createIdentifier(""); - name.autoGenerateKind = 1; + name.autoGenerateKind = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { @@ -41183,57 +50436,63 @@ var ts; return name; } ts.createTempVariable = createTempVariable; + /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2; + name.autoGenerateKind = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; } ts.createLoopVariable = createLoopVariable; + /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3; + name.autoGenerateKind = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; } ts.createUniqueName = createUniqueName; - function getGeneratedNameForNode(node) { + function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4; + name.autoGenerateKind = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; + name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; nextAutoGenerateId++; return name; } ts.getGeneratedNameForNode = getGeneratedNameForNode; + // Punctuation function createToken(token) { return createSynthesizedNode(token); } ts.createToken = createToken; + // Reserved words function createSuper() { - return createSynthesizedNode(97); + return createSynthesizedNode(97 /* SuperKeyword */); } ts.createSuper = createSuper; function createThis() { - return createSynthesizedNode(99); + return createSynthesizedNode(99 /* ThisKeyword */); } ts.createThis = createThis; function createNull() { - return createSynthesizedNode(95); + return createSynthesizedNode(95 /* NullKeyword */); } ts.createNull = createNull; function createTrue() { - return createSynthesizedNode(101); + return createSynthesizedNode(101 /* TrueKeyword */); } ts.createTrue = createTrue; function createFalse() { - return createSynthesizedNode(86); + return createSynthesizedNode(86 /* FalseKeyword */); } ts.createFalse = createFalse; + // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(143); + var node = createSynthesizedNode(144 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -41247,7 +50506,7 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function createComputedPropertyName(expression) { - var node = createSynthesizedNode(144); + var node = createSynthesizedNode(145 /* ComputedPropertyName */); node.expression = expression; return node; } @@ -41258,8 +50517,9 @@ var ts; : node; } ts.updateComputedPropertyName = updateComputedPropertyName; + // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(145); + var node = createSynthesizedNode(146 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -41275,7 +50535,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(146); + var node = createSynthesizedNode(147 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -41299,7 +50559,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(147); + var node = createSynthesizedNode(148 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -41310,8 +50570,9 @@ var ts; : node; } ts.updateDecorator = updateDecorator; + // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148); + var node = createSynthesizedNode(149 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -41331,7 +50592,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149); + var node = createSynthesizedNode(150 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -41353,7 +50614,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(150, typeParameters, parameters, type); + var node = createSignatureDeclaration(151 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -41370,7 +50631,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(151); + var node = createSynthesizedNode(152 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -41398,7 +50659,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(152); + var node = createSynthesizedNode(153 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -41418,7 +50679,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(153); + var node = createSynthesizedNode(154 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -41441,7 +50702,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(154); + var node = createSynthesizedNode(155 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -41462,7 +50723,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(155, typeParameters, parameters, type); + return createSignatureDeclaration(156 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -41470,7 +50731,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(156, typeParameters, parameters, type); + return createSignatureDeclaration(157 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -41478,7 +50739,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(157); + var node = createSynthesizedNode(158 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -41495,6 +50756,7 @@ var ts; : node; } ts.updateIndexSignature = updateIndexSignature; + /* @internal */ function createSignatureDeclaration(kind, typeParameters, parameters, type) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); @@ -41510,12 +50772,13 @@ var ts; ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node) : node; } + // Types function createKeywordTypeNode(kind) { return createSynthesizedNode(kind); } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(158); + var node = createSynthesizedNode(159 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -41529,7 +50792,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(159); + var node = createSynthesizedNode(160 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -41543,7 +50806,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -41551,7 +50814,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161, typeParameters, parameters, type); + return createSignatureDeclaration(162 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -41559,7 +50822,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(162); + var node = createSynthesizedNode(163 /* TypeQuery */); node.exprName = exprName; return node; } @@ -41571,7 +50834,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(163); + var node = createSynthesizedNode(164 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -41583,7 +50846,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(164); + var node = createSynthesizedNode(165 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -41595,7 +50858,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(165); + var node = createSynthesizedNode(166 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -41607,7 +50870,7 @@ var ts; } ts.updateTypleTypeNode = updateTypleTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(166, types); + return createUnionOrIntersectionTypeNode(167 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -41615,7 +50878,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(167, types); + return createUnionOrIntersectionTypeNode(168 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -41634,7 +50897,7 @@ var ts; : node; } function createParenthesizedType(type) { - var node = createSynthesizedNode(168); + var node = createSynthesizedNode(169 /* ParenthesizedType */); node.type = type; return node; } @@ -41646,22 +50909,22 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(169); + return createSynthesizedNode(170 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; - function createTypeOperatorNode(type) { - var node = createSynthesizedNode(170); - node.operator = 127; - node.type = ts.parenthesizeElementTypeMember(type); + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(171 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } ts.createTypeOperatorNode = createTypeOperatorNode; function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(171); + var node = createSynthesizedNode(172 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -41675,7 +50938,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(172); + var node = createSynthesizedNode(173 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -41693,7 +50956,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(173); + var node = createSynthesizedNode(174 /* LiteralType */); node.literal = literal; return node; } @@ -41704,8 +50967,9 @@ var ts; : node; } ts.updateLiteralTypeNode = updateLiteralTypeNode; + // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(174); + var node = createSynthesizedNode(175 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -41717,7 +50981,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(175); + var node = createSynthesizedNode(176 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -41729,7 +50993,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(176); + var node = createSynthesizedNode(177 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -41746,8 +51010,9 @@ var ts; : node; } ts.updateBindingElement = updateBindingElement; + // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(177); + var node = createSynthesizedNode(178 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -41761,7 +51026,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(178); + var node = createSynthesizedNode(179 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -41775,14 +51040,16 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(179); + var node = createSynthesizedNode(180 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); - setEmitFlags(node, 131072); + setEmitFlags(node, 131072 /* NoIndentation */); return node; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { + // Because we are updating existed propertyAccess we want to inherit its emitFlags + // instead of using the default from createPropertyAccess return node.expression !== expression || node.name !== name ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) @@ -41790,7 +51057,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(180); + var node = createSynthesizedNode(181 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -41804,7 +51071,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(181); + var node = createSynthesizedNode(182 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -41820,7 +51087,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(182); + var node = createSynthesizedNode(183 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -41836,7 +51103,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(183); + var node = createSynthesizedNode(184 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); node.template = template; return node; @@ -41850,7 +51117,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(184); + var node = createSynthesizedNode(185 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -41864,7 +51131,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(185); + var node = createSynthesizedNode(186 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -41876,7 +51143,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(186); + var node = createSynthesizedNode(187 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -41900,12 +51167,12 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(187); + var node = createSynthesizedNode(188 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(36 /* EqualsGreaterThanToken */); node.body = ts.parenthesizeConciseBody(body); return node; } @@ -41919,7 +51186,7 @@ var ts; } else { equalsGreaterThanToken = ts.cast(equalsGreaterThanTokenOrBody, function (n) { - return n.kind === 36; + return n.kind === 36 /* EqualsGreaterThanToken */; }); body = bodyOrUndefined; } @@ -41934,7 +51201,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(188); + var node = createSynthesizedNode(189 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -41946,7 +51213,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(189); + var node = createSynthesizedNode(190 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -41958,7 +51225,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(190); + var node = createSynthesizedNode(191 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -41970,7 +51237,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(191); + var node = createSynthesizedNode(192 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -41982,7 +51249,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(192); + var node = createSynthesizedNode(193 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -41995,7 +51262,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(193); + var node = createSynthesizedNode(194 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -42008,12 +51275,12 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(194); + var node = createSynthesizedNode(195 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; - node.left = ts.parenthesizeBinaryOperand(operatorKind, left, true, undefined); + node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); node.operatorToken = operatorToken; - node.right = ts.parenthesizeBinaryOperand(operatorKind, right, false, node.left); + node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left); return node; } ts.createBinary = createBinary; @@ -42025,11 +51292,11 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(195); + var node = createSynthesizedNode(196 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); - node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55); + node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); - node.colonToken = whenFalse ? colonToken : createToken(56); + node.colonToken = whenFalse ? colonToken : createToken(56 /* ColonToken */); node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse); return node; } @@ -42055,7 +51322,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(196); + var node = createSynthesizedNode(197 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -42069,33 +51336,33 @@ var ts; } ts.updateTemplateExpression = updateTemplateExpression; function createTemplateHead(text) { - var node = createSynthesizedNode(14); + var node = createSynthesizedNode(14 /* TemplateHead */); node.text = text; return node; } ts.createTemplateHead = createTemplateHead; function createTemplateMiddle(text) { - var node = createSynthesizedNode(15); + var node = createSynthesizedNode(15 /* TemplateMiddle */); node.text = text; return node; } ts.createTemplateMiddle = createTemplateMiddle; function createTemplateTail(text) { - var node = createSynthesizedNode(16); + var node = createSynthesizedNode(16 /* TemplateTail */); node.text = text; return node; } ts.createTemplateTail = createTemplateTail; function createNoSubstitutionTemplateLiteral(text) { - var node = createSynthesizedNode(13); + var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); node.text = text; return node; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(197); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 ? asteriskTokenOrExpression : expression; + var node = createSynthesizedNode(198 /* YieldExpression */); + node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; } ts.createYield = createYield; @@ -42107,7 +51374,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(198); + var node = createSynthesizedNode(199 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -42119,7 +51386,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(199); + var node = createSynthesizedNode(200 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -42140,11 +51407,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(200); + return createSynthesizedNode(201 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(201); + var node = createSynthesizedNode(202 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -42158,7 +51425,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(202); + var node = createSynthesizedNode(203 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -42172,7 +51439,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(203); + var node = createSynthesizedNode(204 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -42184,7 +51451,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(204); + var node = createSynthesizedNode(205 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -42196,8 +51463,9 @@ var ts; : node; } ts.updateMetaProperty = updateMetaProperty; + // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(205); + var node = createSynthesizedNode(206 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -42211,11 +51479,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(206); + return createSynthesizedNode(207 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; + // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(207); + var block = createSynthesizedNode(208 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -42229,7 +51498,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(208); + var node = createSynthesizedNode(209 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -42244,11 +51513,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(209); + return createSynthesizedNode(210 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(210); + var node = createSynthesizedNode(211 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -42260,7 +51529,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(211); + var node = createSynthesizedNode(212 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -42276,7 +51545,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(212); + var node = createSynthesizedNode(213 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -42290,7 +51559,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(213); + var node = createSynthesizedNode(214 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -42304,7 +51573,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(214); + var node = createSynthesizedNode(215 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -42322,7 +51591,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(215); + var node = createSynthesizedNode(216 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -42338,7 +51607,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(216); + var node = createSynthesizedNode(217 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -42356,7 +51625,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(217); + var node = createSynthesizedNode(218 /* ContinueStatement */); node.label = asName(label); return node; } @@ -42368,7 +51637,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(218); + var node = createSynthesizedNode(219 /* BreakStatement */); node.label = asName(label); return node; } @@ -42380,7 +51649,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(219); + var node = createSynthesizedNode(220 /* ReturnStatement */); node.expression = expression; return node; } @@ -42392,7 +51661,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(220); + var node = createSynthesizedNode(221 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -42406,7 +51675,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(221); + var node = createSynthesizedNode(222 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -42420,7 +51689,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(222); + var node = createSynthesizedNode(223 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -42434,7 +51703,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(223); + var node = createSynthesizedNode(224 /* ThrowStatement */); node.expression = expression; return node; } @@ -42446,7 +51715,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(224); + var node = createSynthesizedNode(225 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -42462,11 +51731,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(225); + return createSynthesizedNode(226 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226); + var node = createSynthesizedNode(227 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -42482,8 +51751,8 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227); - node.flags |= flags & 3; + var node = createSynthesizedNode(228 /* VariableDeclarationList */); + node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; } @@ -42495,7 +51764,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(228); + var node = createSynthesizedNode(229 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -42521,7 +51790,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(229); + var node = createSynthesizedNode(230 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -42543,7 +51812,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(230); + var node = createSynthesizedNode(231 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -42565,7 +51834,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(231); + var node = createSynthesizedNode(232 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -42585,7 +51854,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(232); + var node = createSynthesizedNode(233 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -42603,8 +51872,8 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(233); - node.flags |= flags & (16 | 4 | 512); + var node = createSynthesizedNode(234 /* ModuleDeclaration */); + node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = name; @@ -42622,7 +51891,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(234); + var node = createSynthesizedNode(235 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -42634,7 +51903,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(235); + var node = createSynthesizedNode(236 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -42646,7 +51915,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(236); + var node = createSynthesizedNode(237 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -42658,7 +51927,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(237); + var node = createSynthesizedNode(238 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -42676,7 +51945,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(238); + var node = createSynthesizedNode(239 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -42694,7 +51963,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(239); + var node = createSynthesizedNode(240 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -42708,7 +51977,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(240); + var node = createSynthesizedNode(241 /* NamespaceImport */); node.name = name; return node; } @@ -42720,7 +51989,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(241); + var node = createSynthesizedNode(242 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -42732,7 +52001,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(242); + var node = createSynthesizedNode(243 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -42746,11 +52015,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(243); + var node = createSynthesizedNode(244 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = expression; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -42763,7 +52032,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(244); + var node = createSynthesizedNode(245 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -42781,7 +52050,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(245); + var node = createSynthesizedNode(246 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -42793,7 +52062,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246); + var node = createSynthesizedNode(247 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -42806,8 +52075,9 @@ var ts; : node; } ts.updateExportSpecifier = updateExportSpecifier; + // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(248); + var node = createSynthesizedNode(249 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -42818,8 +52088,9 @@ var ts; : node; } ts.updateExternalModuleReference = updateExternalModuleReference; + // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(249); + var node = createSynthesizedNode(250 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -42835,7 +52106,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(250); + var node = createSynthesizedNode(251 /* JsxSelfClosingElement */); node.tagName = tagName; node.attributes = attributes; return node; @@ -42849,7 +52120,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(251); + var node = createSynthesizedNode(252 /* JsxOpeningElement */); node.tagName = tagName; node.attributes = attributes; return node; @@ -42863,7 +52134,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(252); + var node = createSynthesizedNode(253 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -42874,8 +52145,24 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(254 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(253); + var node = createSynthesizedNode(257 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -42889,7 +52176,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(254); + var node = createSynthesizedNode(258 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -42901,7 +52188,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(255); + var node = createSynthesizedNode(259 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -42913,7 +52200,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(256); + var node = createSynthesizedNode(260 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -42925,8 +52212,9 @@ var ts; : node; } ts.updateJsxExpression = updateJsxExpression; + // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(257); + var node = createSynthesizedNode(261 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -42940,7 +52228,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(258); + var node = createSynthesizedNode(262 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -42952,7 +52240,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(259); + var node = createSynthesizedNode(263 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -42965,8 +52253,8 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(260); - node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + var node = createSynthesizedNode(264 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; } @@ -42978,8 +52266,9 @@ var ts; : node; } ts.updateCatchClause = updateCatchClause; + // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(261); + var node = createSynthesizedNode(265 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -42994,7 +52283,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(262); + var node = createSynthesizedNode(266 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -43008,7 +52297,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(263); + var node = createSynthesizedNode(267 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; return node; } @@ -43019,8 +52308,9 @@ var ts; : node; } ts.updateSpreadAssignment = updateSpreadAssignment; + // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(264); + var node = createSynthesizedNode(268 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -43033,9 +52323,10 @@ var ts; : node; } ts.updateEnumMember = updateEnumMember; + // Top-level nodes function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createSynthesizedNode(265); + var updated = createSynthesizedNode(269 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -43095,6 +52386,9 @@ var ts; return node; } ts.updateSourceFileNode = updateSourceFileNode; + /** + * Creates a shallow, memberwise clone of a node for mutation. + */ function getMutableClone(node) { var clone = getSynthesizedClone(node); clone.pos = node.pos; @@ -43103,29 +52397,54 @@ var ts; return clone; } ts.getMutableClone = getMutableClone; + // Transformation nodes + /** + * Creates a synthetic statement to act as a placeholder for a not-emitted statement in + * order to preserve comments. + * + * @param original The original statement. + */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(287); + var node = createSynthesizedNode(291 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; + /** + * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in + * order to properly emit exports. + */ + /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(291); + var node = createSynthesizedNode(295 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; + /** + * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in + * order to properly emit exports. + */ + /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(290); + var node = createSynthesizedNode(294 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; + /** + * Creates a synthetic expression to act as a placeholder for a not-emitted expression in + * order to preserve comments or sourcemap positions. + * + * @param expression The inner expression to emit. + * @param original The original outer expression. + * @param location The location for the expression. Defaults to the positions from "original" if provided. + */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(288); + var node = createSynthesizedNode(292 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -43141,17 +52460,17 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 289) { + if (node.kind === 293 /* CommaListExpression */) { return node.elements; } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { return [node.left, node.right]; } } return node; } function createCommaList(elements) { - var node = createSynthesizedNode(289); + var node = createSynthesizedNode(293 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -43163,7 +52482,7 @@ var ts; } ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { - var node = ts.createNode(266); + var node = ts.createNode(270 /* Bundle */); node.sourceFiles = sourceFiles; return node; } @@ -43176,55 +52495,70 @@ var ts; } ts.updateBundle = updateBundle; function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { - return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { - return createCall(createArrowFunction(undefined, undefined, param ? [param] : [], undefined, undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { - return createBinary(left, 26, right); + return createBinary(left, 26 /* CommaToken */, right); } ts.createComma = createComma; function createLessThan(left, right) { - return createBinary(left, 27, right); + return createBinary(left, 27 /* LessThanToken */, right); } ts.createLessThan = createLessThan; function createAssignment(left, right) { - return createBinary(left, 58, right); + return createBinary(left, 58 /* EqualsToken */, right); } ts.createAssignment = createAssignment; function createStrictEquality(left, right) { - return createBinary(left, 34, right); + return createBinary(left, 34 /* EqualsEqualsEqualsToken */, right); } ts.createStrictEquality = createStrictEquality; function createStrictInequality(left, right) { - return createBinary(left, 35, right); + return createBinary(left, 35 /* ExclamationEqualsEqualsToken */, right); } ts.createStrictInequality = createStrictInequality; function createAdd(left, right) { - return createBinary(left, 37, right); + return createBinary(left, 37 /* PlusToken */, right); } ts.createAdd = createAdd; function createSubtract(left, right) { - return createBinary(left, 38, right); + return createBinary(left, 38 /* MinusToken */, right); } ts.createSubtract = createSubtract; function createPostfixIncrement(operand) { - return createPostfix(operand, 43); + return createPostfix(operand, 43 /* PlusPlusToken */); } ts.createPostfixIncrement = createPostfixIncrement; function createLogicalAnd(left, right) { - return createBinary(left, 53, right); + return createBinary(left, 53 /* AmpersandAmpersandToken */, right); } ts.createLogicalAnd = createLogicalAnd; function createLogicalOr(left, right) { - return createBinary(left, 54, right); + return createBinary(left, 54 /* BarBarToken */, right); } ts.createLogicalOr = createLogicalOr; function createLogicalNot(operand) { - return createPrefix(51, operand); + return createPrefix(51 /* ExclamationToken */, operand); } ts.createLogicalNot = createLogicalNot; function createVoidZero() { @@ -43232,18 +52566,18 @@ var ts; } ts.createVoidZero = createVoidZero; function createExportDefault(expression) { - return createExportAssignment(undefined, undefined, false, expression); + return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } ts.createExportDefault = createExportDefault; function createExternalModuleExport(exportName) { - return createExportDeclaration(undefined, undefined, createNamedExports([createExportSpecifier(undefined, exportName)])); + return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); } ts.createExternalModuleExport = createExternalModuleExport; function asName(name) { - return typeof name === "string" ? createIdentifier(name) : name; + return ts.isString(name) ? createIdentifier(name) : name; } function asExpression(value) { - return typeof value === "string" || typeof value === "number" ? createLiteral(value) : value; + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -43251,7 +52585,17 @@ var ts; function asToken(value) { return typeof value === "number" ? createToken(value) : value; } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); var emitNode = sourceFile && sourceFile.emitNode; var annotatedNodes = emitNode && emitNode.annotatedNodes; @@ -43263,10 +52607,18 @@ var ts; } } ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + */ + /* @internal */ function getOrCreateEmitNode(node) { if (!node.emitNode) { if (ts.isParseTreeNode(node)) { - if (node.kind === 265) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 269 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -43285,32 +52637,61 @@ var ts; return range; } ts.setTextRange = setTextRange; + /** + * Sets flags that control emit behavior of a node. + */ function setEmitFlags(node, emitFlags) { getOrCreateEmitNode(node).flags = emitFlags; return node; } ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; + /** + * Gets a custom text range to use when emitting source maps. + */ function getSourceMapRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.sourceMapRange) || node; } ts.getSourceMapRange = getSourceMapRange; + /** + * Sets a custom text range to use when emitting source maps. + */ function setSourceMapRange(node, range) { getOrCreateEmitNode(node).sourceMapRange = range; return node; } ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name var SourceMapSource; + /** + * Create an external source map source file reference + */ function createSourceMapSource(fileName, text, skipTrivia) { return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); } ts.createSourceMapSource = createSourceMapSource; + /** + * Gets the TextRange to use for source maps for a token of a node. + */ function getTokenSourceMapRange(node, token) { var emitNode = node.emitNode; var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; return tokenSourceMapRanges && tokenSourceMapRanges[token]; } ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + */ function setTokenSourceMapRange(node, token, range) { var emitNode = getOrCreateEmitNode(node); var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []); @@ -43318,11 +52699,35 @@ var ts; return node; } ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; + /** + * Gets a custom text range to use when emitting comments. + */ function getCommentRange(node) { var emitNode = node.emitNode; return (emitNode && emitNode.commentRange) || node; } ts.getCommentRange = getCommentRange; + /** + * Sets a custom text range to use when emitting comments. + */ function setCommentRange(node, range) { getOrCreateEmitNode(node).commentRange = range; return node; @@ -43356,23 +52761,35 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + /** + * Gets the constant value to emit for an expression. + */ function getConstantValue(node) { var emitNode = node.emitNode; return emitNode && emitNode.constantValue; } ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ function setConstantValue(node, value) { var emitNode = getOrCreateEmitNode(node); emitNode.constantValue = value; return node; } ts.setConstantValue = setConstantValue; + /** + * Adds an EmitHelper to a node. + */ function addEmitHelper(node, helper) { var emitNode = getOrCreateEmitNode(node); emitNode.helpers = ts.append(emitNode.helpers, helper); return node; } ts.addEmitHelper = addEmitHelper; + /** + * Add EmitHelpers to a node. + */ function addEmitHelpers(node, helpers) { if (ts.some(helpers)) { var emitNode = getOrCreateEmitNode(node); @@ -43384,6 +52801,9 @@ var ts; return node; } ts.addEmitHelpers = addEmitHelpers; + /** + * Removes an EmitHelper from a node. + */ function removeEmitHelper(node, helper) { var emitNode = node.emitNode; if (emitNode) { @@ -43395,11 +52815,17 @@ var ts; return false; } ts.removeEmitHelper = removeEmitHelper; + /** + * Gets the EmitHelpers of a node. + */ function getEmitHelpers(node) { var emitNode = node.emitNode; return emitNode && emitNode.helpers; } ts.getEmitHelpers = getEmitHelpers; + /** + * Moves matching emit helpers from a source node to a target node. + */ function moveEmitHelpers(source, target, predicate) { var sourceEmitNode = source.emitNode; var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; @@ -43422,15 +52848,16 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + /* @internal */ function compareEmitHelpers(x, y) { if (x === y) - return 0; + return 0 /* EqualTo */; if (x.priority === y.priority) - return 0; + return 0 /* EqualTo */; if (x.priority === undefined) - return 1; + return 1 /* GreaterThan */; if (y.priority === undefined) - return -1; + return -1 /* LessThan */; return ts.compareValues(x.priority, y.priority); } ts.compareEmitHelpers = compareEmitHelpers; @@ -43445,9 +52872,10 @@ var ts; } ts.setOriginalNode = setOriginalNode; function mergeEmitNode(sourceEmitNode, destEmitNode) { - var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; if (!destEmitNode) destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. if (leadingComments) destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); if (trailingComments) @@ -43464,6 +52892,8 @@ var ts; destEmitNode.constantValue = constantValue; if (helpers) destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -43475,6 +52905,7 @@ var ts; return destRanges; } })(ts || (ts = {})); +/* @internal */ (function (ts) { ts.nullTransformationContext = { enableEmitNotification: ts.noop, @@ -43509,19 +52940,21 @@ var ts; var expression = ts.setTextRange(ts.isIdentifier(memberName) ? ts.createPropertyAccess(target, memberName) : ts.createElementAccess(target, memberName), memberName); - ts.getOrCreateEmitNode(expression).flags |= 64; + ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createFunctionCall(func, thisArg, argumentsList, location) { - return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), undefined, [ + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), + /*typeArguments*/ undefined, [ thisArg ].concat(argumentsList)), location); } ts.createFunctionCall = createFunctionCall; function createFunctionApply(func, thisArg, argumentsExpression, location) { - return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), undefined, [ + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), + /*typeArguments*/ undefined, [ thisArg, argumentsExpression ]), location); @@ -43532,32 +52965,39 @@ var ts; if (start !== undefined) { argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start); } - return ts.createCall(ts.createPropertyAccess(array, "slice"), undefined, argumentsList); + return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); } ts.createArraySlice = createArraySlice; function createArrayConcat(array, values) { - return ts.createCall(ts.createPropertyAccess(array, "concat"), undefined, values); + return ts.createCall(ts.createPropertyAccess(array, "concat"), + /*typeArguments*/ undefined, values); } ts.createArrayConcat = createArrayConcat; function createMathPow(left, right, location) { - return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), undefined, [left, right]), location); + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), + /*typeArguments*/ undefined, [left, right]), location); } ts.createMathPow = createMathPow; function createReactNamespace(reactNamespace, parent) { + // To ensure the emit resolver can properly resolve the namespace, we need to + // treat this identifier as if it were a source tree node by clearing the `Synthesized` + // flag and setting a parent node. var react = ts.createIdentifier(reactNamespace || "React"); - react.flags &= ~8; + react.flags &= ~8 /* Synthesized */; + // Set the parent that is in parse tree + // this makes sure that parent chain is intact for checker to traverse complete scope tree react.parent = ts.getParseTreeNode(parent); return react; } function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); + return createReactNamespace(ts.idText(jsxFactory), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -43577,7 +53017,7 @@ var ts; if (children.length > 1) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; - child.startsOnNewLine = true; + startOnNewLine(child); argumentsList.push(child); } } @@ -43585,11 +53025,33 @@ var ts; argumentsList.push(children[0]); } } - return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), undefined, argumentsList), location); + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); } ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; + // Helpers function getHelperName(name) { - return ts.setEmitFlags(ts.createIdentifier(name), 4096 | 2); + return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); } ts.getHelperName = getHelperName; var valuesHelper = { @@ -43599,7 +53061,8 @@ var ts; }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); - return ts.setTextRange(ts.createCall(getHelperName("__values"), undefined, [expression]), location); + return ts.setTextRange(ts.createCall(getHelperName("__values"), + /*typeArguments*/ undefined, [expression]), location); } ts.createValuesHelper = createValuesHelper; var readHelper = { @@ -43609,7 +53072,8 @@ var ts; }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); - return ts.setTextRange(ts.createCall(getHelperName("__read"), undefined, count !== undefined + return ts.setTextRange(ts.createCall(getHelperName("__read"), + /*typeArguments*/ undefined, count !== undefined ? [iteratorRecord, ts.createLiteral(count)] : [iteratorRecord]), location); } @@ -43622,18 +53086,23 @@ var ts; function createSpreadHelper(context, argumentList, location) { context.requestEmitHelper(readHelper); context.requestEmitHelper(spreadHelper); - return ts.setTextRange(ts.createCall(getHelperName("__spread"), undefined, argumentList), location); + return ts.setTextRange(ts.createCall(getHelperName("__spread"), + /*typeArguments*/ undefined, argumentList), location); } ts.createSpreadHelper = createSpreadHelper; + // Utilities function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { var firstDeclaration = ts.firstOrUndefined(node.declarations); - var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, undefined, boundValue); - return ts.setTextRange(ts.createVariableStatement(undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), node); + var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, + /*typeNode*/ undefined, boundValue); + return ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), + /*location*/ node); } else { - var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), node); - return ts.setTextRange(ts.createStatement(updatedExpression), node); + var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node); + return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node); } } ts.createForOfBindingStatement = createForOfBindingStatement; @@ -43642,7 +53111,7 @@ var ts; return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements)); } else { - return ts.createBlock(ts.createNodeArray([dest, source]), true); + return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true); } } ts.insertLeadingStatement = insertLeadingStatement; @@ -43650,7 +53119,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 222 + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 223 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -43662,46 +53131,47 @@ var ts; function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { var target = skipParentheses(node); switch (target.kind) { - case 71: + case 71 /* Identifier */: return cacheIdentifiers; - case 99: - case 8: - case 9: + case 99 /* ThisKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: return false; - case 177: + case 178 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 178: + case 179 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { - var callee = skipOuterExpressions(expression, 7); + var callee = skipOuterExpressions(expression, 7 /* All */); var thisArg; var target; if (ts.isSuperProperty(callee)) { thisArg = ts.createThis(); target = callee; } - else if (callee.kind === 97) { + else if (callee.kind === 97 /* SuperKeyword */) { thisArg = ts.createThis(); - target = languageVersion < 2 + target = languageVersion < 2 /* ES2015 */ ? ts.setTextRange(ts.createIdentifier("_super"), callee) : callee; } - else if (ts.getEmitFlags(callee) & 4096) { + else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) { thisArg = ts.createVoidZero(); target = parenthesizeForAccess(callee); } else { switch (callee.kind) { - case 179: { + case 180 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name); ts.setTextRange(target, callee); @@ -43712,8 +53182,9 @@ var ts; } break; } - case 180: { + case 181 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); ts.setTextRange(target, callee); @@ -43725,6 +53196,7 @@ var ts; break; } default: { + // for `a()` target is `a` and thisArg is `void 0` thisArg = ts.createVoidZero(); target = parenthesizeForAccess(expression); break; @@ -43735,6 +53207,8 @@ var ts; } ts.createCallBinding = createCallBinding; function inlineExpressions(expressions) { + // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call + // stack size exceeded" errors. return expressions.length > 10 ? ts.createCommaList(expressions) : ts.reduceLeft(expressions, ts.createComma); @@ -43765,14 +53239,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 261: + case 265 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 262: + case 266 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 151: + case 152 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -43782,14 +53256,22 @@ var ts; if (property === firstAccessor) { var properties_9 = []; if (getAccessor) { - var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); + var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, getAccessor.parameters, + /*type*/ undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); properties_9.push(getter); } if (setAccessor) { - var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); + var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, setAccessor.parameters, + /*type*/ undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); @@ -43797,48 +53279,107 @@ var ts; } properties_9.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); properties_9.push(ts.createPropertyAssignment("configurable", ts.createTrue())); - var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), ts.createObjectLiteral(properties_9, multiLine) - ]), firstAccessor); + ]), + /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); } return undefined; } function createExpressionForPropertyAssignment(property, receiver) { - return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), property.initializer), property), property)); + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property)); } function createExpressionForShorthandPropertyAssignment(property, receiver) { - return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, property.name), ts.getSynthesizedClone(property.name)), property), property)); + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), + /*location*/ property), + /*original*/ property)); } function createExpressionForMethodDeclaration(method, receiver) { - return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method)); - } + return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, + /*name*/ undefined, + /*typeParameters*/ undefined, method.parameters, + /*type*/ undefined, method.body), + /*location*/ method), + /*original*/ method)), + /*location*/ method), + /*original*/ method)); + } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ function getInternalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 16384 | 32768); + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); } ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ function isInternalName(node) { - return (ts.getEmitFlags(node) & 32768) !== 0; + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; } ts.isInternalName = isInternalName; + /** + * Gets the local name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A + * local name will *never* be prefixed with an module or namespace export modifier like + * "exports." when emitted as an expression. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 16384); + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */); } ts.getLocalName = getLocalName; + /** + * Gets whether an identifier should only be referred to by its local name. + */ function isLocalName(node) { - return (ts.getEmitFlags(node) & 16384) !== 0; + return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0; } ts.isLocalName = isLocalName; + /** + * Gets the export name of a declaration. This is primarily used for declarations that can be + * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An + * export name will *always* be prefixed with an module or namespace export modifier like + * `"exports."` when emitted as an expression if the name points to an exported symbol. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ function getExportName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 8192); + return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */); } ts.getExportName = getExportName; + /** + * Gets whether an identifier should only be referred to by its export representation if the + * name points to an exported symbol. + */ function isExportName(node) { - return (ts.getEmitFlags(node) & 8192) !== 0; + return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0; } ts.isExportName = isExportName; + /** + * Gets the name of a declaration for use in declarations. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ function getDeclarationName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps); } @@ -43846,33 +53387,52 @@ var ts; function getName(node, allowComments, allowSourceMaps, emitFlags) { var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { - var name_37 = ts.getMutableClone(nodeName); + var name = ts.getMutableClone(nodeName); emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) - emitFlags |= 48; + emitFlags |= 48 /* NoSourceMap */; if (!allowComments) - emitFlags |= 1536; + emitFlags |= 1536 /* NoComments */; if (emitFlags) - ts.setEmitFlags(name_37, emitFlags); - return name_37; + ts.setEmitFlags(name, emitFlags); + return name; } return ts.getGeneratedNameForNode(node); } + /** + * Gets the exported name of a declaration for use in expressions. + * + * An exported name will *always* be prefixed with an module or namespace export modifier like + * "exports." if the name points to an exported symbol. + * + * @param ns The namespace identifier. + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { - if (ns && ts.hasModifier(node, 1)) { + if (ns && ts.hasModifier(node, 1 /* Export */)) { return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); } return getExportName(node, allowComments, allowSourceMaps); } ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName; + /** + * Gets a namespace-qualified name for use in expressions. + * + * @param ns The namespace identifier. + * @param name The name. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); var emitFlags; if (!allowSourceMaps) - emitFlags |= 48; + emitFlags |= 48 /* NoSourceMap */; if (!allowComments) - emitFlags |= 1536; + emitFlags |= 1536 /* NoComments */; if (emitFlags) ts.setEmitFlags(qualifiedName, emitFlags); return qualifiedName; @@ -43887,8 +53447,8 @@ var ts; var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); - if (node.startsOnNewLine) { - updated.startsOnNewLine = true; + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); } ts.aggregateTransformFlags(updated); return updated; @@ -43897,11 +53457,28 @@ var ts; function isUseStrictPrologue(node) { return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } + /** + * Add any necessary prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + * + * @param target: result statements array + * @param source: origin statements array + * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives + * @param visitor: Optional callback used to visit any custom prologue directives. + */ function addPrologue(target, source, ensureUseStrict, visitor) { var offset = addStandardPrologue(target, source, ensureUseStrict); return addCustomPrologue(target, source, offset, visitor); } ts.addPrologue = addPrologue; + /** + * Add just the standard (string-expression) prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ function addStandardPrologue(target, source, ensureUseStrict) { ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; @@ -43926,12 +53503,18 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; + /** + * Add just the custom prologue-directives into target statement-array. + * The function needs to be called during each transformation step. + * This function needs to be called whenever we transform the statement + * list of a source file, namespace, or function-like body. + */ function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { break; @@ -43948,6 +53531,11 @@ var ts; && isUseStrictPrologue(firstStatement); } ts.startsWithUseStrict = startsWithUseStrict; + /** + * Ensures "use strict" directive is added + * + * @param statements An array of statements + */ function ensureUseStrict(statements) { var foundUseStrict = false; for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { @@ -43970,9 +53558,19 @@ var ts; return statements; } ts.ensureUseStrict = ensureUseStrict; + /** + * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended + * order of operations. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 185) { + // If the resulting expression is already parenthesized, we do not need to do any further processing. + if (skipped.kind === 186 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -43980,55 +53578,131 @@ var ts; : operand; } ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand; + /** + * Determines whether the operand to a BinaryExpression needs to be parenthesized. + * + * @param binaryOperator The operator for the BinaryExpression. + * @param operand The operand for the BinaryExpression. + * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the + * BinaryExpression. + */ function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(194, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(194, binaryOperator); + // If the operand has lower precedence, then it needs to be parenthesized to preserve the + // intent of the expression. For example, if the operand is `a + b` and the operator is + // `*`, then we need to parenthesize the operand to preserve the intended order of + // operations: `(a + b) * x`. + // + // If the operand has higher precedence, then it does not need to be parenthesized. For + // example, if the operand is `a * b` and the operator is `+`, then we do not need to + // parenthesize to preserve the intended order of operations: `a * b + x`. + // + // If the operand has the same precedence, then we need to check the associativity of + // the operator based on whether this is the left or right operand of the expression. + // + // For example, if `a / d` is on the right of operator `*`, we need to parenthesize + // to preserve the intended order of operations: `x * (a / d)` + // + // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve + // the intended order of operations: `(a ** b) ** c` + var binaryOperatorPrecedence = ts.getOperatorPrecedence(195 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(195 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { - case -1: + case -1 /* LessThan */: + // If the operand is the right side of a right-associative binary operation + // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary - && binaryOperatorAssociativity === 1 - && operand.kind === 197) { + && binaryOperatorAssociativity === 1 /* Right */ + && operand.kind === 198 /* YieldExpression */) { return false; } return true; - case 1: + case 1 /* GreaterThan */: return false; - case 0: + case 0 /* EqualTo */: if (isLeftSideOfBinary) { - return binaryOperatorAssociativity === 1; + // No need to parenthesize the left operand when the binary operator is + // left associative: + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x + // + // Parentheses are needed for the left operand when the binary operator is + // right associative: + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x + return binaryOperatorAssociativity === 1 /* Right */; } else { if (ts.isBinaryExpression(emittedOperand) && emittedOperand.operatorToken.kind === binaryOperator) { + // No need to parenthesize the right operand when the binary operator and + // operand are the same and one of the following: + // x*(a*b) => x*a*b + // x|(a|b) => x|a|b + // x&(a&b) => x&a&b + // x^(a^b) => x^a^b if (operatorHasAssociativeProperty(binaryOperator)) { return false; } - if (binaryOperator === 37) { - var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0; + // No need to parenthesize the right operand when the binary operator + // is plus (+) if both the left and right operands consist solely of either + // literals of the same kind or binary plus (+) expressions for literals of + // the same kind (recursively). + // "a"+(1+2) => "a"+(1+2) + // "a"+("b"+"c") => "a"+"b"+"c" + if (binaryOperator === 37 /* PlusToken */) { + var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { return false; } } } + // No need to parenthesize the right operand when the operand is right + // associative: + // x/(a**b) -> x/a**b + // x**(a**b) -> x**a**b + // + // Parentheses are needed for the right operand when the operand is left + // associative: + // x/(a*b) -> x/(a*b) + // x**(a/b) -> x**(a/b) var operandAssociativity = ts.getExpressionAssociativity(emittedOperand); - return operandAssociativity === 0; + return operandAssociativity === 0 /* Left */; } } } + /** + * Determines whether a binary operator is mathematically associative. + * + * @param binaryOperator The binary operator. + */ function operatorHasAssociativeProperty(binaryOperator) { - return binaryOperator === 39 - || binaryOperator === 49 - || binaryOperator === 48 - || binaryOperator === 50; - } + // The following operators are associative in JavaScript: + // (a*b)*c -> a*(b*c) -> a*b*c + // (a|b)|c -> a|(b|c) -> a|b|c + // (a&b)&c -> a&(b&c) -> a&b&c + // (a^b)^c -> a^(b^c) -> a^b^c + // + // While addition is associative in mathematics, JavaScript's `+` is not + // guaranteed to be associative as it is overloaded with string concatenation. + return binaryOperator === 39 /* AsteriskToken */ + || binaryOperator === 49 /* BarToken */ + || binaryOperator === 48 /* AmpersandToken */ + || binaryOperator === 50 /* CaretToken */; + } + /** + * This function determines whether an expression consists of a homogeneous set of + * literal expressions or binary plus expressions that all share the same literal kind. + * It is used to determine whether the right-hand operand of a binary plus expression can be + * emitted without parentheses. + */ function getLiteralKindOfBinaryPlusOperand(node) { node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 194 && node.operatorToken.kind === 37) { + if (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -44036,45 +53710,87 @@ var ts; var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind - : 0; + : 0 /* Unknown */; node.cachedLiteralKind = literalKind; return literalKind; } - return 0; + return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); + var conditionalPrecedence = ts.getOperatorPrecedence(196 /* ConditionalExpression */, 55 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { return ts.createParen(condition); } return condition; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 194 && e.operatorToken.kind === 26 + // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions + // so in case when comma expression is introduced as a part of previous transformations + // if should be wrapped in parens since comma operator has the lowest precedence + return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ ? ts.createParen(e) : e; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + return (check.kind === 200 /* ClassExpression */ || + check.kind === 187 /* FunctionExpression */ || + check.kind === 293 /* CommaListExpression */ || + ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) + ? ts.createParen(e) + : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression + * as the expression of a NewExpression node. + * + * @param expression The Expression node. + */ function parenthesizeForNew(expression) { - var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); - switch (emittedExpression.kind) { - case 181: + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 182 /* CallExpression */: return ts.createParen(expression); - case 182: - return emittedExpression.arguments - ? expression - : ts.createParen(expression); + case 183 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; } return parenthesizeForAccess(expression); } ts.parenthesizeForNew = parenthesizeForNew; + /** + * Wraps an expression in parentheses if it is needed in order to use the expression for + * property or element access. + * + * @param expr The expression node. + */ function parenthesizeForAccess(expression) { + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exception is: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 182 || emittedExpression.arguments)) { + && (emittedExpression.kind !== 183 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -44112,7 +53828,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(194, 26); + var commaPrecedence = ts.getOperatorPrecedence(195 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -44123,14 +53839,14 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 186 || kind === 187) { + if (kind === 187 /* FunctionExpression */ || kind === 188 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreateOuterExpressions(expression, mutableCall, 4); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 179 /* ObjectLiteralExpression */ || leftmostExpressionKind === 187 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; @@ -44138,10 +53854,10 @@ var ts; ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 166: - case 167: - case 160: - case 161: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return ts.createParenthesizedType(member); } return member; @@ -44149,8 +53865,8 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 162: - case 170: + case 163 /* TypeQuery */: + case 171 /* TypeOperator */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -44173,24 +53889,28 @@ var ts; } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function getLeftmostExpression(node) { + function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 193: + case 194 /* PostfixUnaryExpression */: node = node.operand; continue; - case 194: + case 195 /* BinaryExpression */: node = node.left; continue; - case 195: + case 196 /* ConditionalExpression */: node = node.condition; continue; - case 181: - case 180: - case 179: + case 182 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 181 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: node = node.expression; continue; - case 288: + case 292 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -44198,7 +53918,7 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body).kind === 178) { + if (!ts.isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 179 /* ObjectLiteralExpression */) { return ts.setTextRange(ts.createParen(body), body); } return body; @@ -44212,32 +53932,32 @@ var ts; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function isOuterExpression(node, kinds) { - if (kinds === void 0) { kinds = 7; } + if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 185: - return (kinds & 1) !== 0; - case 184: - case 202: - case 203: - return (kinds & 2) !== 0; - case 288: - return (kinds & 4) !== 0; + case 186 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 204 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 292 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; } ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { - if (kinds === void 0) { kinds = 7; } + if (kinds === void 0) { kinds = 7 /* All */; } var previousNode; do { previousNode = node; - if (kinds & 1) { + if (kinds & 1 /* Parentheses */) { node = skipParentheses(node); } - if (kinds & 2) { + if (kinds & 2 /* Assertions */) { node = skipAssertions(node); } - if (kinds & 4) { + if (kinds & 4 /* PartiallyEmittedExpressions */) { node = ts.skipPartiallyEmittedExpressions(node); } } while (previousNode !== node); @@ -44245,14 +53965,14 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 185) { + while (node.kind === 186 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 203) { + while (ts.isAssertionExpression(node) || node.kind === 204 /* NonNullExpression */) { node = node.expression; } return node; @@ -44260,15 +53980,29 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 185: return ts.updateParen(outerExpression, expression); - case 184: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 202: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 203: return ts.updateNonNullExpression(outerExpression, expression); - case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); - } - } + case 186 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 185 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 203 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 204 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 292 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + } + } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ function isIgnorableParen(node) { - return node.kind === 185 + return node.kind === 186 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -44276,7 +54010,7 @@ var ts; && !ts.some(ts.getSyntheticTrailingComments(node)); } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { - if (kinds === void 0) { kinds = 7; } + if (kinds === void 0) { kinds = 7 /* All */; } if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } @@ -44284,8 +54018,7 @@ var ts; } ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { - node.startsOnNewLine = true; - return node; + return ts.setStartsOnNewLine(node, /*newLine*/ true); } ts.startOnNewLine = startOnNewLine; function getExternalHelpersModuleName(node) { @@ -44325,24 +54058,35 @@ var ts; } } ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; + /** + * Get the name of that target module from an import or export declaration + */ function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name_38 = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name_38) ? name_38 : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + var name = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 238 && node.importClause) { + if (node.kind === 239 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 244 && node.moduleSpecifier) { + if (node.kind === 245 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; + /** + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 9) { + if (moduleName.kind === 9 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) || ts.getSynthesizedClone(moduleName); @@ -44350,10 +54094,21 @@ var ts; return undefined; } ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral; + /** + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ function tryRenameExternalModule(moduleName, sourceFile) { var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); return rename && ts.createLiteral(rename); } + /** + * Get the name of a module as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function tryGetModuleNameFromFile(file, host, options) { if (!file) { return undefined; @@ -44370,65 +54125,139 @@ var ts; function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } + /** + * Gets the initializer of an BindingOrAssignmentElement. + */ function getInitializerOfBindingOrAssignmentElement(bindingElement) { if (ts.isDeclarationBindingElement(bindingElement)) { + // `1` in `let { a = 1 } = ...` + // `1` in `let { a: b = 1 } = ...` + // `1` in `let { a: {b} = 1 } = ...` + // `1` in `let { a: [b] = 1 } = ...` + // `1` in `let [a = 1] = ...` + // `1` in `let [{a} = 1] = ...` + // `1` in `let [[a] = 1] = ...` return bindingElement.initializer; } if (ts.isPropertyAssignment(bindingElement)) { - return ts.isAssignmentExpression(bindingElement.initializer, true) + // `1` in `({ a: b = 1 } = ...)` + // `1` in `({ a: {b} = 1 } = ...)` + // `1` in `({ a: [b] = 1 } = ...)` + return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) ? bindingElement.initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { + // `1` in `({ a = 1 } = ...)` return bindingElement.objectAssignmentInitializer; } - if (ts.isAssignmentExpression(bindingElement, true)) { + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `1` in `[a = 1] = ...` + // `1` in `[{a} = 1] = ...` + // `1` in `[[a] = 1] = ...` return bindingElement.right; } if (ts.isSpreadElement(bindingElement)) { + // Recovery consistent with existing emit. return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); } } ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement; + /** + * Gets the name of an BindingOrAssignmentElement. + */ function getTargetOfBindingOrAssignmentElement(bindingElement) { if (ts.isDeclarationBindingElement(bindingElement)) { + // `a` in `let { a } = ...` + // `a` in `let { a = 1 } = ...` + // `b` in `let { a: b } = ...` + // `b` in `let { a: b = 1 } = ...` + // `a` in `let { ...a } = ...` + // `{b}` in `let { a: {b} } = ...` + // `{b}` in `let { a: {b} = 1 } = ...` + // `[b]` in `let { a: [b] } = ...` + // `[b]` in `let { a: [b] = 1 } = ...` + // `a` in `let [a] = ...` + // `a` in `let [a = 1] = ...` + // `a` in `let [...a] = ...` + // `{a}` in `let [{a}] = ...` + // `{a}` in `let [{a} = 1] = ...` + // `[a]` in `let [[a]] = ...` + // `[a]` in `let [[a] = 1] = ...` return bindingElement.name; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 261: + case 265 /* PropertyAssignment */: + // `b` in `({ a: b } = ...)` + // `b` in `({ a: b = 1 } = ...)` + // `{b}` in `({ a: {b} } = ...)` + // `{b}` in `({ a: {b} = 1 } = ...)` + // `[b]` in `({ a: [b] } = ...)` + // `[b]` in `({ a: [b] = 1 } = ...)` + // `b.c` in `({ a: b.c } = ...)` + // `b.c` in `({ a: b.c = 1 } = ...)` + // `b[0]` in `({ a: b[0] } = ...)` + // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 262: + case 266 /* ShorthandPropertyAssignment */: + // `a` in `({ a } = ...)` + // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 263: + case 267 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } + // no target return undefined; } - if (ts.isAssignmentExpression(bindingElement, true)) { + if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + // `a` in `[a = 1] = ...` + // `{a}` in `[{a} = 1] = ...` + // `[a]` in `[[a] = 1] = ...` + // `a.b` in `[a.b = 1] = ...` + // `a[0]` in `[a[0] = 1] = ...` return getTargetOfBindingOrAssignmentElement(bindingElement.left); } if (ts.isSpreadElement(bindingElement)) { + // `a` in `[...a] = ...` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } + // `a` in `[a] = ...` + // `{a}` in `[{a}] = ...` + // `[a]` in `[[a]] = ...` + // `a.b` in `[a.b] = ...` + // `a[0]` in `[a[0]] = ...` return bindingElement; } ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; + /** + * Determines whether an BindingOrAssignmentElement is a rest element. + */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 146: - case 176: + case 147 /* Parameter */: + case 177 /* BindingElement */: + // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 198: - case 263: + case 199 /* SpreadElement */: + case 267 /* SpreadAssignment */: + // `...` in `[...a] = ...` return bindingElement; } return undefined; } ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement; + /** + * Gets the property name of a BindingOrAssignmentElement + */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 176: + case 177 /* BindingElement */: + // `a` in `let { a: b } = ...` + // `[a]` in `let { [a]: b } = ...` + // `"a"` in `let { "a": b } = ...` + // `1` in `let { 1: b } = ...` if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) @@ -44436,7 +54265,11 @@ var ts; : propertyName; } break; - case 261: + case 265 /* PropertyAssignment */: + // `a` in `({ a: b } = ...)` + // `[a]` in `({ [a]: b } = ...)` + // `"a"` in `({ "a": b } = ...)` + // `1` in `({ 1: b } = ...)` if (bindingElement.name) { var propertyName = bindingElement.name; return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) @@ -44444,7 +54277,8 @@ var ts; : propertyName; } break; - case 263: + case 267 /* SpreadAssignment */: + // `a` in `({ ...a } = ...)` return bindingElement.name; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); @@ -44456,13 +54290,19 @@ var ts; ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + /** + * Gets the elements of a BindingOrAssignmentPattern + */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 174: - case 175: - case 177: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: + // `a` in `{a}` + // `a` in `[a]` return name.elements; - case 178: + case 179 /* ObjectLiteralExpression */: + // `a` in `{a}` return name.properties; } } @@ -44501,11 +54341,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 174: - case 178: + case 175 /* ObjectBindingPattern */: + case 179 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -44535,6 +54375,9 @@ var ts; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; })(ts || (ts = {})); +/// +/// +/// var ts; (function (ts) { function visitNode(node, visitor, test, lift) { @@ -44561,11 +54404,21 @@ var ts; return visitedNode; } ts.visitNode = visitNode; + /** + * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. + * + * @param nodes The NodeArray to visit. + * @param visitor The callback used to visit a Node. + * @param test A node test to execute for each node. + * @param start An optional value indicating the starting offset at which to start visiting. + * @param count An optional value indicating the maximum number of nodes to visit. + */ function visitNodes(nodes, visitor, test, start, count) { if (nodes === undefined || visitor === undefined) { return nodes; } var updated; + // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { start = 0; @@ -44574,14 +54427,19 @@ var ts; count = length - start; } if (start > 0 || count < length) { - updated = ts.createNodeArray([], nodes.hasTrailingComma && start + count === length); + // If we are not visiting all of the original nodes, we must always create a new array. + // Since this is a fragment of a node array, we do not copy over the previous location + // and will only copy over `hasTrailingComma` if we are including the last element. + updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length); } + // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; ts.aggregateTransformFlags(node); var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { + // Ensure we have a copy of `nodes`, up to the current index. updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma); ts.setTextRange(updated, nodes); } @@ -44605,6 +54463,10 @@ var ts; return updated || nodes; } ts.visitNodes = visitNodes; + /** + * Starts a new lexical environment and visits a statement list, ending the lexical environment + * and merging hoisted declarations upon completion. + */ function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) { context.startLexicalEnvironment(); statements = visitNodes(statements, visitor, ts.isStatement, start); @@ -44615,6 +54477,10 @@ var ts; return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; + /** + * Starts a new lexical environment and visits a parameter list, suspending the lexical + * environment upon completion. + */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } context.startLexicalEnvironment(); @@ -44641,260 +54507,285 @@ var ts; return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 142) || kind === 169) { + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 143 /* LastToken */) || kind === 170 /* ThisType */) { return node; } switch (kind) { - case 71: + // Names + case 71 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 143: + case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 144: + case 145 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); - case 145: + // Signature elements + case 146 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 146: + case 147 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 147: + case 148 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); - case 148: + // Type elements + case 149 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149: + case 150 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150: + case 151 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 151: + case 152 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152: + case 153 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153: + case 154 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154: + case 155 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 155: + case 156 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156: + case 157 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 157: + case 158 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 158: + // Types + case 159 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 159: + case 160 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 160: + case 161 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161: + case 162 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 162: + case 163 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 163: + case 164 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 164: + case 165 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 165: + case 166 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 166: + case 167 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 167: + case 168 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 168: + case 169 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170: + case 171 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171: + case 172 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 172: + case 173 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 173: + case 174 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); - case 174: + // Binding patterns + case 175 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 175: + case 176 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 176: + case 177 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); - case 177: + // Expression + case 178 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 178: + case 179 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 179: + case 180 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 180: + case 181 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 181: + case 182 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 182: + case 183 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 183: + case 184 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 184: + case 185 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 185: + case 186 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 186: + case 187 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 187: + case 188 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 188: + case 189 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 189: + case 190 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 190: + case 191 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191: + case 192 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192: + case 193 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 193: + case 194 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 194: + case 195 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 195: + case 196 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 196: + case 197 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 197: + case 198 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 198: + case 199 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199: + case 200 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 201: + case 202 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 202: + case 203 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 203: + case 204 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 204: + case 205 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 205: + // Misc + case 206 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - case 207: + // Element + case 208 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 208: + case 209 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 210: + case 211 /* ExpressionStatement */: return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 211: + case 212 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 212: + case 213 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 213: + case 214 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 214: + case 215 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 215: + case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 216: + case 217 /* ForOfStatement */: return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 217: + case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 218: + case 219 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 219: + case 220 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220: + case 221 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 221: + case 222 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 222: + case 223 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223: + case 224 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 224: + case 225 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 226: + case 227 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 227: + case 228 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 228: + case 229 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 229: + case 230 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 230: + case 231 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 231: + case 232 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 232: + case 233 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 233: + case 234 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 234: + case 235 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 235: + case 236 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 236: + case 237 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 237: + case 238 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 238: + case 239 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 239: + case 240 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 240: + case 241 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 241: + case 242 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 242: + case 243 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 243: + case 244 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 244: + case 245 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 245: + case 246 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 246: + case 247 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 248: + // Module references + case 249 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); - case 249: + // JSX + case 250 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 250: + case 251 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 251: + case 252 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 252: + case 253 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 253: + case 254 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 257 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 254: + case 258 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 255: + case 259 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 256: + case 260 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 257: + // Clauses + case 261 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258: + case 262 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 259: + case 263 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 260: + case 264 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); - case 261: + // Property assignments + case 265 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 262: + case 266 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 263: + case 267 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); - case 264: + // Enum + case 268 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 265: + // Top-level nodes + case 269 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 288: + // Transformation nodes + case 292 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 289: + case 293 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: + // No need to visit nodes with no children. return node; } } ts.visitEachChild = visitEachChild; + /** + * Extracts the single node from a NodeArray. + * + * @param nodes The NodeArray. + */ function extractSingleNode(nodes) { ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); return ts.singleOrUndefined(nodes); } })(ts || (ts = {})); +/* @internal */ (function (ts) { function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; @@ -44902,6 +54793,14 @@ var ts; function reduceNodeArray(nodes, f, initial) { return nodes ? f(initial, nodes) : initial; } + /** + * Similar to `reduceLeft`, performs a reduction against each child of a node. + * NOTE: Unlike `forEachChild`, this does *not* visit every node. + * + * @param node The node containing the children to reduce. + * @param initial The initial value to supply to the reduction. + * @param f The callback function + */ function reduceEachChild(node, initial, cbNode, cbNodeArray) { if (node === undefined) { return initial; @@ -44909,52 +54808,59 @@ var ts; var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; - if ((kind > 0 && kind <= 142)) { + // No need to visit nodes with no children. + if ((kind > 0 /* FirstToken */ && kind <= 143 /* LastToken */)) { return initial; } - if ((kind >= 158 && kind <= 173)) { + // We do not yet support types. + if ((kind >= 159 /* TypePredicate */ && kind <= 174 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { - case 206: - case 209: - case 200: - case 225: - case 287: + // Leaf nodes + case 207 /* SemicolonClassElement */: + case 210 /* EmptyStatement */: + case 201 /* OmittedExpression */: + case 226 /* DebuggerStatement */: + case 291 /* NotEmittedStatement */: + // No need to visit nodes with no children. break; - case 143: + // Names + case 144 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 144: + case 145 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; - case 146: + // Signature elements + case 147 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 147: + case 148 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; - case 148: + // Type member + case 149 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149: + case 150 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151: + case 152 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -44963,12 +54869,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 152: + case 153 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 153: + case 154 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -44976,55 +54882,57 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154: + case 155 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 174: - case 175: + // Binding patterns + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 176: + case 177 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 177: + // Expression + case 178 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 178: + case 179 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 179: + case 180 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 180: + case 181 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 181: + case 182 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 182: + case 183 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 183: + case 184 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 184: + case 185 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 186: + case 187 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -45032,121 +54940,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 187: + case 188 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 185: - case 188: - case 189: - case 190: - case 191: - case 197: - case 198: - case 203: + case 186 /* ParenthesizedExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 192 /* AwaitExpression */: + case 198 /* YieldExpression */: + case 199 /* SpreadElement */: + case 204 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 192: - case 193: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 194: + case 195 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 195: + case 196 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 196: + case 197 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 199: + case 200 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 201: + case 202 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 202: + case 203 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 205: + // Misc + case 206 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; - case 207: + // Element + case 208 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 208: + case 209 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 210: + case 211 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 211: + case 212 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 212: + case 213 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 213: - case 220: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 214: + case 215 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 215: - case 216: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219: - case 223: + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 221: + case 222 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 222: + case 223 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224: + case 225 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 226: + case 227 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 227: + case 228 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 228: + case 229 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -45155,7 +55065,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 229: + case 230 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -45163,126 +55073,139 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 232: + case 233 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 233: + case 234 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 234: + case 235 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 235: + case 236 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 237: + case 238 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 238: + case 239 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 239: + case 240 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 240: + case 241 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 241: - case 245: + case 242 /* NamedImports */: + case 246 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 242: - case 246: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 243: + case 244 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 244: + case 245 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 248: + // Module references + case 249 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; - case 249: + // JSX + case 250 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 250: - case 251: + case 254 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 254: + case 258 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 252: + case 253 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 253: + case 257 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 255: + case 259 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 256: + case 260 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 257: + // Clauses + case 261 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); - case 258: + // falls through + case 262 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 259: + case 263 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 260: + case 264 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; - case 261: + // Property assignments + case 265 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262: + case 266 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 263: + case 267 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; - case 264: + // Enum + case 268 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 265: + // Top-level nodes + case 269 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; - case 288: + // Transformation nodes + case 292 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 289: + case 293 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -45300,21 +55223,36 @@ var ts; : ts.addRange(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; + /** + * Lifts a NodeArray containing only Statement nodes to a block. + * + * @param nodes The NodeArray. + */ function liftToBlock(nodes) { Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block."); return ts.singleOrUndefined(nodes) || ts.createBlock(nodes); } ts.liftToBlock = liftToBlock; + /** + * Aggregates the TransformFlags for a Node and its subtree. + */ function aggregateTransformFlags(node) { aggregateTransformFlagsForNode(node); return node; } ts.aggregateTransformFlags = aggregateTransformFlags; + /** + * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are + * computed first, then the transform flags for the current node are computed from the subtree + * flags and the state of the current node. Finally, the transform flags of the node are + * returned, excluding any flags that should not be included in its parent node's subtree + * flags. + */ function aggregateTransformFlagsForNode(node) { if (node === undefined) { - return 0; + return 0 /* None */; } - if (node.transformFlags & 536870912) { + if (node.transformFlags & 536870912 /* HasComputedFlags */) { return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind); } var subtreeFlags = aggregateTransformFlagsForSubtree(node); @@ -45322,24 +55260,34 @@ var ts; } function aggregateTransformFlagsForNodeArray(nodes) { if (nodes === undefined) { - return 0; + return 0 /* None */; } - var subtreeFlags = 0; - var nodeArrayFlags = 0; + var subtreeFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { var node = nodes_3[_i]; subtreeFlags |= aggregateTransformFlagsForNode(node); - nodeArrayFlags |= node.transformFlags & ~536870912; + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } - nodes.transformFlags = nodeArrayFlags | 536870912; + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; return subtreeFlags; } + /** + * Aggregates the transform flags for the subtree of a node. + */ function aggregateTransformFlagsForSubtree(node) { - if (ts.hasModifier(node, 2) || (ts.isTypeNode(node) && node.kind !== 201)) { - return 0; - } - return reduceEachChild(node, 0, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); - } + // We do not transform ambient declarations or types, so there is no need to + // recursively aggregate transform flags. + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 202 /* ExpressionWithTypeArguments */)) { + return 0 /* None */; + } + // Aggregate the transform flags of each child. + return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes); + } + /** + * Aggregates the TransformFlags of a child node with the TransformFlags of its + * siblings. + */ function aggregateTransformFlagsForChildNode(transformFlags, node) { return transformFlags | aggregateTransformFlagsForNode(node); } @@ -45349,34 +55297,38 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - Debug.failBadSyntaxKind = Debug.shouldAssert(1) + Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } : ts.noop; - Debug.assertEachNode = Debug.shouldAssert(1) + Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; - Debug.assertNode = Debug.shouldAssert(1) + Debug.assertNode = Debug.shouldAssert(1 /* Normal */) ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } : ts.noop; - Debug.assertOptionalNode = Debug.shouldAssert(1) + Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } : ts.noop; - Debug.assertOptionalToken = Debug.shouldAssert(1) + Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } : ts.noop; - Debug.assertMissingNode = Debug.shouldAssert(1) + Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; + /** + * Injects debug information into frequently used types. + */ function enableDebugInfo() { if (isDebugInfoEnabled) return; + // Add additional properties in debug mode to assist with debugging. Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, - "__debugObjectFlags": { get: function () { return this.flags & 32768 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, - "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 65536 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ ts.objectAllocator.getNodeConstructor(), @@ -45388,11 +55340,11 @@ var ts; var ctor = nodeConstructors_1[_i]; if (!ctor.prototype.hasOwnProperty("__debugKind")) { Object.defineProperties(ctor.prototype, { - "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, - "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, - "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, - "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, - "__debugGetText": { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { value: function (includeTrivia) { if (ts.nodeIsSynthesized(this)) return ""; @@ -45409,6 +55361,7 @@ var ts; Debug.enableDebugInfo = enableDebugInfo; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { function getOriginalNodeId(node) { @@ -45428,86 +55381,99 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 238: + case 239 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" externalImports.push(node); break; - case 237: - if (node.moduleReference.kind === 248) { + case 238 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { + // import x = require("mod") externalImports.push(node); } break; - case 244: + case 245 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { + // export * from "mod" externalImports.push(node); hasExportStarsToExportValues = true; } else { + // export { x, y } from "mod" externalImports.push(node); } } else { + // export { x, y } for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { - var name_39 = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.unescapeLeadingUnderscores(name_39.escapedText), specifier); - var decl = resolver.getReferencedImportDeclaration(name_39) - || resolver.getReferencedValueDeclaration(name_39); + if (!uniqueExports.get(ts.idText(specifier.name))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.idText(name), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + uniqueExports.set(ts.idText(specifier.name), true); exportedNames = ts.append(exportedNames, specifier.name); } } } break; - case 243: + case 244 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { + // export = x exportEquals = node; } break; - case 208: - if (ts.hasModifier(node, 1)) { + case 209 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); } } break; - case 228: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { + case 229 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); hasExportDefault = true; } } else { - var name_40 = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name_40.escapedText))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_40); - uniqueExports.set(ts.unescapeLeadingUnderscores(name_40.escapedText), true); - exportedNames = ts.append(exportedNames, name_40); + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); } } } break; - case 229: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { + case 230 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); hasExportDefault = true; } } else { - var name_41 = node.name; - if (name_41 && !uniqueExports.get(ts.unescapeLeadingUnderscores(name_41.escapedText))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_41); - uniqueExports.set(ts.unescapeLeadingUnderscores(name_41.escapedText), true); - exportedNames = ts.append(exportedNames, name_41); + // export class x { } + var name = node.name; + if (name && !uniqueExports.get(ts.idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.idText(name), true); + exportedNames = ts.append(exportedNames, name); } } } @@ -45515,7 +55481,9 @@ var ts; } } var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); - var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { externalImports.unshift(externalHelpersImportDeclaration); } @@ -45532,13 +55500,15 @@ var ts; } } else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { - uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); exportedNames = ts.append(exportedNames, decl.name); } } return exportedNames; } + /** Use a sparse array as a multi-map. */ function multiMapSparseArrayAdd(map, key, value) { var values = map[key]; if (values) { @@ -45549,7 +55519,23 @@ var ts; } return values; } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 /* StringLiteral */ || + expression.kind === 8 /* NumericLiteral */ || + expression.kind === 13 /* NoSubstitutionTemplateLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); +/// +/// +/*@internal*/ var ts; (function (ts) { var FlattenLevel; @@ -45557,6 +55543,17 @@ var ts; FlattenLevel[FlattenLevel["All"] = 0] = "All"; FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest"; })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {})); + /** + * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param level Indicates the extent to which flattening should occur. + * @param needsValue An optional value indicating whether the value from the right-hand-side of + * the destructuring assignment is needed as part of a larger expression. + * @param createAssignmentCallback An optional callback used to create the assignment expression. + */ function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; var value; @@ -45588,13 +55585,25 @@ var ts; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); if (needsValue) { - value = ensureIdentifier(flattenContext, value, true, location); + // If the right-hand value of the destructuring assignment needs to be preserved (as + // is the case when the destructuring assignment is part of a larger expression), + // then we need to cache the right-hand value. + // + // The source map location for the assignment should point to the entire binary + // expression. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); } else if (ts.nodeIsSynthesized(node)) { + // Generally, the source map location for a destructuring assignment is the root + // expression. + // + // However, if the root expression is synthesized (as in the case + // of the initializer when transforming a ForOfStatement), then the source map + // location should point to the right-hand value of the expression. location = value; } } - flattenBindingOrAssignmentElement(flattenContext, node, value, location, ts.isDestructuringAssignment(node)); + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node)); if (value && needsValue) { if (!ts.some(expressions)) { return value; @@ -45603,7 +55612,9 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - ts.setEmitFlags(expression, 64); + // NOTE: this completely disables source maps, but aligns with the behavior of + // `emitAssignment` in the old emitter. + ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -45617,6 +55628,17 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + /** + * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. + * + * @param node The node to flatten. + * @param visitor An optional visitor used to visit initializers. + * @param context The transformation context. + * @param boundValue The value bound to the declaration. + * @param skipInitializer A value indicating whether to ignore the initializer of `node`. + * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. + * @param level Indicates the extent to which flattening should occur. + */ function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { var pendingExpressions; var pendingDeclarations = []; @@ -45635,11 +55657,11 @@ var ts; }; flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { - var temp = ts.createTempVariable(undefined); + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (hoistTempVariables) { var value = ts.inlineExpressions(pendingExpressions); pendingExpressions = undefined; - emitBindingOrAssignment(temp, value, undefined, undefined); + emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); } else { context.hoistVariableDeclaration(temp); @@ -45650,12 +55672,13 @@ var ts; } } for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) { - var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_42 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original; - var variable = ts.createVariableDeclaration(name_42, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); + var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original; + var variable = ts.createVariableDeclaration(name, + /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; - ts.setTextRange(variable, location_2); - if (ts.isIdentifier(name_42)) { - ts.setEmitFlags(variable, 64); + ts.setTextRange(variable, location); + if (ts.isIdentifier(name)) { + ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); } ts.aggregateTransformFlags(variable); declarations.push(variable); @@ -45674,13 +55697,25 @@ var ts; } } ts.flattenDestructuringBinding = flattenDestructuringBinding; + /** + * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param element The element to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + * @param skipInitializer An optional value indicating whether to include the initializer + * for the element. + */ function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { if (!skipInitializer) { var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression); if (initializer) { + // Combine value and initializer value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer; } else if (!value) { + // Use 'void 0' in absence of value and initializer value = ts.createVoidZero(); } } @@ -45692,13 +55727,26 @@ var ts; flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value, location, element); - } - } + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + } + } + /** + * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ObjectBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); var numElements = elements.length; if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -45708,9 +55756,9 @@ var ts; var element = elements[i]; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); - if (flattenContext.level >= 1 - && !(element.transformFlags & (524288 | 1048576)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + if (flattenContext.level >= 1 /* ObjectRest */ + && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -45723,7 +55771,7 @@ var ts; if (ts.isComputedPropertyName(propertyName)) { computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression); } - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); } } else if (i === numElements - 1) { @@ -45739,16 +55787,33 @@ var ts; flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); } } + /** + * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments. + * + * @param flattenContext Options used to control flattening. + * @param parent The parent element of the pattern. + * @param pattern The ArrayBindingOrAssignmentPattern to flatten. + * @param value The current RHS value to assign to the element. + * @param location The location to use for source maps and comments. + */ function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); var numElements = elements.length; - if (flattenContext.level < 1 && flattenContext.downlevelIteration) { + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + // Read the elements of the iterable into an array value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) ? undefined - : numElements, location), false, location); + : numElements, location), + /*reuseIdentifierExpressions*/ false, location); } - else if (numElements !== 1 && (flattenContext.level < 1 || numElements === 0) + else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) || ts.every(elements, ts.isOmittedExpression)) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", + // then we will create temporary variable. var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); } @@ -45756,9 +55821,11 @@ var ts; var restContainingElements; for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (flattenContext.level >= 1) { - if (element.transformFlags & 1048576) { - var temp = ts.createTempVariable(undefined); + if (flattenContext.level >= 1 /* ObjectRest */) { + // If an array pattern contains an ObjectRest, we must cache the result so that we + // can perform the ObjectRest destructuring in a different declaration + if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); } @@ -45774,11 +55841,11 @@ var ts; } else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var rhsValue = ts.createElementAccess(value, i); - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); } else if (i === numElements - 1) { var rhsValue = ts.createArraySlice(value, i); - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); } } if (bindingElements) { @@ -45791,13 +55858,31 @@ var ts; } } } + /** + * Creates an expression used to provide a default value if a value is `undefined` at runtime. + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value to test. + * @param defaultValue The default value to use if `value` is `undefined` at runtime. + * @param location The location to use for source maps and comments. + */ function createDefaultValueCheck(flattenContext, value, defaultValue, location) { - value = ensureIdentifier(flattenContext, value, true, location); + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value); } + /** + * Creates either a PropertyAccessExpression or an ElementAccessExpression for the + * right-hand side of a transformed destructuring assignment. + * + * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation + * + * @param flattenContext Options used to control flattening. + * @param value The RHS value that is the source of the property. + * @param propertyName The destructuring property name. + */ function createDestructuringPropertyAccess(flattenContext, value, propertyName) { if (ts.isComputedPropertyName(propertyName)) { - var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), false, propertyName); + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } else if (ts.isStringOrNumericLiteral(propertyName)) { @@ -45806,22 +55891,33 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name_43 = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); - return ts.createPropertyAccess(value, name_43); - } - } + var name = ts.createIdentifier(ts.idText(propertyName)); + return ts.createPropertyAccess(value, name); + } + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier. + * + * @param flattenContext Options used to control flattening. + * @param value the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + * @param location The location to use for source maps and comments. + */ function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { if (ts.isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - var temp = ts.createTempVariable(undefined); + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location)); } else { - flattenContext.emitBindingOrAssignment(temp, value, location, undefined); + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); } return temp; } @@ -45841,7 +55937,7 @@ var ts; return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement)); } function makeBindingElement(name) { - return ts.createBindingElement(undefined, undefined, name); + return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); } function makeAssignmentElement(name) { return name; @@ -45851,6 +55947,9 @@ var ts; scoped: false, text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" }; + /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement + * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` + */ function createRestCall(context, value, elements, computedTempVariables, location) { context.requestEmitHelper(restHelper); var propertyNames = []; @@ -45861,6 +55960,7 @@ var ts; if (ts.isComputedPropertyName(propertyName)) { var temp = computedTempVariables[computedTempVariableOffset]; computedTempVariableOffset++; + // typeof _tmp === "symbol" ? _tmp : _tmp + "" propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral("")))); } else { @@ -45868,19 +55968,30 @@ var ts; } } } - return ts.createCall(ts.getHelperName("__rest"), undefined, [ + return ts.createCall(ts.getHelperName("__rest"), + /*typeArguments*/ undefined, [ value, ts.setTextRange(ts.createArrayLiteral(propertyNames), location) ]); } })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { + /** + * Indicates whether to emit type metadata in the new format. + */ var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { + /** Enables substitutions for decorated classes. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; + /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; + /* Enables substitutions for unqualified enum members */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); var ClassFacts; @@ -45892,7 +56003,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -45903,23 +56014,50 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179); - context.enableSubstitution(180); + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); + // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; var currentScopeFirstDeclarationsOfName; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ var enabledSubstitutions; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ var classAliases; + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; return transformSourceFile; + /** + * Transform TypeScript-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -45930,61 +56068,100 @@ var ts; currentSourceFile = undefined; return visited; } + /** + * Visits a node, saving and restoring state variables on the stack. + * + * @param node The node to visit. + */ function saveStateAndInvoke(node, f) { + // Save state var savedCurrentScope = currentScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); + // Restore state if (currentScope !== savedCurrentScope) { currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentScope = savedCurrentScope; return visited; } + /** + * Performs actions that should always occur immediately before visiting a node. + * + * @param node The node to visit. + */ function onBeforeVisitNode(node) { switch (node.kind) { - case 265: - case 235: - case 234: - case 207: + case 269 /* SourceFile */: + case 236 /* CaseBlock */: + case 235 /* ModuleBlock */: + case 208 /* Block */: currentScope = node; currentScopeFirstDeclarationsOfName = undefined; break; - case 229: - case 228: - if (ts.hasModifier(node, 2)) { + case 230 /* ClassDeclaration */: + case 229 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { break; } + // Record these declarations provided that they have a name. if (node.name) { recordEmittedDeclarationInScope(node); } else { - ts.Debug.assert(node.kind === 229 || ts.hasModifier(node, 512)); + // These nodes should always have names unless they are default-exports; + // however, class declaration parsing allows for undefined names, so syntactically invalid + // programs may also have an undefined name. + ts.Debug.assert(node.kind === 230 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } break; } } + /** + * General-purpose node visitor. + * + * @param node The node to visit. + */ function visitor(node) { return saveStateAndInvoke(node, visitorWorker); } + /** + * Visits and possibly transforms any node. + * + * @param node The node to visit. + */ function visitorWorker(node) { - if (node.transformFlags & 1) { + if (node.transformFlags & 1 /* TypeScript */) { + // This node is explicitly marked as TypeScript, so we should transform the node. return visitTypeScript(node); } - else if (node.transformFlags & 2) { + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } return node; } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ function sourceElementVisitor(node) { return saveStateAndInvoke(node, sourceElementVisitorWorker); } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 238: - case 237: - case 243: - case 244: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -45993,54 +56170,91 @@ var ts; function visitEllidableStatement(node) { var parsed = ts.getParseTreeNode(node); if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node return node; } switch (node.kind) { - case 238: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 243: + case 244 /* ExportAssignment */: return visitExportAssignment(node); - case 244: + case 245 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); } } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ function namespaceElementVisitor(node) { return saveStateAndInvoke(node, namespaceElementVisitorWorker); } + /** + * Specialized visitor that visits the immediate children of a namespace. + * + * @param node The node to visit. + */ function namespaceElementVisitorWorker(node) { - if (node.kind === 244 || - node.kind === 238 || - node.kind === 239 || - (node.kind === 237 && - node.moduleReference.kind === 248)) { + if (node.kind === 245 /* ExportDeclaration */ || + node.kind === 239 /* ImportDeclaration */ || + node.kind === 240 /* ImportClause */ || + (node.kind === 238 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 249 /* ExternalModuleReference */)) { + // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { + else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { + // This node is explicitly marked as TypeScript, or is exported at the namespace + // level, so we should transform the node. return visitTypeScript(node); } - else if (node.transformFlags & 2) { + else if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } return node; } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ function classElementVisitor(node) { return saveStateAndInvoke(node, classElementVisitorWorker); } + /** + * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * + * @param node The node to visit. + */ function classElementVisitorWorker(node) { switch (node.kind) { - case 152: + case 153 /* Constructor */: + // TypeScript constructors are transformed in `visitClassDeclaration`. + // We elide them here as `visitorWorker` checks transform flags, which could + // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 149: - case 157: - case 153: - case 154: - case 151: + case 150 /* PropertyDeclaration */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + // Fallback to the default visit behavior. return visitorWorker(node); - case 206: + case 207 /* SemicolonClassElement */: return node; default: ts.Debug.failBadSyntaxKind(node); @@ -46048,105 +56262,170 @@ var ts; } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270) { + if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { return undefined; } - else if (currentNamespace && node.kind === 84) { + else if (currentNamespace && node.kind === 84 /* ExportKeyword */) { return undefined; } return node; } + /** + * Branching visitor, visits a TypeScript syntax node. + * + * @param node The node to visit. + */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2) && ts.isStatement(node)) { + if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + // TypeScript ambient declarations are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); } switch (node.kind) { - case 84: - case 79: + case 84 /* ExportKeyword */: + case 79 /* DefaultKeyword */: + // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - case 114: - case 112: - case 113: - case 117: - case 76: - case 124: - case 131: - case 164: - case 165: - case 163: - case 158: - case 145: - case 119: - case 122: - case 136: - case 133: - case 130: - case 105: - case 137: - case 161: - case 160: - case 162: - case 159: - case 166: - case 167: - case 168: - case 169: - case 170: - case 171: - case 172: - case 173: - case 157: - case 147: - case 231: - case 149: - case 236: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 117 /* AbstractKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 131 /* ReadonlyKeyword */: + // TypeScript accessibility and readonly modifiers are elided. + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 164 /* TypeLiteral */: + case 159 /* TypePredicate */: + case 146 /* TypeParameter */: + case 119 /* AnyKeyword */: + case 122 /* BooleanKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 105 /* VoidKeyword */: + case 137 /* SymbolKeyword */: + case 162 /* ConstructorType */: + case 161 /* FunctionType */: + case 163 /* TypeQuery */: + case 160 /* TypeReference */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + case 170 /* ThisType */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 174 /* LiteralType */: + // TypeScript type nodes are elided. + case 158 /* IndexSignature */: + // TypeScript index signatures are elided. + case 148 /* Decorator */: + // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + case 232 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. return undefined; - case 152: + case 150 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 237 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. + return undefined; + case 153 /* Constructor */: return visitConstructor(node); - case 230: + case 231 /* InterfaceDeclaration */: + // TypeScript interfaces are elided, but some comments may be preserved. + // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 229: + case 230 /* ClassDeclaration */: + // This is a class declaration with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures return visitClassDeclaration(node); - case 199: + case 200 /* ClassExpression */: + // This is a class expression with TypeScript syntax extensions. + // + // TypeScript class syntax extensions include: + // - decorators + // - optional `implements` heritage clause + // - parameter property assignments in the constructor + // - property declarations + // - index signatures + // - method overload signatures return visitClassExpression(node); - case 259: + case 263 /* HeritageClause */: + // This is a heritage clause with TypeScript syntax extensions. + // + // TypeScript heritage clause extensions include: + // - `implements` clause return visitHeritageClause(node); - case 201: + case 202 /* ExpressionWithTypeArguments */: + // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 151: + case 152 /* MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. return visitMethodDeclaration(node); - case 153: + case 154 /* GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 154: + case 155 /* SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 228: + case 229 /* FunctionDeclaration */: + // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 186: + case 187 /* FunctionExpression */: + // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 187: + case 188 /* ArrowFunction */: + // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 146: + case 147 /* Parameter */: + // This is a parameter declaration with TypeScript syntax extensions. + // + // TypeScript parameter declaration syntax extensions include: + // - decorators + // - accessibility modifiers + // - the question mark (?) token for optional parameters + // - type annotations + // - this parameters return visitParameter(node); - case 185: + case 186 /* ParenthesizedExpression */: + // ParenthesizedExpressions are TypeScript if their expression is a + // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 184: - case 202: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 181: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182: + case 183 /* NewExpression */: return visitNewExpression(node); - case 203: + case 204 /* NonNullExpression */: + // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 232: + case 233 /* EnumDeclaration */: + // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 208: + case 209 /* VariableStatement */: + // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 226: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 233: + case 234 /* ModuleDeclaration */: + // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: + // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: ts.Debug.failBadSyntaxKind(node); @@ -46154,10 +56433,13 @@ var ts; } } function visitSourceFile(node) { - var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); - return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); + return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + /** + * Tests whether we should emit a __decorate call for a class declaration. + */ function shouldEmitDecorateCallForClass(node) { if (node.decorators && node.decorators.length > 0) { return true; @@ -46168,61 +56450,104 @@ var ts; } return false; } + /** + * Tests whether we should emit a __decorate call for a parameter declaration. + */ function shouldEmitDecorateCallForParameter(parameter) { return parameter.decorators !== undefined && parameter.decorators.length > 0; } function getClassFacts(node, staticProperties) { - var facts = 0; + var facts = 0 /* None */; if (ts.some(staticProperties)) - facts |= 1; - if (ts.getClassExtendsHeritageClauseElement(node)) - facts |= 64; + facts |= 1 /* HasStaticInitializedProperties */; + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) - facts |= 2; + facts |= 2 /* HasConstructorDecorators */; if (ts.childIsDecorated(node)) - facts |= 4; + facts |= 4 /* HasMemberDecorators */; if (isExportOfNamespace(node)) - facts |= 8; + facts |= 8 /* IsExportOfNamespace */; else if (isDefaultExternalModuleExport(node)) - facts |= 32; + facts |= 32 /* IsDefaultExternalExport */; else if (isNamedExternalModuleExport(node)) - facts |= 16; - if (languageVersion <= 1 && (facts & 7)) - facts |= 128; + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } + /** + * Transforms a class declaration with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has decorators. + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * - The class is an export in a TypeScript namespace. + * + * @param node The node to transform. + */ function visitClassDeclaration(node) { - var staticProperties = getInitializedProperties(node, true); + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); - if (facts & 128) { + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { context.startLexicalEnvironment(); } - var name = node.name || (facts & 5 ? ts.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ ? createClassDeclarationHeadWithDecorators(node, name, facts) : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; - if (facts & 1) { - addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); - } - addClassElementDecorationStatements(statements, node, false); - addClassElementDecorationStatements(statements, node, true); + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); + } + // Write any decorators of the node. + addClassElementDecorationStatements(statements, node, /*isStatic*/ false); + addClassElementDecorationStatements(statements, node, /*isStatic*/ true); addConstructorDecorationStatement(statements, node); - if (facts & 128) { - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - ts.setEmitFlags(outer, 1536); + ts.setEmitFlags(outer, 1536 /* NoComments */); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - ts.setEmitFlags(statement, 1536 | 384); + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); - ts.setEmitFlags(iife, 33554432); - var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, iife) + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, iife) ])); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); @@ -46230,129 +56555,355 @@ var ts; ts.startOnNewLine(varStatement); statements = [varStatement]; } - if (facts & 8) { + // If the class is exported as part of a TypeScript namespace, emit the namespace export. + // Otherwise, if the class was exported at the top level and was decorated, emit an export + // declaration or export default for the class. + if (facts & 8 /* IsExportOfNamespace */) { addExportMemberAssignment(statements, node); } - else if (facts & 128 || facts & 2) { - if (facts & 32) { - statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { + statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } - else if (facts & 16) { - statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); + else if (facts & 16 /* IsNamedExternalExport */) { + statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } } if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); } return ts.singleOrMany(statements); } + /** + * Transforms a non-decorated class declaration and appends the resulting statements. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + * @param facts Precomputed facts about the class. + */ function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - var modifiers = !(facts & 128) + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) : undefined; - var classDeclaration = ts.createClassDeclaration(undefined, modifiers, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64) !== 0)); + var classDeclaration = ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); - if (facts & 1) { - emitFlags |= 32; + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 32 /* NoTrailingSourceMap */; } ts.setTextRange(classDeclaration, node); ts.setOriginalNode(classDeclaration, node); ts.setEmitFlags(classDeclaration, emitFlags); return classDeclaration; } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ function createClassDeclarationHeadWithDecorators(node, name, facts) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // var location = ts.moveRangePastDecorators(node); var classAlias = getClassAliasIfNeeded(node); - var declName = ts.getLocalName(node, false, true); + var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, (facts & 64) !== 0); - var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); + var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(declName, undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) - ], 1)); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declName, + /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* Let */)); ts.setOriginalNode(statement, node); ts.setTextRange(statement, location); ts.setCommentRange(statement, node); return statement; } + /** + * Transforms a class expression with TypeScript syntax into compatible ES6. + * + * This function will only be called when one of the following conditions are met: + * - The class has property declarations with initializers. + * - The class contains a constructor that contains parameters with accessibility modifiers. + * + * @param node The node to transform. + */ function visitClassExpression(node) { - var staticProperties = getInitializedProperties(node, true); + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85; })); - var classExpression = ts.createClassExpression(undefined, node.name, undefined, heritageClauses, members); + var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); + var classExpression = ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, node); - if (staticProperties.length > 0) { + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608) { + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of a class with static initializers. + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } + pendingExpressions = savedPendingExpressions; return classExpression; } - function transformClassMembers(node, hasExtendsClause) { + /** + * Transforms the members of a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); - return ts.setTextRange(ts.createNodeArray(members), node.members); - } - function transformConstructor(node, hasExtendsClause) { + return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members); + } + /** + * Transforms (or creates) a constructor for a class. + * + * @param node The current class. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructor(node, isDerivedClass) { + // Check if we have property assignment inside class declaration. + // If there is a property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144; + var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + // If the class does not contain nodes that require a synthesized constructor, + // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); - return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); - } + var body = transformConstructorBody(node, constructor, isDerivedClass); + // constructor(${parameters}) { + // ${body} + // } + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + } + /** + * Transforms (or creates) the parameters for the constructor of a class with + * parameter property assignments or instance property initializers. + * + * @param constructor The constructor declaration. + */ function transformConstructorParameters(constructor) { + // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: + // If constructor is empty, then + // If ClassHeritag_eopt is present and protoParent is not null, then + // Let constructor be the result of parsing the source text + // constructor(...args) { super (...args);} + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Else, + // Let constructor be the result of parsing the source text + // constructor( ){ } + // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // + // While we could emit the '...args' rest parameter, certain later tools in the pipeline might + // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. + // Instead, we'll avoid using a rest parameter and spread into the super call as + // 'super(...arguments)' instead of 'super(...args)', as you can see in "transformConstructorBody". return ts.visitParameterList(constructor && constructor.parameters, visitor, context) || []; } - function transformConstructorBody(node, constructor, hasExtendsClause) { + /** + * Transforms (or creates) a constructor body for a class with parameter property + * assignments or instance property initializers. + * + * @param node The current class. + * @param constructor The current class constructor. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. + */ + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); if (constructor) { indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(constructor, statements); + // Add parameters with property assignments. Transforms this: + // + // constructor (public x, public y) { + // } + // + // Into this: + // + // constructor (x, y) { + // this.x = x; + // this.y = y; + // } + // var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { - statements.push(ts.createStatement(ts.createCall(ts.createSuper(), undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); - } - var properties = getInitializedProperties(node, false); + else if (isDerivedClass) { + // Add a synthetic `super` call: + // + // super(...arguments); + // + statements.push(ts.createStatement(ts.createCall(ts.createSuper(), + /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); + } + // Add the property initializers. Transforms this: + // + // public x = 1; + // + // Into this: + // + // constructor() { + // this.x = 1; + // } + // + var properties = getInitializedProperties(node, /*isStatic*/ false); addInitializedPropertyStatements(statements, properties, ts.createThis()); if (constructor) { + // The class already had a constructor, so we should add the existing statements, skipping the initial super call. ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } + // End the lexical environment. statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); - return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true), constructor ? constructor.body : undefined); - } + return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true), + /*location*/ constructor ? constructor.body : undefined); + } + /** + * Adds super call and preceding prologue directives into the list of statements. + * + * @param ctor The constructor node. + * @returns index of the statement that follows super call + */ function addPrologueDirectivesAndInitialSuperCall(ctor, result) { if (ctor.body) { var statements = ctor.body.statements; - var index = ts.addPrologue(result, statements, false, visitor); + // add prologue directives to the list (if any) + var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor); if (index === statements.length) { + // list contains nothing but prologue directives (or empty) - exit return index; } var statement = statements[index]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -46360,36 +56911,79 @@ var ts; } return 0; } + /** + * Gets all parameters of a constructor that should be transformed into property assignments. + * + * @param node The constructor node. + */ function getParametersWithPropertyAssignments(node) { return ts.filter(node.parameters, isParameterWithPropertyAssignment); } + /** + * Determines whether a parameter should be transformed into a property assignment. + * + * @param parameter The parameter node. + */ function isParameterWithPropertyAssignment(parameter) { - return ts.hasModifier(parameter, 92) + return ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */) && ts.isIdentifier(parameter.name); } + /** + * Transforms a parameter into a property assignment statement. + * + * @param node The parameter declaration. + */ function transformParameterWithPropertyAssignment(node) { ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - ts.setEmitFlags(propertyName, 1536 | 48); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); - ts.setEmitFlags(localName, 1536); + ts.setEmitFlags(localName, 1536 /* NoComments */); return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1))); } + /** + * Gets all property declarations with initializers on either the static or instance side of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to get properties from the static or instance side of the class. + */ function getInitializedProperties(node, isStatic) { return ts.filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); } + /** + * Gets a value indicating whether a class element is a static property declaration with an initializer. + * + * @param member The class element node. + */ function isStaticInitializedProperty(member) { - return isInitializedProperty(member, true); + return isInitializedProperty(member, /*isStatic*/ true); } + /** + * Gets a value indicating whether a class element is an instance property declaration with an initializer. + * + * @param member The class element node. + */ function isInstanceInitializedProperty(member) { - return isInitializedProperty(member, false); - } + return isInitializedProperty(member, /*isStatic*/ false); + } + /** + * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. + * + * @param member The class element node. + * @param isStatic A value indicating whether the member should be a static or instance member. + */ function isInitializedProperty(member, isStatic) { - return member.kind === 149 - && isStatic === ts.hasModifier(member, 32) + return member.kind === 150 /* PropertyDeclaration */ + && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } + /** + * Generates assignment statements for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ function addInitializedPropertyStatements(statements, properties, receiver) { for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { var property = properties_10[_i]; @@ -46399,37 +56993,84 @@ var ts; statements.push(statement); } } + /** + * Generates assignment expressions for property initializers. + * + * @param properties An array of property declarations to transform. + * @param receiver The receiver on which each property should be assigned. + */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; } + /** + * Transforms a property initializer into an assignment statement. + * + * @param property The property declaration. + * @param receiver The object receiving the property assignment. + */ function transformInitializedProperty(property, receiver) { - var propertyName = visitPropertyNameOfClassElement(property); + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); - var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, propertyName); + var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); return ts.createAssignment(memberAccess, initializer); } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); - } - function isStaticDecoratedClassElement(member) { - return isDecoratedClassElement(member, true); - } - function isInstanceDecoratedClassElement(member) { - return isDecoratedClassElement(member, false); - } - function isDecoratedClassElement(member, isStatic) { - return ts.nodeOrChildIsDecorated(member) - && isStatic === ts.hasModifier(member, 32); - } + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); + } + /** + * Determines whether a class member is a static member of a class that is decorated, or + * has parameters that are decorated. + * + * @param member The class member. + */ + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); + } + /** + * Determines whether a class member is an instance member of a class that is decorated, + * or has parameters that are decorated. + * + * @param member The class member. + */ + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStatic === ts.hasModifier(member, 32 /* Static */); + } + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ function getDecoratorsOfParameters(node) { var decorators; if (node) { @@ -46446,6 +57087,12 @@ var ts; } return decorators; } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ function getAllDecoratorsOfConstructor(node) { var decorators = node.decorators; var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); @@ -46457,19 +57104,31 @@ var ts; parameters: parameters }; } + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param node The class node that contains the member. + * @param member The class member. + */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 151: + case 152 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 149: + case 150 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; } } + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param node The class node that contains the accessor. + * @param accessor The class accessor member. + */ function getAllDecoratorsOfAccessors(node, accessor) { if (!accessor.body) { return undefined; @@ -46486,6 +57145,11 @@ var ts; } return { decorators: decorators, parameters: parameters }; } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ function getAllDecoratorsOfMethod(method) { if (!method.body) { return undefined; @@ -46497,6 +57161,11 @@ var ts; } return { decorators: decorators, parameters: parameters }; } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ function getAllDecoratorsOfProperty(property) { var decorators = property.decorators; if (!decorators) { @@ -46504,6 +57173,12 @@ var ts; } return { decorators: decorators }; } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param node The declaration node. + * @param allDecorators An object containing all of the decorators for the declaration. + */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; @@ -46514,14 +57189,30 @@ var ts; addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ function addClassElementDecorationStatements(statements, node, isStatic) { ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { - var member = members_3[_i]; + for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { + var member = members_4[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -46534,29 +57225,79 @@ var ts; } return expressions; } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, true); - var descriptor = languageVersion > 0 - ? member.kind === 149 + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var descriptor = languageVersion > 0 /* ES3 */ + ? member.kind === 150 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. : ts.createNull() : undefined; var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536); + ts.setEmitFlags(helper, 1536 /* NoComments */); return helper; } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ function addConstructorDecorationStatement(statements, node) { var expression = generateConstructorDecorationExpression(node); if (expression) { statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); } } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); @@ -46564,29 +57305,47 @@ var ts; return undefined; } var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - var localName = ts.getLocalName(node, false, true); + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); var decorate = createDecorateHelper(context, decoratorExpressions, localName); var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536); + ts.setEmitFlags(expression, 1536 /* NoComments */); ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); return expression; } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ function transformDecorator(decorator) { return ts.visitNode(decorator.expression, visitor, ts.isExpression); } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ function transformDecoratorsOfParameter(decorators, parameterOffset) { var expressions; if (decorators) { expressions = []; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; - var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, decorator.expression); - ts.setEmitFlags(helper, 1536); + var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, + /*location*/ decorator.expression); + ts.setEmitFlags(helper, 1536 /* NoComments */); expressions.push(helper); } } return expressions; } + /** + * Adds optional type metadata for a declaration. + * + * @param node The declaration node. + * @param decoratorExpressions The destination array to which to add new decorator expressions. + */ function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { addNewTypeMetadata(node, container, decoratorExpressions); @@ -46612,57 +57371,88 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(36), serializeTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(36), serializeParameterTypesOfNode(node, container)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(36), serializeReturnTypeOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(36 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); } if (properties) { - decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, true))); + decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true))); } } } + /** + * Determines whether to emit the "design:type" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 151 - || kind === 153 - || kind === 154 - || kind === 149; - } + return kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 150 /* PropertyDeclaration */; + } + /** + * Determines whether to emit the "design:returntype" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 151; - } + return node.kind === 152 /* MethodDeclaration */; + } + /** + * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. + * The caller should have already tested whether the node has decorators and whether the + * emitDecoratorMetadata compiler option is set. + * + * @param node The node to test. + */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 229: - case 199: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 151: - case 153: - case 154: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return true; } return false; } + /** + * Serializes the type of a node for use with decorator type metadata. + * + * @param node The node that should have its type serialized. + */ function serializeTypeOfNode(node) { switch (node.kind) { - case 149: - case 146: - case 153: + case 150 /* PropertyDeclaration */: + case 147 /* Parameter */: + case 154 /* GetAccessor */: return serializeTypeNode(node.type); - case 154: + case 155 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 229: - case 199: - case 151: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 152 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); } } + /** + * Serializes the types of the parameters of a node for use with decorator type metadata. + * + * @param node The node that should have its parameter types serialized. + */ function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) @@ -46689,7 +57479,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 153) { + if (container && node.kind === 154 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -46697,6 +57487,11 @@ var ts; } return node.parameters; } + /** + * Serializes the return type of a node for use with decorator type metadata. + * + * @param node The node that should have its return type serialized. + */ function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -46706,63 +57501,81 @@ var ts; } return ts.createVoidZero(); } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ function serializeTypeNode(node) { if (node === undefined) { return ts.createIdentifier("Object"); } switch (node.kind) { - case 105: - case 139: - case 95: - case 130: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 130 /* NeverKeyword */: return ts.createVoidZero(); - case 168: + case 169 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 160: - case 161: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return ts.createIdentifier("Function"); - case 164: - case 165: + case 165 /* ArrayType */: + case 166 /* TupleType */: return ts.createIdentifier("Array"); - case 158: - case 122: + case 159 /* TypePredicate */: + case 122 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); - case 136: + case 136 /* StringKeyword */: return ts.createIdentifier("String"); - case 134: + case 134 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 173: + case 174 /* LiteralType */: switch (node.literal.kind) { - case 9: + case 9 /* StringLiteral */: return ts.createIdentifier("String"); - case 8: + case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); - case 101: - case 86: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: ts.Debug.failBadSyntaxKind(node.literal); break; } break; - case 133: + case 133 /* NumberKeyword */: return ts.createIdentifier("Number"); - case 137: - return languageVersion < 2 + case 137 /* SymbolKeyword */: + return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 159: + case 160 /* TypeReference */: return serializeTypeReferenceNode(node); - case 167: - case 166: + case 168 /* IntersectionType */: + case 167 /* UnionType */: return serializeUnionOrIntersectionType(node); - case 162: - case 170: - case 171: - case 172: - case 163: - case 119: - case 169: + case 163 /* TypeQuery */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 164 /* TypeLiteral */: + case 119 /* AnyKeyword */: + case 170 /* ThisType */: break; default: ts.Debug.failBadSyntaxKind(node); @@ -46771,14 +57584,27 @@ var ts; return ts.createIdentifier("Object"); } function serializeUnionOrIntersectionType(node) { + // Note when updating logic here also update getEntityNameForDecoratorMetadata + // so that aliases can be marked as referenced var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { + // One of the individual is global object, return immediately return serializedIndividual; } else if (serializedUnion) { + // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || serializedUnion.escapedText !== serializedIndividual.escapedText) { @@ -46786,19 +57612,27 @@ var ts; } } else { + // Initialize the union type serializedUnion = serializedIndividual; } } - return serializedUnion; + // If we were able to find common type, use it + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with + * decorator type metadata. + * + * @param node The type reference node. + */ function serializeTypeReferenceNode(node) { switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, true); + var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); var temp = ts.createTempVariable(hoistVariableDeclaration); return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, false); + return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -46810,7 +57644,7 @@ var ts; case ts.TypeReferenceSerializationKind.ArrayLikeType: return ts.createIdentifier("Array"); case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 + return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); case ts.TypeReferenceSerializationKind.TypeWithCallSignature: @@ -46822,127 +57656,279 @@ var ts; return ts.createIdentifier("Object"); } } + /** + * Serializes an entity name as an expression for decorator type metadata. + * + * @param node The entity name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * entity name at runtime. + */ function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { - case 71: - var name_44 = ts.getMutableClone(node); - name_44.flags &= ~8; - name_44.original = undefined; - name_44.parent = ts.getParseTreeNode(currentScope); + case 71 /* Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.getMutableClone(node); + name.flags &= ~8 /* Synthesized */; + name.original = undefined; + name.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_44), ts.createLiteral("undefined")), name_44); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } - return name_44; - case 143: + return name; + case 144 /* QualifiedName */: return serializeQualifiedNameAsExpression(node, useFallback); } } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * + * @param node The qualified name to serialize. + * @param useFallback A value indicating whether to use logical operators to test for the + * qualified name at runtime. + */ function serializeQualifiedNameAsExpression(node, useFallback) { var left; - if (node.left.kind === 71) { + if (node.left.kind === 71 /* Identifier */) { left = serializeEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, true)), temp); + left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); } else { - left = serializeEntityNameAsExpression(node.left, false); + left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); } return ts.createPropertyAccess(left, node.right); } + /** + * Gets an expression that points to the global "Symbol" constructor at runtime if it is + * available. + */ function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } + /** + * Gets an expression that represents a property name. For a computed property, a + * name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; if (ts.isComputedPropertyName(name)) { - return generateNameForComputedPropertyName + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? ts.getGeneratedNameForNode(name) : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.getSynthesizedClone(name); } } - function visitPropertyNameOfClassElement(member) { - var name = member.name; + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { if (ts.isComputedPropertyName(name)) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - if (member.decorators) { + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { var generatedName = ts.getGeneratedNameForNode(name); hoistVariableDeclaration(generatedName); - expression = ts.createAssignment(generatedName, expression); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } + /** + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. + * + * @param member The member whose name should be visited. + */ + function visitPropertyNameOfClassElement(member) { + var name = member.name; + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; } - return ts.updateComputedPropertyName(name, expression); + return ts.updateComputedPropertyName(name, expr); } else { return name; } } + /** + * Transforms a HeritageClause with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. + */ function visitHeritageClause(node) { - if (node.token === 85) { + if (node.token === 85 /* ExtendsKeyword */) { var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(85, types), node); + return ts.setTextRange(ts.createHeritageClause(85 /* ExtendsKeyword */, types), node); } return undefined; } + /** + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * + * This function will only be called when one of the following conditions are met: + * - The node contains type arguments that should be elided. + * + * @param node The ExpressionWithTypeArguments to transform. + */ function visitExpressionWithTypeArguments(node) { - return ts.updateExpressionWithTypeArguments(node, undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - } + return ts.updateExpressionWithTypeArguments(node, + /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + } + /** + * Determines whether to emit a function-like declaration. We should not emit the + * declaration if it does not have a body. + * + * @param node The declaration node. + */ function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked as abstract, public, private, protected, or readonly + * - The node has a computed property name + * + * @param node The method node. + */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + var updated = ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. ts.setCommentRange(updated, node); ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); } return updated; } + /** + * Determines whether to emit an accessor declaration. We should not emit the + * declaration if it does not have a body and is abstract. + * + * @param node The declaration node. + */ function shouldEmitAccessorDeclaration(node) { - return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128)); - } + return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); + } + /** + * Visits a get accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The get accessor node. + */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = ts.updateGetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. ts.setCommentRange(updated, node); ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); } return updated; } + /** + * Visits a set accessor declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as abstract, public, private, or protected + * - The node has a computed property name + * + * @param node The set accessor node. + */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = ts.updateSetAccessor(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. ts.setCommentRange(updated, node); ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); } return updated; } + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is exported from a TypeScript namespace + * - The node has decorators + * + * @param node The function node. + */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); } - var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); @@ -46950,33 +57936,73 @@ var ts; } return updated; } + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node has type annotations + * + * @param node The function expression node. + */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); } - var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); + var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node has type annotations + */ function visitArrowFunction(node) { - var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } + /** + * Visits a parameter declaration node. + * + * This function will be called when one of the following conditions are met: + * - The node has an accessibility modifier. + * - The node has a questionToken. + * - The node's kind is ThisKeyword. + * + * @param node The parameter declaration node. + */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + var parameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); ts.setCommentRange(parameter, node); ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32); + ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); return parameter; } + /** + * Visits a variable statement in a namespace. + * + * This function will be called when one of the following conditions are met: + * - The node is exported from a TypeScript namespace. + */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); if (variables.length === 0) { + // elide statement if there are no initialized variables. return undefined; } return ts.setTextRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); @@ -46988,19 +58014,43 @@ var ts; function transformInitializedVariable(node) { var name = node.name; if (ts.isBindingPattern(name)) { - return ts.flattenDestructuringAssignment(node, visitor, context, 0, false, createNamespaceExportExpression); + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, + /*needsValue*/ false, createNamespaceExportExpression); } else { - return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), + /*location*/ node); } } function visitVariableDeclaration(node) { - return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - } + return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + } + /** + * Visits a parenthesized expression that contains either a type assertion or an `as` + * expression. + * + * @param node The parenthesized expression node. + */ function visitParenthesizedExpression(node) { - var innerExpression = ts.skipOuterExpressions(node.expression, ~2); + var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // We have an expression of the form: (SubExpr). Emitting this as (SubExpr) + // is really not desirable. We would like to emit the subexpression as-is. Omitting + // the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the + // expression. + // + // To preserve comments, we return a "PartiallyEmittedExpression" here which will + // preserve the position information of the original expression. + // + // Due to the auto-parenthesization rules used by the visitor and factory functions + // we can safely elide the parentheses here, as a new synthetic + // ParenthesizedExpression will be inserted if we remove parentheses too + // aggressively. return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -47014,45 +58064,89 @@ var ts; return ts.createPartiallyEmittedExpression(expression, node); } function visitCallExpression(node) { - return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } function visitNewExpression(node) { - return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); - } + return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + } + /** + * Determines whether to emit an enum declaration. + * + * @param node The enum declaration node. + */ function shouldEmitEnumDeclaration(node) { return !ts.isConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } + /** + * Visits an enum declaration. + * + * This function will be called any time a TypeScript enum is encountered. + * + * @param node The enum declaration node. + */ function visitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { return undefined; } var statements = []; - var emitFlags = 2; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the enum. If we emit + // a leading variable declaration, we should not emit leading comments for the + // enum body. if (addVarForEnumOrModuleDeclaration(statements, node)) { + // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 512; + emitFlags |= 512 /* NoLeadingComments */; } } + // `parameterName` is the declaration name used inside of the enum. var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the enum for assignments. var containerName = getNamespaceContainerName(node); - var exportName = ts.hasModifier(node, 1) - ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) - : ts.getLocalName(node, false, true); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); if (hasNamespaceQualifiedExportName(node)) { - var localName = ts.getLocalName(node, false, true); + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) moduleArg = ts.createAssignment(localName, moduleArg); } - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg])); + // (function (x) { + // x[x["y"] = 0] = "y"; + // ... + // })(x || (x = {})); + var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformEnumBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); ts.setTextRange(enumStatement, node); ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); + // Add a DeclarationMarker for the enum to preserve trailing comments and mark + // the end of the declaration. statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } + /** + * Transforms the body of an enum declaration. + * + * @param node The enum declaration node. + */ function transformEnumBody(node, localName) { var savedCurrentNamespaceLocalName = currentNamespaceContainerName; currentNamespaceContainerName = localName; @@ -47061,17 +58155,31 @@ var ts; ts.addRange(statements, ts.map(node.members, transformEnumMember)); ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceLocalName; - return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); - } + return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), + /*multiLine*/ true); + } + /** + * Transforms an enum member into a statement. + * + * @param member The enum member node. + */ function transformEnumMember(member) { - var name = getExpressionForPropertyName(member, false); + // enums don't support computed properties + // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes + // old emitter always generate 'expression' part of the name as-is. + var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false); var valueExpression = transformEnumMemberDeclarationValue(member); var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression); - var outerAssignment = valueExpression.kind === 9 ? + var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); } + /** + * Transforms the value of an enum member. + * + * @param member The enum member node. + */ function transformEnumMemberDeclarationValue(member) { var value = resolver.getConstantValue(member); if (value !== undefined) { @@ -47087,9 +58195,18 @@ var ts; } } } + /** + * Determines whether to elide a module declaration. + * + * @param node The module declaration node. + */ function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } + /** + * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` + * or `exports.x`). + */ function hasNamespaceQualifiedExportName(node) { return isExportOfNamespace(node) || (isExternalModuleExport(node) @@ -47097,6 +58214,10 @@ var ts; && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System); } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + */ function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) { currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); @@ -47106,10 +58227,14 @@ var ts; currentScopeFirstDeclarationsOfName.set(name, node); } } + /** + * Determines whether a declaration is the first declaration with + * the same name emitted in the current scope. + */ function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name_45 = declaredNameInScope(node); - return currentScopeFirstDeclarationsOfName.get(name_45) === node; + var name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; } return true; } @@ -47117,31 +58242,67 @@ var ts; ts.Debug.assertNode(node.name, ts.isIdentifier); return node.name.escapedText; } + /** + * Adds a leading VariableStatement for a enum or module declaration. + */ function addVarForEnumOrModuleDeclaration(statements, node) { + // Emit a variable statement for the module. We emit top-level enums as a `var` + // declaration to avoid static errors in global scripts scripts due to redeclaration. + // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getLocalName(node, false, true)) - ], currentScope.kind === 265 ? 0 : 1)); + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ], currentScope.kind === 269 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { - if (node.kind === 232) { + // Adjust the source map emit to match the old emitter. + if (node.kind === 233 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { ts.setSourceMapRange(statement, node); } + // Trailing comments for module declaration should be emitted after the function closure + // instead of the variable statement: + // + // /** Module comment*/ + // module m1 { + // function foo4Export() { + // } + // } // trailing comment module + // + // Should emit: + // + // /** Module comment*/ + // var m1; + // (function (m1) { + // function foo4Export() { + // } + // })(m1 || (m1 = {})); // trailing comment module + // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 | 4194304); + ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } else { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrap the leading variable declaration in a `MergeDeclarationMarker`. var mergeMarker = ts.createMergeDeclarationMarker(statement); - ts.setEmitFlags(mergeMarker, 1536 | 4194304); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(mergeMarker); return false; } } + /** + * Visits a module declaration node. + * + * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered. + * + * @param node The module declaration node. + */ function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -47149,30 +58310,59 @@ var ts; ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name."); enableSubstitutionForNamespaceExports(); var statements = []; - var emitFlags = 2; + // We request to be advised when the printer is about to print this node. This allows + // us to set up the correct state for later substitutions. + var emitFlags = 2 /* AdviseOnEmitNode */; + // If needed, we should emit a variable declaration for the module. If we emit + // a leading variable declaration, we should not emit leading comments for the + // module body. if (addVarForEnumOrModuleDeclaration(statements, node)) { + // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { - emitFlags |= 512; + emitFlags |= 512 /* NoLeadingComments */; } } + // `parameterName` is the declaration name used inside of the namespace. var parameterName = getNamespaceParameterName(node); + // `containerName` is the expression used inside of the namespace for exports. var containerName = getNamespaceContainerName(node); - var exportName = ts.hasModifier(node, 1) - ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true) - : ts.getLocalName(node, false, true); + // `exportName` is the expression used within this node's container for any exported references. + var exportName = ts.hasModifier(node, 1 /* Export */) + ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true) + : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x || (x = {}) + // exports.x || (exports.x = {}) var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral())); if (hasNamespaceQualifiedExportName(node)) { - var localName = ts.getLocalName(node, false, true); + // `localName` is the expression used within this node's containing scope for any local references. + var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // x = (exports.x || (exports.x = {})) moduleArg = ts.createAssignment(localName, moduleArg); } - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg])); + // (function (x_1) { + // x_1.y = ...; + // })(x || (x = {})); + var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, transformModuleBody(node, containerName)), + /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); ts.setTextRange(moduleStatement, node); ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); + // Add a DeclarationMarker for the namespace to preserve trailing comments and mark + // the end of the declaration. statements.push(ts.createEndOfDeclarationMarker(node)); return statements; } + /** + * Transforms the body of a module declaration. + * + * @param node The module declaration node. + */ function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; @@ -47185,7 +58375,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 234) { + if (body.kind === 235 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -47207,76 +58397,172 @@ var ts; currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ statementsLocation), + /*multiLine*/ true); ts.setTextRange(block, blockLocation); - if (body.kind !== 234) { - ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); + // namespace hello.hi.world { + // function foo() {} + // + // // TODO, blah + // } + // + // should be emitted as + // + // var hello; + // (function (hello) { + // var hi; + // (function (hi) { + // var world; + // (function (world) { + // function foo() { } + // // TODO, blah + // })(world = hi.world || (hi.world = {})); + // })(hi = hello.hi || (hello.hi = {})); + // })(hello || (hello = {})); + // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. + if (body.kind !== 235 /* ModuleBlock */) { + ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 233) { + if (moduleDeclaration.body.kind === 234 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ function visitImportDeclaration(node) { if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; return node; } + // Elide the declaration if the import clause was elided. var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause); return importClause - ? ts.updateImportDeclaration(node, undefined, undefined, importClause, node.moduleSpecifier) + ? ts.updateImportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, importClause, node.moduleSpecifier) : undefined; } + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ function visitImportClause(node) { + // Elide the import clause if we elide both its name and its named bindings. var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings); return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined; } + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ function visitNamedImportBindings(node) { - if (node.kind === 240) { + if (node.kind === 241 /* NamespaceImport */) { + // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } else { + // Elide named imports if all of its import specifiers are elided. var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier); return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined; } } + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ function visitImportSpecifier(node) { + // Elide an import specifier if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ function visitExportAssignment(node) { + // Elide the export assignment if it does not reference a value. return resolver.isValueAliasDeclaration(node) ? ts.visitEachChild(node, visitor, context) : undefined; } + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ function visitExportDeclaration(node) { if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; } if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. return undefined; } + // Elide the export declaration if all of its named exports are elided. var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports); return exportClause - ? ts.updateExportDeclaration(node, undefined, undefined, exportClause, node.moduleSpecifier) + ? ts.updateExportDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, exportClause, node.moduleSpecifier) : undefined; } + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ function visitNamedExports(node) { + // Elide the named exports if all of its export specifiers were elided. var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier); return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined; } + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ function visitExportSpecifier(node) { + // Elide an export specifier if it does not reference a value. return resolver.isValueAliasDeclaration(node) ? node : undefined; } + /** + * Determines whether to emit an import equals declaration. + * + * @param node The import equals declaration node. + */ function shouldEmitImportEqualsDeclaration(node) { + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name return resolver.isReferencedAliasDeclaration(node) || (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node)); } + /** + * Visits an import equals declaration. + * + * @param node The import equals declaration node. + */ function visitImportEqualsDeclaration(node) { if (ts.isExternalModuleImportEqualsDeclaration(node)) { + // Elide external module `import=` if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? ts.visitEachChild(node, visitor, context) : undefined; @@ -47285,61 +58571,100 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - ts.setEmitFlags(moduleReference, 1536 | 2048); + ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + // export var ${name} = ${moduleReference}; + // var ${name} = ${moduleReference}; return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ - ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) + ts.setOriginalNode(ts.createVariableDeclaration(node.name, + /*type*/ undefined, moduleReference), node) ])), node), node); } else { + // exports.${name} = ${moduleReference}; return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); } } + /** + * Gets a value indicating whether the node is exported from a namespace. + * + * @param node The node to test. + */ function isExportOfNamespace(node) { - return currentNamespace !== undefined && ts.hasModifier(node, 1); + return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); } + /** + * Gets a value indicating whether the node is exported from an external module. + * + * @param node The node to test. + */ function isExternalModuleExport(node) { - return currentNamespace === undefined && ts.hasModifier(node, 1); + return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */); } + /** + * Gets a value indicating whether the node is a named export from an external module. + * + * @param node The node to test. + */ function isNamedExternalModuleExport(node) { return isExternalModuleExport(node) - && !ts.hasModifier(node, 512); + && !ts.hasModifier(node, 512 /* Default */); } + /** + * Gets a value indicating whether the node is the default export of an external module. + * + * @param node The node to test. + */ function isDefaultExternalModuleExport(node) { return isExternalModuleExport(node) - && ts.hasModifier(node, 512); + && ts.hasModifier(node, 512 /* Default */); } + /** + * Creates a statement for the provided expression. This is used in calls to `map`. + */ function expressionToStatement(expression) { return ts.createStatement(expression); } function addExportMemberAssignment(statements, node) { - var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); + var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); var statement = ts.createStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.setTextRange(ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, false, true), exportValue)), location); + return ts.setTextRange(ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); } function createNamespaceExportExpression(exportName, exportValue, location) { return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return ts.getNamespaceMemberName(currentNamespaceContainerName, name, false, true); + return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true); } + /** + * Gets the declaration name used inside of a namespace or enum. + */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); ts.setSourceMapRange(name, node.name); return name; } + /** + * Gets the expression used to refer to a namespace or enum within the body + * of its declaration. + */ function getNamespaceContainerName(node) { return ts.getGeneratedNameForNode(node); } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608) { + if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -47349,56 +58674,75 @@ var ts; return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype"); } function getClassMemberPrefix(node, member) { - return ts.hasModifier(member, 32) + return ts.hasModifier(member, 32 /* Static */) ? ts.getDeclarationName(node) : getClassPrototype(node); } function enableSubstitutionForNonQualifiedEnumMembers() { - if ((enabledSubstitutions & 8) === 0) { - enabledSubstitutions |= 8; - context.enableSubstitution(71); + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(71 /* Identifier */); } } function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1) === 0) { - enabledSubstitutions |= 1; - context.enableSubstitution(71); + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(71 /* Identifier */); + // Keep track of class aliases. classAliases = []; } } function enableSubstitutionForNamespaceExports() { - if ((enabledSubstitutions & 2) === 0) { - enabledSubstitutions |= 2; - context.enableSubstitution(71); - context.enableSubstitution(262); - context.enableEmitNotification(233); + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to + // substitute the names of exported members of a namespace. + context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); + // We need to be notified when entering and exiting namespaces. + context.enableEmitNotification(234 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 233; + return ts.getOriginalNode(node).kind === 234 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 232; - } + return ts.getOriginalNode(node).kind === 233 /* EnumDeclaration */; + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ function onEmitNode(hint, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSourceFile = currentSourceFile; if (ts.isSourceFile(node)) { currentSourceFile = node; } - if (enabledSubstitutions & 2 && isTransformedModuleDeclaration(node)) { - applicableSubstitutions |= 2; + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; } - if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { - applicableSubstitutions |= 8; + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } previousOnEmitNode(hint, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSourceFile = savedCurrentSourceFile; } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (hint === 1) { + if (hint === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -47407,26 +58751,28 @@ var ts; return node; } function substituteShorthandPropertyAssignment(node) { - if (enabledSubstitutions & 2) { - var name_46 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_46); + if (enabledSubstitutions & 2 /* NamespaceExports */) { + var name = node.name; + var exportedName = trySubstituteNamespaceExportedName(name); if (exportedName) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.setTextRange(ts.createPropertyAssignment(name_46, initializer), node); + return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); } - return ts.setTextRange(ts.createPropertyAssignment(name_46, exportedName), node); + return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node); } } return node; } function substituteExpression(node) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 179: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -47437,8 +58783,13 @@ var ts; || node; } function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1) { - if (resolver.getNodeCheckFlags(node) & 16777216) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { var classAlias = classAliases[declaration.id]; @@ -47454,13 +58805,17 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { + // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { - var container = resolver.getReferencedExportContainer(node, false); - if (container && container.kind !== 265) { - var substitute = (applicableSubstitutions & 2 && container.kind === 233) || - (applicableSubstitutions & 8 && container.kind === 232); + // If we are nested within a namespace declaration, we may need to qualifiy + // an identifier that is exported from a merged namespace. + var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); + if (container && container.kind !== 269 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 234 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 233 /* EnumDeclaration */); if (substitute) { - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), node); + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), + /*location*/ node); } } } @@ -47475,13 +58830,14 @@ var ts; function substituteConstantValue(node) { var constantValue = tryGetConstEnumValue(node); if (constantValue !== undefined) { + // track the constant value on the node for the printer in needsDotDotForPropertyAccess ts.setConstantValue(node, constantValue); var substitute = ts.createLiteral(constantValue); if (!compilerOptions.removeComments) { var propertyName = ts.isPropertyAccessExpression(node) ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - ts.addSyntheticTrailingComment(substitute, 3, " " + propertyName + " "); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); } return substitute; } @@ -47499,7 +58855,7 @@ var ts; ts.transformTypeScript = transformTypeScript; function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) { var argumentsArray = []; - argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, true)); + argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true)); argumentsArray.push(target); if (memberName) { argumentsArray.push(memberName); @@ -47508,7 +58864,8 @@ var ts; } } context.requestEmitHelper(decorateHelper); - return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray), location); + return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), + /*typeArguments*/ undefined, argumentsArray), location); } var decorateHelper = { name: "typescript:decorate", @@ -47518,7 +58875,8 @@ var ts; }; function createMetadataHelper(context, metadataKey, metadataValue) { context.requestEmitHelper(metadataHelper); - return ts.createCall(ts.getHelperName("__metadata"), undefined, [ + return ts.createCall(ts.getHelperName("__metadata"), + /*typeArguments*/ undefined, [ ts.createLiteral(metadataKey), metadataValue ]); @@ -47531,7 +58889,8 @@ var ts; }; function createParamHelper(context, expression, parameterOffset, location) { context.requestEmitHelper(paramHelper); - return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), undefined, [ + return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), + /*typeArguments*/ undefined, [ ts.createLiteral(parameterOffset), expression ]), location); @@ -47543,10 +58902,14 @@ var ts; text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" }; })(ts || (ts = {})); +/// +/// +/*@internal*/ var ts; (function (ts) { var ES2017SubstitutionFlags; (function (ES2017SubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { @@ -47554,10 +58917,20 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ var enabledSubstitutions; + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ var enclosingSuperContainerFlags = 0; + // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; return transformSourceFile; @@ -47570,46 +58943,98 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16) === 0) { + if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { - case 120: + case 120 /* AsyncKeyword */: + // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 191: + case 192 /* AwaitExpression */: return visitAwaitExpression(node); - case 151: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 187: + case 188 /* ArrowFunction */: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); } } + /** + * Visits an AwaitExpression node. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The node to visit. + */ function visitAwaitExpression(node) { - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); - } + return ts.setOriginalNode(ts.setTextRange(ts.createYield( + /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); + } + /** + * Visits a MethodDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The node to visit. + */ function visitMethodDeclaration(node) { - return ts.updateMethod(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return ts.updateMethod(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + /** + * Visits a FunctionDeclaration node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ function visitFunctionDeclaration(node) { - return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + /** + * Visits a FunctionExpression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ function visitFunctionExpression(node) { - return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + /** + * Visits an ArrowFunction. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The node to visit. + */ function visitArrowFunction(node) { - return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -47617,22 +59042,29 @@ var ts; resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; - var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 187; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; + var isArrowFunction = node.kind === 188 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. if (!isArrowFunction) { var statements = []; - var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, true); + var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); - if (languageVersion >= 2) { - if (resolver.getNodeCheckFlags(node) & 4096) { + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= 2 /* ES2015 */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } @@ -47672,21 +59104,33 @@ var ts; return undefined; } function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 1) === 0) { - enabledSubstitutions |= 1; - context.enableSubstitution(181); - context.enableSubstitution(179); - context.enableSubstitution(180); - context.enableEmitNotification(229); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); - context.enableEmitNotification(152); - } - } + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(182 /* CallExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(230 /* ClassDeclaration */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(153 /* Constructor */); + } + } + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ function onEmitNode(hint, node, emitCallback) { - if (enabledSubstitutions & 1 && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 | 4096); + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -47697,32 +59141,38 @@ var ts; } previousOnEmitNode(hint, node, emitCallback); } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (hint === 1 && enclosingSuperContainerFlags) { + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { return substituteExpression(node); } return node; } function substituteExpression(node) { switch (node.kind) { - case 179: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 181: + case 182 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + if (node.expression.kind === 97 /* SuperKeyword */) { + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97) { + if (node.expression.kind === 97 /* SuperKeyword */) { return createSuperAccessInAsyncMethod(node.argumentExpression, node); } return node; @@ -47733,7 +59183,8 @@ var ts; var argumentExpression = ts.isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ ts.createThis() ].concat(node.arguments)); } @@ -47741,18 +59192,20 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 - || kind === 152 - || kind === 151 - || kind === 153 - || kind === 154; + return kind === 230 /* ClassDeclaration */ + || kind === 153 /* Constructor */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value"), location); + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), location); } } } @@ -47765,9 +59218,16 @@ var ts; }; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); - var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; - return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ + var generatorFunc = ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, body); + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; + return ts.createCall(ts.getHelperName("__awaiter"), + /*typeArguments*/ undefined, [ ts.createThis(), hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(), @@ -47785,10 +59245,15 @@ var ts; text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);\n " }; })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { var ESNextSubstitutionFlags; (function (ESNextSubstitutionFlags) { + /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); function transformESNext(context) { @@ -47813,83 +59278,84 @@ var ts; return visited; } function visitor(node) { - return visitorWorker(node, false); + return visitorWorker(node, /*noDestructuringValue*/ false); } function visitorNoDestructuringValue(node) { - return visitorWorker(node, true); + return visitorWorker(node, /*noDestructuringValue*/ true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120) { + if (node.kind === 120 /* AsyncKeyword */) { return undefined; } return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 8) === 0) { + if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { return node; } switch (node.kind) { - case 191: + case 192 /* AwaitExpression */: return visitAwaitExpression(node); - case 197: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 222: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 178: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 194: + case 195 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 226: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 216: - return visitForOfStatement(node, undefined); - case 214: + case 217 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 215 /* ForStatement */: return visitForStatement(node); - case 190: + case 191 /* VoidExpression */: return visitVoidExpression(node); - case 152: + case 153 /* Constructor */: return visitConstructorDeclaration(node); - case 151: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 153: + case 154 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 154: + case 155 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 187: + case 188 /* ArrowFunction */: return visitArrowFunction(node); - case 146: + case 147 /* Parameter */: return visitParameter(node); - case 210: + case 211 /* ExpressionStatement */: return visitExpressionStatement(node); - case 185: + case 186 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 260: + case 264 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); } } function visitAwaitExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), + /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 216 && statement.awaitModifier) { + if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); @@ -47901,7 +59367,7 @@ var ts; var objects = []; for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { var e = elements_3[_i]; - if (e.kind === 263) { + if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -47913,7 +59379,7 @@ var ts; if (!chunkObject) { chunkObject = []; } - if (e.kind === 261) { + if (e.kind === 265 /* PropertyAssignment */) { var p = e; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } @@ -47928,9 +59394,14 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + // spread elements emit like so: + // non-spread elements are chunked together into object literals, and then all are passed to __assign: + // { a, ...o, b } => __assign({a}, o, {b}); + // If the first element is a spread element, then the first argument to __assign is {}: + // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 178) { + if (objects.length && objects[0].kind !== 179 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -47945,22 +59416,33 @@ var ts; } function visitCatchClause(node) { if (!node.variableDeclaration) { - return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { - return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } - else if (node.operatorToken.kind === 26) { + else if (node.operatorToken.kind === 26 /* CommaToken */) { return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ function visitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { - return ts.flattenDestructuringBinding(node, visitor, context, 1); + // If we are here it is because the name contains a binding pattern with a rest somewhere in it. + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); } @@ -47970,8 +59452,13 @@ var ts; function visitVoidExpression(node) { return ts.visitEachChild(node, visitorNoDestructuringValue, context); } + /** + * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. + * + * @param node A ForOfStatement. + */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576) { + if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -47986,7 +59473,7 @@ var ts; if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) { var bodyLocation = void 0; var statementsLocation = void 0; - var temp = ts.createTempVariable(undefined); + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)]; if (ts.isBlock(node.statement)) { ts.addRange(statements, node.statement.statements); @@ -47995,7 +59482,8 @@ var ts; } return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) - ], 1), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation)); + ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation)); } return node; } @@ -48013,80 +59501,102 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function createDownlevelAwait(expression) { - return enclosingFunctionFlags & 1 - ? ts.createYield(undefined, createAwaitHelper(context, expression)) + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); - var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(undefined); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); - var returnMethod = ts.createTempVariable(undefined); - var callValues = createAsyncValuesHelper(context, expression, node.expression); - var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); var getDone = ts.createPropertyAccess(result, "done"); var getValue = ts.createPropertyAccess(result, "value"); var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); - var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), ts.createVariableDeclaration(result) - ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, createDownlevelAwait(getValue))), node), 256); + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) - ]), 1)), ts.createBlock([ - ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1) - ]), undefined, ts.setEmitFlags(ts.createBlock([ - ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) - ]), 1)) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) ])); } function visitParameter(node) { - if (node.transformFlags & 1048576) { - return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.updateParameter(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); } function visitConstructorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0; - var updated = ts.updateConstructor(node, undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateConstructor(node, + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } function visitGetAccessorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0; - var updated = ts.updateGetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateGetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } function visitSetAccessorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0; - var updated = ts.updateSetAccessor(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + enclosingFunctionFlags = 0 /* Normal */; + var updated = ts.updateSetAccessor(node, + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } function visitMethodDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateMethod(node, undefined, enclosingFunctionFlags & 1 + var updated = ts.updateMethod(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) - : node.modifiers, enclosingFunctionFlags & 2 + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined - : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(undefined, visitor, ts.isToken), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 + : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; @@ -48095,11 +59605,14 @@ var ts; function visitFunctionDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateFunctionDeclaration(node, undefined, enclosingFunctionFlags & 1 + var updated = ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) - : node.modifiers, enclosingFunctionFlags & 2 + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined - : node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; @@ -48108,18 +59621,22 @@ var ts; function visitArrowFunction(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); + var updated = ts.updateArrowFunction(node, node.modifiers, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } function visitFunctionExpression(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 + var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) - : node.modifiers, enclosingFunctionFlags & 2 + : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined - : node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 + : node.asteriskToken, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; @@ -48128,17 +59645,23 @@ var ts; function transformAsyncGeneratorFunctionBody(node) { resumeLexicalEnvironment(); var statements = []; - var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); + var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); + statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); - if (languageVersion >= 2) { - if (resolver.getNodeCheckFlags(node) & 4096) { + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= 2 /* ES2015 */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } @@ -48151,12 +59674,12 @@ var ts; var statements = []; var body = ts.visitNode(node.body, visitor, ts.isConciseBody); if (ts.isBlock(body)) { - statementOffset = ts.addPrologue(statements, body.statements, false, visitor); + statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); } - ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(undefined, node)); + ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); var trailingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { - var block = ts.convertToFunctionBody(body, true); + var block = ts.convertToFunctionBody(body, /*multiLine*/ true); ts.addRange(statements, block.statements.slice(statementOffset)); ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); @@ -48166,12 +59689,15 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576) { + if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { var temp = ts.getGeneratedNameForNode(parameter); - var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + /*doNotRecordTempVariablesInLine*/ false, + /*skipInitializer*/ true); if (ts.some(declarations)) { - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); - ts.setEmitFlags(statement, 1048576); + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); statements = ts.append(statements, statement); } } @@ -48179,21 +59705,33 @@ var ts; return statements; } function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & 1) === 0) { - enabledSubstitutions |= 1; - context.enableSubstitution(181); - context.enableSubstitution(179); - context.enableSubstitution(180); - context.enableEmitNotification(229); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); - context.enableEmitNotification(152); - } - } + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(182 /* CallExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(230 /* ClassDeclaration */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(153 /* Constructor */); + } + } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ function onEmitNode(hint, node, emitCallback) { - if (enabledSubstitutions & 1 && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 | 4096); + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -48204,32 +59742,38 @@ var ts; } previousOnEmitNode(hint, node, emitCallback); } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (hint === 1 && enclosingSuperContainerFlags) { + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { return substituteExpression(node); } return node; } function substituteExpression(node) { switch (node.kind) { - case 179: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 181: + case 182 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + if (node.expression.kind === 97 /* SuperKeyword */) { + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } function substituteElementAccessExpression(node) { - if (node.expression.kind === 97) { + if (node.expression.kind === 97 /* SuperKeyword */) { return createSuperAccessInAsyncMethod(node.argumentExpression, node); } return node; @@ -48240,7 +59784,8 @@ var ts; var argumentExpression = ts.isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); - return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), undefined, [ + return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, [ ts.createThis() ].concat(node.arguments)); } @@ -48248,18 +59793,20 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 - || kind === 152 - || kind === 151 - || kind === 153 - || kind === 154; + return kind === 230 /* ClassDeclaration */ + || kind === 153 /* Constructor */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value"), location); + if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + /*typeArguments*/ undefined, [argumentExpression]), location); } } } @@ -48271,11 +59818,13 @@ var ts; text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" }; function createAssignHelper(context, attributesSegments) { - if (context.getCompilerOptions().target >= 2) { - return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), undefined, attributesSegments); + if (context.getCompilerOptions().target >= 2 /* ES2015 */) { + return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), + /*typeArguments*/ undefined, attributesSegments); } context.requestEmitHelper(assignHelper); - return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); + return ts.createCall(ts.getHelperName("__assign"), + /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; var awaitHelper = { @@ -48285,7 +59834,7 @@ var ts; }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); - return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", @@ -48295,8 +59844,10 @@ var ts; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; - return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ + // Mark this node as originally an async function + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + return ts.createCall(ts.getHelperName("__asyncGenerator"), + /*typeArguments*/ undefined, [ ts.createThis(), ts.createIdentifier("arguments"), generatorFunc @@ -48310,7 +59861,8 @@ var ts; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), + /*typeArguments*/ undefined, [expression]), location); } var asyncValues = { name: "typescript:asyncValues", @@ -48319,24 +59871,36 @@ var ts; }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); - return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), undefined, [expression]), location); + return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), + /*typeArguments*/ undefined, [expression]), location); } })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; return transformSourceFile; + /** + * Transform JSX-specific syntax in a SourceFile. + * + * @param node A SourceFile node. + */ function transformSourceFile(node) { if (node.isDeclarationFile) { return node; } + currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; } function visitor(node) { - if (node.transformFlags & 4) { + if (node.transformFlags & 4 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -48345,11 +59909,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 249: - return visitJsxElement(node, false); - case 250: - return visitJsxSelfClosingElement(node, false); - case 256: + case 250 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ false); + case 251 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ false); + case 254 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 260 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -48357,39 +59923,51 @@ var ts; } function transformJsxChildToExpression(node) { switch (node.kind) { - case 10: + case 10 /* JsxText */: return visitJsxText(node); - case 256: + case 260 /* JsxExpression */: return visitJsxExpression(node); - case 249: - return visitJsxElement(node, true); - case 250: - return visitJsxSelfClosingElement(node, true); + case 250 /* JsxElement */: + return visitJsxElement(node, /*isChild*/ true); + case 251 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 254 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); default: ts.Debug.failBadSyntaxKind(node); return undefined; } } function visitJsxElement(node, isChild) { - return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, node); + return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node); } function visitJsxSelfClosingElement(node, isChild) { - return visitJsxOpeningLikeElement(node, undefined, isChild, node); + return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); + } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); } function visitJsxOpeningLikeElement(node, children, isChild, location) { var tagName = getTagName(node); var objectProperties; var attrs = node.attributes.properties; if (attrs.length === 0) { + // When there are no attributes, React wants "null" objectProperties = ts.createNull(); } else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToExpression) : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument. segments.unshift(ts.createObjectLiteral()); } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. objectProperties = ts.singleOrUndefined(segments); if (!objectProperties) { objectProperties = ts.createAssignHelper(context, segments); @@ -48401,6 +59979,13 @@ var ts; } return element; } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -48413,11 +59998,14 @@ var ts; if (node === undefined) { return ts.createTrue(); } - else if (node.kind === 9) { - var decoded = tryDecodeEntities(node.text); - return decoded ? ts.setTextRange(ts.createLiteral(decoded), node) : node; + else if (node.kind === 9 /* StringLiteral */) { + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); } - else if (node.kind === 256) { + else if (node.kind === 260 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -48428,19 +60016,43 @@ var ts; } } function visitJsxText(node) { - var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, true)); + var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); return fixed === undefined ? undefined : ts.createLiteral(fixed); } + /** + * JSX trims whitespace at the end and beginning of lines, except that the + * start/end of a tag is considered a start/end of a line only if that line is + * on the same line as the closing tag. See examples in + * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model + * + * An equivalent algorithm would be: + * - If there is only one line, return it. + * - If there is only whitespace (but multiple lines), return `undefined`. + * - Split the text into lines. + * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines. + * - Decode entities on each line (individually). + * - Remove empty lines and join the rest with " ". + */ function fixupWhitespaceAndDecodeEntities(text) { var acc; + // First non-whitespace character on this line. var firstNonWhitespace = 0; + // Last non-whitespace character on this line. var lastNonWhitespace = -1; + // These initial values are special because the first line is: + // firstNonWhitespace = 0 to indicate that we want leading whitsepace, + // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace. for (var i = 0; i < text.length; i++) { var c = text.charCodeAt(i); if (ts.isLineBreak(c)) { + // If we've seen any non-whitespace characters on this line, add the 'trim' of the line. + // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.) if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); } + // Reset firstNonWhitespace for the next line. + // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1. firstNonWhitespace = -1; } else if (!ts.isWhiteSpaceSingleLine(c)) { @@ -48451,13 +60063,21 @@ var ts; } } return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it : acc; } function addLineOfJsxText(acc, trimmedLine) { + // We do not escape the string here as that is handled by the printer + // when it emits the literal. We do, however, need to decode JSX entities. var decoded = decodeEntities(trimmedLine); return acc === undefined ? decoded : acc + " " + decoded; } + /** + * Replace entities like " ", "{", and "�" with the characters they encode. + * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references + */ function decodeEntities(text) { return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) { if (decimal) { @@ -48468,35 +60088,43 @@ var ts; } else { var ch = entities.get(word); + // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace) return ch ? String.fromCharCode(ch) : match; } }); } + /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */ function tryDecodeEntities(text) { var decoded = decodeEntities(text); return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 249) { + if (node.kind === 250 /* JsxElement */) { return getTagName(node.openingElement); } else { - var name_47 = node.tagName; - if (ts.isIdentifier(name_47) && ts.isIntrinsicJsxName(name_47.escapedText)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name_47.escapedText)); + var name = node.tagName; + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.idText(name)); } else { - return ts.createExpressionFromEntityName(name_47); + return ts.createExpressionFromEntityName(name); } } } + /** + * Emit an attribute name, which is quoted if it needs to be quoted. Because + * these emit into an object literal property name, we don't need to be worried + * about keywords, just non-identifier characters + */ function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { return name; } else { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(text); } } function visitJsxExpression(node) { @@ -48505,261 +60133,264 @@ var ts; } ts.transformJsx = transformJsx; var entities = ts.createMapFromTemplate({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 }); })(ts || (ts = {})); +/// +/// +/*@internal*/ var ts; (function (ts) { function transformES2016(context) { @@ -48772,11 +60403,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32) === 0) { + if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { - case 194: + case 195 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -48784,9 +60415,9 @@ var ts; } function visitBinaryExpression(node) { switch (node.operatorToken.kind) { - case 62: + case 62 /* AsteriskAsteriskEqualsToken */: return visitExponentiationAssignmentExpression(node); - case 40: + case 40 /* AsteriskAsteriskToken */: return visitExponentiationExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -48798,35 +60429,45 @@ var ts; var left = ts.visitNode(node.left, visitor, ts.isExpression); var right = ts.visitNode(node.right, visitor, ts.isExpression); if (ts.isElementAccessExpression(left)) { + // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration); target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left); } else if (ts.isPropertyAccessExpression(left)) { + // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` var expressionTemp = ts.createTempVariable(hoistVariableDeclaration); target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left); } else { + // Transforms `a **= b` into `a = Math.pow(a, b)` target = left; value = left; } - return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, node)), node); + return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node); } function visitExponentiationExpression(node) { + // Transforms `a ** b` into `Math.pow(a, b)` var left = ts.visitNode(node.left, visitor, ts.isExpression); var right = ts.visitNode(node.right, visitor, ts.isExpression); - return ts.createMathPow(left, right, node); + return ts.createMathPow(left, right, /*location*/ node); } } ts.transformES2016 = transformES2016; })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { var ES2015SubstitutionFlags; (function (ES2015SubstitutionFlags) { + /** Enables substitutions for captured `this` */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis"; + /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); var CopyDirection; @@ -48842,13 +60483,35 @@ var ts; })(Jump || (Jump = {})); var SuperCaptureResult; (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; })(SuperCaptureResult || (SuperCaptureResult = {})); + // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function"; HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction"; HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody"; @@ -48863,33 +60526,58 @@ var ts; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + // We are always in *some* kind of block scope, but only specific block-scope containers are + // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes"; + // A source file is a top-level block scope. HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes"; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; + // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + // Constructors are both new lexical scopes and new block scopes. Constructors are also + // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + // 'do' and 'while' statements are not block scopes. We track that the subtree is contained + // within an IterationStatement to indicate whether the embedded statement is an + // IterationStatementBlock. HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes"; HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes"; + // 'for' statements are new block scopes and have special handling for 'let' declarations. HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes"; HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes"; + // 'for-in' and 'for-of' statements are new block scopes and have special handling for + // 'let' declarations. HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes"; + // Blocks (other than function bodies) are new block scopes. HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes"; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; + // Computed property names track subtree flags differently than their containing members. HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; + // + // Subtree facts + // HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + // + // Subtree masks + // HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; })(HierarchyFacts || (HierarchyFacts = {})); @@ -48904,7 +60592,19 @@ var ts; var currentSourceFile; var currentText; var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } + /** + * Used to track if we are emitting body of the converted loop + */ var convertedLoopState; + /** + * Keeps track of whether substitutions have been enabled for specific cases. + * They are persisted between each SourceFile transformation and should not + * be reset. + */ var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { @@ -48917,28 +60617,41 @@ var ts; ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; currentText = undefined; - hierarchyFacts = 0; + taggedTemplateStringDeclarations = undefined; + hierarchyFacts = 0 /* None */; return visited; } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; return ancestorFacts; } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree, propagating specific facts from the subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated. + * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. + */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 - && node.kind === 219 + return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ + && node.kind === 220 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { - return (node.transformFlags & 128) !== 0 + return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) - || (ts.getEmitFlags(node) & 33554432) !== 0; + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 208 /* Block */))) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { if (shouldVisitNode(node)) { @@ -48950,130 +60663,134 @@ var ts; } function functionBodyVisitor(node) { if (shouldVisitNode(node)) { - return visitBlock(node, true); + return visitBlock(node, /*isFunctionBody*/ true); } return node; } function callExpressionVisitor(node) { - if (node.kind === 97) { - return visitSuperKeyword(true); + if (node.kind === 97 /* SuperKeyword */) { + return visitSuperKeyword(/*isExpressionOfCall*/ true); } return visitor(node); } function visitJavaScript(node) { switch (node.kind) { - case 115: - return undefined; - case 229: + case 115 /* StaticKeyword */: + return undefined; // elide static keyword + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 199: + case 200 /* ClassExpression */: return visitClassExpression(node); - case 146: + case 147 /* Parameter */: return visitParameter(node); - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 187: + case 188 /* ArrowFunction */: return visitArrowFunction(node); - case 186: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 226: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 71: + case 71 /* Identifier */: return visitIdentifier(node); - case 227: + case 228 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 221: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 235: + case 236 /* CaseBlock */: return visitCaseBlock(node); - case 207: - return visitBlock(node, false); - case 218: - case 217: + case 208 /* Block */: + return visitBlock(node, /*isFunctionBody*/ false); + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 222: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 212: - case 213: - return visitDoOrWhileStatement(node, undefined); - case 214: - return visitForStatement(node, undefined); - case 215: - return visitForInStatement(node, undefined); - case 216: - return visitForOfStatement(node, undefined); - case 210: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + case 215 /* ForStatement */: + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + case 216 /* ForInStatement */: + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + case 217 /* ForOfStatement */: + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + case 211 /* ExpressionStatement */: return visitExpressionStatement(node); - case 178: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 260: + case 264 /* CatchClause */: return visitCatchClause(node); - case 262: + case 266 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 144: + case 145 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 177: + case 178 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 181: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182: + case 183 /* NewExpression */: return visitNewExpression(node); - case 185: - return visitParenthesizedExpression(node, true); - case 194: - return visitBinaryExpression(node, true); - case 13: - case 14: - case 15: - case 16: + case 186 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); + case 195 /* BinaryExpression */: + return visitBinaryExpression(node, /*needsDestructuringValue*/ true); + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: return visitTemplateLiteral(node); - case 9: + case 9 /* StringLiteral */: return visitStringLiteral(node); - case 8: + case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 183: + case 184 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 196: + case 197 /* TemplateExpression */: return visitTemplateExpression(node); - case 197: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 198: + case 199 /* SpreadElement */: return visitSpreadElement(node); - case 97: - return visitSuperKeyword(false); - case 99: + case 97 /* SuperKeyword */: + return visitSuperKeyword(/*isExpressionOfCall*/ false); + case 99 /* ThisKeyword */: return visitThisKeyword(node); - case 204: + case 205 /* MetaProperty */: return visitMetaProperty(node); - case 151: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return visitAccessorDeclaration(node); - case 208: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 219: + case 220 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { - var ancestorFacts = enterSubtree(3968, 64); + var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, false); + var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); addCaptureThisForNodeIfNeeded(statements, node); statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } ts.addRange(statements, endLexicalEnvironment()); - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps |= 2; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; var result = ts.visitEachChild(node, visitor, context); convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; return result; @@ -49081,9 +60798,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCaseBlock(node) { - var ancestorFacts = enterSubtree(4032, 0); + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return updated; } function returnCapturedThis(node) { @@ -49091,7 +60808,7 @@ var ts; } function visitReturnStatement(node) { if (convertedLoopState) { - convertedLoopState.nonLocalJumps |= 8; + convertedLoopState.nonLocalJumps |= 8 /* Return */; if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { node = returnCapturedThis(node); } @@ -49108,7 +60825,8 @@ var ts; } function visitThisKeyword(node) { if (convertedLoopState) { - if (hierarchyFacts & 2) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. convertedLoopState.containsLexicalThis = true; return node; } @@ -49130,29 +60848,34 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 218 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || + // check if we can emit break/continue as is + // it is possible if either + // - break/continue is labeled and label is located inside the converted loop + // - break/continue is non-labeled and located in non-converted loop/switch statement + var jump = node.kind === 219 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 218) { - convertedLoopState.nonLocalJumps |= 2; + if (node.kind === 219 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } else { - convertedLoopState.nonLocalJumps |= 4; + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it. labelMarker = "continue"; } } else { - if (node.kind === 218) { + if (node.kind === 219 /* BreakStatement */) { labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); } else { labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -49160,169 +60883,303 @@ var ts; var outParams = convertedLoopState.loopOutParameters; var expr = void 0; for (var i = 0; i < outParams.length; i++) { - var copyExpr = copyOutParameter(outParams[i], 1); + var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); if (i === 0) { expr = copyExpr; } else { - expr = ts.createBinary(expr, 26, copyExpr); + expr = ts.createBinary(expr, 26 /* CommaToken */, copyExpr); } } - returnExpression = ts.createBinary(expr, 26, returnExpression); + returnExpression = ts.createBinary(expr, 26 /* CommaToken */, returnExpression); } return ts.createReturn(returnExpression); } } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a ClassDeclaration and transforms it into a variable statement. + * + * @param node A ClassDeclaration node. + */ function visitClassDeclaration(node) { - var variable = ts.createVariableDeclaration(ts.getLocalName(node, true), undefined, transformClassLikeDeclarationToExpression(node)); + // [source] + // class C { } + // + // [output] + // var C = (function () { + // function C() { + // } + // return C; + // }()); + var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), + /*type*/ undefined, transformClassLikeDeclarationToExpression(node)); ts.setOriginalNode(variable, node); var statements = []; - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([variable])); + var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable])); ts.setOriginalNode(statement, node); ts.setTextRange(statement, node); ts.startOnNewLine(statement); statements.push(statement); - if (ts.hasModifier(node, 1)) { - var exportStatement = ts.hasModifier(node, 512) + // Add an `export default` statement for default exports (for `--target es5 --module es6`) + if (ts.hasModifier(node, 1 /* Export */)) { + var exportStatement = ts.hasModifier(node, 512 /* Default */) ? ts.createExportDefault(ts.getLocalName(node)) : ts.createExternalModuleExport(ts.getLocalName(node)); ts.setOriginalNode(exportStatement, statement); statements.push(exportStatement); } var emitFlags = ts.getEmitFlags(node); - if ((emitFlags & 4194304) === 0) { + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { + // Add a DeclarationMarker as a marker for the end of the declaration statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(statement, emitFlags | 4194304); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); } return ts.singleOrMany(statements); } + /** + * Visits a ClassExpression and transforms it into an expression. + * + * @param node A ClassExpression node. + */ function visitClassExpression(node) { + // [source] + // C = class { } + // + // [output] + // C = (function () { + // function class_1() { + // } + // return class_1; + // }()) return transformClassLikeDeclarationToExpression(node); } + /** + * Transforms a ClassExpression or ClassDeclaration into an expression. + * + * @param node A ClassExpression or ClassDeclaration node. + */ function transformClassLikeDeclarationToExpression(node) { + // [source] + // class C extends D { + // constructor() {} + // method() {} + // get prop() {} + // set prop(v) {} + // } + // + // [output] + // (function (_super) { + // __extends(C, _super); + // function C() { + // } + // C.prototype.method = function () {} + // Object.defineProperty(C.prototype, "prop", { + // get: function() {}, + // set: function() {}, + // enumerable: true, + // configurable: true + // }); + // return C; + // }(D)) if (node.name) { enableSubstitutionsForBlockScopedBindings(); } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); - var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (ts.getEmitFlags(node) & 65536) { - ts.setEmitFlags(classFunction, 65536); - } + var classFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "_super")] : [], + /*type*/ undefined, transformClassBody(node, extendsClauseElement)); + // To preserve the behavior of the old emitter, we explicitly indent + // the body of the function here if it was requested in an earlier + // transformation. + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); + // "inner" and "outer" below are added purely to preserve source map locations from + // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - ts.setEmitFlags(inner, 1536); + ts.setEmitFlags(inner, 1536 /* NoComments */); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - ts.setEmitFlags(outer, 1536); - var result = ts.createParen(ts.createCall(outer, undefined, extendsClauseElement + ts.setEmitFlags(outer, 1536 /* NoComments */); + var result = ts.createParen(ts.createCall(outer, + /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); - ts.addSyntheticLeadingComment(result, 3, "* @class "); + ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); return result; } + /** + * Transforms a ClassExpression or ClassDeclaration into a function body. + * + * @param node A ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ function transformClassBody(node, extendsClauseElement) { var statements = []; startLexicalEnvironment(); addExtendsHelperIfNeeded(statements, node, extendsClauseElement); addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); - var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18); + // Create a synthetic text range for the return statement. + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - ts.setEmitFlags(outer, 1536); + ts.setEmitFlags(outer, 1536 /* NoComments */); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - ts.setEmitFlags(statement, 1536 | 384); + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); - ts.setEmitFlags(block, 1536); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); + ts.setEmitFlags(block, 1536 /* NoComments */); return block; } + /** + * Adds a call to the `__extends` helper if needed for a class. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), extendsClauseElement)); + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + /*location*/ extendsClauseElement)); } } + /** + * Adds the constructor of the class to a class body function. + * + * @param statements The statements of the class body function. + * @param node The ClassExpression or ClassDeclaration node. + * @param extendsClauseElement The expression for the class `extends` clause. + */ function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278, 73); + var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + var constructorFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, ts.getInternalName(node), + /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); if (extendsClauseElement) { - ts.setEmitFlags(constructorFunction, 8); + ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } + /** + * Transforms the parameters of the constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ function transformConstructorParameters(constructor, hasSynthesizedSuper) { + // If the TypeScript transformer needed to synthesize a constructor for property + // initializers, it would have also added a synthetic `...args` parameter and + // `super` call. + // If this is the case, we do not include the synthetic `...args` parameter and + // will instead use the `arguments` object in ES5/3. return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) || []; } + /** + * Transforms the body of a constructor declaration of a class. + * + * @param constructor The constructor for the class. + * @param node The node which contains the constructor. + * @param extendsClauseElement The expression for the class `extends` clause. + * @param hasSynthesizedSuper A value indicating whether the constructor starts with a + * synthesized `super` call. + */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; resumeLexicalEnvironment(); var statementOffset = -1; if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. statementOffset = 0; } else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, false); + statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); } if (constructor) { addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); if (!hasSynthesizedSuper) { + // If no super call has been synthesized, emit custom prologue directives. statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); } ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); } - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95; + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - if (superCaptureStatus === 1 || superCaptureStatus === 2) { + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { statementOffset++; } if (constructor) { - if (superCaptureStatus === 1) { - hierarchyFacts |= 4096; + if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset)); + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. if (isDerivedClass - && superCaptureStatus !== 2 + && superCaptureStatus !== 2 /* ReplaceWithReturn */ && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createIdentifier("_this"))); } ts.addRange(statements, endLexicalEnvironment()); if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, false); + prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), + /*location*/ constructor ? constructor.body.statements : node.members), + /*multiLine*/ true); ts.setTextRange(block, constructor ? constructor.body : node); if (!constructor) { - ts.setEmitFlags(block, 1536); + ts.setEmitFlags(block, 1536 /* NoComments */); } return block; } + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ function isSufficientlyCoveredByReturnStatements(statement) { - if (statement.kind === 219) { + // A return statement is considered covered. + if (statement.kind === 220 /* ReturnStatement */) { return true; } - else if (statement.kind === 211) { + else if (statement.kind === 212 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 207) { + else if (statement.kind === 208 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -49330,175 +61187,312 @@ var ts; } return false; } + /** + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. + * + * @returns The new statement offset into the `statements` array. + */ function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. if (!isDerivedClass) { if (ctor) { addCaptureThisForNodeIfNeeded(statements, ctor); } - return 0; + return 0 /* NoReplacement */; } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. if (!ctor) { statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2; + return 2 /* ReplaceWithReturn */; } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. if (hasSynthesizedSuper) { captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); enableSubstitutionsForCapturedThis(); - return 1; - } + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // var firstStatement; var superCallExpression; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 210 && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } + // Return the result if we have an immediate super() call on the last statement, + // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 | 32768))) { + && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 194 - || superCallExpression.left.kind !== 181) { + if (superCallExpression.kind !== 195 /* BinaryExpression */ + || superCallExpression.left.kind !== 182 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); + // Shift comments from the original super call to the return statement. + ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); statements.push(returnStatement); - return 2; + return 2 /* ReplaceWithReturn */; } + // Perform the capture. captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. if (superCallExpression) { - return 1; + return 1 /* ReplaceSuperCapture */; } - return 0; + return 0 /* NoReplacement */; } function createActualThis() { - return ts.setEmitFlags(ts.createThis(), 4); + return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } function createDefaultSuperCallOrThis() { return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createIdentifier("_super"), ts.createNull()), ts.createFunctionApply(ts.createIdentifier("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); } + /** + * Visits a parameter declaration. + * + * @param node A ParameterDeclaration node. + */ function visitParameter(node) { if (node.dotDotDotToken) { + // rest parameters are elided return undefined; } else if (ts.isBindingPattern(node.name)) { - return ts.setOriginalNode(ts.setTextRange(ts.createParameter(undefined, undefined, undefined, ts.getGeneratedNameForNode(node), undefined, undefined, undefined), node), node); + // Binding patterns are converted into a generated name and are + // evaluated inside the function body. + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); } else if (node.initializer) { - return ts.setOriginalNode(ts.setTextRange(ts.createParameter(undefined, undefined, undefined, node.name, undefined, undefined, undefined), node), node); + // Initializers are elided + return ts.setOriginalNode(ts.setTextRange(ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined), + /*location*/ node), + /*original*/ node); } else { return node; } } + /** + * Gets a value indicating whether we need to add default value assignments for a + * function-like node. + * + * @param node A function-like node. + */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072) !== 0; - } + return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + } + /** + * Adds statements to the body of a function-like node if it contains parameters with + * binding patterns or initializers. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + */ function addDefaultValueAssignmentsIfNeeded(statements, node) { if (!shouldAddDefaultValueAssignments(node)) { return; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_48 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_48)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_48, initializer); + if (ts.isBindingPattern(name)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_48, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); } } } + /** + * Adds statements to the body of a function-like node for parameters with binding patterns + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576)); + statements.push(ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); } } + /** + * Adds statements to the body of a function-like node for parameters with initializers. + * + * @param statements The statements for the new function body. + * @param parameter The parameter for the function. + * @param name The name of the parameter. + * @param initializer The initializer for the parameter. + */ function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ - ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer))), parameter)) - ]), parameter), 1 | 32 | 384)); - statement.startsOnNewLine = true; + ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); + ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 | 32 | 1048576); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); statements.push(statement); } + /** + * Gets a value indicating whether we need to add statements to handle a rest parameter. + * + * @param node A ParameterDeclaration node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 71 && !inConstructorWithSynthesizedSuper; - } + return node && node.dotDotDotToken && node.name.kind === 71 /* Identifier */ && !inConstructorWithSynthesizedSuper; + } + /** + * Adds statements to the body of a function-like node if it contains a rest parameter. + * + * @param statements The statements for the new function body. + * @param node A function-like node. + * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is + * part of a constructor declaration with a + * synthesized call to `super` + */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { return; } + // `declarationName` is the name of the local declaration for the parameter. var declarationName = ts.getMutableClone(parameter.name); - ts.setEmitFlags(declarationName, 48); + ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); + // `expressionName` is the name of the parameter used in expressions. var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ])), parameter), 1048576)); + // var param = []; + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(declarationName, + /*type*/ undefined, ts.createArrayLiteral([])) + ])), + /*location*/ parameter), 1048576 /* CustomPrologue */)); + // for (var _i = restIndex; _i < arguments.length; _i++) { + // param[_i - restIndex] = arguments[_i]; + // } var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) + ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 ? temp - : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), parameter)) + : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), + /*location*/ parameter)) ])); - ts.setEmitFlags(forStatement, 1048576); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } + /** + * Adds a statement to capture the `this` of a function declaration if it is needed. + * + * @param statements The statements for the new function body. + * @param node A node. + */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 && node.kind !== 187) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 188 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } function captureThisForNode(statements, node, initializer, originalStatement) { enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, initializer) + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) ])); - ts.setEmitFlags(captureThisStatement, 1536 | 1048576); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384) { + if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 187: + case 188 /* ArrowFunction */: return statements; - case 151: - case 153: - case 154: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // Methods and accessors cannot be constructors, so 'new.target' will + // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 152: - newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"); + case 153 /* Constructor */: + // Class constructors can only be called with `new`, so `this.constructor` + // should be relatively safe to use. + newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 228: - case 186: - newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4), 93, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4), "constructor"), ts.createVoidZero()); + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + // Functions can be called or constructed, and may have a `this` due to + // being a member or when calling an imported function via `other_1.f()`. + newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: ts.Debug.failBadSyntaxKind(node); break; } - var captureNewTargetStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_newTarget", undefined, newTarget) + var captureNewTargetStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_newTarget", + /*type*/ undefined, newTarget) ])); if (copyOnWrite) { return [captureNewTargetStatement].concat(statements); @@ -49507,24 +61501,32 @@ var ts; } return statements; } + /** + * Adds statements to the class body function for a class to define the members of the + * class. + * + * @param statements The statements for the class body function. + * @param node The ClassExpression or ClassDeclaration node. + */ function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 206: + case 207 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 151: + case 152 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 152: + case 153 /* Constructor */: + // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: ts.Debug.failBadSyntaxKind(node); @@ -49532,133 +61534,208 @@ var ts; } } } + /** + * Transforms a SemicolonClassElement into a statement for a class body function. + * + * @param member The SemicolonClassElement node. + */ function transformSemicolonClassElementToStatement(member) { return ts.setTextRange(ts.createEmptyStatement(), member); } + /** + * Transforms a MethodDeclaration into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param member The MethodDeclaration node. + */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0, 0); + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); - var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name); - var memberFunction = transformFunctionLikeToExpression(member, member, undefined, container); - ts.setEmitFlags(memberFunction, 1536); + var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); + var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); + ts.setEmitFlags(memberFunction, 1536 /* NoComments */); ts.setSourceMapRange(memberFunction, sourceMapRange); - var statement = ts.setTextRange(ts.createStatement(ts.createAssignment(memberName, memberFunction)), member); + var statement = ts.setTextRange(ts.createStatement(ts.createAssignment(memberName, memberFunction)), + /*location*/ member); ts.setOriginalNode(statement, member); ts.setCommentRange(statement, commentRange); - ts.setEmitFlags(statement, 48); - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); + // The location for the statement is used to emit comments only. + // No source map should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 48 /* NoSourceMap */); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } + /** + * Transforms a set of related of get/set accessors into a statement for a class body function. + * + * @param receiver The receiver for the member. + * @param accessors The set of related get/set accessors. + */ function transformAccessorsToStatement(receiver, accessors, container) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, container, false)); - ts.setEmitFlags(statement, 1536); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + // The location for the statement is used to emit source maps only. + // No comments should be emitted for this statement to align with the + // old emitter. + ts.setEmitFlags(statement, 1536 /* NoComments */); ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor)); return statement; } + /** + * Transforms a set of related get/set accessors into an expression for either a class + * body function or an ObjectLiteralExpression with computed properties. + * + * @param receiver The receiver for the member. + */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0, 0); + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + // To align with source maps in the old emitter, the receiver and property name + // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); - ts.setEmitFlags(target, 1536 | 32); + ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - ts.setEmitFlags(propertyName, 1536 | 16); + ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { - var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined, container); + var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container); ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); - ts.setEmitFlags(getterFunction, 512); + ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */); var getter = ts.createPropertyAssignment("get", getterFunction); ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { - var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined, container); + var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container); ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); - ts.setEmitFlags(setterFunction, 512); + ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */); var setter = ts.createPropertyAssignment("set", setterFunction); ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); - var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ target, propertyName, - ts.createObjectLiteral(properties, true) + ts.createObjectLiteral(properties, /*multiLine*/ true) ]); if (startsOnNewLine) { - call.startsOnNewLine = true; + ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } + /** + * Visits an ArrowFunction and transforms it into a FunctionExpression. + * + * @param node An ArrowFunction node. + */ function visitArrowFunction(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 16384 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256, 66); - var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformFunctionBody(node)); ts.setTextRange(func, node); ts.setOriginalNode(func, node); - ts.setEmitFlags(func, 8); - exitSubtree(ancestorFacts, 0, 0); + ts.setEmitFlags(func, 8 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } + /** + * Visits a FunctionExpression node. + * + * @param node a FunctionExpression node. + */ function visitFunctionExpression(node) { - var ancestorFacts = ts.getEmitFlags(node) & 262144 - ? enterSubtree(16278, 69) - : enterSubtree(16286, 65); + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ + ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 + var body = node.transformFlags & 64 /* ES2015 */ ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 + var name = hierarchyFacts & 16384 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; - return ts.updateFunctionExpression(node, undefined, node.asteriskToken, name, undefined, parameters, undefined, body); - } + return ts.updateFunctionExpression(node, + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Visits a FunctionDeclaration node. + * + * @param node a FunctionDeclaration node. + */ function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286, 65); + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 + var body = node.transformFlags & 64 /* ES2015 */ ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 + var name = hierarchyFacts & 16384 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; - return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, undefined, parameters, undefined, body); - } + return ts.updateFunctionDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + } + /** + * Transforms a function-like node into a FunctionExpression. + * + * @param node The function-like node to transform. + * @param location The source-map location for the new FunctionExpression. + * @param name The name of the new FunctionExpression. + */ function transformFunctionLikeToExpression(node, location, name, container) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32) - ? enterSubtree(16286, 65 | 8) - : enterSubtree(16286, 65); + var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) + ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 && !name && (node.kind === 228 || node.kind === 186)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 229 /* FunctionDeclaration */ || node.kind === 187 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; - return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, parameters, undefined, body), location), node); - } + return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body), location), + /*original*/ node); + } + /** + * Transforms the body of a function-like node. + * + * @param node A function-like node. + */ function transformFunctionBody(node) { - var multiLine = false; - var singleLine = false; + var multiLine = false; // indicates whether the block *must* be emitted as multiple lines + var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; var statements = []; @@ -49666,24 +61743,33 @@ var ts; var statementOffset; resumeLexicalEnvironment(); if (ts.isBlock(body)) { - statementOffset = ts.addStandardPrologue(statements, body.statements, false); + // ensureUseStrict is false because no new prologue-directive should be added. + // addStandardPrologue will put already-existing directives at the beginning of the target statement-array + statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false); } addCaptureThisForNodeIfNeeded(statements, node); addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, false); + addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); + // If we added any generated statements, this must be a multi-line block. if (!multiLine && statements.length > 0) { multiLine = true; } if (ts.isBlock(body)) { + // addCustomPrologue puts already-existing directives at the beginning of the target statement-array statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); + // If the original body was a multi-line block, this must be a multi-line block. if (!multiLine && body.multiLine) { multiLine = true; } } else { - ts.Debug.assert(node.kind === 187); + ts.Debug.assert(node.kind === 188 /* ArrowFunction */); + // To align with the old emitter, we use a synthetic end position on the location + // for the statement list we synthesize when we down-level an arrow function with + // an expression function body. This prevents both comments and source maps from + // being emitted for the end position only. statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -49697,72 +61783,103 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); - ts.setEmitFlags(returnStatement, 384 | 32 | 1024); + ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); statements.push(returnStatement); + // To align with the source map emit for the old emitter, we set a custom + // source map location for the close brace. closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); ts.addRange(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, false); + prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + // If we added any final generated statements, this must be a multi-line block if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { multiLine = true; } var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { - ts.setEmitFlags(block, 1); + ts.setEmitFlags(block, 1 /* SingleLine */); } if (closeBraceLocation) { - ts.setTokenSourceMapRange(block, 18, closeBraceLocation); + ts.setTokenSourceMapRange(block, 18 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; } function visitFunctionBodyDownLevel(node) { var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, true)), updated.statements)); + return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), + /*location*/ updated.statements)); } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { + // A function body is not a block scope. return ts.visitEachChild(node, visitor, context); } - var ancestorFacts = hierarchyFacts & 256 - ? enterSubtree(4032, 512) - : enterSubtree(3904, 128); + var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ + ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) + : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */); var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return updated; } + /** + * Visits an ExpressionStatement that contains a destructuring assignment. + * + * @param node An ExpressionStatement node. + */ function visitExpressionStatement(node) { + // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 185: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, false)); - case 194: - return ts.updateStatement(node, visitBinaryExpression(node.expression, false)); + case 186 /* ParenthesizedExpression */: + return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 195 /* BinaryExpression */: + return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a ParenthesizedExpression that may contain a destructuring assignment. + * + * @param node A ParenthesizedExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ function visitParenthesizedExpression(node, needsDestructuringValue) { + // If we are here it is most likely because our expression is a destructuring assignment. if (!needsDestructuringValue) { + // By default we always emit the RHS at the end of a flattened destructuring + // expression. If we are in a state where we do not need the destructuring value, + // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 185: - return ts.updateParen(node, visitParenthesizedExpression(node.expression, false)); - case 194: - return ts.updateParen(node, visitBinaryExpression(node.expression, false)); + case 186 /* ParenthesizedExpression */: + return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 195 /* BinaryExpression */: + return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a BinaryExpression that contains a destructuring assignment. + * + * @param node A BinaryExpression node. + * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs + * of a destructuring assignment. + */ function visitBinaryExpression(node, needsDestructuringValue) { + // If we are here it is because this is a destructuring assignment. if (ts.isDestructuringAssignment(node)) { - return ts.flattenDestructuringAssignment(node, visitor, context, 0, needsDestructuringValue); + return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue); } return ts.visitEachChild(node, visitor, context); } function visitVariableStatement(node) { - var ancestorFacts = enterSubtree(0, ts.hasModifier(node, 1) ? 32 : 0); + var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); var updated; - if (convertedLoopState && (node.declarationList.flags & 3) === 0) { + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + // we are inside a converted loop - hoist variable declarations var assignments = void 0; for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -49770,10 +61887,10 @@ var ts; if (decl.initializer) { var assignment = void 0; if (ts.isBindingPattern(decl.name)) { - assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0); + assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { - assignment = ts.createBinary(decl.name, 58, ts.visitNode(decl.initializer, visitor, ts.isExpression)); + assignment = ts.createBinary(decl.name, 58 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); ts.setTextRange(assignment, decl); } assignments = ts.append(assignments, assignment); @@ -49783,29 +61900,37 @@ var ts; updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); } else { + // none of declarations has initializer - the entire variable statement can be deleted updated = undefined; } } else { updated = ts.visitEachChild(node, visitor, context); } - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return updated; } + /** + * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`). + * + * @param node A VariableDeclarationList node. + */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64) { - if (node.flags & 3) { + if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var declarations = ts.flatMap(node.declarations, node.flags & 1 + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration); var declarationList = ts.createVariableDeclarationList(declarations); ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 + if (node.transformFlags & 8388608 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); if (firstDeclaration) { var lastDeclaration = ts.lastOrUndefined(declarations); @@ -49816,23 +61941,76 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + /** + * Gets a value indicating whether we should emit an explicit initializer for a variable + * declaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ function shouldEmitExplicitInitializerForLetDeclaration(node) { + // Nested let bindings might need to be initialized explicitly to preserve + // ES6 semantic: + // + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // + // Top level bindings never collide with anything and thus don't require + // explicit initialization. As for nested let bindings there are two cases: + // + // - Nested let bindings that were not renamed definitely should be + // initialized explicitly: + // + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // + // Without explicit initialization code in /*1*/ can be executed even if + // some-condition is evaluated to false. + // + // - Renaming introduces fresh name that should not collide with any + // existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding + // declared inside loop body (but not in loop initializer): + // + // let x; + // for (;;) { + // let x; + // } + // + // In downlevel codegen inner 'x' will be renamed so it won't collide + // with outer 'x' however it will should be reset on every iteration as + // if it was declared anew. + // + // * Why non-captured binding? + // - Because if loop contains block scoped binding captured in some + // function then loop body will be rewritten to have a fresh scope + // on every iteration so everything will just work. + // + // * Why loop initializer is excluded? + // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; - var emittedAsTopLevel = (hierarchyFacts & 64) !== 0 + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop - && (hierarchyFacts & 512) !== 0); + && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0); var emitExplicitInitializer = !emittedAsTopLevel - && (hierarchyFacts & 2048) === 0 + && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0 && (!resolver.isDeclarationWithCollidingName(node) || (isDeclaredInLoop && !isCapturedInFunction - && (hierarchyFacts & (1024 | 2048)) === 0)); + && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0)); return emitExplicitInitializer; } + /** + * Visits a VariableDeclaration in a `let` declaration list. + * + * @param node A VariableDeclaration node. + */ function visitVariableDeclarationInLetDeclarationList(node) { + // For binding pattern names that lack initializers there is no point to emit + // explicit initializer since downlevel codegen for destructuring will fail + // in the absence of initializer so all binding elements will say uninitialized var name = node.name; if (ts.isBindingPattern(name)) { return visitVariableDeclaration(node); @@ -49844,91 +62022,108 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a VariableDeclaration node with a binding pattern. + * + * @param node A VariableDeclaration node. + */ function visitVariableDeclaration(node) { - var ancestorFacts = enterSubtree(32, 0); + var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); var updated; if (ts.isBindingPattern(node.name)) { - updated = ts.flattenDestructuringBinding(node, visitor, context, 0, undefined, (ancestorFacts & 32) !== 0); + updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, + /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); } else { updated = ts.visitEachChild(node, visitor, context); } - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return updated; } function recordLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); + convertedLoopState.labels.set(ts.idText(node.label), true); } function resetLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); + convertedLoopState.labels.set(ts.idText(node.label), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { convertedLoopState.labels = ts.createMap(); } var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); - return ts.isIterationStatement(statement, false) - ? visitIterationStatement(statement, node) + return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) + ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 212: - case 213: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 214: + case 215 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 215: + case 216 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 216: + case 217 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert); - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return updated; } function visitDoOrWhileStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts(0, 256, node, outermostLabeledStatement); + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); } function visitForStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts(3008, 1280, node, outermostLabeledStatement); + return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement); } function visitForInStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts(1984, 2304, node, outermostLabeledStatement); + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); } function visitForOfStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts(1984, 2304, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; if (ts.isVariableDeclarationList(node.initializer)) { - if (node.initializer.flags & 3) { + if (node.initializer.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { - var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0, boundValue); + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer); ts.setOriginalNode(declarationList, node.initializer); + // Adjust the source map range for the first declaration to align with the old + // emitter. var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); - statements.push(ts.createVariableStatement(undefined, declarationList)); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, declarationList)); } else { - statements.push(ts.setTextRange(ts.createVariableStatement(undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(undefined), undefined, boundValue) + // The following call does not include the initializer, so we have + // to emit it separately. + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), + /*type*/ undefined, boundValue) ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); } } else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. var assignment = ts.createAssignment(node.initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); - statements.push(ts.createStatement(visitBinaryExpression(assignment, false))); + statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { assignment.end = node.initializer.end; @@ -49951,62 +62146,113 @@ var ts; statements.push(statement); } } - return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + // The old emitter does not emit source maps for the block. + // We add the location to preserve comments. + return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), + /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (var _i = 0, _a = expr; _i < _a.length; _i++) { + // var v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. var counter = ts.createLoopVariable(); - var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); - ts.setEmitFlags(expression, 48 | ts.getEmitFlags(expression)); - var forStatement = ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), - ts.setTextRange(ts.createVariableDeclaration(rhsReference, undefined, expression), node.expression) - ]), node.expression), 2097152), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); - ts.setEmitFlags(forStatement, 256); + var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + // The old emitter does not emit source maps for the expression + ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression)); + var forStatement = ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), + ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), + /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), + /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), + /*location*/ node); + // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. + ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */); ts.setTextRange(forStatement, node); return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); } function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); - var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(undefined); + var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); + var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); - var returnMethod = ts.createTempVariable(undefined); + var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); var values = ts.createValuesHelper(context, expression, node.expression); - var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); - var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); + var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( + /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), + ts.createVariableDeclaration(result, /*type*/ undefined, next) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), + /*incrementor*/ ts.createAssignment(result, next), + /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), + /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) - ]), 1)), ts.createBlock([ - ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1), - ]), undefined, ts.setEmitFlags(ts.createBlock([ - ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) - ]), 1)) + ]), 1 /* SingleLine */)), ts.createBlock([ + ts.createTry( + /*tryBlock*/ ts.createBlock([ + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ]), + /*catchClause*/ undefined, + /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ + ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */) + ]), 1 /* SingleLine */)) ])); } + /** + * Visits an ObjectLiteralExpression with computed propety names. + * + * @param node An ObjectLiteralExpression node. + */ function visitObjectLiteralExpression(node) { + // We are here because a ComputedPropertyName was used somewhere in the expression. var properties = node.properties; var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. var numInitialProperties = numProperties; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 && hierarchyFacts & 4) + if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 144) { + if (property.name.kind === 145 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -50015,29 +62261,37 @@ var ts; if (numInitialPropertiesWithoutYield < numInitialProperties) { numInitialProperties = numInitialPropertiesWithoutYield; } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. var temp = ts.createTempVariable(hoistVariableDeclaration); + // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); if (node.multiLine) { - assignment.startsOnNewLine = true; + ts.startOnNewLine(assignment); } expressions.push(assignment); addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + // We need to clone the temporary identifier so that we can write it on a + // new line expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp); return ts.inlineExpressions(expressions); } return ts.visitEachChild(node, visitor, context); } function shouldConvertIterationStatementBody(node) { - return (resolver.getNodeCheckFlags(node) & 65536) !== 0; + return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } + /** + * Records constituents of name for the given variable to be hoisted in the outer scope. + */ function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { if (!state.hoistedLocalVariables) { state.hoistedLocalVariables = []; } visit(node.name); function visit(node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { state.hoistedLocalVariables.push(node); } else { @@ -50054,11 +62308,13 @@ var ts; if (!shouldConvertIterationStatementBody(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; - convertedLoopState.allowedNonLabeledJumps = 2 | 4; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; } var result = convert - ? convert(node, outermostLabeledStatement, undefined) + ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined) : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); if (convertedLoopState) { convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; @@ -50068,18 +62324,20 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 214: - case 215: - case 216: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 227) { + if (initializer && initializer.kind === 228 /* VariableDeclarationList */) { loopInitializer = initializer; } break; } + // variables that will be passed to the loop as parameters var loopParameters = []; + // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); @@ -50088,13 +62346,21 @@ var ts; var outerConvertedLoopState = convertedLoopState; convertedLoopState = { loopOutParameters: loopOutParameters }; if (outerConvertedLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through if (outerConvertedLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; } if (outerConvertedLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops convertedLoopState.thisName = outerConvertedLoopState.thisName; } if (outerConvertedLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } @@ -50106,61 +62372,83 @@ var ts; if (loopOutParameters.length || lexicalEnvironment) { var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1, statements_4); + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } ts.addRange(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, true); + loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { loopBody.multiLine = true; } else { - loopBody = ts.createBlock([loopBody], true); + loopBody = ts.createBlock([loopBody], /*multiline*/ true); } - var containsYield = (node.statement.transformFlags & 16777216) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4) !== 0; + var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; + var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { - loopBodyFlags |= 8; + loopBodyFlags |= 8 /* CapturesThis */; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144; - } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 2097152)); + loopBodyFlags |= 262144 /* AsyncFunctionBody */; + } + var convertedLoopVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, loopParameters, + /*type*/ undefined, loopBody), loopBodyFlags)) + ]), 2097152 /* NoHoisting */)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; + // propagate state from the inner loop to the outer loop if necessary if (currentState.argumentsName) { + // if alias for arguments is set if (outerConvertedLoopState) { + // pass it to outer converted loop outerConvertedLoopState.argumentsName = currentState.argumentsName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + // this is top level converted loop and we need to create an alias for 'arguments' object + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + /*type*/ undefined, ts.createIdentifier("arguments"))); } } if (currentState.thisName) { + // if alias for this is set if (outerConvertedLoopState) { + // pass it to outer converted loop outerConvertedLoopState.thisName = currentState.thisName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + /*type*/ undefined, ts.createIdentifier("this"))); } } if (currentState.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later if (outerConvertedLoopState) { + // pass them to outer converted loop outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } + // hoist collected variable declarations for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } + // add extra variables to hold out parameters if necessary if (loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; @@ -50170,8 +62458,10 @@ var ts; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); var loop; @@ -50180,9 +62470,13 @@ var ts; } else { var clone_3 = ts.getMutableClone(node); + // clean statement part clone_3.statement = undefined; + // visit childnodes to transform initializer/condition/incrementor parts clone_3 = ts.visitEachChild(clone_3, visitor, context); - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); + // set loop statement + clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); + // reset and re-aggregate the transform flags clone_3.transformFlags = 0; ts.aggregateTransformFlags(clone_3); loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); @@ -50191,9 +62485,9 @@ var ts; return statements; } function copyOutParameter(outParam, copyDirection) { - var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; - var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; - return ts.createBinary(target, 58, source); + var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return ts.createBinary(target, 58 /* EqualsToken */, source); } function copyOutParameters(outParams, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { @@ -50204,40 +62498,44 @@ var ts; function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { var outerConvertedLoopState = convertedLoopState; var statements = []; - var isSimpleLoop = !(state.nonLocalJumps & ~4) && + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + // NOTE: if loop uses only 'continue' it still will be emitted as simple loop + var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); - var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); + var stateVariable = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0, statements); - if (state.nonLocalJumps & 8) { + copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8; + outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value")); } - statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34, ts.createLiteral("object")), returnStatement)); + statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement)); } - if (state.nonLocalJumps & 2) { - statements.push(ts.createIf(ts.createBinary(loopResultName, 34, ts.createLiteral("break")), ts.createBreak())); + if (state.nonLocalJumps & 2 /* Break */) { + statements.push(ts.createIf(ts.createBinary(loopResultName, 34 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -50263,6 +62561,9 @@ var ts; } table.forEach(function (labelMarker, labelText) { var statements = []; + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) { var label = ts.createIdentifier(labelText); statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label)); @@ -50285,33 +62586,42 @@ var ts; } } else { - loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); + loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } } + /** + * Adds the members of an object literal to an array of expressions. + * + * @param expressions An array of expressions. + * @param node An ObjectLiteralExpression node. + * @param receiver The receiver for members of the ObjectLiteralExpression. + * @param numInitialNonComputedProperties The number of initial properties without + * computed property names. + */ function addObjectLiteralMembers(expressions, node, receiver, start) { var properties = node.properties; var numProperties = properties.length; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); } break; - case 151: + case 152 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 261: + case 265 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 262: + case 266 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -50320,72 +62630,108 @@ var ts; } } } + /** + * Transforms a PropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the PropertyAssignment. + * @param property The PropertyAssignment node. + * @param receiver The receiver for the assignment. + */ function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } + /** + * Transforms a ShorthandPropertyAssignment node into an expression. + * + * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment. + * @param property The ShorthandPropertyAssignment node. + * @param receiver The receiver for the assignment. + */ function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } + /** + * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression. + * + * @param node The ObjectLiteralExpression that contains the MethodDeclaration. + * @param method The MethodDeclaration node. + * @param receiver The receiver for the assignment. + */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0, 0); - var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined, container)); + var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); + var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { - var ancestorFacts = enterSubtree(4032, 0); + var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); var updated; ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (ts.isBindingPattern(node.variableDeclaration.name)) { - var temp = ts.createTempVariable(undefined); + var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); var newVariableDeclaration = ts.createVariableDeclaration(temp); ts.setTextRange(newVariableDeclaration, node.variableDeclaration); - var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0, temp); + var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); var list = ts.createVariableDeclarationList(vars); ts.setTextRange(list, node.variableDeclaration); - var destructure = ts.createVariableStatement(undefined, list); + var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list); updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); } else { updated = ts.visitEachChild(node, visitor, context); } - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return updated; } function addStatementToStartOfBlock(block, statement) { var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement); return ts.updateBlock(block, [statement].concat(transformedStatements)); } + /** + * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a + * PropertyAssignment. + * + * @param node A MethodDeclaration node. + */ function visitMethodDeclaration(node) { + // We should only get here for methods on an object literal with regular identifier names. + // Methods on classes are handled in visitClassDeclaration/visitClassExpression. + // Methods with computed property names are handled in visitObjectLiteralExpression. ts.Debug.assert(!ts.isComputedPropertyName(node.name)); - var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined, undefined); - ts.setEmitFlags(functionExpression, 512 | ts.getEmitFlags(functionExpression)); - return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), node); - } + var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined); + ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); + return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), + /*location*/ node); + } + /** + * Visits an AccessorDeclaration of an ObjectLiteralExpression. + * + * @param node An AccessorDeclaration node. + */ function visitAccessorDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286, 65); + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; - if (node.transformFlags & 32768) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 153) { + if (node.kind === 154 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -50395,45 +62741,121 @@ var ts; else { updated = ts.visitEachChild(node, visitor, context); } - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } + /** + * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment. + * + * @param node A ShorthandPropertyAssignment node. + */ function visitShorthandPropertyAssignment(node) { - return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), node); + return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), + /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0, 8192); + var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 32768 : 0); + exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); return updated; } + /** + * Visits a YieldExpression node. + * + * @param node A YieldExpression node. + */ function visitYieldExpression(node) { + // `yield` expressions are transformed using the generators transformer. return ts.visitEachChild(node, visitor, context); } + /** + * Visits an ArrayLiteralExpression that contains a spread element. + * + * @param node An ArrayLiteralExpression node. + */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64) { - return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); + if (node.transformFlags & 64 /* ES2015 */) { + // We are here because we contain a SpreadElementExpression. + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a CallExpression that contains either a spread element or `super`. + * + * @param node a CallExpression. + */ function visitCallExpression(node) { - if (ts.getEmitFlags(node) & 33554432) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64) { - return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + if (node.transformFlags & 64 /* ES2015 */) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } - return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); + return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); + // The class statements are the statements generated by visiting the first statement of the + // body (1), while all other statements are added to remainingStatements (2) var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper var variable = varStatement.declarationList.declarations[0]; var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // var C_1; + // }()) + // var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); var funcStatements = func.body.statements; @@ -50441,44 +62863,89 @@ var ts; var classBodyEnd = -1; var statements = []; if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); if (extendsCall) { statements.push(extendsCall); classBodyStart++; } + // The next statement is the function declaration. statements.push(funcStatements[classBodyStart]); classBodyStart++; + // Add the class alias following the declaration. statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } + // Find the trailing 'return' statement (4) while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { classBodyEnd--; } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. ts.addRange(statements, funcStatements, classBodyEnd + 1); } + // Add the remaining statements of the outer wrapper. ts.addRange(statements, remainingStatements); - ts.addRange(statements, classStatements, 1); - return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, undefined, undefined, undefined, undefined, func.parameters, undefined, ts.updateBlock(func.body, statements))), undefined, call.arguments)))); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); } function visitImmediateSuperCallInBody(node) { - return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + // We are here either because SuperKeyword was used somewhere in the expression, or + // because we contain a SpreadElementExpression. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97) { - ts.setEmitFlags(thisArg, 4); + if (node.expression.kind === 97 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall; - if (node.transformFlags & 524288) { - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + if (node.transformFlags & 524288 /* ContainsSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); - } - if (node.expression.kind === 97) { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 97 /* SuperKeyword */) { var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createIdentifier("_this"), initializer) @@ -50486,14 +62953,40 @@ var ts; } return ts.setOriginalNode(resultingCall, node); } + /** + * Visits a NewExpression that contains a spread element. + * + * @param node A NewExpression node. + */ function visitNewExpression(node) { - if (node.transformFlags & 524288) { + if (node.transformFlags & 524288 /* ContainsSpread */) { + // We are here because we contain a SpreadElementExpression. + // [source] + // new C(...a) + // + // [output] + // new ((_a = C).bind.apply(_a, [void 0].concat(a)))() var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); + return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), + /*typeArguments*/ undefined, []); } return ts.visitEachChild(node, visitor, context); } + /** + * Transforms an array of Expression nodes that contains a SpreadExpression. + * + * @param elements The array of Expression nodes. + * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array. + * @param multiLine A value indicating whether the result should be emitted on multiple lines. + */ function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) { + // [source] + // [a, ...b, c] + // + // [output] + // [a].concat(b, [c]) + // Map spans of spread expressions into their expressions and spans of other + // expressions into an array literal. var numElements = elements.length; var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) { return visitPartition(partition, multiLine, hasTrailingComma && end === numElements); @@ -50503,7 +62996,7 @@ var ts; var firstSegment = segments[0]; if (ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) - && (ts.getEmitFlags(firstSegment.expression) & 4096) + && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) && firstSegment.expression.escapedText === "___spread") { return segments[0]; } @@ -50513,10 +63006,11 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 178 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } + // Rewrite using the pattern .concat(, , ...) return ts.createArrayConcat(segments.shift(), segments); } } @@ -50534,28 +63028,56 @@ var ts; function visitSpreadElement(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } + /** + * Transforms the expression of a SpreadExpression node. + * + * @param node A SpreadExpression node. + */ function visitExpressionOfSpread(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } + /** + * Visits a template literal. + * + * @param node A template literal. + */ function visitTemplateLiteral(node) { return ts.setTextRange(ts.createLiteral(node.text), node); } + /** + * Visits a string literal with an extended unicode escape. + * + * @param node A string literal. + */ function visitStringLiteral(node) { if (node.hasExtendedUnicodeEscape) { return ts.setTextRange(ts.createLiteral(node.text), node); } return node; } + /** + * Visits a binary or octal (ES6) numeric literal. + * + * @param node A string literal. + */ function visitNumericLiteral(node) { - if (node.numericLiteralFlags & 48) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { return ts.setTextRange(ts.createNumericLiteral(node.text), node); } return node; } + /** + * Visits a TaggedTemplateExpression node. + * + * @param node A TaggedTemplateExpression node. + */ function visitTaggedTemplateExpression(node) { + // Visit the tag expression var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - var temp = ts.createTempVariable(hoistVariableDeclaration); - var templateArguments = [temp]; + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; var cookedStrings = []; var rawStrings = []; var template = node.template; @@ -50573,23 +63095,60 @@ var ts; templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); } } - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, undefined, templateArguments) - ])); + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ function getRawLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - var isLast = node.kind === 13 || node.kind === 16; + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 13 /* NoSubstitutionTemplateLiteral */ || node.kind === 16 /* TemplateTail */; text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. text = text.replace(/\r\n?/g, "\n"); return ts.setTextRange(ts.createLiteral(text), node); } + /** + * Visits a TemplateExpression node. + * + * @param node A TemplateExpression node. + */ function visitTemplateExpression(node) { var expressions = []; addTemplateHead(expressions, node); addTemplateSpans(expressions, node); + // createAdd will check if each expression binds less closely than binary '+'. + // If it does, it wraps the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" var expression = ts.reduceLeft(expressions, ts.createAdd); if (ts.nodeIsSynthesized(expression)) { expression.pos = node.pos; @@ -50597,76 +63156,137 @@ var ts; } return expression; } + /** + * Gets a value indicating whether we need to include the head of a TemplateExpression. + * + * @param node A TemplateExpression node. + */ function shouldAddTemplateHead(node) { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() ts.Debug.assert(node.templateSpans.length !== 0); return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; } + /** + * Adds the head of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ function addTemplateHead(expressions, node) { if (!shouldAddTemplateHead(node)) { return; } expressions.push(ts.createLiteral(node.head.text)); } + /** + * Visits and adds the template spans of a TemplateExpression to an array of expressions. + * + * @param expressions An array of expressions. + * @param node A TemplateExpression node. + */ function addTemplateSpans(expressions, node) { for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span_6 = _a[_i]; expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. if (span_6.literal.text.length !== 0) { expressions.push(ts.createLiteral(span_6.literal.text)); } } } + /** + * Visits the `super` keyword + */ function visitSuperKeyword(isExpressionOfCall) { - return hierarchyFacts & 8 + return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") : ts.createIdentifier("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 && node.name.escapedText === "target") { - if (hierarchyFacts & 8192) { - hierarchyFacts |= 32768; + if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { + if (hierarchyFacts & 8192 /* ComputedPropertyName */) { + hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } else { - hierarchyFacts |= 16384; + hierarchyFacts |= 16384 /* NewTarget */; } return ts.createIdentifier("_newTarget"); } return node; } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to be printed. + * @param emitCallback The callback used to emit the node. + */ function onEmitNode(hint, node, emitCallback) { - if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { - var ancestorFacts = enterSubtree(16286, ts.getEmitFlags(node) & 8 - ? 65 | 16 - : 65); + if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { + // If we are tracking a captured `this`, keep track of the enclosing function. + var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ + : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); - exitSubtree(ancestorFacts, 0, 0); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return; } previousOnEmitNode(hint, node, emitCallback); } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains block-scoped bindings (e.g. `let` or `const`). + */ function enableSubstitutionsForBlockScopedBindings() { - if ((enabledSubstitutions & 2) === 0) { - enabledSubstitutions |= 2; - context.enableSubstitution(71); + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(71 /* Identifier */); } } + /** + * Enables a more costly code path for substitutions when we determine a source file + * contains a captured `this`. + */ function enableSubstitutionsForCapturedThis() { - if ((enabledSubstitutions & 1) === 0) { - enabledSubstitutions |= 1; - context.enableSubstitution(99); - context.enableEmitNotification(152); - context.enableEmitNotification(151); - context.enableEmitNotification(153); - context.enableEmitNotification(154); - context.enableEmitNotification(187); - context.enableEmitNotification(186); - context.enableEmitNotification(228); - } - } + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(99 /* ThisKeyword */); + context.enableEmitNotification(153 /* Constructor */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(188 /* ArrowFunction */); + context.enableEmitNotification(187 /* FunctionExpression */); + context.enableEmitNotification(229 /* FunctionDeclaration */); + } + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (hint === 1) { + if (hint === 1 /* Expression */) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -50674,8 +63294,13 @@ var ts; } return node; } + /** + * Hooks substitutions for non-expression identifiers. + */ function substituteIdentifier(node) { - if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { + // Only substitute the identifier if we have enabled substitutions for block-scoped + // bindings. + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var original = ts.getParseTreeNode(node, ts.isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return ts.setTextRange(ts.getGeneratedNameForNode(original), node); @@ -50683,29 +63308,45 @@ var ts; } return node; } + /** + * Determines whether a name is the name of a declaration with a colliding name. + * NOTE: This function expects to be called with an original source tree node. + * + * @param node An original source tree node. + */ function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 176: - case 229: - case 232: - case 226: + case 177 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 227 /* VariableDeclaration */: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } return false; } + /** + * Substitutes an expression. + * + * @param node An Expression node. + */ function substituteExpression(node) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 99: + case 99 /* ThisKeyword */: return substituteThisKeyword(node); } return node; } + /** + * Substitutes an expression identifier. + * + * @param node An Identifier node. + */ function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); @@ -50716,11 +63357,17 @@ var ts; function isPartOfClassBody(declaration, node) { var currentNode = ts.getParseTreeNode(node); if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. return false; } var blockScope = ts.getEnclosingBlockScopeContainer(declaration); while (currentNode) { if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. return false; } if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { @@ -50730,15 +63377,20 @@ var ts; } return false; } + /** + * Substitutes `this` when contained within an arrow function. + * + * @param node The ThisKeyword node. + */ function substituteThisKeyword(node) { - if (enabledSubstitutions & 1 - && hierarchyFacts & 16) { + if (enabledSubstitutions & 1 /* CapturedThis */ + && hierarchyFacts & 16 /* CapturesThis */) { return ts.setTextRange(ts.createIdentifier("_this"), node); } return node; } function getClassMemberPrefix(node, member) { - return ts.hasModifier(member, 32) + return ts.hasModifier(member, 32 /* Static */) ? ts.getInternalName(node) : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); } @@ -50750,19 +63402,19 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 210) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 211 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 181) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 182 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; - if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97) { + if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 97 /* SuperKeyword */) { return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 198) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 199 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -50772,18 +63424,154 @@ var ts; ts.transformES2015 = transformES2015; function createExtendsHelper(context, name) { context.requestEmitHelper(extendsHelper); - return ts.createCall(ts.getHelperName("__extends"), undefined, [ + return ts.createCall(ts.getHelperName("__extends"), + /*typeArguments*/ undefined, [ name, ts.createIdentifier("_super") ]); } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } var extendsHelper = { name: "typescript:extends", scoped: false, priority: 0, text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; })(ts || (ts = {})); +/// +/// +// Transforms generator functions into a compatible ES5 representation with similar runtime +// semantics. This is accomplished by first transforming the body of each generator +// function into an intermediate representation that is the compiled into a JavaScript +// switch statement. +// +// Many functions in this transformer will contain comments indicating the expected +// intermediate representation. For illustrative purposes, the following intermediate +// language is used to define this intermediate representation: +// +// .nop - Performs no operation. +// .local NAME, ... - Define local variable declarations. +// .mark LABEL - Mark the location of a label. +// .br LABEL - Jump to a label. If jumping out of a protected +// region, all .finally blocks are executed. +// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey. +// If jumping out of a protected region, all .finally +// blocks are executed. +// .yield (x) - Yield the value of the optional expression `x`. +// Resume at the next label. +// .yieldstar (x) - Delegate yield to the value of the optional +// expression `x`. Resume at the next label. +// NOTE: `x` must be an Iterator, not an Iterable. +// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or +// "break" abrupt completions jump to the CONTINUE or +// BREAK labels, respectively. +// .endloop - Marks the end of a loop. +// .with (x) - Marks the beginning of a WithStatement block, using +// the supplied expression. +// .endwith - Marks the end of a WithStatement. +// .switch - Marks the beginning of a SwitchStatement. +// .endswitch - Marks the end of a SwitchStatement. +// .labeled NAME - Marks the beginning of a LabeledStatement with the +// supplied name. +// .endlabeled - Marks the end of a LabeledStatement. +// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the +// labels for each block. +// .catch (x) - Marks the beginning of a catch block. +// .finally - Marks the beginning of a finally block. +// .endfinally - Marks the end of a finally block. +// .endtry - Marks the end of a protected region. +// .throw (x) - Throws the value of the expression `x`. +// .return (x) - Returns the value of the expression `x`. +// +// In addition, the illustrative intermediate representation introduces some special +// variables: +// +// %sent% - Either returns the next value sent to the generator, +// returns the result of a delegated yield, or throws +// the exception sent to the generator. +// %error% - Returns the value of the current exception in a +// catch block. +// +// This intermediate representation is then compiled into JavaScript syntax. The resulting +// compilation output looks something like the following: +// +// function f() { +// var /*locals*/; +// /*functions*/ +// return __generator(function (state) { +// switch (state.label) { +// /*cases per label*/ +// } +// }); +// } +// +// Each of the above instructions corresponds to JavaScript emit similar to the following: +// +// .local NAME | var NAME; +// -------------------------------|---------------------------------------------- +// .mark LABEL | case LABEL: +// -------------------------------|---------------------------------------------- +// .br LABEL | return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL]; +// -------------------------------|---------------------------------------------- +// .yield (x) | return [4 /*yield*/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .yieldstar (x) | return [5 /*yield**/, x]; +// .mark RESUME | case RESUME: +// a = %sent%; | a = state.sent(); +// -------------------------------|---------------------------------------------- +// .with (_a) | with (_a) { +// a(); | a(); +// | } +// | state.label = LABEL; +// .mark LABEL | case LABEL: +// | with (_a) { +// b(); | b(); +// | } +// .endwith | +// -------------------------------|---------------------------------------------- +// | case 0: +// | state.trys = []; +// | ... +// .try TRY, CATCH, FINALLY, END | +// .mark TRY | case TRY: +// | state.trys.push([TRY, CATCH, FINALLY, END]); +// .nop | +// a(); | a(); +// .br END | return [3 /*break*/, END]; +// .catch (e) | +// .mark CATCH | case CATCH: +// | e = state.sent(); +// b(); | b(); +// .br END | return [3 /*break*/, END]; +// .finally | +// .mark FINALLY | case FINALLY: +// c(); | c(); +// .endfinally | return [7 /*endfinally*/]; +// .endtry | +// .mark END | case END: +/*@internal*/ var ts; (function (ts) { var OpCode; @@ -50798,13 +63586,15 @@ var ts; OpCode[OpCode["YieldStar"] = 7] = "YieldStar"; OpCode[OpCode["Return"] = 8] = "Return"; OpCode[OpCode["Throw"] = 9] = "Throw"; - OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; + OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block })(OpCode || (OpCode = {})); + // whether a generated code block is opening or closing at the current operation for a FunctionBuilder var BlockAction; (function (BlockAction) { BlockAction[BlockAction["Open"] = 0] = "Open"; BlockAction[BlockAction["Close"] = 1] = "Close"; })(BlockAction || (BlockAction = {})); + // the kind for a generated code block in a FunctionBuilder var CodeBlockKind; (function (CodeBlockKind) { CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception"; @@ -50813,6 +63603,7 @@ var ts; CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop"; CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled"; })(CodeBlockKind || (CodeBlockKind = {})); + // the state for a generated code exception block var ExceptionBlockState; (function (ExceptionBlockState) { ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try"; @@ -50820,6 +63611,7 @@ var ts; ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally"; ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done"; })(ExceptionBlockState || (ExceptionBlockState = {})); + // NOTE: changes to this enum should be reflected in the __generator helper. var Instruction; (function (Instruction) { Instruction[Instruction["Next"] = 0] = "Next"; @@ -50833,11 +63625,11 @@ var ts; })(Instruction || (Instruction = {})); function getInstructionName(instruction) { switch (instruction) { - case 2: return "return"; - case 3: return "break"; - case 4: return "yield"; - case 5: return "yield*"; - case 7: return "endfinally"; + case 2 /* Return */: return "return"; + case 3 /* Break */: return "break"; + case 4 /* Yield */: return "yield"; + case 5 /* YieldStar */: return "yield*"; + case 7 /* Endfinally */: return "endfinally"; } } function transformGenerators(context) { @@ -50851,36 +63643,57 @@ var ts; var renamedCatchVariableDeclarations; var inGeneratorFunctionBody; var inStatementContainingYield; - var blocks; - var blockOffsets; - var blockActions; - var blockStack; - var labelOffsets; - var labelExpressions; - var nextLabelId = 1; - var operations; - var operationArguments; - var operationLocations; - var state; - var blockIndex = 0; - var labelNumber = 0; + // The following three arrays store information about generated code blocks. + // All three arrays are correlated by their index. This approach is used over allocating + // objects to store the same information to avoid GC overhead. + // + var blocks; // Information about the code block + var blockOffsets; // The operation offset at which a code block begins or ends + var blockActions; // Whether the code block is opened or closed + var blockStack; // A stack of currently open code blocks + // Labels are used to mark locations in the code that can be the target of a Break (jump) + // operation. These are translated into case clauses in a switch statement. + // The following two arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var labelOffsets; // The operation offset at which the label is defined. + var labelExpressions; // The NumericLiteral nodes bound to each label. + var nextLabelId = 1; // The next label id to use. + // Operations store information about generated code for the function body. This + // Includes things like statements, assignments, breaks (jumps), and yields. + // The following three arrays are correlated by their index. This approach is used over + // allocating objects to store the same information to avoid GC overhead. + // + var operations; // The operation to perform. + var operationArguments; // The arguments to the operation. + var operationLocations; // The source map location for the operation. + var state; // The name of the state object used by the generator at runtime. + // The following variables store information used by the `build` function: + // + var blockIndex = 0; // The index of the current block. + var labelNumber = 0; // The current label number. var labelNumbers; - var lastOperationWasAbrupt; - var lastOperationWasCompletion; - var clauses; - var statements; - var exceptionBlockStack; - var currentExceptionBlock; - var withBlockStack; + var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue). + var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw). + var clauses; // The case clauses generated for labels. + var statements; // The statements for the current label. + var exceptionBlockStack; // A stack of containing exception blocks. + var currentExceptionBlock; // The current exception block. + var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; } + /** + * Visits a node. + * + * @param node The node to visit. + */ function visitor(node) { var transformFlags = node.transformFlags; if (inStatementContainingYield) { @@ -50889,56 +63702,66 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256) { + else if (transformFlags & 256 /* Generator */) { return visitGenerator(node); } - else if (transformFlags & 512) { + else if (transformFlags & 512 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { return node; } } + /** + * Visits a node that is contained within a statement that contains yield. + * + * @param node The node to visit. + */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 212: + case 213 /* DoStatement */: return visitDoStatement(node); - case 213: + case 214 /* WhileStatement */: return visitWhileStatement(node); - case 221: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 222: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); } } + /** + * Visits a node that is contained within a generator function. + * + * @param node The node to visit. + */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return visitAccessorDeclaration(node); - case 208: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 214: + case 215 /* ForStatement */: return visitForStatement(node); - case 215: + case 216 /* ForInStatement */: return visitForInStatement(node); - case 218: + case 219 /* BreakStatement */: return visitBreakStatement(node); - case 217: + case 218 /* ContinueStatement */: return visitContinueStatement(node); - case 219: + case 220 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216) { + if (node.transformFlags & 16777216 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 | 33554432)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -50946,42 +63769,67 @@ var ts; } } } + /** + * Visits a node that contains a YieldExpression. + * + * @param node The node to visit. + */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 194: + case 195 /* BinaryExpression */: return visitBinaryExpression(node); - case 195: + case 196 /* ConditionalExpression */: return visitConditionalExpression(node); - case 197: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 177: + case 178 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 178: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 180: + case 181 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 181: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182: + case 183 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); } } + /** + * Visits a generator function. + * + * @param node The node to visit. + */ function visitGenerator(node) { switch (node.kind) { - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); return ts.visitEachChild(node, visitor, context); } } + /** + * Visits a function declaration. + * + * This will be called when one of the following conditions are met: + * - The function declaration is a generator function. + * - The function declaration is contained within the body of a generator function. + * + * @param node The node to visit. + */ function visitFunctionDeclaration(node) { + // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body)), node), node); + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, node.modifiers, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -50993,6 +63841,8 @@ var ts; inStatementContainingYield = savedInStatementContainingYield; } if (inGeneratorFunctionBody) { + // Function declarations in a generator function body are hoisted + // to the top of the lexical scope and elided from the current statement. hoistFunctionDeclaration(node); return undefined; } @@ -51000,9 +63850,24 @@ var ts; return node; } } + /** + * Visits a function expression. + * + * This will be called when one of the following conditions are met: + * - The function expression is a generator function. + * - The function expression is contained within the body of a generator function. + * + * @param node The node to visit. + */ function visitFunctionExpression(node) { + // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(undefined, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body)), node), node); + node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformGeneratorFunctionBody(node.body)), + /*location*/ node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -51015,6 +63880,14 @@ var ts; } return node; } + /** + * Visits a get or set accessor declaration. + * + * This will be called when one of the following conditions are met: + * - The accessor is contained within the body of a generator function. + * + * @param node The node to visit. + */ function visitAccessorDeclaration(node) { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; var savedInStatementContainingYield = inStatementContainingYield; @@ -51025,7 +63898,13 @@ var ts; inStatementContainingYield = savedInStatementContainingYield; return node; } + /** + * Transforms the body of a generator function declaration. + * + * @param node The function body to transform. + */ function transformGeneratorFunctionBody(body) { + // Save existing generator state var statements = []; var savedInGeneratorFunctionBody = inGeneratorFunctionBody; var savedInStatementContainingYield = inStatementContainingYield; @@ -51040,6 +63919,7 @@ var ts; var savedOperationArguments = operationArguments; var savedOperationLocations = operationLocations; var savedState = state; + // Initialize generator state inGeneratorFunctionBody = true; inStatementContainingYield = false; blocks = undefined; @@ -51052,13 +63932,15 @@ var ts; operations = undefined; operationArguments = undefined; operationLocations = undefined; - state = ts.createTempVariable(undefined); + state = ts.createTempVariable(/*recordTempVariable*/ undefined); + // Build the generator resumeLexicalEnvironment(); - var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); + var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); ts.addRange(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); + // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; blocks = savedBlocks; @@ -51074,13 +63956,22 @@ var ts; state = savedState; return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); } + /** + * Visits a variable statement. + * + * This will be called when one of the following conditions are met: + * - The variable statement is contained within the body of a generator function. + * + * @param node The node to visit. + */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216) { + if (node.transformFlags & 16777216 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { - if (ts.getEmitFlags(node) & 1048576) { + // Do not hoist custom prologues. + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -51094,45 +63985,77 @@ var ts; return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } + /** + * Visits a binary expression. + * + * This will be called when one of the following conditions are met: + * - The node contains a YieldExpression. + * + * @param node The node to visit. + */ function visitBinaryExpression(node) { switch (ts.getExpressionAssociativity(node)) { - case 0: + case 0 /* Left */: return visitLeftAssociativeBinaryExpression(node); - case 1: + case 1 /* Right */: return visitRightAssociativeBinaryExpression(node); default: ts.Debug.fail("Unknown associativity."); } } function isCompoundAssignment(kind) { - return kind >= 59 - && kind <= 70; + return kind >= 59 /* FirstCompoundAssignment */ + && kind <= 70 /* LastCompoundAssignment */; } function getOperatorForCompoundAssignment(kind) { switch (kind) { - case 59: return 37; - case 60: return 38; - case 61: return 39; - case 62: return 40; - case 63: return 41; - case 64: return 42; - case 65: return 45; - case 66: return 46; - case 67: return 47; - case 68: return 48; - case 69: return 49; - case 70: return 50; - } - } + case 59 /* PlusEqualsToken */: return 37 /* PlusToken */; + case 60 /* MinusEqualsToken */: return 38 /* MinusToken */; + case 61 /* AsteriskEqualsToken */: return 39 /* AsteriskToken */; + case 62 /* AsteriskAsteriskEqualsToken */: return 40 /* AsteriskAsteriskToken */; + case 63 /* SlashEqualsToken */: return 41 /* SlashToken */; + case 64 /* PercentEqualsToken */: return 42 /* PercentToken */; + case 65 /* LessThanLessThanEqualsToken */: return 45 /* LessThanLessThanToken */; + case 66 /* GreaterThanGreaterThanEqualsToken */: return 46 /* GreaterThanGreaterThanToken */; + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 47 /* GreaterThanGreaterThanGreaterThanToken */; + case 68 /* AmpersandEqualsToken */: return 48 /* AmpersandToken */; + case 69 /* BarEqualsToken */: return 49 /* BarToken */; + case 70 /* CaretEqualsToken */: return 50 /* CaretToken */; + } + } + /** + * Visits a right-associative binary expression containing `yield`. + * + * @param node The node to visit. + */ function visitRightAssociativeBinaryExpression(node) { var left = node.left, right = node.right; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 179: + case 180 /* PropertyAccessExpression */: + // [source] + // a.b = yield; + // + // [intermediate] + // .local _a + // _a = a; + // .yield resumeLabel + // .mark resumeLabel + // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 180: + case 181 /* ElementAccessExpression */: + // [source] + // a[b] = yield; + // + // [intermediate] + // .local _a, _b + // _a = a; + // _b = b; + // .yield resumeLabel + // .mark resumeLabel + // _a[_b] = %sent%; target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -51154,9 +64077,17 @@ var ts; if (ts.isLogicalOperator(node.operatorToken.kind)) { return visitLogicalBinaryExpression(node); } - else if (node.operatorToken.kind === 26) { + else if (node.operatorToken.kind === 26 /* CommaToken */) { return visitCommaExpression(node); } + // [source] + // a() + (yield) + c() + // + // [intermediate] + // .local _a + // _a = a(); + // .yield resumeLabel + // _a + %sent% + c() var clone_4 = ts.getMutableClone(node); clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); @@ -51164,73 +64095,176 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a logical binary expression containing `yield`. + * + * @param node A node to visit. + */ function visitLogicalBinaryExpression(node) { + // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need + // to be transformed as such: + // + // [source] + // x = a() && yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brfalse resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; + // + // [source] + // x = a() || yield; + // + // [intermediate] + // .local _a + // _a = a(); + // .brtrue resultLabel, (_a) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .mark resultLabel + // x = _a; var resultLabel = defineLabel(); var resultLocal = declareLocal(); - emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), node.left); - if (node.operatorToken.kind === 53) { - emitBreakWhenFalse(resultLabel, resultLocal, node.left); + emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left); + if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + // Logical `&&` shortcuts when the left-hand operand is falsey. + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); } else { - emitBreakWhenTrue(resultLabel, resultLocal, node.left); + // Logical `||` shortcuts when the left-hand operand is truthy. + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); } - emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), node.right); + emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right); markLabel(resultLabel); return resultLocal; } + /** + * Visits a comma expression containing `yield`. + * + * @param node The node to visit. + */ function visitCommaExpression(node) { + // [source] + // x = a(), yield, b(); + // + // [intermediate] + // a(); + // .yield resumeLabel + // .mark resumeLabel + // x = %sent%, b(); var pendingExpressions = []; visit(node.left); visit(node.right); return ts.inlineExpressions(pendingExpressions); function visit(node) { - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { visit(node.left); visit(node.right); } else { if (containsYield(node) && pendingExpressions.length > 0) { - emitWorker(1, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + emitWorker(1 /* Statement */, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); pendingExpressions = []; } pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); } } } + /** + * Visits a conditional expression containing `yield`. + * + * @param node The node to visit. + */ function visitConditionalExpression(node) { + // [source] + // x = a() ? yield : b(); + // + // [intermediate] + // .local _a + // .brfalse whenFalseLabel, (a()) + // .yield resumeLabel + // .mark resumeLabel + // _a = %sent%; + // .br resultLabel + // .mark whenFalseLabel + // _a = b(); + // .mark resultLabel + // x = _a; + // We only need to perform a specific transformation if a `yield` expression exists + // in either the `whenTrue` or `whenFalse` branches. + // A `yield` in the condition will be handled by the normal visitor. if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { var whenFalseLabel = defineLabel(); var resultLabel = defineLabel(); var resultLocal = declareLocal(); - emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), node.condition); - emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), node.whenTrue); + emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition); + emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue); emitBreak(resultLabel); markLabel(whenFalseLabel); - emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), node.whenFalse); + emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse); markLabel(resultLabel); return resultLocal; } return ts.visitEachChild(node, visitor, context); } + /** + * Visits a `yield` expression. + * + * @param node The node to visit. + */ function visitYieldExpression(node) { + // [source] + // x = yield a(); + // + // [intermediate] + // .yield resumeLabel, (a()) + // .mark resumeLabel + // x = %sent%; var resumeLabel = defineLabel(); var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (node.asteriskToken) { - var iterator = (ts.getEmitFlags(node.expression) & 8388608) === 0 - ? ts.createValuesHelper(context, expression, node) + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 + ? ts.createValuesHelper(context, expression, /*location*/ node) : expression; - emitYieldStar(iterator, node); + emitYieldStar(iterator, /*location*/ node); } else { - emitYield(expression, node); + emitYield(expression, /*location*/ node); } markLabel(resumeLabel); - return createGeneratorResume(node); + return createGeneratorResume(/*location*/ node); } + /** + * Visits an ArrayLiteralExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ function visitArrayLiteralExpression(node) { - return visitElements(node.elements, undefined, undefined, node.multiLine); - } + return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + } + /** + * Visits an array of expressions containing one or more YieldExpression nodes + * and returns an expression for the resulting value. + * + * @param elements The elements to visit. + * @param multiLine Whether array literals created should be emitted on multiple lines. + */ function visitElements(elements, leadingElement, location, multiLine) { + // [source] + // ar = [1, yield, 2]; + // + // [intermediate] + // .local _a + // _a = [1]; + // .yield resumeLabel + // .mark resumeLabel + // ar = _a.concat([%sent%, 2]); var numInitialElements = countInitialNodesWithoutYield(elements); var temp; if (numInitialElements > 0) { @@ -51261,6 +64295,23 @@ var ts; } } function visitObjectLiteralExpression(node) { + // [source] + // o = { + // a: 1, + // b: yield, + // c: 2 + // }; + // + // [intermediate] + // .local _a + // _a = { + // a: 1 + // }; + // .yield resumeLabel + // .mark resumeLabel + // o = (_a.b = %sent%, + // _a.c = 2, + // _a); var properties = node.properties; var multiLine = node.multiLine; var numInitialProperties = countInitialNodesWithoutYield(properties); @@ -51278,15 +64329,29 @@ var ts; var visited = ts.visitNode(expression, visitor, ts.isExpression); if (visited) { if (multiLine) { - visited.startsOnNewLine = true; + ts.startOnNewLine(visited); } expressions.push(visited); } return expressions; } } + /** + * Visits an ElementAccessExpression that contains a YieldExpression. + * + * @param node The node to visit. + */ function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { + // [source] + // a = x[yield]; + // + // [intermediate] + // .local _a + // _a = x; + // .yield resumeLabel + // .mark resumeLabel + // a = _a[%sent%] var clone_5 = ts.getMutableClone(node); clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); @@ -51295,16 +64360,39 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, true), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), node), node); + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { + // [source] + // a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a).b; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // _b.apply(_a, _c.concat([%sent%, 2])); + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg; + return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), + /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (ts.forEach(node.arguments, containsYield)) { + // [source] + // new a.b(1, yield, 2); + // + // [intermediate] + // .local _a, _b, _c + // _b = (_a = a.b).bind; + // _c = [1]; + // .yield resumeLabel + // .mark resumeLabel + // new (_b.apply(_a, _c.concat([%sent%, 2]))); var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, ts.createVoidZero())), undefined, []), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, + /*leadingElement*/ ts.createVoidZero())), + /*typeArguments*/ undefined, []), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -51333,35 +64421,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 207: + case 208 /* Block */: return transformAndEmitBlock(node); - case 210: + case 211 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 211: + case 212 /* IfStatement */: return transformAndEmitIfStatement(node); - case 212: + case 213 /* DoStatement */: return transformAndEmitDoStatement(node); - case 213: + case 214 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 214: + case 215 /* ForStatement */: return transformAndEmitForStatement(node); - case 215: + case 216 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 217: + case 218 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 218: + case 219 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 219: + case 220 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 220: + case 221 /* WithStatement */: return transformAndEmitWithStatement(node); - case 221: + case 222 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 222: + case 223 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 223: + case 224 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 224: + case 225 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -51381,9 +64469,9 @@ var ts; function transformAndEmitVariableDeclarationList(node) { for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; - var name_49 = ts.getSynthesizedClone(variable.name); - ts.setCommentRange(name_49, variable.name); - hoistVariableDeclaration(name_49); + var name = ts.getSynthesizedClone(variable.name); + ts.setCommentRange(name, variable.name); + hoistVariableDeclaration(name); } var variables = ts.getInitializedVariables(node); var numVariables = variables.length; @@ -51410,10 +64498,23 @@ var ts; } function transformAndEmitIfStatement(node) { if (containsYield(node)) { + // [source] + // if (x) + // /*thenStatement*/ + // else + // /*elseStatement*/ + // + // [intermediate] + // .brfalse elseLabel, (x) + // /*thenStatement*/ + // .br endLabel + // .mark elseLabel + // /*elseStatement*/ + // .mark endLabel if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { var endLabel = defineLabel(); var elseLabel = node.elseStatement ? defineLabel() : undefined; - emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), node.expression); + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression); transformAndEmitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { emitBreak(endLabel); @@ -51432,9 +64533,23 @@ var ts; } function transformAndEmitDoStatement(node) { if (containsYield(node)) { + // [source] + // do { + // /*body*/ + // } + // while (i < 10); + // + // [intermediate] + // .loop conditionLabel, endLabel + // .mark loopLabel + // /*body*/ + // .mark conditionLabel + // .brtrue loopLabel, (i < 10) + // .endloop + // .mark endLabel var conditionLabel = defineLabel(); var loopLabel = defineLabel(); - beginLoopBlock(conditionLabel); + beginLoopBlock(/*continueLabel*/ conditionLabel); markLabel(loopLabel); transformAndEmitEmbeddedStatement(node.statement); markLabel(conditionLabel); @@ -51458,6 +64573,19 @@ var ts; } function transformAndEmitWhileStatement(node) { if (containsYield(node)) { + // [source] + // while (i < 10) { + // /*body*/ + // } + // + // [intermediate] + // .loop loopLabel, endLabel + // .mark loopLabel + // .brfalse endLabel, (i < 10) + // /*body*/ + // .br loopLabel + // .endloop + // .mark endLabel var loopLabel = defineLabel(); var endLabel = beginLoopBlock(loopLabel); markLabel(loopLabel); @@ -51483,6 +64611,23 @@ var ts; } function transformAndEmitForStatement(node) { if (containsYield(node)) { + // [source] + // for (var i = 0; i < 10; i++) { + // /*body*/ + // } + // + // [intermediate] + // .local i + // i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (i < 10) + // /*body*/ + // .mark incrementLabel + // i++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); var endLabel = beginLoopBlock(incrementLabel); @@ -51535,14 +64680,36 @@ var ts; return node; } function transformAndEmitForInStatement(node) { + // TODO(rbuckton): Source map locations if (containsYield(node)) { - var keysArray = declareLocal(); - var key = declareLocal(); - var keysIndex = ts.createLoopVariable(); + // [source] + // for (var p in o) { + // /*body*/ + // } + // + // [intermediate] + // .local _a, _b, _i + // _a = []; + // for (_b in o) _a.push(_b); + // _i = 0; + // .loop incrementLabel, endLoopLabel + // .mark conditionLabel + // .brfalse endLoopLabel, (_i < _a.length) + // p = _a[_i]; + // /*body*/ + // .mark incrementLabel + // _b++; + // .br conditionLabel + // .endloop + // .mark endLoopLabel + var keysArray = declareLocal(); // _a + var key = declareLocal(); // _b + var keysIndex = ts.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); emitAssignment(keysArray, ts.createArrayLiteral()); - emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), undefined, [key])))); + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, ts.createLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); @@ -51573,6 +64740,18 @@ var ts; } } function visitForInStatement(node) { + // [source] + // for (var x in a) { + // /*body*/ + // } + // + // [intermediate] + // .local x + // .loop + // for (x in a) { + // /*body*/ + // } + // .endloop if (inStatementContainingYield) { beginScriptLoopBlock(); } @@ -51593,49 +64772,62 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { - emitBreak(label, node); + emitBreak(label, /*location*/ node); } else { + // invalid continue without a containing loop. Leave the node as is, per #17875. emitStatement(node); } } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findContinueTarget(node.label && ts.idText(node.label)); if (label > 0) { - return createInlineBreak(label, node); + return createInlineBreak(label, /*location*/ node); } } return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { - emitBreak(label, node); + emitBreak(label, /*location*/ node); } else { + // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875. emitStatement(node); } } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findBreakTarget(node.label && ts.idText(node.label)); if (label > 0) { - return createInlineBreak(label, node); + return createInlineBreak(label, /*location*/ node); } } return ts.visitEachChild(node, visitor, context); } function transformAndEmitReturnStatement(node) { - emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), node); + emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); } function visitReturnStatement(node) { - return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), node); + return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); } function transformAndEmitWithStatement(node) { if (containsYield(node)) { + // [source] + // with (x) { + // /*body*/ + // } + // + // [intermediate] + // .with (x) + // /*body*/ + // .endwith beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression))); transformAndEmitEmbeddedStatement(node.statement); endWithBlock(); @@ -51646,32 +64838,67 @@ var ts; } function transformAndEmitSwitchStatement(node) { if (containsYield(node.caseBlock)) { + // [source] + // switch (x) { + // case a: + // /*caseStatements*/ + // case b: + // /*caseStatements*/ + // default: + // /*defaultStatements*/ + // } + // + // [intermediate] + // .local _a + // .switch endLabel + // _a = x; + // switch (_a) { + // case a: + // .br clauseLabels[0] + // } + // switch (_a) { + // case b: + // .br clauseLabels[1] + // } + // .br clauseLabels[2] + // .mark clauseLabels[0] + // /*caseStatements*/ + // .mark clauseLabels[1] + // /*caseStatements*/ + // .mark clauseLabels[2] + // /*caseStatements*/ + // .endswitch + // .mark endLabel var caseBlock = node.caseBlock; var numClauses = caseBlock.clauses.length; var endLabel = beginSwitchBlock(); var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)); + // Create labels for each clause and find the index of the first default clause. var clauseLabels = []; var defaultClauseIndex = -1; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 258 && defaultClauseIndex === -1) { + if (clause.kind === 262 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } + // Emit switch statements for each run of case clauses either from the first case + // clause or the next case clause with a `yield` in its expression, up to the next + // case clause with a `yield` in its expression. var clausesWritten = 0; var pendingClauses = []; while (clausesWritten < numClauses) { var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 257) { + if (clause.kind === 261 /* CaseClause */) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; } pendingClauses.push(ts.createCaseClause(ts.visitNode(caseClause.expression, visitor, ts.isExpression), [ - createInlineBreak(clauseLabels[i], caseClause.expression) + createInlineBreak(clauseLabels[i], /*location*/ caseClause.expression) ])); } else { @@ -51716,7 +64943,17 @@ var ts; } function transformAndEmitLabeledStatement(node) { if (containsYield(node)) { - beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + // [source] + // x: { + // /*body*/ + // } + // + // [intermediate] + // .labeled "x", endLabel + // /*body*/ + // .endlabeled + // .mark endLabel + beginLabeledBlock(ts.idText(node.label)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -51726,7 +64963,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginScriptLabeledBlock(ts.idText(node.label)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -51735,10 +64972,40 @@ var ts; return node; } function transformAndEmitThrowStatement(node) { - emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), node); + emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), + /*location*/ node); } function transformAndEmitTryStatement(node) { if (containsYield(node)) { + // [source] + // try { + // /*tryBlock*/ + // } + // catch (e) { + // /*catchBlock*/ + // } + // finally { + // /*finallyBlock*/ + // } + // + // [intermediate] + // .local _a + // .try tryLabel, catchLabel, finallyLabel, endLabel + // .mark tryLabel + // .nop + // /*tryBlock*/ + // .br endLabel + // .catch + // .mark catchLabel + // _a = %error%; + // /*catchBlock*/ + // .br endLabel + // .finally + // .mark finallyLabel + // /*finallyBlock*/ + // .endfinally + // .endtry + // .mark endLabel beginExceptionBlock(); transformAndEmitEmbeddedStatement(node.tryBlock); if (node.catchClause) { @@ -51756,7 +65023,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216) !== 0; + return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -51769,7 +65036,7 @@ var ts; } function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (hint === 1) { + if (hint === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -51781,14 +65048,14 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_50 = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; - if (name_50) { - var clone_6 = ts.getMutableClone(name_50); + var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; + if (name) { + var clone_6 = ts.getMutableClone(name); ts.setSourceMapRange(clone_6, node); ts.setCommentRange(clone_6, node); return clone_6; @@ -51800,20 +65067,23 @@ var ts; } function cacheExpression(node) { var temp; - if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096) { + if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) { return node; } temp = ts.createTempVariable(hoistVariableDeclaration); - emitAssignment(temp, node, node); + emitAssignment(temp, node, /*location*/ node); return temp; } function declareLocal(name) { var temp = name ? ts.createUniqueName(name) - : ts.createTempVariable(undefined); + : ts.createTempVariable(/*recordTempVariable*/ undefined); hoistVariableDeclaration(temp); return temp; } + /** + * Defines a label, uses as the target of a Break operation. + */ function defineLabel() { if (!labelOffsets) { labelOffsets = []; @@ -51823,10 +65093,18 @@ var ts; labelOffsets[label] = -1; return label; } + /** + * Marks the current operation with the specified label. + */ function markLabel(label) { ts.Debug.assert(labelOffsets !== undefined, "No labels were defined."); labelOffsets[label] = operations ? operations.length : 0; } + /** + * Begins a block operation (With, Break/Continue, Try/Catch/Finally) + * + * @param block Information about the block. + */ function beginBlock(block) { if (!blocks) { blocks = []; @@ -51835,104 +65113,136 @@ var ts; blockStack = []; } var index = blockActions.length; - blockActions[index] = 0; + blockActions[index] = 0 /* Open */; blockOffsets[index] = operations ? operations.length : 0; blocks[index] = block; blockStack.push(block); return index; } + /** + * Ends the current block operation. + */ function endBlock() { var block = peekBlock(); ts.Debug.assert(block !== undefined, "beginBlock was never called."); var index = blockActions.length; - blockActions[index] = 1; + blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; blocks[index] = block; blockStack.pop(); return block; } + /** + * Gets the current open block. + */ function peekBlock() { return ts.lastOrUndefined(blockStack); } + /** + * Gets the kind of the current open block. + */ function peekBlockKind() { var block = peekBlock(); return block && block.kind; } + /** + * Begins a code block for a generated `with` statement. + * + * @param expression An identifier representing expression for the `with` block. + */ function beginWithBlock(expression) { var startLabel = defineLabel(); var endLabel = defineLabel(); markLabel(startLabel); beginBlock({ - kind: 1, + kind: 1 /* With */, expression: expression, startLabel: startLabel, endLabel: endLabel }); } + /** + * Ends a code block for a generated `with` statement. + */ function endWithBlock() { - ts.Debug.assert(peekBlockKind() === 1); + ts.Debug.assert(peekBlockKind() === 1 /* With */); var block = endBlock(); markLabel(block.endLabel); } + /** + * Begins a code block for a generated `try` statement. + */ function beginExceptionBlock() { var startLabel = defineLabel(); var endLabel = defineLabel(); markLabel(startLabel); beginBlock({ - kind: 0, - state: 0, + kind: 0 /* Exception */, + state: 0 /* Try */, startLabel: startLabel, endLabel: endLabel }); emitNop(); return endLabel; } + /** + * Enters the `catch` clause of a generated `try` statement. + * + * @param variable The catch variable. + */ function beginCatchBlock(variable) { - ts.Debug.assert(peekBlockKind() === 0); + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); + // generated identifiers should already be unique within a file var name; if (ts.isGeneratedIdentifier(variable.name)) { name = variable.name; hoistVariableDeclaration(variable.name); } else { - var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); + var text = ts.idText(variable.name); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); renamedCatchVariableDeclarations = []; - context.enableSubstitution(71); + context.enableSubstitution(71 /* Identifier */); } renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name; } var exception = peekBlock(); - ts.Debug.assert(exception.state < 1); + ts.Debug.assert(exception.state < 1 /* Catch */); var endLabel = exception.endLabel; emitBreak(endLabel); var catchLabel = defineLabel(); markLabel(catchLabel); - exception.state = 1; + exception.state = 1 /* Catch */; exception.catchVariable = name; exception.catchLabel = catchLabel; - emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, [])); + emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [])); emitNop(); } + /** + * Enters the `finally` block of a generated `try` statement. + */ function beginFinallyBlock() { - ts.Debug.assert(peekBlockKind() === 0); + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); var exception = peekBlock(); - ts.Debug.assert(exception.state < 2); + ts.Debug.assert(exception.state < 2 /* Finally */); var endLabel = exception.endLabel; emitBreak(endLabel); var finallyLabel = defineLabel(); markLabel(finallyLabel); - exception.state = 2; + exception.state = 2 /* Finally */; exception.finallyLabel = finallyLabel; } + /** + * Ends the code block for a generated `try` statement. + */ function endExceptionBlock() { - ts.Debug.assert(peekBlockKind() === 0); + ts.Debug.assert(peekBlockKind() === 0 /* Exception */); var exception = endBlock(); var state = exception.state; - if (state < 2) { + if (state < 2 /* Finally */) { emitBreak(exception.endLabel); } else { @@ -51940,52 +65250,83 @@ var ts; } markLabel(exception.endLabel); emitNop(); - exception.state = 3; - } + exception.state = 3 /* Done */; + } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * the source tree and not from generated code. + * + * @param labelText Names from containing labeled statements. + */ function beginScriptLoopBlock() { beginBlock({ - kind: 3, + kind: 3 /* Loop */, isScript: true, breakLabel: -1, continueLabel: -1 }); } + /** + * Begins a code block that supports `break` or `continue` statements that are defined in + * generated code. Returns a label used to mark the operation to which to jump when a + * `break` statement targets this block. + * + * @param continueLabel A Label used to mark the operation to which to jump when a + * `continue` statement targets this block. + */ function beginLoopBlock(continueLabel) { var breakLabel = defineLabel(); beginBlock({ - kind: 3, + kind: 3 /* Loop */, isScript: false, breakLabel: breakLabel, continueLabel: continueLabel, }); return breakLabel; } + /** + * Ends a code block that supports `break` or `continue` statements that are defined in + * generated code or in the source tree. + */ function endLoopBlock() { - ts.Debug.assert(peekBlockKind() === 3); + ts.Debug.assert(peekBlockKind() === 3 /* Loop */); var block = endBlock(); var breakLabel = block.breakLabel; if (!block.isScript) { markLabel(breakLabel); } } + /** + * Begins a code block that supports `break` statements that are defined in the source + * tree and not from generated code. + * + */ function beginScriptSwitchBlock() { beginBlock({ - kind: 2, + kind: 2 /* Switch */, isScript: true, breakLabel: -1 }); } + /** + * Begins a code block that supports `break` statements that are defined in generated code. + * Returns a label used to mark the operation to which to jump when a `break` statement + * targets this block. + */ function beginSwitchBlock() { var breakLabel = defineLabel(); beginBlock({ - kind: 2, + kind: 2 /* Switch */, isScript: false, breakLabel: breakLabel, }); return breakLabel; } + /** + * Ends a code block that supports `break` statements that are defined in generated code. + */ function endSwitchBlock() { - ts.Debug.assert(peekBlockKind() === 2); + ts.Debug.assert(peekBlockKind() === 2 /* Switch */); var block = endBlock(); var breakLabel = block.breakLabel; if (!block.isScript) { @@ -51994,7 +65335,7 @@ var ts; } function beginScriptLabeledBlock(labelText) { beginBlock({ - kind: 4, + kind: 4 /* Labeled */, isScript: true, labelText: labelText, breakLabel: -1 @@ -52003,28 +65344,43 @@ var ts; function beginLabeledBlock(labelText) { var breakLabel = defineLabel(); beginBlock({ - kind: 4, + kind: 4 /* Labeled */, isScript: false, labelText: labelText, breakLabel: breakLabel }); } function endLabeledBlock() { - ts.Debug.assert(peekBlockKind() === 4); + ts.Debug.assert(peekBlockKind() === 4 /* Labeled */); var block = endBlock(); if (!block.isScript) { markLabel(block.breakLabel); } } + /** + * Indicates whether the provided block supports `break` statements. + * + * @param block A code block. + */ function supportsUnlabeledBreak(block) { - return block.kind === 2 - || block.kind === 3; - } + return block.kind === 2 /* Switch */ + || block.kind === 3 /* Loop */; + } + /** + * Indicates whether the provided block supports `break` statements with labels. + * + * @param block A code block. + */ function supportsLabeledBreakOrContinue(block) { - return block.kind === 4; + return block.kind === 4 /* Labeled */; } + /** + * Indicates whether the provided block supports `continue` statements. + * + * @param block A code block. + */ function supportsUnlabeledContinue(block) { - return block.kind === 3; + return block.kind === 3 /* Loop */; } function hasImmediateContainingLabeledBlock(labelText, start) { for (var j = start; j >= 0; j--) { @@ -52040,6 +65396,11 @@ var ts; } return false; } + /** + * Finds the label that is the target for a `break` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ function findBreakTarget(labelText) { if (blockStack) { if (labelText) { @@ -52064,6 +65425,11 @@ var ts; } return 0; } + /** + * Finds the label that is the target for a `continue` statement. + * + * @param labelText An optional name of a containing labeled statement. + */ function findContinueTarget(labelText) { if (blockStack) { if (labelText) { @@ -52085,6 +65451,11 @@ var ts; } return 0; } + /** + * Creates an expression that can be used to indicate the value for a label. + * + * @param label A label. + */ function createLabel(label) { if (label > 0) { if (labelExpressions === undefined) { @@ -52101,64 +65472,153 @@ var ts; } return ts.createOmittedExpression(); } + /** + * Creates a numeric literal for the provided instruction. + */ function createInstruction(instruction) { var literal = ts.createLiteral(instruction); - ts.addSyntheticTrailingComment(literal, 3, getInstructionName(instruction)); + ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); return literal; } + /** + * Creates a statement that can be used indicate a Break operation to the provided label. + * + * @param label A label. + * @param location An optional source map location for the statement. + */ function createInlineBreak(label, location) { ts.Debug.assertLessThan(0, label, "Invalid label"); return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ - createInstruction(3), + createInstruction(3 /* Break */), createLabel(label) ])), location); } + /** + * Creates a statement that can be used indicate a Return operation. + * + * @param expression The expression for the return statement. + * @param location An optional source map location for the statement. + */ function createInlineReturn(expression, location) { return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression - ? [createInstruction(2), expression] - : [createInstruction(2)])), location); + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), location); } + /** + * Creates an expression that can be used to resume from a Yield operation. + */ function createGeneratorResume(location) { - return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), undefined, []), location); + return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), + /*typeArguments*/ undefined, []), location); } + /** + * Emits an empty instruction. + */ function emitNop() { - emitWorker(0); + emitWorker(0 /* Nop */); } + /** + * Emits a Statement. + * + * @param node A statement. + */ function emitStatement(node) { if (node) { - emitWorker(1, [node]); + emitWorker(1 /* Statement */, [node]); } else { emitNop(); } } + /** + * Emits an Assignment operation. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param location An optional source map location for the assignment. + */ function emitAssignment(left, right, location) { - emitWorker(2, [left, right], location); - } + emitWorker(2 /* Assign */, [left, right], location); + } + /** + * Emits a Break operation to the specified label. + * + * @param label A label. + * @param location An optional source map location for the assignment. + */ function emitBreak(label, location) { - emitWorker(3, [label], location); - } + emitWorker(3 /* Break */, [label], location); + } + /** + * Emits a Break operation to the specified label when a condition evaluates to a truthy + * value at runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ function emitBreakWhenTrue(label, condition, location) { - emitWorker(4, [label, condition], location); - } + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + /** + * Emits a Break to the specified label when a condition evaluates to a falsey value at + * runtime. + * + * @param label A label. + * @param condition The condition. + * @param location An optional source map location for the assignment. + */ function emitBreakWhenFalse(label, condition, location) { - emitWorker(5, [label, condition], location); - } + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + /** + * Emits a YieldStar operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ function emitYieldStar(expression, location) { - emitWorker(7, [expression], location); - } + emitWorker(7 /* YieldStar */, [expression], location); + } + /** + * Emits a Yield operation for the provided expression. + * + * @param expression An optional value for the yield operation. + * @param location An optional source map location for the assignment. + */ function emitYield(expression, location) { - emitWorker(6, [expression], location); - } + emitWorker(6 /* Yield */, [expression], location); + } + /** + * Emits a Return operation for the provided expression. + * + * @param expression An optional value for the operation. + * @param location An optional source map location for the assignment. + */ function emitReturn(expression, location) { - emitWorker(8, [expression], location); - } + emitWorker(8 /* Return */, [expression], location); + } + /** + * Emits a Throw operation for the provided expression. + * + * @param expression A value for the operation. + * @param location An optional source map location for the assignment. + */ function emitThrow(expression, location) { - emitWorker(9, [expression], location); + emitWorker(9 /* Throw */, [expression], location); } + /** + * Emits an Endfinally operation. This is used to handle `finally` block semantics. + */ function emitEndfinally() { - emitWorker(10); - } + emitWorker(10 /* Endfinally */); + } + /** + * Emits an operation. + * + * @param code The OpCode for the operation. + * @param args The optional arguments for the operation. + */ function emitWorker(code, args, location) { if (operations === undefined) { operations = []; @@ -52166,6 +65626,7 @@ var ts; operationLocations = []; } if (labelOffsets === undefined) { + // mark entry point markLabel(defineLabel()); } var operationIndex = operations.length; @@ -52173,6 +65634,9 @@ var ts; operationArguments[operationIndex] = args; operationLocations[operationIndex] = location; } + /** + * Builds the generator function body. + */ function build() { blockIndex = 0; labelNumber = 0; @@ -52185,8 +65649,17 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 524288)); - } + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*type*/ undefined, ts.createBlock(buildResult, + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); + } + /** + * Builds the statements for the generator function body. + */ function buildStatements() { if (operations) { for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) { @@ -52200,41 +65673,56 @@ var ts; if (clauses) { var labelExpression = ts.createPropertyAccess(state, "label"); var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); - switchStatement.startsOnNewLine = true; - return [switchStatement]; + return [ts.startOnNewLine(switchStatement)]; } if (statements) { return statements; } return []; } + /** + * Flush the current label and advance to a new label. + */ function flushLabel() { if (!statements) { return; } - appendLabel(!lastOperationWasAbrupt); + appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt); lastOperationWasAbrupt = false; lastOperationWasCompletion = false; labelNumber++; } + /** + * Flush the final label of the generator function body. + */ function flushFinalLabel(operationIndex) { if (isFinalLabelReachable(operationIndex)) { tryEnterLabel(operationIndex); withBlockStack = undefined; - writeReturn(undefined, undefined); + writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); } if (statements && clauses) { - appendLabel(false); + appendLabel(/*markLabelEnd*/ false); } updateLabelExpressions(); } + /** + * Tests whether the final label of the generator function body + * is reachable by user code. + */ function isFinalLabelReachable(operationIndex) { + // if the last operation was *not* a completion (return/throw) then + // the final label is reachable. if (!lastOperationWasCompletion) { return true; } + // if there are no labels defined or referenced, then the final label is + // not reachable. if (!labelOffsets || !labelExpressions) { return false; } + // if the label for this offset is referenced, then the final label + // is reachable. for (var label = 0; label < labelOffsets.length; label++) { if (labelOffsets[label] === operationIndex && labelExpressions[label]) { return true; @@ -52242,20 +65730,33 @@ var ts; } return false; } + /** + * Appends a case clause for the last label and sets the new label. + * + * @param markLabelEnd Indicates that the transition between labels was a fall-through + * from a previous case clause and the change in labels should be + * reflected on the `state` object. + */ function appendLabel(markLabelEnd) { if (!clauses) { clauses = []; } if (statements) { if (withBlockStack) { + // The previous label was nested inside one or more `with` blocks, so we + // surround the statements in generated `with` blocks to create the same environment. for (var i = withBlockStack.length - 1; i >= 0; i--) { var withBlock = withBlockStack[i]; statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))]; } } if (currentExceptionBlock) { + // The previous label was nested inside of an exception block, so we must + // indicate entry into a protected region by pushing the label numbers + // for each block in the protected region. var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; - statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), undefined, [ + statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + /*typeArguments*/ undefined, [ ts.createArrayLiteral([ createLabel(startLabel), createLabel(catchLabel), @@ -52266,12 +65767,17 @@ var ts; currentExceptionBlock = undefined; } if (markLabelEnd) { + // The case clause for the last label falls through to this label, so we + // add an assignment statement to reflect the change in labels. statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); } } clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); statements = undefined; } + /** + * Tries to enter into a new label at the current operation index. + */ function tryEnterLabel(operationIndex) { if (!labelOffsets) { return; @@ -52291,6 +65797,9 @@ var ts; } } } + /** + * Updates literal expressions for labels with actual label numbers. + */ function updateLabelExpressions() { if (labelExpressions !== undefined && labelNumbers !== undefined) { for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) { @@ -52310,14 +65819,17 @@ var ts; } } } + /** + * Tries to enter or leave a code block. + */ function tryEnterOrLeaveBlock(operationIndex) { if (blocks) { for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { var block = blocks[blockIndex]; var blockAction = blockActions[blockIndex]; switch (block.kind) { - case 0: - if (blockAction === 0) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { if (!exceptionBlockStack) { exceptionBlockStack = []; } @@ -52327,18 +65839,18 @@ var ts; exceptionBlockStack.push(currentExceptionBlock); currentExceptionBlock = block; } - else if (blockAction === 1) { + else if (blockAction === 1 /* Close */) { currentExceptionBlock = exceptionBlockStack.pop(); } break; - case 1: - if (blockAction === 0) { + case 1 /* With */: + if (blockAction === 0 /* Open */) { if (!withBlockStack) { withBlockStack = []; } withBlockStack.push(block); } - else if (blockAction === 1) { + else if (blockAction === 1 /* Close */) { withBlockStack.pop(); } break; @@ -52346,45 +65858,56 @@ var ts; } } } + /** + * Writes an operation as a statement to the current label's statement list. + * + * @param operation The OpCode of the operation + */ function writeOperation(operationIndex) { tryEnterLabel(operationIndex); tryEnterOrLeaveBlock(operationIndex); + // early termination, nothing else to process in this label if (lastOperationWasAbrupt) { return; } lastOperationWasAbrupt = false; lastOperationWasCompletion = false; var opcode = operations[operationIndex]; - if (opcode === 0) { + if (opcode === 0 /* Nop */) { return; } - else if (opcode === 10) { + else if (opcode === 10 /* Endfinally */) { return writeEndfinally(); } var args = operationArguments[operationIndex]; - if (opcode === 1) { + if (opcode === 1 /* Statement */) { return writeStatement(args[0]); } var location = operationLocations[operationIndex]; switch (opcode) { - case 2: + case 2 /* Assign */: return writeAssign(args[0], args[1], location); - case 3: + case 3 /* Break */: return writeBreak(args[0], location); - case 4: + case 4 /* BreakWhenTrue */: return writeBreakWhenTrue(args[0], args[1], location); - case 5: + case 5 /* BreakWhenFalse */: return writeBreakWhenFalse(args[0], args[1], location); - case 6: + case 6 /* Yield */: return writeYield(args[0], location); - case 7: + case 7 /* YieldStar */: return writeYieldStar(args[0], location); - case 8: + case 8 /* Return */: return writeReturn(args[0], location); - case 9: + case 9 /* Throw */: return writeThrow(args[0], location); } } + /** + * Writes a statement to the current label's statement list. + * + * @param statement A statement to write. + */ function writeStatement(statement) { if (statement) { if (!statements) { @@ -52395,65 +65918,179 @@ var ts; } } } + /** + * Writes an Assign operation to the current label's statement list. + * + * @param left The left-hand side of the assignment. + * @param right The right-hand side of the assignment. + * @param operationLocation The source map location for the operation. + */ function writeAssign(left, right, operationLocation) { writeStatement(ts.setTextRange(ts.createStatement(ts.createAssignment(left, right)), operationLocation)); } + /** + * Writes a Throw operation to the current label's statement list. + * + * @param expression The value to throw. + * @param operationLocation The source map location for the operation. + */ function writeThrow(expression, operationLocation) { lastOperationWasAbrupt = true; lastOperationWasCompletion = true; writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation)); } + /** + * Writes a Return operation to the current label's statement list. + * + * @param expression The value to return. + * @param operationLocation The source map location for the operation. + */ function writeReturn(expression, operationLocation) { lastOperationWasAbrupt = true; lastOperationWasCompletion = true; writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression - ? [createInstruction(2), expression] - : [createInstruction(2)])), operationLocation), 384)); - } + ? [createInstruction(2 /* Return */), expression] + : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a Break operation to the current label's statement list. + * + * @param label The label for the Break. + * @param operationLocation The source map location for the operation. + */ function writeBreak(label, operationLocation) { lastOperationWasAbrupt = true; writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ - createInstruction(3), + createInstruction(3 /* Break */), createLabel(label) - ])), operationLocation), 384)); - } + ])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a BreakWhenTrue operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ function writeBreakWhenTrue(label, condition, operationLocation) { writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ - createInstruction(3), + createInstruction(3 /* Break */), createLabel(label) - ])), operationLocation), 384)), 1)); - } + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a BreakWhenFalse operation to the current label's statement list. + * + * @param label The label for the Break. + * @param condition The condition for the Break. + * @param operationLocation The source map location for the operation. + */ function writeBreakWhenFalse(label, condition, operationLocation) { writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ - createInstruction(3), + createInstruction(3 /* Break */), createLabel(label) - ])), operationLocation), 384)), 1)); - } + ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); + } + /** + * Writes a Yield operation to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ function writeYield(expression, operationLocation) { lastOperationWasAbrupt = true; writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression - ? [createInstruction(4), expression] - : [createInstruction(4)])), operationLocation), 384)); - } + ? [createInstruction(4 /* Yield */), expression] + : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */)); + } + /** + * Writes a YieldStar instruction to the current label's statement list. + * + * @param expression The expression to yield. + * @param operationLocation The source map location for the operation. + */ function writeYieldStar(expression, operationLocation) { lastOperationWasAbrupt = true; writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([ - createInstruction(5), + createInstruction(5 /* YieldStar */), expression - ])), operationLocation), 384)); + ])), operationLocation), 384 /* NoTokenSourceMaps */)); } + /** + * Writes an Endfinally instruction to the current label's statement list. + */ function writeEndfinally() { lastOperationWasAbrupt = true; writeStatement(ts.createReturn(ts.createArrayLiteral([ - createInstruction(7) + createInstruction(7 /* Endfinally */) ]))); } } ts.transformGenerators = transformGenerators; function createGeneratorHelper(context, body) { context.requestEmitHelper(generatorHelper); - return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]); - } + return ts.createCall(ts.getHelperName("__generator"), + /*typeArguments*/ undefined, [ts.createThis(), body]); + } + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts var generatorHelper = { name: "typescript:generator", scoped: false, @@ -52461,39 +66098,66 @@ var ts; text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); +/// +/// +/*@internal*/ var ts; (function (ts) { + /** + * Transforms ES5 syntax into ES3 syntax. + * + * @param context Context and state information for the transformation. + */ function transformES5(context) { var compilerOptions = context.getCompilerOptions(); + // enable emit notification only if using --jsx preserve or react-native var previousOnEmitNode; var noSubstitution; - if (compilerOptions.jsx === 1 || compilerOptions.jsx === 3) { + if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(251); - context.enableEmitNotification(252); - context.enableEmitNotification(250); + context.enableEmitNotification(252 /* JsxOpeningElement */); + context.enableEmitNotification(253 /* JsxClosingElement */); + context.enableEmitNotification(251 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179); - context.enableSubstitution(261); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(265 /* PropertyAssignment */); return transformSourceFile; + /** + * Transforms an ES5 source file to ES3. + * + * @param node A SourceFile + */ function transformSourceFile(node) { return node; } + /** + * Called by the printer just before a node is printed. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node. + */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 251: - case 252: - case 250: + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; } previousOnEmitNode(hint, node, emitCallback); } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { if (node.id && noSubstitution && noSubstitution[node.id]) { return previousOnSubstituteNode(hint, node); @@ -52507,6 +66171,11 @@ var ts; } return node; } + /** + * Substitutes a PropertyAccessExpression whose name is a reserved word. + * + * @param node A PropertyAccessExpression + */ function substitutePropertyAccessExpression(node) { var literalName = trySubstituteReservedName(node.name); if (literalName) { @@ -52514,6 +66183,11 @@ var ts; } return node; } + /** + * Substitutes a PropertyAssignment whose name is a reserved word. + * + * @param node A PropertyAssignment + */ function substitutePropertyAssignment(node) { var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name); if (literalName) { @@ -52521,9 +66195,14 @@ var ts; } return node; } + /** + * If an identifier name is a reserved word, returns a string literal for the name. + * + * @param name An Identifier + */ function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); - if (token >= 72 && token <= 107) { + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); + if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -52531,6 +66210,10 @@ var ts; } ts.transformES5 = transformES5; })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { function transformModule(context) { @@ -52541,7 +66224,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -52551,26 +66234,32 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71); - context.enableSubstitution(194); - context.enableSubstitution(192); - context.enableSubstitution(193); - context.enableSubstitution(262); - context.enableEmitNotification(265); - var moduleInfoMap = []; - var deferredExports = []; - var currentSourceFile; - var currentModuleInfo; - var noSubstitution; + context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. + context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(269 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var currentSourceFile; // The current file. + var currentModuleInfo; // The ExternalModuleInfo for the current file. + var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } currentSourceFile = node; currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions); moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo; + // Perform the transformation. var transformModule = getTransformModuleDelegate(moduleKind); var updated = transformModule(node); currentSourceFile = undefined; @@ -52584,56 +66273,118 @@ var ts; } return false; } + /** + * Transforms a SourceFile into a CommonJS module. + * + * @param node The SourceFile node. + */ function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); - addExportEqualsIfNeeded(statements, false); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); ts.addRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. ts.addEmitHelper(updated, exportStarHelper); } ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } + /** + * Transforms a SourceFile into an AMD module. + * + * @param node The SourceFile node. + */ function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // An AMD define function has the following shape: + // + // define(id?, dependencies?, factory); + // + // This has the shape of the following: + // + // define(name, ["module1", "module2"], function (module1Alias) { ... } + // + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // + // import "module" + // + // or + // + // /// + // + // we need to add modules without alias names to the end of the dependencies list + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + // Create an updated SourceFile: + // + // define(moduleName?, ["module1", "module2"], function ... return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ + ts.createStatement(ts.createCall(define, + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, "require"), - ts.createParameter(undefined, undefined, undefined, "exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) - ]), node.statements)); - } + ]), + /*location*/ node.statements)); + } + /** + * Transforms a SourceFile into a UMD module. + * + * @param node The SourceFile node. + */ function transformUMDModule(node) { - var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); - var umdHeader = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "factory")], undefined, ts.setTextRange(ts.createBlock([ + var umdHeader = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*type*/ undefined, ts.setTextRange(ts.createBlock([ ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ - ts.createVariableStatement(undefined, [ - ts.createVariableDeclaration("v", undefined, ts.createCall(ts.createIdentifier("factory"), undefined, [ + ts.createVariableStatement( + /*modifiers*/ undefined, [ + ts.createVariableDeclaration("v", + /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), + /*typeArguments*/ undefined, [ ts.createIdentifier("require"), ts.createIdentifier("exports") ])) ]), - ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1) + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, (moduleName ? [moduleName] : []).concat([ + ts.createStatement(ts.createCall(ts.createIdentifier("define"), + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") @@ -52641,25 +66392,60 @@ var ts; ts.createIdentifier("factory") ]))) ]))) - ], true), undefined)); + ], + /*multiLine*/ true), + /*location*/ undefined)); + // Create an updated SourceFile: + // + // (function (factory) { + // if (typeof module === "object" && typeof module.exports === "object") { + // var v = factory(require, exports); + // if (v !== undefined) module.exports = v; + // } + // else if (typeof define === 'function' && define.amd) { + // define(["require", "exports"], factory); + // } + // })(function ...) return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(umdHeader, undefined, [ - ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, "require"), - ts.createParameter(undefined, undefined, undefined, "exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + ts.createStatement(ts.createCall(umdHeader, + /*typeArguments*/ undefined, [ + // Add the module body function argument: + // + // function (require, exports) ... + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) - ]), node.statements)); - } + ]), + /*location*/ node.statements)); + } + /** + * Collect the additional asynchronous dependencies for the module. + * + * @param node The source file. + * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies. + */ function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function var unaliasedModuleNames = []; + // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. var importAliasNames = []; + // Fill in amd-dependency tags for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(ts.createLiteral(amdDependency.path)); - importAliasNames.push(ts.createParameter(undefined, undefined, undefined, amdDependency.name)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(ts.createLiteral(amdDependency.path)); @@ -52667,13 +66453,20 @@ var ts; } for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) { var importNode = _c[_b]; + // Find the name of the external module var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); + // Find the name of the module alias, if there is one var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); + // It is possible that externalModuleName is undefined if it is not string literal. + // This can happen in the invalid import syntax. + // E.g : "import * from alias from 'someLib';" if (externalModuleName) { if (includeNonAmdDependencies && importAliasName) { - ts.setEmitFlags(importAliasName, 4); + // Set emitFlags on the name of the classDeclaration + // This is so that when printer will not substitute the identifier + ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(ts.createParameter(undefined, undefined, undefined, importAliasName)); + importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -52682,19 +66475,30 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + /** + * Transforms a SourceFile into an AMD or UMD module body. + * + * @param node The SourceFile node. + */ function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; - var statementOffset = ts.addPrologue(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); } + // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); - addExportEqualsIfNeeded(statements, true); + // Append the 'export =' statement if provided. + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); + // End the lexical environment for the module body + // and merge any new lexical declarations. ts.addRange(statements, endLexicalEnvironment()); - var body = ts.createBlock(statements, true); + var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { + // If we have any `export * from ...` declarations + // we need to inform the emitter to add the __export helper. ts.addEmitHelper(body, exportStarHelper); } if (needUMDDynamicImportHelper) { @@ -52702,6 +66506,14 @@ var ts; } return body; } + /** + * Adds the down-level representation of `export=` to the statement list if one exists + * in the source file. + * + * @param statements The Statement list to modify. + * @param emitAsReturn A value indicating whether to emit the `export=` statement as a + * return statement. + */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); @@ -52709,44 +66521,54 @@ var ts; if (emitAsReturn) { var statement = ts.createReturn(expressionResult); ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 384 | 1536); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 1536); + ts.setEmitFlags(statement, 1536 /* NoComments */); statements.push(statement); } } } } + // + // Top-Level Source Element Visitors + // + /** + * Visits a node at the top level of the source file. + * + * @param node The node to visit. + */ function sourceElementVisitor(node) { switch (node.kind) { - case 238: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 244: + case 245 /* ExportDeclaration */: return visitExportDeclaration(node); - case 243: + case 244 /* ExportAssignment */: return visitExportAssignment(node); - case 208: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 229: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 290: + case 294 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 291: + case 295 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, importCallExpressionVisitor, context); } } function importCallExpressionVisitor(node) { - if (!(node.transformFlags & 67108864)) { + // This visitor does not need to descend into the tree if there is no dynamic import, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } if (ts.isImportCall(node)) { @@ -52757,56 +66579,171 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); - } - } - function transformImportCallExpressionUMD(node) { + return createImportCallExpressionCommonJS(argument, containsLexicalThis); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); needUMDDynamicImportHelper = true; - return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); - } - function transformImportCallExpressionAMD(node) { + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), - ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); - } - function transformImportCallExpressionCommonJS(node) { - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); - } + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + } + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { + // import "mod"; return ts.setTextRange(ts.createStatement(createRequireCall(node)), node); } else { var variables = []; if (namespaceDeclaration && !ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + // import * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, createRequireCall(node))); } else { - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + // import d from "mod"; + // import { x, y } from "mod"; + // import d, { x, y } from "mod"; + // import d, * as n from "mod"; + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), + /*type*/ undefined, createRequireCall(node))); if (namespaceDeclaration && ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 ? 2 : 0)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), + /*location*/ node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { - statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node)), node) - ], languageVersion >= 2 ? 2 : 0))); + // import d, * as n from "mod"; + statements = ts.append(statements, ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + /*type*/ undefined, ts.getGeneratedNameForNode(node)), + /*location*/ node) + ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); } @@ -52815,33 +66752,47 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Creates a `require()` call to import an external module. + * + * @param importNode The declararation to import. + */ function createRequireCall(importNode) { var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var args = []; if (moduleName) { args.push(moduleName); } - return ts.createCall(ts.createIdentifier("require"), undefined, args); + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args); } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; if (moduleKind !== ts.ModuleKind.AMD) { - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(node.name, createRequireCall(node))), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) - ], languageVersion >= 2 ? 2 : 0)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), + /*type*/ undefined, createRequireCall(node)) + ], + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node)); } } else { - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); } @@ -52850,17 +66801,28 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Visits an ExportDeclaration node. + * + * @param The node to visit. + */ function visitExportDeclaration(node) { if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. return undefined; } var generatedName = ts.getGeneratedNameForNode(node); if (node.exportClause) { var statements = []; + // export { x, y } from "mod"; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) - ])), node)); + statements.push(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(generatedName, + /*type*/ undefined, createRequireCall(node)) + ])), + /*location*/ node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -52870,9 +66832,15 @@ var ts; return ts.singleOrMany(statements); } else { + // export * from "mod"; return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ function visitExportAssignment(node) { if (node.isExportEquals) { return undefined; @@ -52880,23 +66848,35 @@ var ts; var statements; var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, node, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, node, true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } + /** + * Visits a FunctionDeclaration node. + * + * @param node The node to visit. + */ function visitFunctionDeclaration(node) { var statements; - if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), node), node)); + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), + /*location*/ node), + /*original*/ node)); } else { statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); } @@ -52905,15 +66885,23 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Visits a ClassDeclaration node. + * + * @param node The node to visit. + */ function visitClassDeclaration(node) { var statements; - if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + if (ts.hasModifier(node, 1 /* Export */)) { + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( + /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); } else { statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); } @@ -52922,12 +66910,19 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Visits a VariableStatement node. + * + * @param node The node to visit. + */ function visitVariableStatement(node) { var statements; var variables; var expressions; - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { var modifiers = void 0; + // If we're exporting these variables, then these just become assignments to 'exports.x'. + // We only want to emit assignments for variables with initializers. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var variable = _a[_i]; if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { @@ -52951,6 +66946,7 @@ var ts; statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); } @@ -52959,25 +66955,60 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Transforms an exported variable with an initializer into an expression. + * + * @param node The node to transform. + */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), undefined, context, 0, false, createExportExpression); + return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), + /*visitor*/ undefined, context, 0 /* All */, + /*needsValue*/ false, createExportExpression); } else { - return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), + /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); } } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, add the exports of the elided variable + // statement. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } return node; } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 4194304) !== 0; - } + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. var id = ts.getOriginalNodeId(node); var statements = deferredExports[id]; if (statements) { @@ -52986,6 +67017,15 @@ var ts; } return node; } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfImportDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; @@ -53000,10 +67040,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240: + case 241 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241: + case 242 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -53013,12 +67053,30 @@ var ts; } return statements; } + /** + * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfImportEqualsDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; } return appendExportsOfDeclaration(statements, decl); } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + */ function appendExportsOfVariableStatement(statements, node) { if (currentModuleInfo.exportEquals) { return statements; @@ -53029,6 +67087,15 @@ var ts; } return statements; } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfBindingElement(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; @@ -53046,72 +67113,136 @@ var ts; } return statements; } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfHoistedDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; } - if (ts.hasModifier(decl, 1)) { - var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); - statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); + statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); } if (decl.name) { statements = appendExportsOfDeclaration(statements, decl); } return statements; } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + */ function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; - statements = appendExportStatement(statements, exportSpecifier.name, name, exportSpecifier.name); + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); } } return statements; } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ function appendExportStatement(statements, exportName, expression, location, allowComments) { statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); return statements; } function createUnderscoreUnderscoreESModule() { var statement; - if (languageVersion === 0) { - statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + if (languageVersion === 0 /* ES3 */) { + statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); } else { - statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ ts.createIdentifier("exports"), ts.createLiteral("__esModule"), ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createLiteral(true)) + ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true)) ]) ])); } - ts.setEmitFlags(statement, 1048576); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); return statement; } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ function createExportStatement(name, value, location, allowComments) { var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); if (!allowComments) { - ts.setEmitFlags(statement, 1536); + ts.setEmitFlags(statement, 1536 /* NoComments */); } return statement; } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ function createExportExpression(name, value, location) { return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ function modifierVisitor(node) { + // Elide module-specific modifiers. switch (node.kind) { - case 84: - case 79: + case 84 /* ExportKeyword */: + case 79 /* DefaultKeyword */: return undefined; } return node; } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265) { + if (node.kind === 269 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -53124,12 +67255,21 @@ var ts; previousOnEmitNode(hint, node, emitCallback); } } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); if (node.id && noSubstitution[node.id]) { return node; } - if (hint === 1) { + if (hint === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -53137,10 +67277,18 @@ var ts; } return node; } + /** + * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported + * or exported symbol. + * + * @param node The node to substitute. + */ function substituteShorthandPropertyAssignment(node) { var name = node.name; var exportedOrImportedName = substituteExpressionIdentifier(name); if (exportedOrImportedName !== name) { + // A shorthand property with an assignment initializer is probably part of a + // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node); @@ -53149,20 +67297,31 @@ var ts; } return node; } + /** + * Substitution for an Expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteExpression(node) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 194: + case 195 /* BinaryExpression */: return substituteBinaryExpression(node); - case 193: - case 192: + case 194 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; } + /** + * Substitution for an Identifier expression that may contain an imported or exported + * symbol. + * + * @param node The node to substitute. + */ function substituteExpressionIdentifier(node) { - if (ts.getEmitFlags(node) & 4096) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { return ts.createPropertyAccess(externalHelpersModuleName, node); @@ -53171,23 +67330,39 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 265) { - return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node); + if (exportContainer && exportContainer.kind === 269 /* SourceFile */) { + return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), + /*location*/ node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (ts.isImportClause(importDeclaration)) { - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), node); + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); } else if (ts.isImportSpecifier(importDeclaration)) { - var name_51 = importDeclaration.propertyName || importDeclaration.name; - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_51)), node); + var name = importDeclaration.propertyName || importDeclaration.name; + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), + /*location*/ node); } } } return node; } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. if (ts.isAssignmentOperator(node.operatorToken.kind) && ts.isIdentifier(node.left) && !ts.isGeneratedIdentifier(node.left) @@ -53195,30 +67370,48 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { var exportedNames = getExports(node.left); if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. var expression = node; for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; - expression = createExportExpression(exportName, expression, node); + expression = createExportExpression(exportName, expression, /*location*/ node); } return expression; } } return node; } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteUnaryExpression(node) { - if ((node.operator === 43 || node.operator === 44) + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 - ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 ? 59 : 60), ts.createLiteral(1)), node) + var expression = node.kind === 194 /* PostfixUnaryExpression */ + ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), + /*location*/ node) : node; for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { var exportName = exportedNames_2[_i]; + // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } @@ -53227,6 +67420,11 @@ var ts; } return node; } + /** + * Gets the additional exports of a name. + * + * @param name The name. + */ function getExports(name) { if (!ts.isGeneratedIdentifier(name)) { var valueDeclaration = resolver.getReferencedImportDeclaration(name) @@ -53239,6 +67437,7 @@ var ts; } } ts.transformModule = transformModule; + // emit output for the __export helper function var exportStarHelper = { name: "typescript:export-star", scoped: true, @@ -53247,15 +67446,20 @@ var ts; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); return compilerOptions.importHelpers - ? ts.createCall(ts.getHelperName("__exportStar"), undefined, [module, ts.createIdentifier("exports")]) - : ts.createCall(ts.createIdentifier("__export"), undefined, [module]); + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); } + // emit helper for dynamic import var dynamicImportUMDHelper = { name: "typescript:dynamicimport-sync-require", scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { function transformSystemModule(context) { @@ -53267,47 +67471,77 @@ var ts; var previousOnEmitNode = context.onEmitNode; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; - context.enableSubstitution(71); - context.enableSubstitution(194); - context.enableSubstitution(192); - context.enableSubstitution(193); - context.enableEmitNotification(265); - var moduleInfoMap = []; - var deferredExports = []; - var exportFunctionsMap = []; - var noSubstitutionMap = []; - var currentSourceFile; - var moduleInfo; - var exportFunction; - var contextObject; + context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(269 /* SourceFile */); // Restore state when substituting nodes in a file. + var moduleInfoMap = []; // The ExternalModuleInfo for each file. + var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. + var exportFunctionsMap = []; // The export function associated with a source file. + var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file. + var currentSourceFile; // The current file. + var moduleInfo; // ExternalModuleInfo for the current file. + var exportFunction; // The export function for the current file. + var contextObject; // The context object for the current file. var hoistedStatements; var enclosingBlockScopedContainer; - var noSubstitution; + var noSubstitution; // Set of nodes for which substitution rules should be ignored. return transformSourceFile; + /** + * Transforms the module aspects of a SourceFile. + * + * @param node The SourceFile node. + */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); currentSourceFile = node; enclosingBlockScopedContainer = node; + // System modules have the following shape: + // + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // + // The parameter 'exports' here is a callback '(name: string, value: T) => T' that + // is used to publish exported values. 'exports' returns its 'value' argument so in + // most cases expressions that mutate exported values can be rewritten as: + // + // expr -> exports('name', expr) + // + // The only exception in this rule is postfix unary operators, + // see comment to 'substitutePostfixUnaryExpression' for more details + // Collect information about the external module and dependency groups. moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions); + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. exportFunction = ts.createUniqueName("exports"); exportFunctionsMap[id] = exportFunction; contextObject = ts.createUniqueName("context"); + // Add the body of the module. var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); - var moduleBodyFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, exportFunction), - ts.createParameter(undefined, undefined, undefined, contextObject) - ], undefined, moduleBodyBlock); + var moduleBodyFunction = ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + ], + /*type*/ undefined, moduleBodyBlock); + // Write the call to `System.register` + // Clear the emit-helpers flag for later passes since we'll have already used it in the module body + // So the helper will be emit at the correct position instead of at the top of the source-file var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName + ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) - ]), node.statements)), 1024); + ]), node.statements)), 1024 /* NoTrailingComments */); if (!(compilerOptions.outFile || compilerOptions.out)) { ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } @@ -53323,16 +67557,22 @@ var ts; enclosingBlockScopedContainer = undefined; return ts.aggregateTransformFlags(updated); } + /** + * Collects the dependency groups for this files imports. + * + * @param externalImports The imports for the file. + */ function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); if (externalModuleName) { var text = externalModuleName.text; var groupIndex = groupIndices.get(text); if (groupIndex !== undefined) { + // deduplicate/group entries in dependency list by the dependency name dependencyGroups[groupIndex].externalImports.push(externalImport); } else { @@ -53346,42 +67586,124 @@ var ts; } return dependencyGroups; } + /** + * Adds the statements for the module body function for the source file. + * + * @param node The source file for the module. + * @param dependencyGroups The grouped dependencies of the module. + */ function createSystemModuleBody(node, dependencyGroups) { + // Shape of the body in system modules: + // + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // + // i.e: + // + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // + // Will be transformed to: + // + // function(exports) { + // function foo() { return y + file_1.x(); } + // exports("foo", foo); + // var file_1, y; + // return { + // setters: [ + // function(v) { file_1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } var statements = []; + // We start a new lexical environment in this function body, but *not* in the + // body of the execute function. This allows us to emit temporary declarations + // only in the outer module body and not in the inner one. startLexicalEnvironment(); - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + // Add any prologue directives. + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("__moduleName", undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) + // var __moduleName = context_1 && context_1.id; + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("__moduleName", + /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id"))) ]))); + // Visit the synthetic external helpers import declaration if present ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); + // Visit the statements of the source file, emitting any transformations into + // the `executeStatements` array. We do this *before* we fill the `setters` array + // as we both emit transformations as well as aggregate some data used when creating + // setters. This allows us to reduce the number of times we need to loop through the + // statements of the source file. var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); + // Emit early exports for function declarations. ts.addRange(statements, hoistedStatements); + // We emit hoisted variables early to align roughly with our previous emit output. + // Two key differences in this approach are: + // - Temporary variables will appear at the top rather than at the bottom of the file ts.addRange(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), - ts.createPropertyAssignment("execute", ts.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, ts.createBlock(executeStatements, true))) + ts.createPropertyAssignment("execute", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true))) ]); moduleObject.multiLine = true; statements.push(ts.createReturn(moduleObject)); - return ts.createBlock(statements, true); + return ts.createBlock(statements, /*multiLine*/ true); } + /** + * Adds an exportStar function to a statement list if it is needed for the file. + * + * @param statements A statement list. + */ function addExportStarIfNeeded(statements) { if (!moduleInfo.hasExportStarsToExportValues) { return; } + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + // local names set should only be added if we have anything exported if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 244 && externalImport.exportClause) { + if (externalImport.kind === 245 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } } if (!hasExportDeclarationWithExportClause) { - var exportStarFunction_1 = createExportStarFunction(undefined); + // we still need to emit exportStar helper + var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined); statements.push(exportStarFunction_1); return exportStarFunction_1.name; } @@ -53393,31 +67715,43 @@ var ts; if (exportedLocalName.escapedText === "default") { continue; } + // write name of exported declaration, i.e 'export var x...' exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); } } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 244) { + if (externalImport.kind !== 245 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; if (!exportDecl.exportClause) { + // export * from ... continue; } for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); + // write name of indirectly exported entry, i.e. 'export {x} from ...' + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); - statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exportedNamesStorageRef, undefined, ts.createObjectLiteral(exportedNames, true)) + statements.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exportedNamesStorageRef, + /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true)) ]))); var exportStarFunction = createExportStarFunction(exportedNamesStorageRef); statements.push(exportStarFunction); return exportStarFunction.name; } + /** + * Creates an exportStar function for the file, with an optional set of excluded local + * names. + * + * @param localNames An optional reference to an object containing a set of excluded local + * names. + */ function createExportStarFunction(localNames) { var exportStarFunction = ts.createUniqueName("exportStar"); var m = ts.createIdentifier("m"); @@ -53425,24 +67759,40 @@ var ts; var exports = ts.createIdentifier("exports"); var condition = ts.createStrictInequality(n, ts.createLiteral("default")); if (localNames) { - condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), undefined, [n]))); - } - return ts.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [ts.createParameter(undefined, undefined, undefined, m)], undefined, ts.createBlock([ - ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(exports, undefined, ts.createObjectLiteral([])) + condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), + /*typeArguments*/ undefined, [n]))); + } + return ts.createFunctionDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, exportStarFunction, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*type*/ undefined, ts.createBlock([ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(exports, + /*type*/ undefined, ts.createObjectLiteral([])) ])), ts.createForIn(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(n, undefined) + ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) ])), - ts.createStatement(ts.createCall(exportFunction, undefined, [exports])) - ], true)); - } + ts.createStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [exports])) + ], /*multiline*/ true)); + } + /** + * Creates an array setter callbacks for each dependency group. + * + * @param exportStarFunction A reference to an exportStarFunction for the file. + * @param dependencyGroups An array of grouped dependencies. + */ function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { var group = dependencyGroups_1[_i]; + // derive a unique name for parameter from the first named entry in the group var localName = ts.forEach(group.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; @@ -53450,54 +67800,94 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { - case 238: + case 239 /* ImportDeclaration */: if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required break; } - case 237: + // falls through + case 238 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); + // save import into the local statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 244: + case 245 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { + // export {a, b as c} from 'foo' + // + // emit as: + // + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } - statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); + statements.push(ts.createStatement(ts.createCall(exportFunction, + /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); } else { - statements.push(ts.createStatement(ts.createCall(exportStarFunction, undefined, [parameterName]))); + // export * from 'foo' + // + // emit as: + // + // exportStar(foo_1_1); + statements.push(ts.createStatement(ts.createCall(exportStarFunction, + /*typeArguments*/ undefined, [parameterName]))); } break; } } - setters.push(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, ts.createBlock(statements, true))); + setters.push(ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true))); } - return ts.createArrayLiteral(setters, true); + return ts.createArrayLiteral(setters, /*multiLine*/ true); } + // + // Top-level Source Element Visitors + // + /** + * Visit source elements at the top-level of a module. + * + * @param node The node to visit. + */ function sourceElementVisitor(node) { switch (node.kind) { - case 238: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 244: + case 245 /* ExportDeclaration */: + // ExportDeclarations are elided as they are handled via + // `appendExportsOfDeclaration`. return undefined; - case 243: + case 244 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); } } + /** + * Visits an ImportDeclaration node. + * + * @param node The node to visit. + */ function visitImportDeclaration(node) { var statements; if (node.importClause) { hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); } @@ -53506,11 +67896,17 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Visits an ImportEqualsDeclaration node. + * + * @param node The node to visit. + */ function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); } @@ -53519,28 +67915,43 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Visits an ExportAssignment node. + * + * @param node The node to visit. + */ function visitExportAssignment(node) { if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. return undefined; } var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true); } else { - return createExportStatement(ts.createIdentifier("default"), expression, true); + return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true); } } + /** + * Visits a FunctionDeclaration, hoisting it to the outer module body function. + * + * @param node The node to visit. + */ function visitFunctionDeclaration(node) { - if (ts.hasModifier(node, 1)) { - hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); + if (ts.hasModifier(node, 1 /* Export */)) { + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); } else { hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); } @@ -53549,12 +67960,22 @@ var ts; } return undefined; } + /** + * Visits a ClassDeclaration, hoisting its name to the outer module body function. + * + * @param node The node to visit. + */ function visitClassDeclaration(node) { var statements; + // Hoist the name of the class declaration to the outer module body function. var name = ts.getLocalName(node); hoistVariableDeclaration(name); - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); + // Rewrite the class declaration into an assignment of a class expression. + statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + /*modifiers*/ undefined, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); } @@ -53563,12 +67984,18 @@ var ts; } return ts.singleOrMany(statements); } + /** + * Visits a variable statement, hoisting declared names to the top-level module body. + * Each declaration is rewritten into an assignment expression. + * + * @param node The node to visit. + */ function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) { return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); } var expressions; - var isExportedDeclaration = ts.hasModifier(node, 1); + var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var variable = _a[_i]; @@ -53584,14 +68011,20 @@ var ts; statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); } if (isMarkedDeclaration) { + // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); } else { - statements = appendExportsOfVariableStatement(statements, node, false); + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); } return ts.singleOrMany(statements); } + /** + * Hoists the declared names of a VariableDeclaration or BindingElement. + * + * @param node The declaration to hoist. + */ function hoistBindingElement(node) { if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { @@ -53605,41 +68038,103 @@ var ts; hoistVariableDeclaration(ts.getSynthesizedClone(node.name)); } } + /** + * Determines whether a VariableDeclarationList should be hoisted. + * + * @param node The node to test. + */ function shouldHoistVariableDeclarationList(node) { - return (ts.getEmitFlags(node) & 2097152) === 0 - && (enclosingBlockScopedContainer.kind === 265 - || (ts.getOriginalNode(node).flags & 3) === 0); - } + // hoist only non-block scoped declarations or block scoped declarations parented by source file + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 + && (enclosingBlockScopedContainer.kind === 269 /* SourceFile */ + || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); + } + /** + * Transform an initialized variable declaration into an expression. + * + * @param node The node to transform. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) - ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); - } + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ false, createAssignment) + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; + } + /** + * Creates an assignment expression for an exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ function createExportedVariableAssignment(name, value, location) { - return createVariableAssignment(name, value, location, true); - } + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true); + } + /** + * Creates an assignment expression for a non-exported variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + */ function createNonExportedVariableAssignment(name, value, location) { - return createVariableAssignment(name, value, location, false); - } + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false); + } + /** + * Creates an assignment expression for a variable declaration. + * + * @param name The name of the variable. + * @param value The value of the variable's initializer. + * @param location The source map location for the assignment. + * @param isExportedDeclaration A value indicating whether the variable is exported. + */ function createVariableAssignment(name, value, location, isExportedDeclaration) { hoistVariableDeclaration(ts.getSynthesizedClone(name)); return isExportedDeclaration ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location))) : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)); } + /** + * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged + * and transformed declaration. + * + * @param node The node to visit. + */ function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208) { + // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding + // declaration we do not emit a leading variable declaration. To preserve the + // begin/end semantics of the declararation and to properly handle exports + // we wrapped the leading variable declaration in a `MergeDeclarationMarker`. + // + // To balance the declaration, we defer the exports of the elided variable + // statement until we visit this declaration's `EndOfDeclarationMarker`. + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); - var isExportedDeclaration = ts.hasModifier(node.original, 1); + var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); } return node; } + /** + * Determines whether a node has an associated EndOfDeclarationMarker. + * + * @param node The node to test. + */ function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 4194304) !== 0; - } + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; + } + /** + * Visits a DeclarationMarker used as a placeholder for the end of a transformed + * declaration. + * + * @param node The node to visit. + */ function visitEndOfDeclarationMarker(node) { + // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual + // end of the transformed declaration. We use this marker to emit any deferred exports + // of the declaration. var id = ts.getOriginalNodeId(node); var statements = deferredExports[id]; if (statements) { @@ -53648,6 +68143,15 @@ var ts; } return node; } + /** + * Appends the exports of an ImportDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfImportDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; @@ -53662,10 +68166,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240: + case 241 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241: + case 242 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -53675,12 +68179,32 @@ var ts; } return statements; } + /** + * Appends the export of an ImportEqualsDeclaration to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfImportEqualsDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; } return appendExportsOfDeclaration(statements, decl); } + /** + * Appends the exports of a VariableStatement to a statement list, returning the statement + * list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param node The VariableStatement whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export each VariableDeclaration of + * `nodes` declaration list. + */ function appendExportsOfVariableStatement(statements, node, exportSelf) { if (moduleInfo.exportEquals) { return statements; @@ -53693,6 +68217,16 @@ var ts; } return statements; } + /** + * Appends the exports of a VariableDeclaration or BindingElement to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + * @param exportSelf A value indicating whether to also export the declaration itself. + */ function appendExportsOfBindingElement(statements, decl, exportSelf) { if (moduleInfo.exportEquals) { return statements; @@ -53709,19 +68243,28 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); + excludeName = ts.idText(decl.name); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } return statements; } + /** + * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list, + * returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration whose exports are to be recorded. + */ function appendExportsOfHoistedDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; } var excludeName; - if (ts.hasModifier(decl, 1)) { - var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; + if (ts.hasModifier(decl, 1 /* Export */)) { + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } @@ -53730,12 +68273,21 @@ var ts; } return statements; } + /** + * Appends the exports of a declaration to a statement list, returning the statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param decl The declaration to export. + * @param excludeName An optional name to exclude from exports. + */ function appendExportsOfDeclaration(statements, decl, excludeName) { if (moduleInfo.exportEquals) { return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; @@ -53746,67 +68298,104 @@ var ts; } return statements; } + /** + * Appends the down-level representation of an export to a statement list, returning the + * statement list. + * + * @param statements A statement list to which the down-level export statements are to be + * appended. If `statements` is `undefined`, a new array is allocated if statements are + * appended. + * @param exportName The name of the export. + * @param expression The expression to export. + * @param allowComments Whether to allow comments on the export. + */ function appendExportStatement(statements, exportName, expression, allowComments) { statements = ts.append(statements, createExportStatement(exportName, expression, allowComments)); return statements; } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ function createExportStatement(name, value, allowComments) { var statement = ts.createStatement(createExportExpression(name, value)); ts.startOnNewLine(statement); if (!allowComments) { - ts.setEmitFlags(statement, 1536); + ts.setEmitFlags(statement, 1536 /* NoComments */); } return statement; } + /** + * Creates a call to the current file's export function to export a value. + * + * @param name The bound name of the export. + * @param value The exported value. + */ function createExportExpression(name, value) { var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; - ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536); - return ts.setCommentRange(ts.createCall(exportFunction, undefined, [exportName, value]), value); - } + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); + } + // + // Top-Level or Nested Source Element Visitors + // + /** + * Visit nested elements at the top-level of a module. + * + * @param node The node to visit. + */ function nestedElementVisitor(node) { switch (node.kind) { - case 208: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 228: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 229: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 214: + case 215 /* ForStatement */: return visitForStatement(node); - case 215: + case 216 /* ForInStatement */: return visitForInStatement(node); - case 216: + case 217 /* ForOfStatement */: return visitForOfStatement(node); - case 212: + case 213 /* DoStatement */: return visitDoStatement(node); - case 213: + case 214 /* WhileStatement */: return visitWhileStatement(node); - case 222: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 220: + case 221 /* WithStatement */: return visitWithStatement(node); - case 221: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 235: + case 236 /* CaseBlock */: return visitCaseBlock(node); - case 257: + case 261 /* CaseClause */: return visitCaseClause(node); - case 258: + case 262 /* DefaultClause */: return visitDefaultClause(node); - case 224: + case 225 /* TryStatement */: return visitTryStatement(node); - case 260: + case 264 /* CatchClause */: return visitCatchClause(node); - case 207: + case 208 /* Block */: return visitBlock(node); - case 290: + case 294 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 291: + case 295 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); } } + /** + * Visits the body of a ForStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; @@ -53814,6 +68403,11 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } + /** + * Visits the body of a ForInStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; @@ -53821,6 +68415,11 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } + /** + * Visits the body of a ForOfStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; @@ -53828,10 +68427,21 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } + /** + * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or + * ForOfStatement. + * + * @param node The node to test. + */ function shouldHoistForInitializer(node) { return ts.isVariableDeclarationList(node) && shouldHoistVariableDeclarationList(node); } + /** + * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement + * + * @param node The node to visit. + */ function visitForInitializer(node) { if (!node) { return node; @@ -53840,7 +68450,10 @@ var ts; var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; - expressions = ts.append(expressions, transformInitializedVariable(variable, false)); + expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } } return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); } @@ -53848,21 +68461,51 @@ var ts; return ts.visitEachChild(node, nestedElementVisitor, context); } } + /** + * Visits the body of a DoStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitDoStatement(node) { return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } + /** + * Visits the body of a WhileStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitWhileStatement(node) { return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } + /** + * Visits the body of a LabeledStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitLabeledStatement(node) { return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } + /** + * Visits the body of a WithStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitWithStatement(node) { return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } + /** + * Visits the body of a SwitchStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitSwitchStatement(node) { return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); } + /** + * Visits the body of a CaseBlock to hoist declarations. + * + * @param node The node to visit. + */ function visitCaseBlock(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; @@ -53870,15 +68513,35 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } + /** + * Visits the body of a CaseClause to hoist declarations. + * + * @param node The node to visit. + */ function visitCaseClause(node) { return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); } + /** + * Visits the body of a DefaultClause to hoist declarations. + * + * @param node The node to visit. + */ function visitDefaultClause(node) { return ts.visitEachChild(node, nestedElementVisitor, context); } + /** + * Visits the body of a TryStatement to hoist declarations. + * + * @param node The node to visit. + */ function visitTryStatement(node) { return ts.visitEachChild(node, nestedElementVisitor, context); } + /** + * Visits the body of a CatchClause to hoist declarations. + * + * @param node The node to visit. + */ function visitCatchClause(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; @@ -53886,6 +68549,11 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } + /** + * Visits the body of a Block to hoist declarations. + * + * @param node The node to visit. + */ function visitBlock(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; @@ -53893,15 +68561,23 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } + // + // Destructuring Assignment Visitors + // + /** + * Visit nodes to flatten destructuring assignments to exported symbols. + * + * @param node The node to visit. + */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 - && node.kind === 194) { + if (node.transformFlags & 1024 /* DestructuringAssignment */ + && node.kind === 195 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -53909,16 +68585,38 @@ var ts; } } function visitImportCallExpression(node) { - return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); - } + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); + } + /** + * Visits a DestructuringAssignment to flatten destructuring to exported symbols. + * + * @param node The node to visit. + */ function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, true); + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, + /*needsValue*/ true); } return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } + /** + * Determines whether the target of a destructuring assigment refers to an exported symbol. + * + * @param node The destructuring target. + */ function hasExportedReferenceInDestructuringTarget(node) { - if (ts.isAssignmentExpression(node, true)) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { return hasExportedReferenceInDestructuringTarget(node.left); } else if (ts.isSpreadElement(node)) { @@ -53938,22 +68636,40 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 265; + return container !== undefined && container.kind === 269 /* SourceFile */; } else { return false; } } + // + // Modifier Visitors + // + /** + * Visit nodes to elide module-specific modifiers. + * + * @param node The node to visit. + */ function modifierVisitor(node) { switch (node.kind) { - case 84: - case 79: + case 84 /* ExportKeyword */: + case 79 /* DefaultKeyword */: return undefined; } return node; } + // + // Emit Notification + // + /** + * Hook for node emit notifications. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback A callback used to emit the node in the printer. + */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265) { + if (node.kind === 269 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -53972,50 +68688,90 @@ var ts; previousOnEmitNode(hint, node, emitCallback); } } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); if (isSubstitutionPrevented(node)) { return node; } - if (hint === 1) { + if (hint === 1 /* Expression */) { return substituteExpression(node); } return node; } + /** + * Substitute the expression, if necessary. + * + * @param node The node to substitute. + */ function substituteExpression(node) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 194: + case 195 /* BinaryExpression */: return substituteBinaryExpression(node); - case 192: - case 193: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; } + /** + * Substitution for an Identifier expression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteExpressionIdentifier(node) { - if (ts.getEmitFlags(node) & 4096) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { return ts.createPropertyAccess(externalHelpersModuleName, node); } return node; } + // When we see an identifier in an expression position that + // points to an imported symbol, we should substitute a qualified + // reference to the imported symbol if one is needed. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (ts.isImportClause(importDeclaration)) { - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), node); + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), + /*location*/ node); } else if (ts.isImportSpecifier(importDeclaration)) { - return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), + /*location*/ node); } } } return node; } + /** + * Substitution for a BinaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteBinaryExpression(node) { + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. if (ts.isAssignmentOperator(node.operatorToken.kind) && ts.isIdentifier(node.left) && !ts.isGeneratedIdentifier(node.left) @@ -54023,6 +68779,7 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) { var exportedNames = getExports(node.left); if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. var expression = node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { var exportName = exportedNames_3[_i]; @@ -54033,23 +68790,37 @@ var ts; } return node; } + /** + * Substitution for a UnaryExpression that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ function substituteUnaryExpression(node) { - if ((node.operator === 43 || node.operator === 44) + // When we see a prefix or postfix increment expression whose operand is an exported + // symbol, we should ensure all exports of that symbol are updated with the correct + // value. + // + // - We do not substitute generated identifiers for any reason. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We do not substitute identifiers that were originally the name of an enum or + // namespace due to how they are transformed in TypeScript. + // - We only substitute identifiers that are exported at the top level. + if ((node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) && ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand) && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 + var expression = node.kind === 194 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 193) { - expression = node.operator === 43 + if (node.kind === 194 /* PostfixUnaryExpression */) { + expression = node.operator === 43 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); } @@ -54058,14 +68829,19 @@ var ts; } return node; } + /** + * Gets the exports of a name. + * + * @param name The name. + */ function getExports(name) { var exportedNames; if (!ts.isGeneratedIdentifier(name)) { var valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { - var exportContainer = resolver.getReferencedExportContainer(name, false); - if (exportContainer && exportContainer.kind === 265) { + var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); + if (exportContainer && exportContainer.kind === 269 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -54073,18 +68849,31 @@ var ts; } return exportedNames; } + /** + * Prevent substitution of a node for this transformer. + * + * @param node The node which should not be substituted. + */ function preventSubstitution(node) { if (noSubstitution === undefined) noSubstitution = []; noSubstitution[ts.getNodeId(node)] = true; return node; } + /** + * Determines whether a node should not be substituted. + * + * @param node The node to test. + */ function isSubstitutionPrevented(node) { return noSubstitution && node.id && noSubstitution[node.id]; } } ts.transformSystemModule = transformSystemModule; })(ts || (ts = {})); +/// +/// +/*@internal*/ var ts; (function (ts) { function transformES2015Module(context) { @@ -54093,8 +68882,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(265); - context.enableSubstitution(71); + context.enableEmitNotification(269 /* SourceFile */); + context.enableSubstitution(71 /* Identifier */); var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { @@ -54106,7 +68895,9 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + ts.append(statements, ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -54118,16 +68909,28 @@ var ts; } function visitor(node) { switch (node.kind) { - case 237: + case 238 /* ImportEqualsDeclaration */: + // Elide `import=` as it is not legal with --module ES6 return undefined; - case 243: + case 244 /* ExportAssignment */: return visitExportAssignment(node); } return node; } function visitExportAssignment(node) { + // Elide `export=` as it is not legal with --module ES6 return node.isExportEquals ? undefined : node; } + // + // Emit Notification + // + /** + * Hook for node emit. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ function onEmitNode(hint, node, emitCallback) { if (ts.isSourceFile(node)) { currentSourceFile = node; @@ -54138,15 +68941,24 @@ var ts; previousOnEmitNode(hint, node, emitCallback); } } + // + // Substitutions + // + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (ts.isIdentifier(node) && hint === 1) { + if (ts.isIdentifier(node) && hint === 1 /* Expression */) { return substituteExpressionIdentifier(node); } return node; } function substituteExpressionIdentifier(node) { - if (ts.getEmitFlags(node) & 4096) { + if (ts.getEmitFlags(node) & 4096 /* HelperName */) { var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile); if (externalHelpersModuleName) { return ts.createPropertyAccess(externalHelpersModuleName, node); @@ -54157,6 +68969,20 @@ var ts; } ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/* @internal */ var ts; (function (ts) { function getModuleTransformer(moduleKind) { @@ -54189,32 +69015,44 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && customTransformers.before); transformers.push(ts.transformTypeScript); - if (jsx === 2) { + if (jsx === 2 /* React */) { transformers.push(ts.transformJsx); } - if (languageVersion < 5) { + if (languageVersion < 6 /* ESNext */) { transformers.push(ts.transformESNext); } - if (languageVersion < 4) { + if (languageVersion < 4 /* ES2017 */) { transformers.push(ts.transformES2017); } - if (languageVersion < 3) { + if (languageVersion < 3 /* ES2016 */) { transformers.push(ts.transformES2016); } - if (languageVersion < 2) { + if (languageVersion < 2 /* ES2015 */) { transformers.push(ts.transformES2015); transformers.push(ts.transformGenerators); } transformers.push(getModuleTransformer(moduleKind)); - if (languageVersion < 1) { + // The ES5 transformer is last so that it can substitute expressions like `exports.default` + // for ES3. + if (languageVersion < 1 /* ES5 */) { transformers.push(ts.transformES5); } ts.addRange(transformers, customTransformers && customTransformers.after); return transformers; } ts.getTransformers = getTransformers; + /** + * Transforms an array of SourceFiles by passing them through each transformer. + * + * @param resolver The emit resolver provided by the checker. + * @param host The emit host object used to interact with the file system. + * @param options Compiler options to surface in the `TransformationContext`. + * @param nodes An array of nodes to transform. + * @param transforms An array of `TransformerFactory` callbacks. + * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. + */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(292); + var enabledSyntaxKindFeatures = new Array(296 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -54224,7 +69062,9 @@ var ts; var emitHelpers; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; - var state = 0; + var state = 0 /* Uninitialized */; + // The transformation context is provided to each transformer as part of transformer + // initialization. var context = { getCompilerOptions: function () { return options; }, getEmitResolver: function () { return resolver; }, @@ -54243,26 +69083,31 @@ var ts; isEmitNotificationEnabled: isEmitNotificationEnabled, get onSubstituteNode() { return onSubstituteNode; }, set onSubstituteNode(value) { - ts.Debug.assert(state < 1, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); onSubstituteNode = value; }, get onEmitNode() { return onEmitNode; }, set onEmitNode(value) { - ts.Debug.assert(state < 1, "Cannot modify transformation hooks after initialization has completed."); + ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); onEmitNode = value; } }; + // Ensure the parse tree is clean before applying transformations for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } ts.performance.mark("beforeTransform"); + // Chain together and initialize each transformer. var transformation = ts.chain.apply(void 0, transformers)(context); - state = 1; + // prevent modification of transformation hooks. + state = 1 /* Initialized */; + // Transform each node. var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot); - state = 2; + // prevent modification of the lexical environment. + state = 2 /* Completed */; ts.performance.mark("afterTransform"); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { @@ -54274,28 +69119,55 @@ var ts; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; } + /** + * Enables expression substitutions in the pretty printer for the provided SyntaxKind. + */ function enableSubstitution(kind) { - ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); - enabledSyntaxKindFeatures[kind] |= 1; + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; } + /** + * Determines whether expression substitutions are enabled for the provided node. + */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 - && (ts.getEmitFlags(node) & 4) === 0; - } + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0; + } + /** + * Emits a node with possible substitution. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. + */ function substituteNode(hint, node) { - ts.Debug.assert(state < 3, "Cannot substitute a node after the result is disposed."); + ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; } + /** + * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. + */ function enableEmitNotification(kind) { - ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); - enabledSyntaxKindFeatures[kind] |= 2; + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; } + /** + * Determines whether before/after emit notifications should be raised in the pretty + * printer when it emits a node. + */ function isEmitNotificationEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (ts.getEmitFlags(node) & 2) !== 0; - } + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 + || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0; + } + /** + * Emits a node with possible emit notification. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ function emitNodeWithNotification(hint, node, emitCallback) { - ts.Debug.assert(state < 3, "Cannot invoke TransformationResult callbacks after the result is disposed."); + ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); if (node) { if (isEmitNotificationEnabled(node)) { onEmitNode(hint, node, emitCallback); @@ -54305,10 +69177,13 @@ var ts; } } } + /** + * Records a hoisted variable declaration for the provided name within a lexical environment. + */ function hoistVariableDeclaration(name) { - ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); - var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); if (!lexicalEnvironmentVariableDeclarations) { lexicalEnvironmentVariableDeclarations = [decl]; } @@ -54316,9 +69191,12 @@ var ts; lexicalEnvironmentVariableDeclarations.push(decl); } } + /** + * Records a hoisted function declaration within a lexical environment. + */ function hoistFunctionDeclaration(func) { - ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -54326,31 +69204,45 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Starts a new lexical environment. Any existing hoisted variable or function declarations + * are pushed onto a stack, and the related storage variables are reset. + */ function startLexicalEnvironment() { - ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + // Save the current lexical environment. Rather than resizing the array we adjust the + // stack size variable. This allows us to reuse existing array slots we've + // already allocated between transformations to avoid allocation and GC overhead during + // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; } + /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { - ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); lexicalEnvironmentSuspended = true; } + /** Resumes a suspended lexical environment, usually before visiting a function body. */ function resumeLexicalEnvironment() { - ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); lexicalEnvironmentSuspended = false; } + /** + * Ends a lexical environment. The previous set of hoisted declarations are restored and + * any hoisted declarations added in this environment are returned. + */ function endLexicalEnvironment() { - ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { @@ -54358,7 +69250,8 @@ var ts; statements = lexicalEnvironmentFunctionDeclarations.slice(); } if (lexicalEnvironmentVariableDeclarations) { - var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); + var statement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); if (!statements) { statements = [statement]; } @@ -54367,6 +69260,7 @@ var ts; } } } + // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; @@ -54377,24 +69271,26 @@ var ts; return statements; } function requestEmitHelper(helper) { - ts.Debug.assert(state > 0, "Cannot modify the transformation context during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); emitHelpers = ts.append(emitHelpers, helper); } function readEmitHelpers() { - ts.Debug.assert(state > 0, "Cannot modify the transformation context during initialization."); - ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); var helpers = emitHelpers; emitHelpers = undefined; return helpers; } function dispose() { - if (state < 3) { + if (state < 3 /* Disposed */) { + // Clean up emit nodes on parse tree for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { var node = nodes_5[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + // Release references to external entries for GC purposes. lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentVariableDeclarationsStack = undefined; lexicalEnvironmentFunctionDeclarations = undefined; @@ -54402,12 +69298,15 @@ var ts; onSubstituteNode = undefined; onEmitNode = undefined; emitHelpers = undefined; - state = 3; + // Prevent further use of the transformation result. + state = 3 /* Disposed */; } } } ts.transformNodes = transformNodes; })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { @@ -54416,13 +69315,13 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, false); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 266; + var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var isBundledEmit = sourceFileOrBundle.kind === 270 /* Bundle */; var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -54445,19 +69344,30 @@ var ts; var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; + // Contains the reference paths that needs to go in the declaration file. + // Collecting this separately because reference paths need to be first thing in the declaration file + // and we could be collecting these paths from multiple files into single one with --out option var referencesOutput = ""; var usedTypeDirectiveReferences; + // Emit references corresponding to each file var emittedReferencedFiles = []; var addedGlobalFileReference = false; var allSourcesModuleElementDeclarationEmitInfo = []; ts.forEach(sourceFiles, function (sourceFile) { + // Dont emit for javascript file if (ts.isSourceFileJavaScript(sourceFile)) { return; } + // Check what references need to be added if (!compilerOptions.noResolve) { ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // Emit reference in dts, if the file reference was not already emitted if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } @@ -54480,11 +69390,12 @@ var ts; write("}"); writeLine(); } + // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 238); + ts.Debug.assert(aliasEmitInfo.node.kind === 239 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -54502,6 +69413,9 @@ var ts; moduleElementDeclarationEmitInfo = []; } if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + // in case if we didn't write any external module specifiers in .d.ts we need to emit something + // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); writeLine(); } @@ -54519,7 +69433,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -54534,6 +69448,7 @@ var ts; var writer = ts.createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; + writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; @@ -54557,10 +69472,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 226) { + if (declaration.kind === 227 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 241 || declaration.kind === 242 || declaration.kind === 239) { + else if (declaration.kind === 242 /* NamedImports */ || declaration.kind === 243 /* ImportSpecifier */ || declaration.kind === 240 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -54570,8 +69485,17 @@ var ts; if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } + // If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration + // then we don't need to write it at this point. We will write it when we actually see its declaration + // Eg. + // export function bar(a: foo.Foo) { } + // import foo = require("foo"); + // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, + // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 238) { + if (moduleElementEmitInfo.node.kind === 239 /* ImportDeclaration */) { + // we have to create asynchronous output only after we have collected complete information + // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; } else { @@ -54579,12 +69503,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 233) { + if (nodeToCheck.kind === 234 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 233) { + if (nodeToCheck.kind === 234 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -54609,12 +69533,14 @@ var ts; } } function handleSymbolAccessibilityError(symbolAccessibilityResult) { - if (symbolAccessibilityResult.accessibility === 0) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // write the aliases if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { + // Report error reportedDeclarationError = true; var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { @@ -54628,7 +69554,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { @@ -54637,26 +69563,37 @@ var ts; emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } function reportInaccessibleThisError() { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - var shouldUseResolverType = declaration.kind === 146 && + // use the checker's type, not the declared type, + // for optional parameter properties + // and also for non-optional initialized parameters that aren't a parameter property + // these types may need to add `undefined`. + var shouldUseResolverType = declaration.kind === 147 /* Parameter */ && (resolver.isRequiredInitializedParameter(declaration) || resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { + // Write the type emitType(type); } else { errorNameNode = declaration.name; - var format = 4 | - 16384 | - (shouldUseResolverType ? 8192 : 0); + var format = 4 /* UseTypeOfFunction */ | + 16384 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -54665,11 +69602,12 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); if (signature.type) { + // Write the type emitType(signature.type); } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -54699,7 +69637,8 @@ var ts; if (declaration) { var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, false, true, newLine, ts.writeCommentRange); + // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -54708,74 +69647,76 @@ var ts; } function emitType(type) { switch (type.kind) { - case 119: - case 136: - case 133: - case 122: - case 134: - case 137: - case 105: - case 139: - case 95: - case 130: - case 169: - case 173: + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 134 /* ObjectKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 130 /* NeverKeyword */: + case 170 /* ThisType */: + case 174 /* LiteralType */: return writeTextOfNode(currentText, type); - case 201: + case 202 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 159: + case 160 /* TypeReference */: return emitTypeReference(type); - case 162: + case 163 /* TypeQuery */: return emitTypeQuery(type); - case 164: + case 165 /* ArrayType */: return emitArrayType(type); - case 165: + case 166 /* TupleType */: return emitTupleType(type); - case 166: + case 167 /* UnionType */: return emitUnionType(type); - case 167: + case 168 /* IntersectionType */: return emitIntersectionType(type); - case 168: + case 169 /* ParenthesizedType */: return emitParenType(type); - case 170: + case 171 /* TypeOperator */: return emitTypeOperator(type); - case 171: + case 172 /* IndexedAccessType */: return emitIndexedAccessType(type); - case 172: + case 173 /* MappedType */: return emitMappedType(type); - case 160: - case 161: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 163: + case 164 /* TypeLiteral */: return emitTypeLiteral(type); - case 71: + case 71 /* Identifier */: return emitEntityName(type); - case 143: + case 144 /* QualifiedName */: return emitEntityName(type); - case 158: + case 159 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { - if (entityName.kind === 71) { + if (entityName.kind === 71 /* Identifier */) { writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 143 ? entityName.left : entityName.expression; - var right = entityName.kind === 143 ? entityName.right : entityName.name; + var left = entityName.kind === 144 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 144 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 237 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, + // Aliases can be written asynchronously so use correct enclosing declaration + entityName.parent.kind === 238 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 || node.expression.kind === 179); + ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 180 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -54862,6 +69803,7 @@ var ts; if (type.members.length) { writeLine(); increaseIndent(); + // write members emitLines(type.members); decreaseIndent(); } @@ -54874,9 +69816,13 @@ var ts; currentIdentifiers = node.identifiers; isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComments*/ true); emitLines(node.statements); } + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. + // The temp name will be of the form _default_counter. + // Note that export default is only allowed at most once in a module, so we + // do not need to keep track of created temp names. function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; @@ -54884,9 +69830,9 @@ var ts; var count = 0; while (true) { count++; - var name_52 = baseName + "_" + count; - if (!currentIdentifiers.has(name_52)) { - return name_52; + var name = baseName + "_" + count; + if (!currentIdentifiers.has(name)) { + return name; } } } @@ -54899,13 +69845,13 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; } function emitExportAssignment(node) { - if (node.expression.kind === 71) { + if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } @@ -54919,8 +69865,10 @@ var ts; } write(";"); writeLine(); - if (node.expression.kind === 71) { + // Make all the declarations visible for the export name + if (node.expression.kind === 71 /* Identifier */) { var nodes = resolver.collectLinkedAliases(node.expression); + // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } } @@ -54931,10 +69879,11 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 237 || - (node.parent.kind === 265 && isCurrentFileExternalModule)) { + else if (node.kind === 238 /* ImportEqualsDeclaration */ || + (node.parent.kind === 269 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 265) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 269 /* SourceFile */) { + // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -54943,7 +69892,7 @@ var ts; }); } else { - if (node.kind === 238) { + if (node.kind === 239 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -54961,62 +69910,66 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 228: + case 229 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 208: + case 209 /* VariableStatement */: return writeVariableStatement(node); - case 230: + case 231 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 229: + case 230 /* ClassDeclaration */: return writeClassDeclaration(node); - case 231: + case 232 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 232: + case 233 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 233: + case 234 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 238: + case 239 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 265) { + // If the node is parented in the current source file we need to emit export declare or just export + if (node.parent.kind === 269 /* SourceFile */) { var modifiers = ts.getModifierFlags(node); - if (modifiers & 1) { + // If the node is exported + if (modifiers & 1 /* Export */) { write("export "); } - if (modifiers & 512) { + if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 && needsDeclare) { + else if (node.kind !== 231 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } } function emitClassMemberDeclarationFlags(flags) { - if (flags & 8) { + if (flags & 8 /* Private */) { write("private "); } - else if (flags & 16) { + else if (flags & 16 /* Protected */) { write("protected "); } - if (flags & 32) { + if (flags & 32 /* Static */) { write("static "); } - if (flags & 64) { + if (flags & 64 /* Readonly */) { write("readonly "); } - if (flags & 128) { + if (flags & 128 /* Abstract */) { write("abstract "); } } function writeImportEqualsDeclaration(node) { + // note usage of writer. methods instead of aliases created, just to make sure we are using + // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { write("export "); } write("import "); @@ -55042,7 +69995,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 240) { + if (namedBindings.kind === 241 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -55052,7 +70005,7 @@ var ts; } function writeImportDeclaration(node) { emitJsDocComments(node); - if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 1 /* Export */)) { write("export "); } write("import "); @@ -55063,9 +70016,10 @@ var ts; } if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { if (currentWriterPos !== writer.getTextPos()) { + // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 240) { + if (node.importClause.namedBindings.kind === 241 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -55082,20 +70036,24 @@ var ts; writer.writeLine(); } function emitExternalModuleSpecifier(parent) { - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 233; + // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). + // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered + // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' + // so compiler will treat them as external modules. + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 234 /* ModuleDeclaration */; var moduleSpecifier; - if (parent.kind === 237) { + if (parent.kind === 238 /* ImportEqualsDeclaration */) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 233) { + else if (parent.kind === 234 /* ModuleDeclaration */) { moduleSpecifier = parent.name; } else { var node = parent; moduleSpecifier = node.moduleSpecifier; } - if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); if (moduleName) { write('"'); @@ -55115,7 +70073,9 @@ var ts; } function emitExportSpecifier(node) { emitImportOrExportSpecifier(node); + // Make all the declarations visible for the export name var nodes = resolver.collectLinkedAliases(node.propertyName || node.name); + // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { @@ -55143,7 +70103,7 @@ var ts; write("global "); } else { - if (node.flags & 16) { + if (node.flags & 16 /* Namespace */) { write("namespace "); } else { @@ -55156,7 +70116,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 234) { + while (node.body && node.body.kind !== 235 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -55226,7 +70186,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 151 && ts.hasModifier(node.parent, 8); + return node.parent.kind === 152 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -55234,17 +70194,18 @@ var ts; emitJsDocComments(node); decreaseIndent(); writeTextOfNode(currentText, node.name); + // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - (node.parent.parent && node.parent.parent.kind === 163)) { - ts.Debug.assert(node.parent.kind === 151 || - node.parent.kind === 150 || - node.parent.kind === 160 || - node.parent.kind === 161 || - node.parent.kind === 155 || - node.parent.kind === 156); + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 164 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 152 /* MethodDeclaration */ || + node.parent.kind === 151 /* MethodSignature */ || + node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.kind === 156 /* CallSignature */ || + node.parent.kind === 157 /* ConstructSignature */); emitType(node.constraint); } else { @@ -55253,15 +70214,15 @@ var ts; } if (node.default && !isPrivateMethodTypeParameter(node)) { write(" = "); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - (node.parent.parent && node.parent.parent.kind === 163)) { - ts.Debug.assert(node.parent.kind === 151 || - node.parent.kind === 150 || - node.parent.kind === 160 || - node.parent.kind === 161 || - node.parent.kind === 155 || - node.parent.kind === 156); + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 164 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 152 /* MethodDeclaration */ || + node.parent.kind === 151 /* MethodSignature */ || + node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.kind === 156 /* CallSignature */ || + node.parent.kind === 157 /* ConstructSignature */); emitType(node.default); } else { @@ -55269,36 +70230,37 @@ var ts; } } function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 229: + case 230 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 230: + case 231 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 156: + case 157 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 155: + case 156 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151: - case 150: - if (ts.hasModifier(node.parent, 32)) { + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229) { + else if (node.parent.parent.kind === 230 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 228: + case 229 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 231: + case 232 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -55326,17 +70288,20 @@ var ts; if (ts.isEntityNameExpression(node.expression)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } - else if (!isImplementsList && node.expression.kind === 95) { + else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } function getHeritageClauseVisibilityError() { var diagnosticMessage; - if (node.parent.parent.kind === 229) { + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 230 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } else { + // interface is inaccessible diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; } return { @@ -55351,7 +70316,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92)) { + if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { emitPropertyDeclaration(param); } }); @@ -55362,17 +70327,17 @@ var ts; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); var tempVarName; if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - tempVarName = baseTypeNode.expression.kind === 95 ? + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? "null" : emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + }, !ts.findAncestor(node, function (n) { return n.kind === 234 /* ModuleDeclaration */; })); } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128)) { + if (ts.hasModifier(node, 128 /* Abstract */)) { write("abstract "); } write("class "); @@ -55389,10 +70354,10 @@ var ts; } } else { - emitHeritageClause([baseTypeNode], false); + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); } } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -55413,7 +70378,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -55425,7 +70390,7 @@ var ts; enclosingDeclaration = prevEnclosingDeclaration; } function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } emitJsDocComments(node); @@ -55434,54 +70399,66 @@ var ts; write(";"); writeLine(); } + function bindingNameContainsVisibleBindingElement(node) { + return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); + } + function isVariableDeclarationVisible(node) { + return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); + } function emitVariableDeclaration(node) { - if (node.kind !== 226 || resolver.isDeclarationVisible(node)) { + // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted + // so there is no check needed to see if declaration is visible + if (node.kind !== 227 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - writeTextOfNode(currentText, node.name); - if ((node.kind === 149 || node.kind === 148 || - (node.kind === 146 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); + // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor + // we don't want to emit property declaration with "?" + if ((node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */ || + (node.kind === 147 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 149 || node.kind === 148) && node.parent.kind === 163) { + if ((node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */) && node.parent.kind === 164 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { write(" = "); resolver.writeLiteralConstValue(node, writer); } - else if (!ts.hasModifier(node, 8)) { + else if (!ts.hasModifier(node, 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 226) { + if (node.kind === 227 /* VariableDeclaration */) { return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 || node.kind === 148 || - (node.kind === 146 && ts.hasModifier(node.parent, 8))) { - if (ts.hasModifier(node, 32)) { + else if (node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */ || + (node.kind === 147 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 || node.kind === 146) { + else if (node.parent.kind === 230 /* ClassDeclaration */ || node.kind === 147 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { + // Interfaces cannot have types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; @@ -55497,10 +70474,15 @@ var ts; } : undefined; } function emitBindingPattern(bindingPattern) { + // Only select visible, non-omitted expression from the bindingPattern's elements. + // We have to do this to avoid emitting trailing commas. + // For example: + // original: var [, c,,] = [ 2,3,4] + // emitted: declare var c: number; // instead of declare var c:number, ; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 200) { + if (element.kind !== 201 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { elements.push(element); } } @@ -55521,21 +70503,25 @@ var ts; } else { writeTextOfNode(currentText, bindingElement.name); - writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError); + writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); } } } } function emitTypeOfVariableDeclarationFromTypeLiteral(node) { + // if this is property of type literal, + // or is parameter of method/call/construct/index signature of type literal + // emit only if type is specified if (node.type) { write(": "); emitType(node.type); } } function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { + // If binding pattern doesn't have name, then there is nothing to be emitted for declaration file i.e. const [,] = [1,2]. if (ts.every(node.declarationList && node.declarationList.declarations, function (decl) { return decl.name && ts.isEmptyBindingPattern(decl.name); })) { return; } @@ -55550,12 +70536,12 @@ var ts; else { write("var "); } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, resolver.isDeclarationVisible); + emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); write(";"); writeLine(); } function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -55563,13 +70549,14 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64)); - writeTextOfNode(currentText, node.name); - if (!ts.hasModifier(node, 8)) { + emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); + writeNameOfDeclaration(node, getAccessorNameVisibilityError); + if (!ts.hasModifier(node, 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 153 ? accessors.setAccessor : accessors.getAccessor; + // couldn't get type for the first accessor, try the another one + var anotherAccessor = node.kind === 154 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -55582,82 +70569,161 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 153 - ? accessor.type + return accessor.kind === 154 /* GetAccessor */ + ? accessor.type // Getter - return type : accessor.parameters.length > 0 - ? accessor.parameters[0].type + ? accessor.parameters[0].type // Setter parameter type : undefined; } } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 154) { - if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32)) { + if (accessorWithTypeAnnotation.kind === 155 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - typeName: accessorWithTypeAnnotation.name - }; } else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32)) { + if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: accessorWithTypeAnnotation.name + }; } } function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } + // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting + // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 228) { + if (node.kind === 229 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 151 || node.kind === 152) { + else if (node.kind === 152 /* MethodDeclaration */ || node.kind === 153 /* Constructor */) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 228) { + if (node.kind === 229 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 152) { + else if (node.kind === 153 /* Constructor */) { write("constructor"); } else { - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getMethodNameVisibilityError); if (ts.hasQuestionToken(node)) { write("?"); } } emitSignatureDeclaration(node); } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + if (ts.hasDynamicName(node)) { + // If this node has a dynamic name, it can only be an identifier or property access because + // we've already skipped it otherwise. + ts.Debug.assert(resolver.isLateBound(node)); + writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); + } + else { + // If this node is a computed name, it can only be a symbol, because we've already skipped + // it if it's not a well known symbol. In that case, the text of the name will be exactly + // what we want, namely the name expression enclosed in brackets. + writeTextOfNode(currentText, node.name); + } + } + function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + var entityName = node.name.expression; + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + writeTextOfNode(currentText, node.name); } function emitSignatureDeclarationWithJsDocComments(node) { emitJsDocComments(node); @@ -55667,21 +70733,26 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 157) { + if (node.kind === 158 /* IndexSignature */) { + // Index signature can have readonly modifier emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 && ts.hasModifier(node, 8)) { + if (node.kind === 153 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { write("();"); writeLine(); return; } - if (node.kind === 156 || node.kind === 161) { + // Construct signature or constructor type write new Signature + if (node.kind === 157 /* ConstructSignature */ || node.kind === 162 /* ConstructorType */) { write("new "); } - else if (node.kind === 160) { + else if (node.kind === 161 /* FunctionType */) { var currentOutput = writer.getText(); + // Do not generate incorrect type when function type with type parameters is type argument + // This could happen if user used space between two '<' making it error free + // e.g var x: A< (a: Tany)=>Tany>; if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { closeParenthesizedFunctionType = true; write("("); @@ -55690,21 +70761,24 @@ var ts; emitTypeParameters(node.typeParameters); write("("); } + // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 157) { + if (node.kind === 158 /* IndexSignature */) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 160 || node.kind === 161; - if (isFunctionTypeOrConstructorType || node.parent.kind === 163) { + // If this is not a constructor and is not private, emit the return type + var isFunctionTypeOrConstructorType = node.kind === 161 /* FunctionType */ || node.kind === 162 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 164 /* TypeLiteral */) { + // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 152 && !ts.hasModifier(node, 8)) { + else if (node.kind !== 153 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -55718,46 +70792,50 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 156: + case 157 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 155: + case 156 /* CallSignature */: + // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 157: + case 158 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151: - case 150: - if (ts.hasModifier(node, 32)) { + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 229) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { + // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 228: + case 229 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -55778,6 +70856,9 @@ var ts; write("..."); } if (ts.isBindingPattern(node.name)) { + // For bindingPattern, we can't simply writeTextOfNode from the source file + // because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted. + // Therefore, we will have to recursively emit each element in the bindingPattern. emitBindingPattern(node.name); } else { @@ -55787,12 +70868,12 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 160 || - node.parent.kind === 161 || - node.parent.parent.kind === 163) { + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.parent.kind === 164 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!ts.hasModifier(node.parent, 8)) { + else if (!ts.hasModifier(node.parent, 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { @@ -55805,48 +70886,52 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 152: + case 153 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 156: + case 157 /* ConstructSignature */: + // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 155: + case 156 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157: + case 158 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151: - case 150: - if (ts.hasModifier(node.parent, 32)) { + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229) { + else if (node.parent.parent.kind === 230 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { + // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 228: + case 229 /* FunctionDeclaration */: return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; @@ -55855,12 +70940,13 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 174) { + // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. + if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 175) { + else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -55871,20 +70957,43 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 200) { + if (bindingElement.kind === 201 /* OmittedExpression */) { + // If bindingElement is an omittedExpression (i.e. containing elision), + // we will emit blank space (although this may differ from users' original code, + // it allows emitSeparatedList to write separator appropriately) + // Example: + // original: function foo([, x, ,]) {} + // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 176) { + else if (bindingElement.kind === 177 /* BindingElement */) { if (bindingElement.propertyName) { + // bindingElement has propertyName property in the following case: + // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" + // We have to explicitly emit the propertyName before descending into its binding elements. + // Example: + // original: function foo({y: [a,b,c]}) {} + // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { if (ts.isBindingPattern(bindingElement.name)) { + // If it is a nested binding pattern, we will recursively descend into each element and emit each one separately. + // In the case of rest element, we will omit rest element. + // Example: + // original: function foo([a, [[b]], c] = [1,[["string"]], 3]) {} + // emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void; + // original with rest: function foo([a, ...c]) {} + // emit : declare function foo([a, ...c]): void; emitBindingPattern(bindingElement.name); } else { - ts.Debug.assert(bindingElement.name.kind === 71); + ts.Debug.assert(bindingElement.name.kind === 71 /* Identifier */); + // If the node is just an identifier, we will simply emit the text associated with the node's name + // Example: + // original: function foo({y = 10, x}) {} + // emit : declare function foo({y, x}: {number, any}): void; if (bindingElement.dotDotDotToken) { write("..."); } @@ -55896,58 +71005,68 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 228: - case 233: - case 237: - case 230: - case 229: - case 231: - case 232: + case 229 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 231 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 208: + case 209 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 238: - return emitModuleElement(node, !node.importClause); - case 244: + case 239 /* ImportDeclaration */: + // Import declaration without import clause is visible, otherwise it is not visible + return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); + case 245 /* ExportDeclaration */: return emitExportDeclaration(node); - case 152: - case 151: - case 150: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return writeFunctionDeclaration(node); - case 156: - case 155: - case 157: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return emitAccessorDeclaration(node); - case 149: - case 148: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return emitPropertyDeclaration(node); - case 264: + case 268 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 243: + case 244 /* ExportAssignment */: return emitExportAssignment(node); - case 265: + case 269 /* SourceFile */: return emitSourceFile(node); } } + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (referencedFile.isDeclarationFile) { + // Declaration file, use declaration file name declFileName = referencedFile.fileName; } else { + // Get the declaration file path ts.forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); referencesOutput += "/// " + newLine; } return addedBundledEmitReference; function getDeclFileName(emitFileNames, sourceFileOrBundle) { - var isBundledEmit = sourceFileOrBundle.kind === 266; + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + var isBundledEmit = sourceFileOrBundle.kind === 270 /* Bundle */; if (isBundledEmit && !addBundledFileReference) { return; } @@ -55957,11 +71076,12 @@ var ts; } } } + /* @internal */ function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { - var sourceFiles = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); @@ -55970,6 +71090,7 @@ var ts; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; + // apply asynchronous additions to the synchronous output ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.asynchronousOutput) { declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); @@ -55983,8 +71104,11 @@ var ts; } ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { + // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -55997,11 +71121,14 @@ var ts; var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; - var sourceMapDir; + var sourceMapDir; // The directory in which sourcemap will be + // Current source map file and its index in the sources list var sourceMapSourceIndex; + // Last recorded and encoded spans var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; + // Source map data var sourceMapData; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { @@ -56015,9 +71142,19 @@ var ts; getText: getText, getSourceMappingURL: getSourceMappingURL, }; + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ function skipSourceTrivia(pos) { return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); } + /** + * Initialize the SourceMapWriter for a new output file. + * + * @param filePath The path to the generated output file. + * @param sourceMapFilePath The path to the output source map file. + * @param sourceFileOrBundle The input source file or bundle for the program. + */ function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { if (disabled) { return; @@ -56027,10 +71164,13 @@ var ts; } currentSource = undefined; currentSourceText = undefined; + // Current source map file and its index in the sources list sourceMapSourceIndex = -1; + // Last recorded and encoded spans lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; lastEncodedNameIndex = 0; + // Initialize source map data sourceMapData = { sourceMapFilePath: sourceMapFilePath, jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, @@ -56043,18 +71183,26 @@ var ts; sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, sourceMapDecodedMappings: [] }; + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { sourceMapData.sourceMapSourceRoot += ts.directorySeparator; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 265) { + if (sourceFileOrBundle.kind === 269 /* SourceFile */) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + // The relative paths are relative to the common directory sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); } else { sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); @@ -56064,6 +71212,9 @@ var ts; sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); } } + /** + * Reset the SourceMapWriter to an empty state. + */ function reset() { if (disabled) { return; @@ -56076,26 +71227,35 @@ var ts; lastEncodedNameIndex = undefined; sourceMapData = undefined; } + // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { return; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Line/Comma delimiters if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + // Emit comma to separate the entry if (sourceMapData.sourceMapMappings) { sourceMapData.sourceMapMappings += ","; } } else { + // Emit line delimiters for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { sourceMapData.sourceMapMappings += ";"; } prevEncodedEmittedColumn = 1; } + // 1. Relative Column 0 based sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + // 2. Relative sourceIndex sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + // 3. Relative sourceLine 0 based sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + // 4. Relative sourceColumn 0 based sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + // 5. Relative namePosition 0 based if (lastRecordedSourceMapSpan.nameIndex >= 0) { ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); @@ -56104,6 +71264,14 @@ var ts; lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } + /** + * Emits a mapping. + * + * If the position is synthetic (undefined or a negative value), no mapping will be + * created. + * + * @param pos The position. + */ function emitPos(pos) { if (disabled || ts.positionIsSynthesized(pos)) { return; @@ -56112,17 +71280,21 @@ var ts; ts.performance.mark("beforeSourcemap"); } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); + // Convert the location to be one-based. sourceLinePos.line++; sourceLinePos.character++; var emittedLine = writer.getLine(); var emittedColumn = writer.getColumn(); + // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine !== emittedLine || lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + // Encode the last recordedSpan before assigning new encodeLastRecordedSourceMapSpan(); + // New span lastRecordedSourceMapSpan = { emittedLine: emittedLine, emittedColumn: emittedColumn, @@ -56132,6 +71304,7 @@ var ts; }; } else { + // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; @@ -56141,6 +71314,13 @@ var ts; ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ function emitNodeWithSourceMap(hint, node, emitCallback) { if (disabled) { return emitCallback(hint, node); @@ -56156,14 +71336,14 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 287 - && (emitFlags & 16) === 0 + if (node.kind !== 291 /* NotEmittedStatement */ + && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); } if (source) setSourceFile(oldSource); - if (emitFlags & 64) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { disabled = true; emitCallback(hint, node); disabled = false; @@ -56173,8 +71353,8 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 287 - && (emitFlags & 32) === 0 + if (node.kind !== 291 /* NotEmittedStatement */ + && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); } @@ -56182,6 +71362,14 @@ var ts; setSourceFile(oldSource); } } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { if (disabled) { return emitCallback(token, tokenPos); @@ -56190,35 +71378,48 @@ var ts; var emitFlags = emitNode && emitNode.flags; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); - if ((emitFlags & 128) === 0 && tokenPos >= 0) { + if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } tokenPos = emitCallback(token, tokenPos); if (range) tokenPos = range.end; - if ((emitFlags & 256) === 0 && tokenPos >= 0) { + if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } return tokenPos; } + /** + * Set the current source file. + * + * @param sourceFile The source file. + */ function setSourceFile(sourceFile) { if (disabled) { return; } currentSource = sourceFile; currentSourceText = currentSource.text; + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); + // The one that can be used from program to get the actual source file sourceMapData.inputSourceFileNames.push(currentSource.fileName); if (compilerOptions.inlineSources) { sourceMapData.sourceMapSourcesContent.push(currentSource.text); } } } + /** + * Gets the text for the source map. + */ function getText() { if (disabled) { return; @@ -56234,11 +71435,15 @@ var ts; sourcesContent: sourceMapData.sourceMapSourcesContent, }); } + /** + * Gets the SourceMappingURL for the source map. + */ function getSourceMappingURL() { if (disabled) { return; } if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } @@ -56256,17 +71461,24 @@ var ts; throw TypeError(inValue + ": not a 64 based value"); } function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 if (inValue < 0) { inValue = ((-inValue) << 1) + 1; } else { inValue = inValue << 1; } + // Encode 5 bits at a time starting from least significant bits var encodedStr = ""; do { - var currentDigit = inValue & 31; + var currentDigit = inValue & 31; // 11111 inValue = inValue >> 5; if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) currentDigit = currentDigit | 32; } encodedStr = encodedStr + base64FormatEncode(currentDigit); @@ -56274,6 +71486,8 @@ var ts; return encodedStr; } })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { function createCommentWriter(printerOptions, emitPos) { @@ -56309,18 +71523,24 @@ var ts; var emitFlags = emitNode && emitNode.flags; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { + // Both pos and end are synthesized, so just emit the node without comments. emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback); } else { if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287; - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; - var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; + var isEmittedNode = node.kind !== 291 /* NotEmittedStatement */; + // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. + // It is expensive to walk entire tree just to set one kind of node to have no comments. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } + // Save current container state on the stack. var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; @@ -56329,7 +71549,9 @@ var ts; } if (!skipTrailingComments) { containerEnd = end; - if (node.kind === 227) { + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === 228 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -56340,9 +71562,12 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("postEmitNodeWithComment"); } + // Restore previous container state. containerPos = savedContainerPos; containerEnd = savedContainerEnd; declarationListContainerEnd = savedDeclarationListContainerEnd; + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. if (!skipTrailingComments && isEmittedNode) { emitTrailingComments(end); } @@ -56376,11 +71601,11 @@ var ts; } } function emitLeadingSynthesizedComment(comment) { - if (comment.kind === 2) { + if (comment.kind === 2 /* SingleLineCommentTrivia */) { writer.writeLine(); } writeSynthesizedComment(comment); - if (comment.hasTrailingNewLine || comment.kind === 2) { + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { writer.writeLine(); } else { @@ -56398,16 +71623,16 @@ var ts; } function writeSynthesizedComment(comment) { var text = formatSynthesizedComment(comment); - var lineMap = comment.kind === 3 ? ts.computeLineStarts(text) : undefined; + var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined; ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine); } function formatSynthesizedComment(comment) { - return comment.kind === 3 + return comment.kind === 3 /* MultiLineCommentTrivia */ ? "/*" + comment.text + "*/" : "//" + comment.text; } function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) { - if (emitFlags & 2048) { + if (emitFlags & 2048 /* NoNestedComments */) { disabled = true; emitCallback(hint, node); disabled = false; @@ -56422,15 +71647,15 @@ var ts; } var pos = detachedRange.pos, end = detachedRange.end; var emitFlags = ts.getEmitFlags(node); - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; - var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024) !== 0; + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; + var skipTrailingComments = disabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); } if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 2048 && !disabled) { + if (emitFlags & 2048 /* NoNestedComments */ && !disabled) { disabled = true; emitCallback(node); disabled = false; @@ -56442,7 +71667,7 @@ var ts; ts.performance.mark("beginEmitBodyWithDetachedCommetns"); } if (!skipTrailingComments) { - emitLeadingComments(detachedRange.end, true); + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); if (hasWrittenComment && !writer.isAtStartOfLine()) { writer.writeLine(); } @@ -56457,6 +71682,14 @@ var ts; forEachLeadingCommentToEmit(pos, emitLeadingComment); } else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); } } @@ -56465,11 +71698,12 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; } + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space if (emitPos) emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); @@ -56478,7 +71712,7 @@ var ts; if (hasTrailingNewLine) { writer.writeLine(); } - else { + else if (kind === 3 /* MultiLineCommentTrivia */) { writer.write(" "); } } @@ -56486,12 +71720,13 @@ var ts; if (disabled || pos === -1) { return; } - emitLeadingComments(pos, true); + emitLeadingComments(pos, /*isEmittedNode*/ true); } function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); } @@ -56517,6 +71752,7 @@ var ts; } } function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space if (emitPos) emitPos(commentPos); ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); @@ -56530,16 +71766,18 @@ var ts; } } function forEachLeadingCommentToEmit(pos, cb) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments if (containerPos === -1 || pos !== containerPos) { if (hasDetachedComments(pos)) { forEachLeadingCommentWithoutDetachedComments(cb); } else { - ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); } } } function forEachTrailingCommentToEmit(end, cb) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { ts.forEachTrailingCommentRange(currentText, end, cb); } @@ -56563,6 +71801,7 @@ var ts; return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { + // get the leading comments from detachedPos var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); @@ -56570,7 +71809,7 @@ var ts; else { detachedCommentsInfo = undefined; } - ts.forEachLeadingCommentRange(currentText, pos, cb, pos); + ts.forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); } function emitDetachedCommentsAndUpdateCommentsInfo(range) { var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); @@ -56590,16 +71829,36 @@ var ts; if (emitPos) emitPos(commentEnd); } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + */ function isTripleSlashComment(commentPos, commentEnd) { return ts.isRecognizedTripleSlashComment(currentText, commentPos, commentEnd); } } ts.createCommentWriter = createCommentWriter; })(ts || (ts = {})); +/// +/// +/// +/// +/// var ts; (function (ts) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); + /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); @@ -56607,7 +71866,7 @@ var ts; if (sourceFiles.length) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); } } @@ -56625,25 +71884,31 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve function getOutputExtension(sourceFile, options) { - if (options.jsx === 1) { + if (options.jsx === 1 /* Preserve */) { if (ts.isSourceFileJavaScript(sourceFile)) { - if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { - return ".jsx"; + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; } } - else if (sourceFile.languageVariant === 1) { - return ".jsx"; + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; } } - return ".js"; + return ".js" /* Js */; } function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266) { + if (sourceFileOrBundle.kind === 270 /* Bundle */) { return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); } return ts.getOriginalSourceFile(sourceFileOrBundle); } + /*@internal*/ + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -56658,20 +71923,28 @@ var ts; var isOwnFileEmit; var emitSkipped = false; var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, false); + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); + // Create a printer to print the nodes var printer = createPrinter(compilerOptions, { + // resolver hooks hasGlobalName: resolver.hasGlobalName, + // transform hooks onEmitNode: transform.emitNodeWithNotification, substituteNode: transform.substituteNode, + // sourcemap hooks onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, onEmitSourceMapOfPosition: sourceMap.emitPos, + // emitter hooks onEmitHelpers: emitHelpers, onSetSourceFile: setSourceFile, }); + // Emit each output file ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree transform.dispose(); return { emitSkipped: emitSkipped, @@ -56681,6 +71954,7 @@ var ts; }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { if (!emitOnlyDtsFiles) { printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); @@ -56705,8 +71979,8 @@ var ts; } } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 266 ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 265 ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 269 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); if (bundle) { @@ -56721,15 +71995,19 @@ var ts; writer.writeLine(); var sourceMappingURL = sourceMap.getSourceMappingURL(); if (sourceMappingURL) { - writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment } + // Write the source map if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false, sourceFiles); + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); } + // Record source map data for the test harness. if (sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } + // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + // Reset state sourceMap.reset(); writer.reset(); currentSourceFile = undefined; @@ -56742,7 +72020,7 @@ var ts; } function emitHelpers(node, writeLines) { var helpersEmitted = false; - var bundle = node.kind === 266 ? node : undefined; + var bundle = node.kind === 270 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -56757,8 +72035,13 @@ var ts; for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { var helper = _b[_a]; if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. if (shouldSkip) continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. if (shouldBundle) { if (bundledHelpers.get(helper.name)) { continue; @@ -56767,6 +72050,7 @@ var ts; } } else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers continue; } writeLines(helper.text); @@ -56786,37 +72070,39 @@ var ts; var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; var currentSourceFile; - var nodeIdToGeneratedName; - var autoGeneratedIdToGeneratedName; - var generatedNames; - var tempFlagsStack; - var tempFlags; + var nodeIdToGeneratedName; // Map of generated names for specific nodes. + var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. + var generatedNames; // Set of names generated by the NameGenerator. + var tempFlagsStack; // Stack of enclosing name generation scopes. + var tempFlags; // TempFlags for the current name generation scope. var writer; var ownWriter; reset(); return { + // public API printNode: printNode, printFile: printFile, printBundle: printBundle, + // internal API writeNode: writeNode, writeFile: writeFile, writeBundle: writeBundle }; function printNode(hint, node, sourceFile) { switch (hint) { - case 0: + case 0 /* SourceFile */: ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node."); break; - case 2: + case 2 /* IdentifierName */: ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node."); break; - case 1: + case 1 /* Expression */: ts.Debug.assert(ts.isExpression(node), "Expected an Expression node."); break; } switch (node.kind) { - case 265: return printFile(node); - case 266: return printBundle(node); + case 269 /* SourceFile */: return printFile(node); + case 270 /* Bundle */: return printBundle(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -56844,7 +72130,7 @@ var ts; emitHelpersIndirect(bundle); for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; - print(0, sourceFile, sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); } reset(); writer = previousWriter; @@ -56854,7 +72140,7 @@ var ts; setWriter(output); emitShebangIfNeeded(sourceFile); emitPrologueDirectivesIfNeeded(sourceFile); - print(0, sourceFile, sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); reset(); writer = previousWriter; } @@ -56888,23 +72174,25 @@ var ts; autoGeneratedIdToGeneratedName = []; generatedNames = ts.createMap(); tempFlagsStack = []; - tempFlags = 0; + tempFlags = 0 /* Auto */; comments.reset(); - setWriter(undefined); + setWriter(/*output*/ undefined); } + // TODO: Should this just be `emit`? + // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 function emitIfPresent(node) { if (node) { emit(node); } } function emit(node) { - pipelineEmitWithNotification(4, node); + pipelineEmitWithNotification(4 /* Unspecified */, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2, node); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } function emitExpression(node) { - pipelineEmitWithNotification(1, node); + pipelineEmitWithNotification(1 /* Expression */, node); } function pipelineEmitWithNotification(hint, node) { if (onEmitNode) { @@ -56916,7 +72204,7 @@ var ts; } function pipelineEmitWithComments(hint, node) { node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0) { + if (emitNodeWithComments && hint !== 0 /* SourceFile */) { emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); } else { @@ -56924,7 +72212,7 @@ var ts; } } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 && hint !== 2) { + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); } else { @@ -56933,11 +72221,11 @@ var ts; } function pipelineEmitWithHint(hint, node) { switch (hint) { - case 0: return pipelineEmitSourceFile(node); - case 2: return pipelineEmitIdentifierName(node); - case 1: return pipelineEmitExpression(node); - case 3: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4: return pipelineEmitUnspecified(node); + case 0 /* SourceFile */: return pipelineEmitSourceFile(node); + case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); + case 1 /* Expression */: return pipelineEmitExpression(node); + case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + case 4 /* Unspecified */: return pipelineEmitUnspecified(node); } } function pipelineEmitSourceFile(node) { @@ -56955,207 +72243,246 @@ var ts; } function pipelineEmitUnspecified(node) { var kind = node.kind; + // Reserved words + // Strict mode reserved words + // Contextual keywords if (ts.isKeyword(kind)) { writeTokenNode(node); return; } switch (kind) { - case 14: - case 15: - case 16: + // Pseudo-literals + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: return emitLiteral(node); - case 71: + // Identifiers + case 71 /* Identifier */: return emitIdentifier(node); - case 143: + // Parse tree nodes + // Names + case 144 /* QualifiedName */: return emitQualifiedName(node); - case 144: + case 145 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 145: + // Signature elements + case 146 /* TypeParameter */: return emitTypeParameter(node); - case 146: + case 147 /* Parameter */: return emitParameter(node); - case 147: + case 148 /* Decorator */: return emitDecorator(node); - case 148: + // Type members + case 149 /* PropertySignature */: return emitPropertySignature(node); - case 149: + case 150 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 150: + case 151 /* MethodSignature */: return emitMethodSignature(node); - case 151: + case 152 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 152: + case 153 /* Constructor */: return emitConstructor(node); - case 153: - case 154: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return emitAccessorDeclaration(node); - case 155: + case 156 /* CallSignature */: return emitCallSignature(node); - case 156: + case 157 /* ConstructSignature */: return emitConstructSignature(node); - case 157: + case 158 /* IndexSignature */: return emitIndexSignature(node); - case 158: + // Types + case 159 /* TypePredicate */: return emitTypePredicate(node); - case 159: + case 160 /* TypeReference */: return emitTypeReference(node); - case 160: + case 161 /* FunctionType */: return emitFunctionType(node); - case 161: + case 277 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 162 /* ConstructorType */: return emitConstructorType(node); - case 162: + case 163 /* TypeQuery */: return emitTypeQuery(node); - case 163: + case 164 /* TypeLiteral */: return emitTypeLiteral(node); - case 164: + case 165 /* ArrayType */: return emitArrayType(node); - case 165: + case 166 /* TupleType */: return emitTupleType(node); - case 166: + case 167 /* UnionType */: return emitUnionType(node); - case 167: + case 168 /* IntersectionType */: return emitIntersectionType(node); - case 168: + case 169 /* ParenthesizedType */: return emitParenthesizedType(node); - case 201: + case 202 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 169: + case 170 /* ThisType */: return emitThisType(); - case 170: + case 171 /* TypeOperator */: return emitTypeOperator(node); - case 171: + case 172 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 172: + case 173 /* MappedType */: return emitMappedType(node); - case 173: + case 174 /* LiteralType */: return emitLiteralType(node); - case 174: + case 272 /* JSDocAllType */: + write("*"); + return; + case 273 /* JSDocUnknownType */: + write("?"); + return; + case 274 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 275 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 276 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 278 /* JSDocVariadicType */: + return emitJSDocVariadicType(node); + // Binding patterns + case 175 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 175: + case 176 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 176: + case 177 /* BindingElement */: return emitBindingElement(node); - case 205: + // Misc + case 206 /* TemplateSpan */: return emitTemplateSpan(node); - case 206: + case 207 /* SemicolonClassElement */: return emitSemicolonClassElement(); - case 207: + // Statements + case 208 /* Block */: return emitBlock(node); - case 208: + case 209 /* VariableStatement */: return emitVariableStatement(node); - case 209: + case 210 /* EmptyStatement */: return emitEmptyStatement(); - case 210: + case 211 /* ExpressionStatement */: return emitExpressionStatement(node); - case 211: + case 212 /* IfStatement */: return emitIfStatement(node); - case 212: + case 213 /* DoStatement */: return emitDoStatement(node); - case 213: + case 214 /* WhileStatement */: return emitWhileStatement(node); - case 214: + case 215 /* ForStatement */: return emitForStatement(node); - case 215: + case 216 /* ForInStatement */: return emitForInStatement(node); - case 216: + case 217 /* ForOfStatement */: return emitForOfStatement(node); - case 217: + case 218 /* ContinueStatement */: return emitContinueStatement(node); - case 218: + case 219 /* BreakStatement */: return emitBreakStatement(node); - case 219: + case 220 /* ReturnStatement */: return emitReturnStatement(node); - case 220: + case 221 /* WithStatement */: return emitWithStatement(node); - case 221: + case 222 /* SwitchStatement */: return emitSwitchStatement(node); - case 222: + case 223 /* LabeledStatement */: return emitLabeledStatement(node); - case 223: + case 224 /* ThrowStatement */: return emitThrowStatement(node); - case 224: + case 225 /* TryStatement */: return emitTryStatement(node); - case 225: + case 226 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 226: + // Declarations + case 227 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 227: + case 228 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 228: + case 229 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 229: + case 230 /* ClassDeclaration */: return emitClassDeclaration(node); - case 230: + case 231 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 231: + case 232 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 232: + case 233 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 233: + case 234 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 234: + case 235 /* ModuleBlock */: return emitModuleBlock(node); - case 235: + case 236 /* CaseBlock */: return emitCaseBlock(node); - case 236: + case 237 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 237: + case 238 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 238: + case 239 /* ImportDeclaration */: return emitImportDeclaration(node); - case 239: + case 240 /* ImportClause */: return emitImportClause(node); - case 240: + case 241 /* NamespaceImport */: return emitNamespaceImport(node); - case 241: + case 242 /* NamedImports */: return emitNamedImports(node); - case 242: + case 243 /* ImportSpecifier */: return emitImportSpecifier(node); - case 243: + case 244 /* ExportAssignment */: return emitExportAssignment(node); - case 244: + case 245 /* ExportDeclaration */: return emitExportDeclaration(node); - case 245: + case 246 /* NamedExports */: return emitNamedExports(node); - case 246: + case 247 /* ExportSpecifier */: return emitExportSpecifier(node); - case 247: + case 248 /* MissingDeclaration */: return; - case 248: + // Module references + case 249 /* ExternalModuleReference */: return emitExternalModuleReference(node); - case 10: + // JSX (non-expression) + case 10 /* JsxText */: return emitJsxText(node); - case 251: - return emitJsxOpeningElement(node); - case 252: - return emitJsxClosingElement(node); - case 253: + case 252 /* JsxOpeningElement */: + case 255 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 253 /* JsxClosingElement */: + case 256 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 257 /* JsxAttribute */: return emitJsxAttribute(node); - case 254: + case 258 /* JsxAttributes */: return emitJsxAttributes(node); - case 255: + case 259 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 256: + case 260 /* JsxExpression */: return emitJsxExpression(node); - case 257: + // Clauses + case 261 /* CaseClause */: return emitCaseClause(node); - case 258: + case 262 /* DefaultClause */: return emitDefaultClause(node); - case 259: + case 263 /* HeritageClause */: return emitHeritageClause(node); - case 260: + case 264 /* CatchClause */: return emitCatchClause(node); - case 261: + // Property assignments + case 265 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 262: + case 266 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 263: + case 267 /* SpreadAssignment */: return emitSpreadAssignment(node); - case 264: + // Enum + case 268 /* EnumMember */: return emitEnumMember(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1, node)); + return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { writeTokenNode(node); @@ -57165,83 +72492,91 @@ var ts; function pipelineEmitExpression(node) { var kind = node.kind; switch (kind) { - case 8: + // Literals + case 8 /* NumericLiteral */: return emitNumericLiteral(node); - case 9: - case 12: - case 13: + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: return emitLiteral(node); - case 71: + // Identifiers + case 71 /* Identifier */: return emitIdentifier(node); - case 86: - case 95: - case 97: - case 101: - case 99: - case 91: + // Reserved words + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 101 /* TrueKeyword */: + case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: writeTokenNode(node); return; - case 177: + // Expressions + case 178 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 178: + case 179 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 179: + case 180 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 180: + case 181 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 181: + case 182 /* CallExpression */: return emitCallExpression(node); - case 182: + case 183 /* NewExpression */: return emitNewExpression(node); - case 183: + case 184 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 184: + case 185 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 185: + case 186 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 186: + case 187 /* FunctionExpression */: return emitFunctionExpression(node); - case 187: + case 188 /* ArrowFunction */: return emitArrowFunction(node); - case 188: + case 189 /* DeleteExpression */: return emitDeleteExpression(node); - case 189: + case 190 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 190: + case 191 /* VoidExpression */: return emitVoidExpression(node); - case 191: + case 192 /* AwaitExpression */: return emitAwaitExpression(node); - case 192: + case 193 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 193: + case 194 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 194: + case 195 /* BinaryExpression */: return emitBinaryExpression(node); - case 195: + case 196 /* ConditionalExpression */: return emitConditionalExpression(node); - case 196: + case 197 /* TemplateExpression */: return emitTemplateExpression(node); - case 197: + case 198 /* YieldExpression */: return emitYieldExpression(node); - case 198: + case 199 /* SpreadElement */: return emitSpreadExpression(node); - case 199: + case 200 /* ClassExpression */: return emitClassExpression(node); - case 200: + case 201 /* OmittedExpression */: return; - case 202: + case 203 /* AsExpression */: return emitAsExpression(node); - case 203: + case 204 /* NonNullExpression */: return emitNonNullExpression(node); - case 204: + case 205 /* MetaProperty */: return emitMetaProperty(node); - case 249: + // JSX + case 250 /* JsxElement */: return emitJsxElement(node); - case 250: + case 251 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 288: + case 254 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 292 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 289: + case 293 /* CommaListExpression */: return emitCommaList(node); } } @@ -57253,30 +72588,46 @@ var ts; onEmitHelpers(node, writeLines); } } + // + // Literals/Pseudo-literals + // + // SyntaxKind.NumericLiteral function emitNumericLiteral(node) { emitLiteral(node); } + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail function emitLiteral(node) { var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { + && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writer.writeLiteral(text); } else { write(text); } } + // + // Identifiers + // function emitIdentifier(node) { - write(getTextOfNode(node, false)); + write(getTextOfNode(node, /*includeTrivia*/ false)); emitTypeArguments(node, node.typeArguments); } + // + // Names + // function emitQualifiedName(node) { emitEntityName(node.left); write("."); emit(node.right); } function emitEntityName(node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { emitExpression(node); } else { @@ -57288,6 +72639,9 @@ var ts; emitExpression(node.expression); write("]"); } + // + // Signature elements + // function emitTypeParameter(node) { emit(node.name); emitWithPrefix(" extends ", node.constraint); @@ -57297,15 +72651,25 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); - emit(node.name); + if (node.name) { + emit(node.name); + } emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); + if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitWithPrefix(": ", node.type); + } emitExpressionWithPrefix(" = ", node.initializer); } function emitDecorator(decorator) { write("@"); emitExpression(decorator.expression); } + // + // Type members + // function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); @@ -57349,7 +72713,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 153 ? "get " : "set "); + write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -57380,6 +72744,9 @@ var ts; function emitSemicolonClassElement() { write(";"); } + // + // Types + // function emitTypePredicate(node) { emit(node.parameterName); write(" is "); @@ -57395,6 +72762,24 @@ var ts; write(" => "); emit(node.type); } + function emitJSDocFunctionType(node) { + write("function"); + emitParameters(node, node.parameters); + write(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + write("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + write("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + write("="); + } function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); @@ -57408,24 +72793,28 @@ var ts; } function emitTypeLiteral(node) { write("{"); - var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; - emitList(node, node.members, flags | 262144); + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); write("}"); } function emitArrayType(node) { emit(node.elementType); write("[]"); } + function emitJSDocVariadicType(node) { + write("..."); + emit(node.type); + } function emitTupleType(node) { write("["); - emitList(node, node.elementTypes, 336); + emitList(node, node.elementTypes, 336 /* TupleTypeElements */); write("]"); } function emitUnionType(node) { - emitList(node, node.types, 260); + emitList(node, node.types, 260 /* UnionTypeConstituents */); } function emitIntersectionType(node) { - emitList(node, node.types, 264); + emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { write("("); @@ -57449,7 +72838,7 @@ var ts; function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); write("{"); - if (emitFlags & 1) { + if (emitFlags & 1 /* SingleLine */) { write(" "); } else { @@ -57461,13 +72850,13 @@ var ts; write(" "); } write("["); - pipelineEmitWithNotification(3, node.typeParameter); + pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); write("]"); emitIfPresent(node.questionToken); write(": "); emit(node.type); write(";"); - if (emitFlags & 1) { + if (emitFlags & 1 /* SingleLine */) { write(" "); } else { @@ -57479,6 +72868,9 @@ var ts; function emitLiteralType(node) { emitExpression(node.literal); } + // + // Binding patterns + // function emitObjectBindingPattern(node) { var elements = node.elements; if (elements.length === 0) { @@ -57486,7 +72878,7 @@ var ts; } else { write("{"); - emitList(node, elements, 432); + emitList(node, elements, 432 /* ObjectBindingPatternElements */); write("}"); } } @@ -57497,7 +72889,7 @@ var ts; } else { write("["); - emitList(node, node.elements, 304); + emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); write("]"); } } @@ -57507,19 +72899,22 @@ var ts; emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } + // + // Expressions + // function emitArrayLiteralExpression(node) { var elements = node.elements; - var preferNewLine = node.multiLine ? 32768 : 0; - emitExpressionList(node, elements, 4466 | preferNewLine); + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { - var indentedFlag = ts.getEmitFlags(node) & 65536; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } - var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; - emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); } @@ -57527,10 +72922,10 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; - if (!(ts.getEmitFlags(node) & 131072)) { + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; - var dotToken = ts.createToken(23); + var dotToken = ts.createToken(23 /* DotToken */); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); @@ -57544,15 +72939,20 @@ var ts; emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal function needsDotDotForPropertyAccess(expression) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { + // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23)) < 0; + && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + // check if constant enum value is integer var constantValue = ts.getConstantValue(expression); + // isFinite handles cases when constantValue is undefined return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue && printerOptions.removeComments; @@ -57567,13 +72967,13 @@ var ts; function emitCallExpression(node) { emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 1296); + emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { write("new "); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 9488); + emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); @@ -57630,24 +73030,36 @@ var ts; emitExpression(node.operand); } function shouldEmitWhitespaceBeforeOperand(node) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. var operand = node.operand; - return operand.kind === 192 - && ((node.operator === 37 && (operand.operator === 37 || operand.operator === 43)) - || (node.operator === 38 && (operand.operator === 38 || operand.operator === 44))); + return operand.kind === 193 /* PrefixUnaryExpression */ + && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) + || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); writeTokenText(node.operator); } function emitBinaryExpression(node) { - var isCommaOperator = node.operatorToken.kind !== 26; + var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); - emitTrailingCommentsOfPosition(node.operatorToken.end, true); + emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -57671,7 +73083,7 @@ var ts; } function emitTemplateExpression(node) { emit(node.head); - emitList(node, node.templateSpans, 131072); + emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { write("yield"); @@ -57705,20 +73117,27 @@ var ts; write("."); emit(node.name); } + // + // Misc + // function emitTemplateSpan(node) { emitExpression(node.expression); emit(node.literal); } + // + // Statements + // function emitBlock(node) { - writeToken(17, node.pos, node); - emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); + writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18, node.statements.end, node); + writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { - var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; emitList(node, node.statements, format); } function emitVariableStatement(node) { @@ -57734,16 +73153,16 @@ var ts; write(";"); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); write(" "); - writeToken(19, openParenPos, node); + writeToken(19 /* OpenParenToken */, openParenPos, node); emitExpression(node.expression); - writeToken(20, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, node); - if (node.elseStatement.kind === 211) { + writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + if (node.elseStatement.kind === 212 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -57772,9 +73191,9 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos); write(" "); - writeToken(19, openParenPos, node); + writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); emitForBinding(node.initializer); write(";"); emitExpressionWithPrefix(" ", node.condition); @@ -57784,29 +73203,29 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos); write(" "); - writeToken(19, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos); emitForBinding(node.initializer); write(" in "); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos); write(" "); emitWithSuffix(node.awaitModifier, " "); - writeToken(19, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos); emitForBinding(node.initializer); write(" of "); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 227) { + if (node.kind === 228 /* VariableDeclarationList */) { emit(node); } else { @@ -57815,12 +73234,12 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos); + writeToken(77 /* ContinueKeyword */, node.pos); emitWithPrefix(" ", node.label); write(";"); } function emitBreakStatement(node) { - writeToken(72, node.pos); + writeToken(72 /* BreakKeyword */, node.pos); emitWithPrefix(" ", node.label); write(";"); } @@ -57829,14 +73248,14 @@ var ts; if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, contextNode); + pos = writeToken(token, pos, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { - emitTrailingCommentsOfPosition(pos, true); + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96, node.pos, node); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); emitExpressionWithPrefix(" ", node.expression); write(";"); } @@ -57847,11 +73266,11 @@ var ts; emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); write(" "); - writeToken(19, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end); write(" "); emit(node.caseBlock); } @@ -57879,9 +73298,12 @@ var ts; } } function emitDebuggerStatement(node) { - writeToken(78, node.pos); + writeToken(78 /* DebuggerKeyword */, node.pos); write(";"); } + // + // Declarations + // function emitVariableDeclaration(node) { emit(node.name); emitWithPrefix(": ", node.type); @@ -57889,7 +73311,7 @@ var ts; } function emitVariableDeclarationList(node) { write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); - emitList(node, node.declarations, 272); + emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); @@ -57910,30 +73332,19 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = ts.getEmitFlags(node) & 65536; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 524288) { - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + pushNameGenerationScope(node); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { - pushNameGenerationScope(); - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } - popNameGenerationScope(); + emitBlockFunctionBody(body); } + popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); } @@ -57955,7 +73366,13 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { - if (ts.getEmitFlags(body) & 1) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + if (ts.getEmitFlags(body) & 1 /* SingleLine */) { return true; } if (body.multiLine) { @@ -57964,14 +73381,14 @@ var ts; if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (shouldWriteLeadingLineTerminator(body, body.statements, 2) - || shouldWriteClosingLineTerminator(body, body.statements, 2)) { + if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) + || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { return false; } var previousStatement; for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { var statement = _b[_a]; - if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2)) { + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { return false; } previousStatement = statement; @@ -57991,22 +73408,23 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, body); } function emitBlockFunctionBodyOnSingleLine(body) { - emitBlockFunctionBodyWorker(body, true); + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); } function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { - var statementOffset = emitPrologueDirectives(body.statements, true); + // Emit all the prologue directives (like "use strict"). + var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); var pos = writer.getTextPos(); emitHelpersIndirect(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); - emitList(body, body.statements, 384); + emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { - emitList(body, body.statements, 1, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); } } function emitClassDeclaration(node) { @@ -58017,17 +73435,15 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = ts.getEmitFlags(node) & 65536; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256); - pushNameGenerationScope(); + emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); write(" {"); - emitList(node, node.members, 65); + emitList(node, node.members, 65 /* ClassMembers */); write("}"); - popNameGenerationScope(); if (indentedFlag) { decreaseIndent(); } @@ -58038,9 +73454,9 @@ var ts; write("interface "); emit(node.name); emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256); + emitList(node, node.heritageClauses, 256 /* HeritageClauses */); write(" {"); - emitList(node, node.members, 65); + emitList(node, node.members, 65 /* InterfaceMembers */); write("}"); } function emitTypeAliasDeclaration(node) { @@ -58057,20 +73473,18 @@ var ts; emitModifiers(node, node.modifiers); write("enum "); emit(node.name); - pushNameGenerationScope(); write(" {"); - emitList(node, node.members, 81); + emitList(node, node.members, 81 /* EnumMembers */); write("}"); - popNameGenerationScope(); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); - if (~node.flags & 512) { - write(node.flags & 16 ? "namespace " : "module "); + if (~node.flags & 512 /* GlobalAugmentation */) { + write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); } emit(node.name); var body = node.body; - while (body.kind === 233) { + while (body.kind === 234 /* ModuleDeclaration */) { write("."); emit(body.name); body = body.body; @@ -58079,16 +73493,16 @@ var ts; emit(body); } function emitModuleBlock(node) { - pushNameGenerationScope(); + pushNameGenerationScope(node); write("{"); - emitBlockStatements(node, isEmptyBlock(node)); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); write("}"); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos); - emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end); + writeToken(17 /* OpenBraceToken */, node.pos); + emitList(node, node.clauses, 65 /* CaseBlockClauses */); + writeToken(18 /* CloseBraceToken */, node.clauses.end); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); @@ -58099,7 +73513,7 @@ var ts; write(";"); } function emitModuleReference(node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { emitExpression(node); } else { @@ -58165,7 +73579,7 @@ var ts; } function emitNamedImportsOrExports(node) { write("{"); - emitList(node, node.elements, 432); + emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); write("}"); } function emitImportOrExportSpecifier(node) { @@ -58175,44 +73589,61 @@ var ts; } emit(node.name); } + // + // Module references + // function emitExternalModuleReference(node) { write("require("); emitExpression(node.expression); write(")"); } + // + // JSX + // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072); + emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { write("<"); emitJsxTagName(node.tagName); write(" "); + // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } write("/>"); } - function emitJsxOpeningElement(node) { + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { write("<"); - emitJsxTagName(node.tagName); - writeIfAny(node.attributes.properties, " "); - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap + if (node.attributes.properties && node.attributes.properties.length > 0) { + write(" "); + emit(node.attributes); + } } write(">"); } function emitJsxText(node) { - writer.writeLiteral(getTextOfNode(node, true)); + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } - function emitJsxClosingElement(node) { + function emitJsxClosingElementOrFragment(node) { write(""); } function emitJsxAttributes(node) { - emitList(node, node.properties, 131328); + emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); @@ -58232,13 +73663,16 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71) { + if (node.kind === 71 /* Identifier */) { emitExpression(node); } else { emit(node); } } + // + // Clauses + // function emitCaseClause(node) { write("case "); emitExpression(node.expression); @@ -58251,16 +73685,30 @@ var ts; } function emitCaseOrDefaultClauseStatements(parentNode, statements) { var emitAsSingleStatement = statements.length === 1 && - (ts.nodeIsSynthesized(parentNode) || + ( + // treat synthesized nodes as located on the same line for emit purposes + ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + // e.g: + // case 0: // Zero + // case 1: // One + // case 2: // two + // return "hi"; + // If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment. + // So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments. + // However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement) + // comment "// two" will not be emitted in emitNodeWithComments. + // Therefore, we have to do the check here to emit such comment. if (statements.length > 0) { + // We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line + // Note: we can't use parentNode.end as such position includes statements. emitTrailingCommentsOfPosition(statements.pos); } - var format = 81985; + var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { write(" "); - format &= ~(1 | 64); + format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } @@ -58268,24 +73716,34 @@ var ts; write(" "); writeTokenText(node.token); write(" "); - emitList(node, node.types, 272); + emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); write(" "); if (node.variableDeclaration) { - writeToken(19, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); write(" "); } emit(node.block); } + // + // Property assignments + // function emitPropertyAssignment(node) { emit(node.name); write(": "); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512) === 0) { + if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) { var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } @@ -58304,14 +73762,22 @@ var ts; emitExpression(node.expression); } } + // + // Enum + // function emitEnumMember(node) { emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } + // + // Top-level nodes + // function emitSourceFile(node) { writeLine(); var statements = node.statements; if (emitBodyWithDetachedComments) { + // Emit detached comment if there are no prologue directives or if the first node is synthesized. + // The synthesized node will have no leading comment so some comments may be missed. var shouldEmitDetachedComment = statements.length === 0 || !ts.isPrologueDirective(statements[0]) || ts.nodeIsSynthesized(statements[0]); @@ -58324,18 +73790,23 @@ var ts; } function emitSourceFileWorker(node) { var statements = node.statements; - pushNameGenerationScope(); + pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); - emitList(node, statements, 1, index === -1 ? statements.length : index); - popNameGenerationScope(); + emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + popNameGenerationScope(node); } + // Transformation nodes function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 272); + emitExpressionList(node, node.elements, 272 /* CommaListElements */); } + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { for (var i = 0; i < statements.length; i++) { var statement = statements[i]; @@ -58352,6 +73823,7 @@ var ts; } } else { + // return index of the first non prologue directive return i; } } @@ -58367,7 +73839,7 @@ var ts; for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; setSourceFile(sourceFile); - emitPrologueDirectives(sourceFile.statements, true, seenPrologueDirectives); + emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } } } @@ -58383,15 +73855,19 @@ var ts; else { for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { var sourceFile = _b[_a]; + // Emit only the first encountered shebang if (emitShebangIfNeeded(sourceFile)) { break; } } } } + // + // Helpers + // function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328); + emitList(node, modifiers, 131328 /* Modifiers */); write(" "); } } @@ -58414,7 +73890,7 @@ var ts; } } function emitEmbeddedStatement(parent, node) { - if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1) { + if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { write(" "); emit(node); } @@ -58426,43 +73902,43 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 24577); + emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960); + emitList(parentNode, typeArguments, 26960 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960); + emitList(parentNode, typeParameters, 26960 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360); + emitList(parentNode, parameters, 1360 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); return parameter - && parameter.pos === parentNode.pos - && !(ts.isArrowFunction(parentNode) && parentNode.type) - && !ts.some(parentNode.decorators) - && !ts.some(parentNode.modifiers) - && !ts.some(parentNode.typeParameters) - && !ts.some(parameter.decorators) - && !ts.some(parameter.modifiers) - && !parameter.dotDotDotToken - && !parameter.questionToken - && !parameter.type - && !parameter.initializer - && ts.isIdentifier(parameter.name); + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 & ~1024); + emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); } } function emitParametersForIndexSignature(parentNode, parameters) { - emitList(parentNode, parameters, 4432); + emitList(parentNode, parameters, 4432 /* IndexSignatureParameters */); } function emitList(parentNode, children, format, start, count) { emitNodeList(emit, parentNode, children, format, start, count); @@ -58474,11 +73950,11 @@ var ts; if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; - if (isUndefined && format & 8192) { + if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } var isEmpty = isUndefined || start >= children.length || count === 0; - if (isEmpty && format & 16384) { + if (isEmpty && format & 16384 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } @@ -58487,55 +73963,70 @@ var ts; } return; } - if (format & 7680) { + if (format & 7680 /* BracketsMask */) { write(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); } if (isEmpty) { - if (format & 1) { + // Write a line terminator if the parent node was multi-line + if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 && !(format & 262144)) { + else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { write(" "); } } else { - var mayEmitInterveningComments = (format & 131072) === 0; + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { writeLine(); shouldEmitInterveningComments = false; } - else if (format & 128) { + else if (format & 128 /* SpaceBetweenBraces */) { write(" "); } - if (format & 64) { + // Increase the indent, if requested. + if (format & 64 /* Indented */) { increaseIndent(); } + // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; + // Write the delimiter if this is not the first node. if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , if (delimiter && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } write(delimiter); + // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { - if ((format & (3 | 64)) === 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* LinesMask */ | 64 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } writeLine(); shouldEmitInterveningComments = false; } - else if (previousSibling && format & 256) { + else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { write(" "); } } + // Emit this child. if (shouldEmitInterveningComments) { if (emitTrailingCommentsOfPosition) { var commentRange = ts.getCommentRange(child); @@ -58552,27 +74043,36 @@ var ts; } previousSibling = child; } - var hasTrailingComma = (format & 32) && children.hasTrailingComma; - if (format & 16 && hasTrailingComma) { + // Write a trailing comma, if requested. + var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; + if (format & 16 /* CommaDelimited */ && hasTrailingComma) { write(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } - if (format & 64) { + // Decrease the indent, if requested. + if (format & 64 /* Indented */) { decreaseIndent(); } + // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); } - else if (format & 128) { + else if (format & 128 /* SpaceBetweenBraces */) { write(" "); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } - if (format & 7680) { + if (format & 7680 /* BracketsMask */) { write(getClosingBracket(format)); } } @@ -58588,11 +74088,6 @@ var ts; function decreaseIndent() { writer.decreaseIndent(); } - function writeIfAny(nodes, text) { - if (ts.some(nodes)) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -58613,7 +74108,7 @@ var ts; return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { - if (ts.getEmitFlags(node) & 1) { + if (ts.getEmitFlags(node) & 1 /* SingleLine */) { write(" "); } else { @@ -58623,8 +74118,9 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = guessIndentation(lines); - for (var i = 0; i < lines.length; i++) { - var line = indentation ? lines[i].slice(indentation) : lines[i]; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var lineText = lines_1[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); @@ -58634,8 +74130,8 @@ var ts; } function guessIndentation(lines) { var indentation; - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var line = lines_1[_a]; + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { if (indentation === undefined || i < indentation) { @@ -58656,6 +74152,10 @@ var ts; write(valueToWriteWhenNotIndenting); } } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. function decreaseIndentIf(value1, value2) { if (value1) { decreaseIndent(); @@ -58665,11 +74165,11 @@ var ts; } } function shouldWriteLeadingLineTerminator(parentNode, children, format) { - if (format & 1) { + if (format & 1 /* MultiLine */) { return true; } - if (format & 2) { - if (format & 32768) { + if (format & 2 /* PreserveLines */) { + if (format & 32768 /* PreferNewLine */) { return true; } var firstChild = children[0]; @@ -58688,10 +74188,10 @@ var ts; } } function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { - if (format & 1) { + if (format & 1 /* MultiLine */) { return true; } - else if (format & 2) { + else if (format & 2 /* PreserveLines */) { if (previousNode === undefined || nextNode === undefined) { return false; } @@ -58703,15 +74203,15 @@ var ts; } } else { - return nextNode.startsOnNewLine; + return ts.getStartsOnNewLine(nextNode); } } function shouldWriteClosingLineTerminator(parentNode, children, format) { - if (format & 1) { - return (format & 65536) === 0; + if (format & 1 /* MultiLine */) { + return (format & 65536 /* NoTrailingNewLine */) === 0; } - else if (format & 2) { - if (format & 32768) { + else if (format & 2 /* PreserveLines */) { + if (format & 32768 /* PreferNewLine */) { return true; } var lastChild = ts.lastOrUndefined(children); @@ -58731,19 +74231,20 @@ var ts; } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { - var startsOnNewLine = node.startsOnNewLine; + var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { - return (format & 32768) !== 0; + return (format & 32768 /* PreferNewLine */) !== 0; } return startsOnNewLine; } - return (format & 32768) !== 0; + return (format & 32768 /* PreferNewLine */) !== 0; } function needsIndentation(parent, node1, node2) { parent = skipSynthesizedParentheses(parent); node1 = skipSynthesizedParentheses(node1); node2 = skipSynthesizedParentheses(node2); - if (node2.startsOnNewLine) { + // Always use a newline for synthesized code if the synthesizer desires it. + if (ts.getStartsOnNewLine(node2)) { return true; } return !ts.nodeIsSynthesized(parent) @@ -58756,7 +74257,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 185 && ts.nodeIsSynthesized(node)) { + while (node.kind === 186 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -58766,9 +74267,9 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } - else if (node.kind === 9 && node.textSourceNode) { + else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); } else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { @@ -58777,10 +74278,10 @@ var ts; return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } function getLiteralTextOfNode(node) { - if (node.kind === 9 && node.textSourceNode) { + if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 ? + return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } @@ -58790,19 +74291,47 @@ var ts; } return ts.getLiteralText(node, currentSourceFile); } - function pushNameGenerationScope() { + /** + * Push a new name generation scope. + */ + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } tempFlagsStack.push(tempFlags); tempFlags = 0; } - function popNameGenerationScope() { + /** + * Pop the current name generation scope. + */ + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } tempFlags = tempFlagsStack.pop(); } + /** + * Generate the text for a generated identifier. + */ function generateName(name) { - if (name.autoGenerateKind === 4) { - var node = getNodeForGeneratedName(name); - return generateNameCached(node); + if (name.autoGenerateKind === 4 /* Node */) { + // Node names generate unique names based on their original node + // and are cached based on that node's id. + if (name.skipNameGenerationScope) { + var savedTempFlags = tempFlags; + popNameGenerationScope(/*node*/ undefined); + var result = generateNameCached(getNodeForGeneratedName(name)); + pushNameGenerationScope(/*node*/ undefined); + tempFlags = savedTempFlags; + return result; + } + else { + return generateNameCached(getNodeForGeneratedName(name)); + } } else { + // Auto, Loop, and Unique names are cached based on their unique + // autoGenerateId. var autoGenerateId = name.autoGenerateId; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } @@ -58811,45 +74340,66 @@ var ts; var nodeId = ts.getNodeId(node); return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); } + /** + * Returns a value indicating whether a name is unique globally, within the current file, + * or within the NameGenerator. + */ function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) && !generatedNames.has(name); } + /** + * Returns a value indicating whether a name is unique within a container. + */ function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); - if (local && local.flags & (107455 | 1048576 | 2097152)) { + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } } return true; } + /** + * Return the next available name in the pattern _a ... _z, _0, _1, ... + * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + */ function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_53 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_53)) { + var name = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name)) { tempFlags |= flags; - return name_53; + return name; } } while (true) { - var count = tempFlags & 268435455; + var count = tempFlags & 268435455 /* CountMask */; tempFlags++; + // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_54 = count < 26 - ? "_" + String.fromCharCode(97 + count) + var name = count < 26 + ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_54)) { - return name_54; + if (isUniqueName(name)) { + return name; } } } } + /** + * Generate a name that is unique within the current file and doesn't conflict with any names + * in global scope. The name is formed by adding an '_n' suffix to the specified base name, + * where n is a positive integer. Note that names generated by makeTempVariableName and + * makeUniqueName are guaranteed to never conflict. + */ function makeUniqueName(baseName) { - if (baseName.charCodeAt(baseName.length - 1) !== 95) { + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { baseName += "_"; } var i = 1; @@ -58862,19 +74412,32 @@ var ts; i++; } } + /** + * Generates a unique name for a ModuleDeclaration or EnumDeclaration. + */ function generateNameForModuleOrEnum(node) { var name = getTextOfNode(node.name); + // Use module/enum name itself if it is unique, otherwise make a unique variation return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } + /** + * Generates a unique name for an ImportDeclaration or ExportDeclaration. + */ function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } + /** + * Generates a unique name for a default export. + */ function generateNameForExportDefault() { return makeUniqueName("default"); } + /** + * Generates a unique name for a class expression. + */ function generateNameForClassExpression() { return makeUniqueName("class"); } @@ -58882,85 +74445,98 @@ var ts; if (ts.isIdentifier(node.name)) { return generateNameCached(node.name); } - return makeTempVariableName(0); + return makeTempVariableName(0 /* Auto */); } + /** + * Generates a unique name from a node. + */ function generateNameForNode(node) { switch (node.kind) { - case 71: + case 71 /* Identifier */: return makeUniqueName(getTextOfNode(node)); - case 233: - case 232: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 238: - case 244: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 228: - case 229: - case 243: + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + case 244 /* ExportAssignment */: return generateNameForExportDefault(); - case 199: + case 200 /* ClassExpression */: return generateNameForClassExpression(); - case 151: - case 153: - case 154: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: - return makeTempVariableName(0); + return makeTempVariableName(0 /* Auto */); } } + /** + * Generates a unique identifier for a node. + */ function makeName(name) { switch (name.autoGenerateKind) { - case 1: - return makeTempVariableName(0); - case 2: - return makeTempVariableName(268435456); - case 3: - return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */); + case 2 /* Loop */: + return makeTempVariableName(268435456 /* _i */); + case 3 /* Unique */: + return makeUniqueName(ts.idText(name)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } + /** + * Gets the node from which a name should be generated. + */ function getNodeForGeneratedName(name) { var autoGenerateId = name.autoGenerateId; var node = name; var original = node.original; while (original) { node = original; + // if "node" is a different generated name (having a different + // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 + && node.autoGenerateKind === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } original = node.original; } + // otherwise, return the original node for the source; return node; } } ts.createPrinter = createPrinter; function createDelimiterMap() { var delimiters = []; - delimiters[0] = ""; - delimiters[16] = ","; - delimiters[4] = " |"; - delimiters[8] = " &"; + delimiters[0 /* None */] = ""; + delimiters[16 /* CommaDelimited */] = ","; + delimiters[4 /* BarDelimited */] = " |"; + delimiters[8 /* AmpersandDelimited */] = " &"; return delimiters; } function getDelimiter(format) { - return delimiters[format & 28]; + return delimiters[format & 28 /* DelimitersMask */]; } function createBracketsMap() { var brackets = []; - brackets[512] = ["{", "}"]; - brackets[1024] = ["(", ")"]; - brackets[2048] = ["<", ">"]; - brackets[4096] = ["[", "]"]; + brackets[512 /* Braces */] = ["{", "}"]; + brackets[1024 /* Parenthesis */] = ["(", ")"]; + brackets[2048 /* AngleBrackets */] = ["<", ">"]; + brackets[4096 /* SquareBrackets */] = ["[", "]"]; return brackets; } function getOpeningBracket(format) { - return brackets[format & 7680][0]; + return brackets[format & 7680 /* BracketsMask */][0]; } function getClosingBracket(format) { - return brackets[format & 7680][1]; + return brackets[format & 7680 /* BracketsMask */][1]; } + // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { TempFlags[TempFlags["Auto"] = 0] = "Auto"; @@ -58970,19 +74546,23 @@ var ts; var ListFormat; (function (ListFormat) { ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + // Whitespace ListFormat[ListFormat["Indented"] = 64] = "Indented"; ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces ListFormat[ListFormat["Braces"] = 512] = "Braces"; ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; @@ -58991,11 +74571,13 @@ var ts; ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + // Other ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; @@ -59022,7 +74604,7 @@ var ts; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; @@ -59034,23 +74616,410 @@ var ts; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { - var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } - while (true) { - var fileName = ts.combinePaths(searchPath, configName); - if (fileExists(fileName)) { - return fileName; + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; + function createBuilder(options) { + var isModuleEmit; + var fileInfos = ts.createMap(); + var semanticDiagnosticsPerFile = ts.createMap(); + /** The map has key by source file's path that has been changed */ + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; + var emitHandler; + return { + updateProgram: updateProgram, + getFilesAffectedBy: getFilesAffectedBy, + emitChangedFiles: emitChangedFiles, + getSemanticDiagnostics: getSemanticDiagnostics, + clear: clear + }; + function createProgramGraph(program) { + var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; + if (isModuleEmit !== currentIsModuleEmit) { + isModuleEmit = currentIsModuleEmit; + emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; + ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { + // Add new file info + createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, + // Remove existing file info + onDeleteValue: removeExistingFileInfo, + // We will update in place instead of deleting existing value and adding new one + onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } + }); + } + function registerChangedFile(path) { + changedFilesSet.set(path, true); + // All changed files need to re-evaluate its semantic diagnostics + semanticDiagnosticsPerFile.delete(path); + } + function addNewFileInfo(program, sourceFile) { + registerChangedFile(sourceFile.path); + emitHandler.onAddSourceFile(program, sourceFile); + return { version: sourceFile.version, signature: undefined }; + } + function removeExistingFileInfo(_existingFileInfo, path) { + // Since we dont need to track removed file as changed file + // We can just remove its diagnostics + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); + emitHandler.onRemoveSourceFile(path); + } + function updateExistingFileInfo(program, existingInfo, sourceFile) { + if (existingInfo.version !== sourceFile.version) { + registerChangedFile(sourceFile.path); + existingInfo.version = sourceFile.version; + emitHandler.onUpdateSourceFile(program, sourceFile); } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + registerChangedFile(sourceFile.path); } - searchPath = parentPath; } - return undefined; + function ensureProgramGraph(program) { + if (!emitHandler) { + createProgramGraph(program); + } + } + function updateProgram(newProgram) { + if (emitHandler) { + createProgramGraph(newProgram); + } + } + function getFilesAffectedBy(program, path) { + ensureProgramGraph(program); + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); + } + function emitChangedFiles(program, writeFileCallback) { + ensureProgramGraph(program); + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + // With --out or --outFile all outputs go into single file, do it only once + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; + } + var seenFiles = ts.createMap(); + var result; + changedFilesSet.forEach(function (_true, path) { + // Get the affected Files by this program + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + // Affected files shouldnt have cached diagnostics + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + // Emit the affected file + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); + } + }); + }); + changedFilesSet.clear(); + return result || ts.emptyArray; + } + function getSemanticDiagnostics(program, cancellationToken) { + ensureProgramGraph(program); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + // We dont need to cache the diagnostics just return them from program + return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + var diagnostics; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + function clear() { + isModuleEmit = undefined; + emitHandler = undefined; + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * @return {boolean} indicates if the shape signature has changed since last update. + */ + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + info.signature = latestSignature; + } + else { + var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = options.computeHash(emitOutput.outputFiles[0].text); + info.signature = latestSignature; + } + else { + latestSignature = prevSignature; + } + } + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + // Use cached result + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getNonModuleEmitHandler() { + return { + onAddSourceFile: ts.noop, + onRemoveSourceFile: ts.noop, + onUpdateSourceFile: ts.noop, + onUpdateSourceFileWithSameVersion: ts.returnFalse, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function getFilesAffectedByUpdatedShape(program, sourceFile) { + var options = program.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (options && (options.out || options.outFile)) { + return [sourceFile]; + } + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + } + function getModuleEmitHandler() { + var references = ts.createMap(); + return { + onAddSourceFile: setReferences, + onRemoveSourceFile: onRemoveSourceFile, + onUpdateSourceFile: updateReferences, + onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function setReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + } + function updateReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + else { + references.delete(sourceFile.path); + } + } + function updateReferencesTrackingChangedReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (!newReferences) { + // Changed if we had references + return references.delete(sourceFile.path); + } + var oldReferences = references.get(sourceFile.path); + references.set(sourceFile.path, newReferences); + if (!oldReferences || oldReferences.size !== newReferences.size) { + return true; + } + // If there are any new references that werent present previously there is change + return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || + // Otherwise its changed if there are more references previously than now + !!oldReferences.size; + } + function onRemoveSourceFile(removedFilePath) { + // Remove existing references + references.forEach(function (referencesInFile, filePath) { + if (referencesInFile.has(removedFilePath)) { + // add files referencing the removedFilePath, as changed files too + var referencedByInfo = fileInfos.get(filePath); + if (referencedByInfo) { + registerChangedFile(filePath); + } + } + }); + // Delete the entry for the removed file path + references.delete(removedFilePath); + } + function getReferencedByPaths(referencedFilePath) { + return ts.mapDefinedIter(references.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + }); + } + function getFilesAffectedByUpdatedShape(program, sourceFile) { + if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFile]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + var path = sourceFile.path; + seenFileNamesMap.set(path, sourceFile); + var queue = getReferencedByPaths(path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = program.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { + queue.push.apply(queue, getReferencedByPaths(currentPath)); + } + } + } + // Return array of values that needs emit + return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); + } + } + } + ts.createBuilder = createBuilder; +})(ts || (ts = {})); +/// +/// +/// +/// +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); } ts.findConfigFile = findConfigFile; function resolveTripleslashReference(moduleName, containingFile) { @@ -59059,12 +75028,15 @@ var ts; return ts.normalizePath(referencedFileName); } ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { var commonPathComponents; var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); - sourcePathComponents.pop(); + sourcePathComponents.pop(); // The base file name is not part of the common directory path if (!commonPathComponents) { + // first file commonPathComponents = sourcePathComponents; return; } @@ -59072,16 +75044,20 @@ var ts; for (var i = 0; i < n; i++) { if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { + // Failed to find any common path component return true; } + // New common path found that is 0 -> i-1 commonPathComponents.length = i; break; } } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents if (sourcePathComponents.length < commonPathComponents.length) { commonPathComponents.length = sourcePathComponents.length; } }); + // A common path can not be found when paths span multiple drives on windows, for example if (failed) { return ""; } @@ -59094,6 +75070,8 @@ var ts; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { @@ -59138,6 +75116,7 @@ var ts; var mtimeBefore = ts.sys.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification if (fingerprint && fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -59208,18 +75187,23 @@ var ts; var output = ""; for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { var diagnostic = diagnostics_1[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + output += formatDiagnostic(diagnostic, host); } return output; } ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; @@ -59247,6 +75231,7 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; + var context = ""; if (diagnostic.file) { var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; @@ -59258,34 +75243,40 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += host.getNewLine(); + context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); - lineContent = lineContent.replace("\t", " "); - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + host.getNewLine(); - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += redForegroundEscapeSequence; if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { - output += lineContent.replace(/./g, "~"); + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); } - output += resetEscapeSequence; - output += host.getNewLine(); + context += resetEscapeSequence; } output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; @@ -59293,13 +75284,17 @@ var ts; var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += context; + } output += host.getNewLine(); } return output; } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { - if (typeof messageText === "string") { + if (ts.isString(messageText)) { return messageText; } else { @@ -59328,18 +75323,86 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_55 = names_1[_i]; + var name = names_1[_i]; var result = void 0; - if (cache.has(name_55)) { - result = cache.get(name_55); + if (cache.has(name)) { + result = cache.get(name); } else { - cache.set(name_55, result = loader(name_55, containingFile)); + cache.set(name, result = loader(name, containingFile)); } resolutions.push(result); } return resolutions; } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + // If we haven't create a program yet or has changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + /** + * Determined if source file needs to be re-created even if its text hasnt changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + // If any of these options change, we cant reuse old source file even if version match + // The change in options like these could result in change in syntax tree change + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param rootNames - A set of root files. + * @param options - The compiler options which should be used. + * @param host - The host interacts with the underlying file system. + * @param oldProgram - Reuses an old program structure. + * @returns A 'Program' object. + */ function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -59352,9 +75415,19 @@ var ts; var cachedDeclarationDiagnosticsForFile = {}; var resolvedTypeReferenceDirectives = ts.createMap(); var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); @@ -59364,12 +75437,15 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -59391,16 +75467,27 @@ var ts; var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } + // Map from a stringified PackageId to the source file with that id. + // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). + // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around. var packageIdToSourceFile = ts.createMap(); + // Maps from a SourceFile's `.path` to the name of the package it was imported with. var sourceFileToPackageName = ts.createMap(); + // See `sourceFileIsRedirectedTo`. var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); - if (structuralIsReused !== 2) { - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + if (structuralIsReused !== 2 /* Completely */) { + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); 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 resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); @@ -59408,19 +75495,39 @@ var ts; processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. if (!skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file if (!options.lib) { - processRootFile(getDefaultLibraryFileName(), true); + processRootFile(getDefaultLibraryFileName(), /*isDefaultLib*/ true); } else { ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), true); + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true); }); } } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); } - var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + ts.Debug.assert(!!missingFilePaths); + // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks moduleResolutionCache = undefined; + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; program = { getRootFileNames: function () { return rootNames; }, @@ -59451,7 +75558,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -59464,12 +75571,16 @@ var ts; if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path commonSourceDirectory += ts.directorySeparator; } } @@ -59477,44 +75588,77 @@ var ts; } function getClassifiableNames() { if (!classifiableNames) { + // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var sourceFile = files_2[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var sourceFile = files_1[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (structuralIsReused === 0 && !file.ambientModuleNames.length) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile); } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occured during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_3 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_3.push(resolvedModule); } - return result_4; + return result_3; } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - if (file === oldSourceFile) { + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); if (oldResolvedModule) { if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); } (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); continue; } } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) var resolvesToAmbientModuleInNonModifiedFile = false; if (ts.contains(file.ambientModuleNames, moduleName)) { resolvesToAmbientModuleInNonModifiedFile = true; @@ -59529,19 +75673,24 @@ var ts; (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) : ts.emptyArray; + // Combine results of resolutions and predicted results if (!result) { + // There were no unresolved/ambient resolutions. ts.Debug.assert(resolutions.length === moduleNames.length); return resolutions; } var j = 0; for (var i = 0; i < result.length; i++) { if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { result[i] = undefined; } @@ -59553,15 +75702,19 @@ var ts; } ts.Debug.assert(j === resolutions.length); return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); if (resolutionToFile) { + // module used to be resolved to file - ignore it return false; } var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); if (!(ambientModule && ambientModule.declarations)) { return false; } + // at least one of declarations should come from non-modified source file var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { var f = ts.getSourceFileOfNode(d); return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; @@ -59577,24 +75730,34 @@ var ts; } function tryReuseStructureFromOldProgram() { if (!oldProgram) { - return 0; + return 0 /* Not */; } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused var oldOptions = oldProgram.getCompilerOptions(); if (ts.changesAffectModuleResolution(oldOptions, options)) { - return oldProgram.structureIsReused = 0; + return oldProgram.structureIsReused = 0 /* Not */; } - ts.Debug.assert(!(oldProgram.structureIsReused & (2 | 1))); + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure var oldRootNames = oldProgram.getRootFileNames(); if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return oldProgram.structureIsReused = 0; + return oldProgram.structureIsReused = 0 /* Not */; } if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return oldProgram.structureIsReused = 0; + return oldProgram.structureIsReused = 0 /* Not */; } + // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; var filePaths = []; var modifiedSourceFiles = []; - oldProgram.structureIsReused = 2; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } var oldSourceFiles = oldProgram.getSourceFiles(); var SeenPackageName; (function (SeenPackageName) { @@ -59602,26 +75765,30 @@ var ts; SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; })(SeenPackageName || (SeenPackageName = {})); var seenPackageNames = ts.createMap(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) - : host.getSourceFile(oldSourceFile.fileName, options.target); + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); if (!newSourceFile) { - return oldProgram.structureIsReused = 0; + return oldProgram.structureIsReused = 0 /* Not */; } ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { + // We got `newSourceFile` by path, so it is actually for the unredirected file. + // This lets us know if the unredirected file has changed. If it has we should break the redirect. if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { - return oldProgram.structureIsReused = 0; + // Underlying file has changed. Might not redirect anymore. Must rebuild program. + return oldProgram.structureIsReused = 0 /* Not */; } fileChanged = false; - newSourceFile = oldSourceFile; + newSourceFile = oldSourceFile; // Use the redirect. } else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + // If a redirected-to source file changes, the redirect may be broken. if (newSourceFile !== oldSourceFile) { - return oldProgram.structureIsReused = 0; + return oldProgram.structureIsReused = 0 /* Not */; } fileChanged = false; } @@ -59632,41 +75799,62 @@ var ts; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { + // If there are 2 different source files for the same package name and at least one of them changes, + // they might become redirects. So we must rebuild the program. var prevKind = seenPackageNames.get(packageName); - var newKind = fileChanged ? 1 : 0; - if ((prevKind !== undefined && newKind === 1) || prevKind === 1) { - return oldProgram.structureIsReused = 0; + var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) { + return oldProgram.structureIsReused = 0 /* Not */; } seenPackageNames.set(packageName, newKind); } if (fileChanged) { + // The `newSourceFile` object was created for the new program. if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { - oldProgram.structureIsReused = 1; + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; } + // check tripleslash references if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - oldProgram.structureIsReused = 1; + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; } + // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - oldProgram.structureIsReused = 1; + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - oldProgram.structureIsReused = 1; + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; } - if ((oldSourceFile.flags & 524288) !== (newSourceFile.flags & 524288)) { - oldProgram.structureIsReused = 1; + if ((oldSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */) !== (newSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - oldProgram.structureIsReused = 1; + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } + // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } - if (oldProgram.structureIsReused !== 2) { + if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); @@ -59674,9 +75862,10 @@ var ts; var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { - oldProgram.structureIsReused = 1; + oldProgram.structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); } else { @@ -59686,9 +75875,10 @@ var ts; if (resolveTypeReferenceDirectiveNamesWorker) { var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { - oldProgram.structureIsReused = 1; + oldProgram.structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); } else { @@ -59696,29 +75886,31 @@ var ts; } } } - if (oldProgram.structureIsReused !== 2) { + if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { - return oldProgram.structureIsReused = 1; - } - for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { - var p = _d[_c]; - filesByName.set(p, undefined); + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { - var modifiedFile = modifiedSourceFiles_2[_e]; + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsSet = oldProgram.redirectTargetsSet; - return oldProgram.structureIsReused = 2; + return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return { @@ -59742,19 +75934,27 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; } function getDiagnosticsProducingTypeChecker() { - return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } function dropDiagnosticsProducingTypeChecker() { diagnosticsProducingTypeChecker = undefined; } function getTypeChecker() { - return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); @@ -59767,10 +75967,13 @@ var ts; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { return { @@ -59781,6 +75984,14 @@ var ts; }; } } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); @@ -59814,6 +76025,7 @@ var ts; } function getDeclarationDiagnostics(sourceFile, cancellationToken) { var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) if (!sourceFile || options.out || options.outFile) { return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } @@ -59822,12 +76034,11 @@ var ts; } } function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - if (ts.isCheckJsEnabledForFile(sourceFile, options)) { - sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); - } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -59839,6 +76050,15 @@ var ts; } catch (e) { if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. noDiagnosticsTypeChecker = undefined; diagnosticsProducingTypeChecker = undefined; } @@ -59850,20 +76070,32 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); + if (isCheckJs) { + diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + } return ts.filter(diagnostics, shouldReportDiagnostic); }); } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ function shouldReportDiagnostic(diagnostic) { var file = diagnostic.file, start = diagnostic.start; if (file) { @@ -59873,9 +76105,11 @@ var ts; var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); if (!result) { + // non-empty line return true; } if (result[3]) { + // @ts-ignore return false; } line--; @@ -59890,64 +76124,68 @@ var ts; walk(sourceFile); return diagnostics; function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child switch (parent.kind) { - case 146: - case 149: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } - case 151: - case 150: - case 152: - case 153: - case 154: - case 186: - case 228: - case 187: - case 226: + // falls through + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 227 /* VariableDeclaration */: + // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); return; } } switch (node.kind) { - case 237: + case 238 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 243: + case 244 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 259: + case 263 /* HeritageClause */: var heritageClause = node; - if (heritageClause.token === 108) { + if (heritageClause.token === 108 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 230: + case 231 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 233: + case 234 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 231: + case 232 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 232: + case 233 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 203: + case 204 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 202: + case 203 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 184: - ts.Debug.fail(); + case 185 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; parent = node; @@ -59959,44 +76197,50 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } switch (parent.kind) { - case 229: - case 151: - case 150: - case 152: - case 153: - case 154: - case 186: - case 228: - case 187: + case 230 /* ClassDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } - case 208: + // falls through + case 209 /* VariableStatement */: + // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 208); + return checkModifiers(nodes, parent.kind === 209 /* VariableStatement */); } break; - case 149: + case 150 /* PropertyDeclaration */: + // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 115) { + if (modifier.kind !== 115 /* StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); } } return; } break; - case 146: + case 147 /* Parameter */: + // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 181: - case 182: - case 201: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 202 /* ExpressionWithTypeArguments */: + // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return; @@ -60012,21 +76256,24 @@ var ts; for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { var modifier = modifiers_1[_i]; switch (modifier.kind) { - case 76: + case 76 /* ConstKeyword */: if (isConstValid) { continue; } - case 114: - case 112: - case 113: - case 131: - case 124: - case 117: + // to report error, + // falls through + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 124 /* DeclareKeyword */: + case 117 /* AbstractKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); break; - case 115: - case 84: - case 79: + // These are all legal modifiers. + case 115 /* StaticKeyword */: + case 84 /* ExportKeyword */: + case 79 /* DefaultKeyword */: } } } @@ -60034,6 +76281,8 @@ var ts; var start = nodes.pos; return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node function createDiagnosticForNode(node, message, arg0, arg1, arg2) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); } @@ -60045,6 +76294,7 @@ var ts; function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); }); } @@ -60077,15 +76327,15 @@ var ts; return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, undefined); + processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*packageId*/ undefined); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.kind === 9 - ? b.kind === 9 && a.text === b.text - : b.kind === 71 && a.escapedText === b.escapedText; + return a.kind === 9 /* StringLiteral */ + ? b.kind === 9 /* StringLiteral */ && a.text === b.text + : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -60093,22 +76343,26 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import var imports; var moduleAugmentations; var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. if (options.importHelpers && (options.isolatedModules || isExternalModuleFile) && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; } for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collectModuleReferences(node, false); - if ((file.flags & 524288) || isJavaScriptFile) { + collectModuleReferences(node, /*inAmbientModule*/ false); + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { collectDynamicImportOrRequireCalls(node); } } @@ -60118,9 +76372,9 @@ var ts; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 238: - case 237: - case 244: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; @@ -60128,26 +76382,40 @@ var ts; if (!moduleNameExpr.text) { break; } + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { (imports || (imports = [])).push(moduleNameExpr); } break; - case 233: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { + case 234 /* ModuleDeclaration */: + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module (ambientModules || (ambientModules = [])).push(nameText); } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists var body = node.body; if (body) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var statement = _a[_i]; - collectModuleReferences(statement, true); + collectModuleReferences(statement, /*inAmbientModule*/ true); } } } @@ -60155,10 +76423,10 @@ var ts; } } function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, true)) { + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { (imports || (imports = [])).push(node.arguments[0]); } - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9) { + else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { (imports || (imports = [])).push(node.arguments[0]); } else { @@ -60166,6 +76434,7 @@ var ts; } } } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile, ref) { return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); } @@ -60182,7 +76451,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } return sourceFile; @@ -60197,10 +76466,11 @@ var ts; } var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); if (fail && !sourceFileWithAddedExtension) - fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); return sourceFileWithAddedExtension; } } + /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { var args = []; @@ -60236,12 +76506,17 @@ var ts; }); return redirect; } + // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { sourceFilesFoundSearchingNodeModules.set(file_1.path, false); if (!options.noResolve) { @@ -60259,6 +76534,7 @@ var ts; } return file_1; } + // We haven't looked for this file, do so now and cache result var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); @@ -60266,11 +76542,13 @@ var ts; else { fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } - }); + }, shouldCreateNewSourceFile); if (packageId) { var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { + // Some other SourceFile already exists with this package name and version. + // Instead of creating a duplicate, just redirect to the existing one. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); redirectTargetsSet.set(fileFromPackageId.path, true); filesByName.set(path, dupFile); @@ -60279,6 +76557,7 @@ var ts; return dupFile; } else if (file) { + // This is the first source file to have this packageId. packageIdToSourceFile.set(packageIdKey, file); sourceFileToPackageName.set(path, packageId.name); } @@ -60289,6 +76568,7 @@ var ts; file.path = path; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case var existingFile = filesByNameIgnoreCase.get(pathLowerCase); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); @@ -60302,6 +76582,7 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } + // always process imported modules to record module name resolutions processImportedModules(file); if (isDefaultLib) { files.unshift(file); @@ -60315,21 +76596,24 @@ var ts; function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, undefined, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, /*packageId*/ undefined, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file var fileName = ref.fileName.toLocaleLowerCase(); ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); if (previousResolution && previousResolution.primary) { return; @@ -60337,20 +76621,26 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error if (previousResolution) { + // Don't bother reading the file again if it's the same file. if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } } + // don't overwrite previous resolution result saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } } @@ -60379,6 +76669,7 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); @@ -60396,7 +76687,14 @@ var ts; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve @@ -60409,7 +76707,7 @@ var ts; else if (shouldAddFile) { var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); - findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end, resolution.packageId); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -60417,6 +76715,7 @@ var ts; } } else { + // no imports - drop cached module resolutions file.resolvedModules = undefined; } } @@ -60479,12 +76778,12 @@ var ts; continue; } if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - createDiagnosticForOptionPaths(true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (ts.isArray(options.paths[key])) { var len = options.paths[key].length; if (len === 0) { - createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } for (var i = 0; i < len; i++) { var subst = options.paths[key][i]; @@ -60500,7 +76799,7 @@ var ts; } } else { - createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } @@ -60516,6 +76815,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } if (options.mapRoot && !options.sourceMap) { + // Error to specify --mapRoot without --sourcemap createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); } if (options.declarationDir) { @@ -60529,14 +76829,14 @@ var ts; if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } - if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } - var languageVersion = options.target || 0; + var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (options.isolatedModules) { - if (options.module === ts.ModuleKind.None && languageVersion < 2) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); @@ -60545,10 +76845,12 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } + // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); @@ -60558,10 +76860,14 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } - if (options.outDir || - options.sourceRoot || + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { + // Precalculate and cache the common source directory var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } @@ -60587,6 +76893,7 @@ var ts; else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createMap(); @@ -60595,19 +76902,24 @@ var ts; verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); } + // Verify that all the emit files are unique and don't overwrite input files function verifyEmitFilePath(emitFileName, emitFilesSeen) { if (emitFileName) { var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file if (filesByName.has(emitFilePath)) { var chain_1; if (!options.configFilePath) { - chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + // The program is from either an inferred project or an external project + chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { @@ -60642,7 +76954,7 @@ var ts; for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { var pathProp = pathsSyntax_2[_i]; if (ts.isObjectLiteralExpression(pathProp.initializer) && - createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, undefined, message, arg0)) { + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { needCompilerDiagnostic = false; } } @@ -60658,10 +76970,10 @@ var ts; return ts.emptyArray; } function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(true, option1, option2, message, option1, option2); + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); } function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(false, option1, undefined, message, arg0); + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -60673,7 +76985,7 @@ var ts; } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { - _compilerOptionsObjectLiteralSyntax = null; + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword if (options.configFile && options.configFile.jsonObject) { for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { var prop = _a[_i]; @@ -60700,24 +77012,31 @@ var ts; } } ts.createProgram = createProgram; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { - case ".ts": - case ".d.ts": + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. return undefined; - case ".tsx": + case ".tsx" /* Tsx */: return needJsx(); - case ".jsx": + case ".jsx" /* Jsx */: return needJsx() || needAllowJs(); - case ".js": + case ".js" /* Js */: return needAllowJs(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -60730,9 +77049,10 @@ var ts; var res = imports.map(function (i) { return i.text; }); for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9) { + if (aug.kind === 9 /* StringLiteral */) { res.push(aug.text); } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. } return res; } @@ -60741,7 +77061,7 @@ var ts; (function (ts) { var ScriptSnapshot; (function (ScriptSnapshot) { - var StringScriptSnapshot = (function () { + var StringScriptSnapshot = /** @class */ (function () { function StringScriptSnapshot(text) { this.text = text; } @@ -60754,6 +77074,8 @@ var ts; return this.text.length; }; StringScriptSnapshot.prototype.getChangeRange = function () { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. return undefined; }; return StringScriptSnapshot; @@ -60763,7 +77085,7 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - var TextChange = (function () { + var TextChange = /** @class */ (function () { function TextChange() { } return TextChange; @@ -60839,27 +77161,56 @@ var ts; (function (ScriptElementKind) { ScriptElementKind["unknown"] = ""; ScriptElementKind["warning"] = "warning"; + /** predefined type (void) or keyword (class) */ ScriptElementKind["keyword"] = "keyword"; + /** top level script node */ ScriptElementKind["scriptElement"] = "script"; + /** module foo {} */ ScriptElementKind["moduleElement"] = "module"; + /** class X {} */ ScriptElementKind["classElement"] = "class"; + /** var x = class X {} */ ScriptElementKind["localClassElement"] = "local class"; + /** interface Y {} */ ScriptElementKind["interfaceElement"] = "interface"; + /** type T = ... */ ScriptElementKind["typeElement"] = "type"; + /** enum E */ ScriptElementKind["enumElement"] = "enum"; ScriptElementKind["enumMemberElement"] = "enum member"; + /** + * Inside module and script only + * const v = .. + */ ScriptElementKind["variableElement"] = "var"; + /** Inside function */ ScriptElementKind["localVariableElement"] = "local var"; + /** + * Inside module and script only + * function f() { } + */ ScriptElementKind["functionElement"] = "function"; + /** Inside function */ ScriptElementKind["localFunctionElement"] = "local function"; + /** class X { [public|private]* foo() {} } */ ScriptElementKind["memberFunctionElement"] = "method"; + /** class X { [public|private]* [get|set] foo:number; } */ ScriptElementKind["memberGetAccessorElement"] = "getter"; ScriptElementKind["memberSetAccessorElement"] = "setter"; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ ScriptElementKind["memberVariableElement"] = "property"; + /** class X { constructor() { } } */ ScriptElementKind["constructorImplementationElement"] = "constructor"; + /** interface Y { ():number; } */ ScriptElementKind["callSignatureElement"] = "call"; + /** interface Y { []:number; } */ ScriptElementKind["indexSignatureElement"] = "index"; + /** interface Y { new():Y; } */ ScriptElementKind["constructSignatureElement"] = "construct"; + /** function foo(*Y*: string) */ ScriptElementKind["parameterElement"] = "parameter"; ScriptElementKind["typeParameterElement"] = "type parameter"; ScriptElementKind["primitiveType"] = "primitive type"; @@ -60869,6 +77220,9 @@ var ts; ScriptElementKind["letElement"] = "let"; ScriptElementKind["directory"] = "directory"; ScriptElementKind["externalModuleName"] = "external module name"; + /** + * + */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; @@ -60936,9 +77290,11 @@ var ts; ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {})); })(ts || (ts = {})); +// These utilities are common to multiple language service features. +/* @internal */ var ts; (function (ts) { - ts.scanner = ts.createScanner(5, true); + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -60949,64 +77305,66 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 146: - case 226: - case 176: - case 149: - case 148: - case 261: - case 262: - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: - case 187: - case 260: - case 253: - return 1; - case 145: - case 230: - case 231: - case 163: - return 2; - case 283: - return node.name === undefined ? 1 | 2 : 2; - case 264: - case 229: - return 1 | 2; - case 233: + case 147 /* Parameter */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 264 /* CatchClause */: + case 257 /* JsxAttribute */: + return 1 /* Value */; + case 146 /* TypeParameter */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 164 /* TypeLiteral */: + return 2 /* Type */; + case 288 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; + case 268 /* EnumMember */: + case 230 /* ClassDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 234 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { - return 4 | 1; + return 4 /* Namespace */ | 1 /* Value */; } - else if (ts.getModuleInstanceState(node) === 1) { - return 4 | 1; + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; } else { - return 4; - } - case 232: - case 241: - case 242: - case 237: - case 238: - case 243: - case 244: - return 7; - case 265: - return 4 | 1; - } - return 7; + return 4 /* Namespace */; + } + case 233 /* EnumDeclaration */: + case 242 /* NamedImports */: + case 243 /* ImportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 239 /* ImportDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: + return 7 /* All */; + // An external module can be a Value + case 269 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 265) { - return 1; + if (node.kind === 269 /* SourceFile */) { + return 1 /* Value */; } - else if (node.parent.kind === 243) { - return 7; + else if (node.parent.kind === 244 /* ExportAssignment */) { + return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); @@ -61015,31 +77373,34 @@ var ts; return getMeaningFromDeclaration(node.parent); } else if (isTypeReference(node)) { - return 2; + return 2 /* Type */; } else if (isNamespaceReference(node)) { - return 4; + return 4 /* Namespace */; } else if (ts.isTypeParameterDeclaration(node.parent)) { - ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); - return 2; + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; } else { - return 1; + return 1 /* Value */; } } ts.getMeaningFromLocation = getMeaningFromLocation; function getMeaningFromRightHandSideOfImportEquals(node) { - ts.Debug.assert(node.kind === 71); - if (node.parent.kind === 143 && + ts.Debug.assert(node.kind === 71 /* Identifier */); + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 237) { - return 1 | 2 | 4; + node.parent.parent.kind === 238 /* ImportEqualsDeclaration */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } - return 4; + return 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 143) { + while (node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -61051,27 +77412,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 143) { - while (root.parent && root.parent.kind === 143) { + if (root.parent.kind === 144 /* QualifiedName */) { + while (root.parent && root.parent.kind === 144 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 159 && !isLastClause; + return root.parent.kind === 160 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 179) { - while (root.parent && root.parent.kind === 179) { + if (root.parent.kind === 180 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 180 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 201 && root.parent.parent.kind === 259) { + if (!isLastClause && root.parent.kind === 202 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 263 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 229 && root.parent.parent.token === 108) || - (decl.kind === 230 && root.parent.parent.token === 85); + return (decl.kind === 230 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || + (decl.kind === 231 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); } return false; } @@ -61080,25 +77441,25 @@ var ts; node = node.parent; } switch (node.kind) { - case 99: - return !ts.isPartOfExpression(node); - case 169: + case 99 /* ThisKeyword */: + return !ts.isExpressionNode(node); + case 170 /* ThisType */: return true; } switch (node.parent.kind) { - case 159: + case 160 /* TypeReference */: return true; - case 201: + case 202 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 181); + return isCallOrNewExpressionTarget(node, 182 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 182); + return isCallOrNewExpressionTarget(node, 183 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -61111,7 +77472,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 223 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -61120,14 +77481,14 @@ var ts; } ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { - return node.kind === 71 && - (node.parent.kind === 218 || node.parent.kind === 217) && + return node.kind === 71 /* Identifier */ && + (node.parent.kind === 219 /* BreakStatement */ || node.parent.kind === 218 /* ContinueStatement */) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { - return node.kind === 71 && - node.parent.kind === 222 && + return node.kind === 71 /* Identifier */ && + node.parent.kind === 223 /* LabeledStatement */ && node.parent.label === node; } function isLabelName(node) { @@ -61135,40 +77496,40 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 143 && node.parent.right === node; + return node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 179 && node.parent.name === node; + return node && node.parent && node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 233 && node.parent.name === node; + return node.parent.kind === 234 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { - return node.kind === 71 && + return node.kind === 71 /* Identifier */ && ts.isFunctionLike(node.parent) && node.parent.name === node; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 149: - case 148: - case 261: - case 264: - case 151: - case 150: - case 153: - case 154: - case 233: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 268 /* EnumMember */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 234 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 180: + case 181 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 144: + case 145 /* ComputedPropertyName */: return true; - case 173: - return node.parent.parent.kind === 171; + case 174 /* LiteralType */: + return node.parent.parent.kind === 172 /* IndexedAccessType */; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -61178,7 +77539,10 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 283) { + if (node.kind === 288 /* JSDocTypedefTag */) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. node = node.parent.parent; } while (true) { @@ -61187,17 +77551,17 @@ var ts; return undefined; } switch (node.kind) { - case 265: - case 151: - case 150: - case 228: - case 186: - case 153: - case 154: - case 229: - case 230: - case 232: - case 233: + case 269 /* SourceFile */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return node; } } @@ -61205,91 +77569,95 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 265: - return ts.isExternalModule(node) ? "module" : "script"; - case 233: - return "module"; - case 229: - case 199: - return "class"; - case 230: return "interface"; - case 231: return "type"; - case 232: return "enum"; - case 226: + case 269 /* SourceFile */: + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; + case 234 /* ModuleDeclaration */: + return "module" /* moduleElement */; + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + return "class" /* classElement */; + case 231 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 232 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 233 /* EnumDeclaration */: return "enum" /* enumElement */; + case 227 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 176: + case 177 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 187: - case 228: - case 186: - return "function"; - case 153: return "getter"; - case 154: return "setter"; - case 151: - case 150: - return "method"; - case 149: - case 148: - return "property"; - case 157: return "index"; - case 156: return "construct"; - case 155: return "call"; - case 152: return "constructor"; - case 145: return "type parameter"; - case 264: return "enum member"; - case 146: return ts.hasModifier(node, 92) ? "property" : "parameter"; - case 237: - case 242: - case 239: - case 246: - case 240: - return "alias"; - case 283: - return "type"; - case 194: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + return "function" /* functionElement */; + case 154 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 155 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 158 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 157 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 156 /* CallSignature */: return "call" /* callSignatureElement */; + case 153 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 146 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 268 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 147 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 238 /* ImportEqualsDeclaration */: + case 243 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 247 /* ExportSpecifier */: + case 241 /* NamespaceImport */: + return "alias" /* alias */; + case 288 /* JSDocTypedefTag */: + return "type" /* typeElement */; + case 195 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { - case 0: - return ""; - case 1: - case 2: + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: var rightKind = getNodeKind(right); - return rightKind === "" ? "const" : rightKind; - case 3: - return "method"; - case 4: - return "property"; - case 5: - return ts.isFunctionExpression(right) ? "method" : "property"; + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; default: { ts.assertTypeIsNever(kind); - return ""; + return "" /* unknown */; } } default: - return ""; + return "" /* unknown */; } function getKindOfVariableDeclaration(v) { return ts.isConst(v) - ? "const" + ? "const" /* constElement */ : ts.isLet(v) - ? "let" - : "var"; + ? "let" /* letElement */ + : "var" /* variableElement */; } } ts.getNodeKind = getNodeKind; function isThis(node) { switch (node.kind) { - case 99: + case 99 /* ThisKeyword */: + // case SyntaxKind.ThisType: TODO: GH#9267 return true; - case 71: - return ts.identifierIsThisKeyword(node) && node.parent.kind === 146; + case 71 /* Identifier */: + // 'this' as a parameter + return ts.identifierIsThisKeyword(node) && node.parent.kind === 147 /* Parameter */; default: return false; } } ts.isThis = isThis; + // Matches the beginning of a triple slash directive var tripleSlashDirectivePrefixRegex = /^\/\/\/\s* position || !isCompletedNode(candidate, sourceFile); + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { @@ -61328,121 +77700,130 @@ var ts; return false; } switch (n.kind) { - case 229: - case 230: - case 232: - case 178: - case 174: - case 163: - case 207: - case 234: - case 235: - case 241: - case 245: - return nodeEndsWith(n, 18, sourceFile); - case 260: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 179 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 164 /* TypeLiteral */: + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 236 /* CaseBlock */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: + return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); + case 264 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 182: + case 183 /* NewExpression */: if (!n.arguments) { return true; } - case 181: - case 185: - case 168: - return nodeEndsWith(n, 20, sourceFile); - case 160: - case 161: + // falls through + case 182 /* CallExpression */: + case 186 /* ParenthesizedExpression */: + case 169 /* ParenthesizedType */: + return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 152: - case 153: - case 154: - case 228: - case 186: - case 151: - case 150: - case 156: - case 155: - case 187: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 188 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 20, sourceFile); - case 233: + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); + case 234 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 211: + case 212 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 210: + case 211 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25); - case 177: - case 175: - case 180: - case 144: - case 165: - return nodeEndsWith(n, 22, sourceFile); - case 157: + hasChildOfKind(n, 25 /* SemicolonToken */); + case 178 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 181 /* ElementAccessExpression */: + case 145 /* ComputedPropertyName */: + case 166 /* TupleType */: + return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); + case 158 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } - return hasChildOfKind(n, 22, sourceFile); - case 257: - case 258: + return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 214: - case 215: - case 216: - case 213: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 212: - var hasWhileKeyword = findChildOfKind(n, 106, sourceFile); + case 213 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + var hasWhileKeyword = findChildOfKind(n, 106 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { - return nodeEndsWith(n, 20, sourceFile); + return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 162: + case 163 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 189: - case 188: - case 190: - case 197: - case 198: + case 190 /* TypeOfExpression */: + case 189 /* DeleteExpression */: + case 191 /* VoidExpression */: + case 198 /* YieldExpression */: + case 199 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 183: + case 184 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 196: + case 197 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 205: + case 206 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 244: - case 238: + case 245 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 192: + case 193 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 194: + case 195 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 195: + case 196 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; } } ts.isCompletedNode = isCompletedNode; + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { + var last_2 = ts.lastOrUndefined(children); + if (last_2.kind === expectedLastToken) { return true; } - else if (last.kind === 25 && children.length !== 1) { + else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -61450,6 +77831,10 @@ var ts; } function findListItemInfo(node) { var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. if (!list) { return undefined; } @@ -61470,37 +77855,57 @@ var ts; } ts.findChildOfKind = findChildOfKind; function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { + // find syntax list that covers the span of the node if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) { return c; } }); + // Either we didn't find an appropriate list, or the list must contain us. ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); return syntaxList; } ts.findContainingList = findContainingList; + /* Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is keyword or identifier)) + */ function getTouchingWord(sourceFile, position, includeJsDocComment) { return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; + /* Gets the token whose text has range [start, end) and position >= start + * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) + */ function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, false, includePrecedingTokenAtEndPosition, false, includeJsDocComment); + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeEndPosition, includeJsDocComment); + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { + // exit early return current; } + // find the child that contains 'position' for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; if (!includeJsDocComment && ts.isJSDocNode(child)) { @@ -61508,10 +77913,11 @@ var ts; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); if (start > position) { + // If this child begins after position, then all subsequent children will as well. break; } var end = child.getEnd(); - if (position < end || (position === end && (child.kind === 1 || includeEndPosition))) { + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { current = child; continue outer; } @@ -61525,8 +77931,18 @@ var ts; return current; } } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position, false); + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -61537,12 +77953,16 @@ var ts; return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it return n; } var children = n.getChildren(); - for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { - var child = children_2[_i]; - var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || + for (var _i = 0, children_3 = children; _i < children_3.length; _i++) { + var child = children_3[_i]; + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child (child.pos === previousToken.end); if (shouldDiveInChildNode && nodeHasTokens(child)) { return find(child); @@ -61552,6 +77972,10 @@ var ts; } } ts.findNextToken = findNextToken; + /** + * Finds the rightmost token satisfying `token.end <= position`, + * excluding `JsxText` tokens containing only whitespace. + */ function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { var result = find(startNode || sourceFile); ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); @@ -61561,7 +77985,7 @@ var ts; return n; } var children = n.getChildren(); - var candidate = findRightmostChildNodeWithTokens(children, children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); return candidate && findRightmostToken(candidate); } function find(n) { @@ -61571,26 +77995,40 @@ var ts; var children = n.getChildren(); for (var i = 0; i < children.length; i++) { var child = children[i]; + // Note that the span of a node's tokens is [node.getStart(...), node.end). + // Given that `position < child.end` and child has constituent tokens, we distinguish these cases: + // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`): + // we need to find the last token in a previous child. + // 2) `position` is within the same span: we recurse on `child`. if (position < child.end) { var start = child.getStart(sourceFile, includeJsDoc); - var lookInPreviousChild = (start >= position) || + var lookInPreviousChild = (start >= position) || // cursor in the leading trivia !nodeHasTokens(child) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { - var candidate = findRightmostChildNodeWithTokens(children, i); + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); return candidate && findRightmostToken(candidate); } else { + // candidate should be in this node return find(child); } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265 || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 269 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); return candidate && findRightmostToken(candidate); } } + /** + * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. + */ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; @@ -61609,6 +78047,10 @@ var ts; if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). if (start < position && position < end) { return true; } @@ -61619,24 +78061,33 @@ var ts; return false; } ts.isInString = isInString; + /** + * returns true if the position is in between the open and close elements of an JSX expression. + */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, false); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; } - if (token.kind === 10) { + if (token.kind === 10 /* JsxText */) { return true; } - if (token.kind === 27 && token.parent.kind === 10) { + //
Hello |
+ if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 10 /* JsxText */) { return true; } - if (token.kind === 27 && token.parent.kind === 256) { + //
{ |
or
+ if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 260 /* JsxExpression */) { return true; } - if (token && token.kind === 18 && token.parent.kind === 256) { + //
{ + // | + // } < /div> + if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 260 /* JsxExpression */) { return true; } - if (token.kind === 27 && token.parent.kind === 252) { + //
|
+ if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 253 /* JsxClosingElement */) { return true; } return false; @@ -61647,16 +78098,23 @@ var ts; } ts.isWhiteSpaceOnlyJsxText = isWhiteSpaceOnlyJsxText; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, false); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; + /** + * Returns true if the cursor at position in sourceFile is within a comment. + * + * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) + * @param predicate Additional predicate to test on the comment range. + */ function isInComment(sourceFile, position, tokenAtPosition, predicate) { - return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, false, undefined, tokenAtPosition, predicate); + return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate); } ts.isInComment = isInComment; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, false); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + // First, we have to see if this position actually landed in a comment. var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); function jsDocPrefix(c) { @@ -61666,52 +78124,54 @@ var ts; } ts.hasDocComment = hasDocComment; function nodeHasTokens(n) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note: getWidth() does not take trivia into account. return n.getWidth() !== 0; } function getNodeModifiers(node) { var flags = ts.getCombinedModifierFlags(node); var result = []; - if (flags & 8) - result.push("private"); - if (flags & 16) - result.push("protected"); - if (flags & 4) - result.push("public"); - if (flags & 32) - result.push("static"); - if (flags & 128) - result.push("abstract"); - if (flags & 1) - result.push("export"); - if (ts.isInAmbientContext(node)) - result.push("declare"); - return result.length > 0 ? result.join(",") : ""; + if (flags & 8 /* Private */) + result.push("private" /* privateMemberModifier */); + if (flags & 16 /* Protected */) + result.push("protected" /* protectedMemberModifier */); + if (flags & 4 /* Public */) + result.push("public" /* publicMemberModifier */); + if (flags & 32 /* Static */) + result.push("static" /* staticModifier */); + if (flags & 128 /* Abstract */) + result.push("abstract" /* abstractModifier */); + if (flags & 1 /* Export */) + result.push("export" /* exportedModifier */); + if (node.flags & 2097152 /* Ambient */) + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 159 || node.kind === 181) { + if (node.kind === 160 /* TypeReference */ || node.kind === 182 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 229 || node.kind === 230) { + if (ts.isFunctionLike(node) || node.kind === 230 /* ClassDeclaration */ || node.kind === 231 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isWord(kind) { - return kind === 71 || ts.isKeyword(kind); + return kind === 71 /* Identifier */ || ts.isKeyword(kind); } ts.isWord = isWord; function isPropertyName(kind) { - return kind === 9 || kind === 8 || isWord(kind); + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); } function isComment(kind) { - return kind === 2 || kind === 3; + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; } ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { - if (kind === 9 - || kind === 12 + if (kind === 9 /* StringLiteral */ + || kind === 12 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; } @@ -61719,7 +78179,7 @@ var ts; } ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; function isPunctuation(kind) { - return 17 <= kind && kind <= 70; + return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; function isInsideTemplateLiteral(node, position) { @@ -61729,9 +78189,9 @@ var ts; ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { switch (kind) { - case 114: - case 112: - case 113: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: return true; } return false; @@ -61743,38 +78203,27 @@ var ts; return result; } ts.cloneCompilerOptions = cloneCompilerOptions; - function compareDataObjects(dst, src) { - if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { - return false; - } - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { - return false; - } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; - } - } - } - return true; - } - ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 177 || - node.kind === 178) { - if (node.parent.kind === 194 && + if (node.kind === 178 /* ArrayLiteralExpression */ || + node.kind === 179 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 195 /* BinaryExpression */ && node.parent.left === node && - node.parent.operatorToken.kind === 58) { + node.parent.operatorToken.kind === 58 /* EqualsToken */) { return true; } - if (node.parent.kind === 216 && + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 217 /* ForOfStatement */ && node.parent.initializer === node) { return true; } - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 261 ? node.parent.parent : node.parent)) { + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 265 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -61787,14 +78236,14 @@ var ts; } ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, undefined, function (c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return tripleSlashDirectivePrefixRegex.test(commentText); }); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, undefined, function (c) { + return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { var commentText = sourceFile.text.substring(c.pos, c.end); return !tripleSlashDirectivePrefixRegex.test(commentText); }); @@ -61808,27 +78257,27 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + ts.typeKeywords = [ + 119 /* AnyKeyword */, + 122 /* BooleanKeyword */, + 130 /* NeverKeyword */, + 133 /* NumberKeyword */, + 134 /* ObjectKeyword */, + 136 /* StringKeyword */, + 137 /* SymbolKeyword */, + 105 /* VoidKeyword */, + ]; function isTypeKeyword(kind) { - switch (kind) { - case 119: - case 122: - case 130: - case 133: - case 134: - case 136: - case 137: - case 105: - return true; - default: - return false; - } + return ts.contains(ts.typeKeywords, kind); } ts.isTypeKeyword = isTypeKeyword; + /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536)); - return moduleSymbol.name.charCodeAt(0) === 34; + ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); + return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; + /** Returns `true` the first time it encounters a node and `false` afterwards. */ function nodeSeenTracker() { var seen = []; return function (node) { @@ -61838,9 +78287,11 @@ var ts; } ts.nodeSeenTracker = nodeSeenTracker; })(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 146; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 147 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -61865,6 +78316,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { @@ -61898,46 +78350,46 @@ var ts; return displayPart(text, displayPartKind(symbol)); function displayPartKind(symbol) { var flags = symbol.flags; - if (flags & 3) { + if (flags & 3 /* Variable */) { return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; } - else if (flags & 4) { + else if (flags & 4 /* Property */) { return ts.SymbolDisplayPartKind.propertyName; } - else if (flags & 32768) { + else if (flags & 32768 /* GetAccessor */) { return ts.SymbolDisplayPartKind.propertyName; } - else if (flags & 65536) { + else if (flags & 65536 /* SetAccessor */) { return ts.SymbolDisplayPartKind.propertyName; } - else if (flags & 8) { + else if (flags & 8 /* EnumMember */) { return ts.SymbolDisplayPartKind.enumMemberName; } - else if (flags & 16) { + else if (flags & 16 /* Function */) { return ts.SymbolDisplayPartKind.functionName; } - else if (flags & 32) { + else if (flags & 32 /* Class */) { return ts.SymbolDisplayPartKind.className; } - else if (flags & 64) { + else if (flags & 64 /* Interface */) { return ts.SymbolDisplayPartKind.interfaceName; } - else if (flags & 384) { + else if (flags & 384 /* Enum */) { return ts.SymbolDisplayPartKind.enumName; } - else if (flags & 1536) { + else if (flags & 1536 /* Module */) { return ts.SymbolDisplayPartKind.moduleName; } - else if (flags & 8192) { + else if (flags & 8192 /* Method */) { return ts.SymbolDisplayPartKind.methodName; } - else if (flags & 262144) { + else if (flags & 262144 /* TypeParameter */) { return ts.SymbolDisplayPartKind.typeParameterName; } - else if (flags & 524288) { + else if (flags & 524288 /* TypeAlias */) { return ts.SymbolDisplayPartKind.aliasName; } - else if (flags & 2097152) { + else if (flags & 2097152 /* Alias */) { return ts.SymbolDisplayPartKind.aliasName; } return ts.SymbolDisplayPartKind.text; @@ -61976,6 +78428,9 @@ var ts; } ts.textPart = textPart; var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ function getNewLineOrDefaultFromHost(host) { return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; } @@ -62007,31 +78462,38 @@ var ts; } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536; + flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; return mapToDisplayParts(function (writer) { typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); }); } ts.signatureToDisplayParts = signatureToDisplayParts; function getDeclaredName(typeChecker, symbol, location) { - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever is under the cursor. + if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { return ts.getTextOfIdentifierOrLiteral(location); } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); return typeChecker.symbolToString(localExportDefaultSymbol || symbol); } ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 242 || location.parent.kind === 246) && + (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -62047,9 +78509,15 @@ var ts; } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { + // First check to see if the script kind was specified by the host. Chances are the host + // may override the default script kind for the file extension. return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -62058,33 +78526,154 @@ var ts; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; function getOpenBrace(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. return constructor.body.getFirstToken(sourceFile); } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; + function getSourceFileImportLocation(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } + ts.getSourceFileImportLocation = getSourceFileImportLocation; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_7 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_7)) { + clone_7.textSourceNode = node; + } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; + } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + /* @internal */ + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512 /* NoLeadingComments */); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + if (firstChild) { + suppressLeading(firstChild); + } + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024 /* NoTrailingComments */); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + // As an optimization, jump straight to the end of the list. + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + if (lastChild) { + suppressTrailing(lastChild); + } + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; })(ts || (ts = {})); +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +/* @internal */ var ts; (function (ts) { var BreakpointResolver; (function (BreakpointResolver) { + /** + * Get the breakpoint span in given sourceFile + */ function spanInSourceFileAtLocation(sourceFile, position) { + // Cannot set breakpoint in dts file if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, false); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { + // Get previous token if the token is returned starts on new line + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use + // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + // It's a blank line if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { return undefined; } } - if (ts.isInAmbientContext(tokenAtLocation)) { + // Cannot set breakpoint in ambient declarations + if (tokenAtLocation.flags & 2097152 /* Ambient */) { return undefined; } + // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { var start = startNode.decorators ? @@ -62113,176 +78702,225 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 208: + case 209 /* VariableStatement */: + // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 226: - case 149: - case 148: + case 227 /* VariableDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return spanInVariableDeclaration(node); - case 146: + case 147 /* Parameter */: return spanInParameterDeclaration(node); - case 228: - case 151: - case 150: - case 153: - case 154: - case 152: - case 186: - case 187: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 207: + case 208 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 234: + // falls through + case 235 /* ModuleBlock */: return spanInBlock(node); - case 260: + case 264 /* CatchClause */: return spanInBlock(node.block); - case 210: + case 211 /* ExpressionStatement */: + // span on the expression return textSpan(node.expression); - case 219: + case 220 /* ReturnStatement */: + // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 213: + case 214 /* WhileStatement */: + // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 212: + case 213 /* DoStatement */: + // span in statement of the do statement return spanInNode(node.statement); - case 225: + case 226 /* DebuggerStatement */: + // span on debugger keyword return textSpan(node.getChildAt(0)); - case 211: + case 212 /* IfStatement */: + // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 222: + case 223 /* LabeledStatement */: + // span in statement return spanInNode(node.statement); - case 218: - case 217: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: + // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 214: + case 215 /* ForStatement */: return spanInForStatement(node); - case 215: + case 216 /* ForInStatement */: + // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 216: + case 217 /* ForOfStatement */: + // span in initializer return spanInInitializerOfForLike(node); - case 221: + case 222 /* SwitchStatement */: + // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 257: - case 258: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + // span in first statement of the clause return spanInNode(node.statements[0]); - case 224: + case 225 /* TryStatement */: + // span in try block return spanInBlock(node.tryBlock); - case 223: + case 224 /* ThrowStatement */: + // span in throw ... return textSpan(node, node.expression); - case 243: + case 244 /* ExportAssignment */: + // span on export = id return textSpan(node, node.expression); - case 237: + case 238 /* ImportEqualsDeclaration */: + // import statement without including semicolon return textSpan(node, node.moduleReference); - case 238: + case 239 /* ImportDeclaration */: + // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 244: + case 245 /* ExportDeclaration */: + // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 233: - if (ts.getModuleInstanceState(node) !== 1) { + case 234 /* ModuleDeclaration */: + // span on complete module if it is instantiated + if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 229: - case 232: - case 264: - case 176: + // falls through + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 177 /* BindingElement */: + // span on complete node return textSpan(node); - case 220: + case 221 /* WithStatement */: + // span in statement return spanInNode(node.statement); - case 147: + case 148 /* Decorator */: return spanInNodeArray(node.parent.decorators); - case 174: - case 175: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return spanInBindingPattern(node); - case 230: - case 231: + // No breakpoint in interface, type alias + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: return undefined; - case 25: - case 1: + // Tokens: + case 25 /* SemicolonToken */: + case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); - case 26: + case 26 /* CommaToken */: return spanInPreviousNode(node); - case 17: + case 17 /* OpenBraceToken */: return spanInOpenBraceToken(node); - case 18: + case 18 /* CloseBraceToken */: return spanInCloseBraceToken(node); - case 22: + case 22 /* CloseBracketToken */: return spanInCloseBracketToken(node); - case 19: + case 19 /* OpenParenToken */: return spanInOpenParenToken(node); - case 20: + case 20 /* CloseParenToken */: return spanInCloseParenToken(node); - case 56: + case 56 /* ColonToken */: return spanInColonToken(node); - case 29: - case 27: + case 29 /* GreaterThanToken */: + case 27 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); - case 106: + // Keywords: + case 106 /* WhileKeyword */: return spanInWhileKeyword(node); - case 82: - case 74: - case 87: + case 82 /* ElseKeyword */: + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: return spanInNextNode(node); - case 142: + case 143 /* OfKeyword */: return spanInOfKeyword(node); default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } - if ((node.kind === 71 || - node.kind === 198 || - node.kind === 261 || - node.kind === 262) && + // Set breakpoint on identifier element of destructuring pattern + // a or ...c or d: x from + // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + if ((node.kind === 71 /* Identifier */ || + node.kind === 199 /* SpreadElement */ || + node.kind === 265 /* PropertyAssignment */ || + node.kind === 266 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 194) { + if (node.kind === 195 /* BinaryExpression */) { var binaryExpression = node; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); } - if (binaryExpression.operatorToken.kind === 58 && + if (binaryExpression.operatorToken.kind === 58 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression return textSpan(node); } - if (binaryExpression.operatorToken.kind === 26) { + if (binaryExpression.operatorToken.kind === 26 /* CommaToken */) { return spanInNode(binaryExpression.left); } } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { switch (node.parent.kind) { - case 212: + case 213 /* DoStatement */: + // Set span as if on while keyword return spanInPreviousNode(node); - case 147: + case 148 /* Decorator */: + // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 214: - case 216: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: return textSpan(node); - case 194: - if (node.parent.operatorToken.kind === 26) { + case 195 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 26 /* CommaToken */) { + // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 187: + case 188 /* ArrowFunction */: if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } break; } } - if (node.parent.kind === 261 && + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.kind === 265 /* PropertyAssignment */ && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 184 && node.parent.type === node) { + // Breakpoint in type assertion goes to its operand + if (node.parent.kind === 185 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNextNode(node.parent.type); } + // return type of function go to previous token if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } - if ((node.parent.kind === 226 || - node.parent.kind === 146)) { + // initializer of variable/parameter declaration go to previous node + if ((node.parent.kind === 227 /* VariableDeclaration */ || + node.parent.kind === 147 /* Parameter */)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -62290,49 +78928,63 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 194) { + if (node.parent.kind === 195 /* BinaryExpression */) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || binaryExpression.operatorToken === node)) { + // If initializer of destructuring assignment move to previous token return spanInPreviousNode(node); } } + // Default go to parent to set the breakpoint return spanInNode(node.parent); } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 227 && + if (variableDeclaration.parent.kind === 228 /* VariableDeclarationList */ && variableDeclaration.parent.declarations[0] === variableDeclaration) { + // First declaration - include let keyword return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } else { + // Span only on this declaration return textSpan(variableDeclaration); } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 215) { + // If declaration of for in statement, just set the span in parent + if (variableDeclaration.parent.parent.kind === 216 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } + // If this is a destructuring pattern, set breakpoint in binding pattern if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); } + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' if (variableDeclaration.initializer || - ts.hasModifier(variableDeclaration, 1) || - variableDeclaration.parent.parent.kind === 216) { + ts.hasModifier(variableDeclaration, 1 /* Export */) || + variableDeclaration.parent.parent.kind === 217 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 227 && + if (variableDeclaration.parent.kind === 228 /* VariableDeclarationList */ && variableDeclaration.parent.declarations[0] !== variableDeclaration) { + // If we cannot set breakpoint on this declaration, set it on previous one + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if that's the case, + // use preceding token instead return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } } function canHaveSpanInParameterDeclaration(parameter) { + // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - ts.hasModifier(parameter, 4 | 8); + ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */); } function spanInParameterDeclaration(parameter) { if (ts.isBindingPattern(parameter.name)) { + // Set breakpoint in binding pattern return spanInBindingPattern(parameter.name); } else if (canHaveSpanInParameterDeclaration(parameter)) { @@ -62342,24 +78994,29 @@ var ts; var functionDeclaration = parameter.parent; var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); if (indexOfParameter) { + // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } else { + // Set breakpoint in the function declaration body return spanInNode(functionDeclaration.body); } } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return ts.hasModifier(functionDeclaration, 1) || - (functionDeclaration.parent.kind === 229 && functionDeclaration.kind !== 152); + return ts.hasModifier(functionDeclaration, 1 /* Export */) || + (functionDeclaration.parent.kind === 230 /* ClassDeclaration */ && functionDeclaration.kind !== 153 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { + // No breakpoints in the function signature if (!functionDeclaration.body) { return undefined; } if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { + // Set the span on whole function declaration return textSpan(functionDeclaration); } + // Set span in function body return spanInNode(functionDeclaration.body); } function spanInFunctionBlock(block) { @@ -62371,28 +79028,34 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 233: - if (ts.getModuleInstanceState(block.parent) !== 1) { + case 234 /* ModuleDeclaration */: + if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } - case 213: - case 211: - case 215: + // falls through + // Set on parent if on same line otherwise on first statement + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 216 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 214: - case 216: + // Set span on previous token if it starts on same line otherwise on the first statement of the block + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } + // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 227) { + if (forLikeStatement.initializer.kind === 228 /* VariableDeclarationList */) { + // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); } } else { + // Expression - set breakpoint in it return spanInNode(forLikeStatement.initializer); } } @@ -62408,66 +79071,84 @@ var ts; } } function spanInBindingPattern(bindingPattern) { - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 200 ? element : undefined; }); + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 201 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - if (bindingPattern.parent.kind === 176) { + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 177 /* BindingElement */) { return textSpan(bindingPattern.parent); } + // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 175 && node.kind !== 174); - var elements = node.kind === 177 ? + ts.Debug.assert(node.kind !== 176 /* ArrayBindingPattern */ && node.kind !== 175 /* ObjectBindingPattern */); + var elements = node.kind === 178 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 200 ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 201 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } - return textSpan(node.parent.kind === 194 ? node.parent : node); + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 195 /* BinaryExpression */ ? node.parent : node); } + // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 232: + case 233 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 229: + case 230 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 235: + case 236 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } + // Default to parent node return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 234: - if (ts.getModuleInstanceState(node.parent.parent) !== 1) { + case 235 /* ModuleBlock */: + // If this is not an instantiated module block, no bp span + if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 232: - case 229: + // falls through + case 233 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: + // Span on close brace token return textSpan(node); - case 207: + case 208 /* Block */: if (ts.isFunctionBlock(node.parent)) { + // Span on close brace token return textSpan(node); } - case 260: + // falls through + case 264 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 235: + case 236 /* CaseBlock */: + // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 174: + case 175 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + // Default to parent node default: if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements var objectLiteral = node.parent; return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); } @@ -62476,74 +79157,85 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 175: + case 176 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements var arrayLiteral = node.parent; return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); } + // Default to parent node return spanInNode(node.parent); } } function spanInOpenParenToken(node) { - if (node.parent.kind === 212 || - node.parent.kind === 181 || - node.parent.kind === 182) { + if (node.parent.kind === 213 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 182 /* CallExpression */ || + node.parent.kind === 183 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 185) { + if (node.parent.kind === 186 /* ParenthesizedExpression */) { return spanInNextNode(node); } + // Default to parent node return spanInNode(node.parent); } function spanInCloseParenToken(node) { + // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 186: - case 228: - case 187: - case 151: - case 150: - case 153: - case 154: - case 152: - case 213: - case 212: - case 214: - case 216: - case 181: - case 182: - case 185: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 186 /* ParenthesizedExpression */: return spanInPreviousNode(node); + // Default to parent node default: return spanInNode(node.parent); } } function spanInColonToken(node) { + // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 261 || - node.parent.kind === 146) { + node.parent.kind === 265 /* PropertyAssignment */ || + node.parent.kind === 147 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 184) { + if (node.parent.kind === 185 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 212) { + if (node.parent.kind === 213 /* DoStatement */) { + // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } + // Default to parent node return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 216) { + if (node.parent.kind === 217 /* ForOfStatement */) { + // Set using next token return spanInNextNode(node); } + // Default to parent node return spanInNode(node.parent); } } @@ -62554,445 +79246,531 @@ var ts; var ts; (function (ts) { function createClassifier() { - var scanner = ts.createScanner(5, false); - var noRegexTable = []; - noRegexTable[71] = true; - noRegexTable[9] = true; - noRegexTable[8] = true; - noRegexTable[12] = true; - noRegexTable[99] = true; - noRegexTable[43] = true; - noRegexTable[44] = true; - noRegexTable[20] = true; - noRegexTable[22] = true; - noRegexTable[18] = true; - noRegexTable[101] = true; - noRegexTable[86] = true; - var templateStack = []; - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 125 || - keyword2 === 135 || - keyword2 === 123 || - keyword2 === 115) { - return true; - } - return false; - } - return true; - } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0; i < dense.length; i += 3) { - var start = dense[i]; - var length_6 = dense[i + 1]; - var type = dense[i + 2]; - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); - } - } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1: return ts.TokenClass.Comment; - case 3: return ts.TokenClass.Keyword; - case 4: return ts.TokenClass.NumberLiteral; - case 5: return ts.TokenClass.Operator; - case 6: return ts.TokenClass.StringLiteral; - case 8: return ts.TokenClass.Whitespace; - case 10: return ts.TokenClass.Punctuation; - case 2: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 9: - case 17: - default: - return ts.TokenClass.Identifier; - } - } + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); } + // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), + // we will be more conservative in order to avoid conflicting with the syntactic classifier. function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; - var token = 0; - var lastNonTriviaToken = 0; - while (templateStack.length > 0) { - templateStack.pop(); - } - switch (lexState) { - case 3: - text = "\"\\\n" + text; - offset = 3; - break; - case 2: - text = "'\\\n" + text; - offset = 3; - break; - case 1: - text = "/*\n" + text; - offset = 3; - break; - case 4: - text = "`\n" + text; - offset = 2; - break; - case 5: - text = "}\n" + text; - offset = 2; - case 6: - templateStack.push(14); - break; + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(14 /* TemplateHead */); } scanner.setText(text); - var result = { - endOfLineState: 0, - spans: [] - }; + var endOfLineState = 0 /* None */; + var spans = []; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. var angleBracketStack = 0; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 41 || token === 63) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 12) { - token = 12; - } - } - else if (lastNonTriviaToken === 23 && isKeyword(token)) { - token = 71; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - token = 71; - } - else if (lastNonTriviaToken === 71 && - token === 27) { - angleBracketStack++; - } - else if (token === 29 && angleBracketStack > 0) { - angleBracketStack--; + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; } - else if (token === 119 || - token === 136 || - token === 133 || - token === 122 || - token === 137) { + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + token = 12 /* RegularExpressionLiteral */; + } + break; + case 27 /* LessThanToken */: + if (lastNonTriviaToken === 71 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 29 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: if (angleBracketStack > 0 && !syntacticClassifierAbsent) { - token = 71; + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 71 /* Identifier */; } - } - else if (token === 14) { + break; + case 14 /* TemplateHead */: templateStack.push(token); - } - else if (token === 17) { + break; + case 17 /* OpenBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } - } - else if (token === 18) { + break; + case 18 /* CloseBraceToken */: + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); - if (lastTemplateStackToken === 14) { + if (lastTemplateStackToken === 14 /* TemplateHead */) { token = scanner.reScanTemplateToken(); - if (token === 16) { + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 16 /* TemplateTail */) { templateStack.pop(); } else { - ts.Debug.assertEqual(token, 15, "Should have been a template middle."); + ts.Debug.assertEqual(token, 15 /* TemplateMiddle */, "Should have been a template middle."); } } else { - ts.Debug.assertEqual(lastTemplateStackToken, 17, "Should have been an open brace"); + ts.Debug.assertEqual(lastTemplateStackToken, 17 /* OpenBraceToken */, "Should have been an open brace"); templateStack.pop(); } } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9) { - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92) { - numBackslashes++; - } - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 - ? 3 - : 2; - } + break; + default: + if (!ts.isKeyword(token)) { + break; } - } - else if (token === 3) { - if (scanner.isUnterminated()) { - result.endOfLineState = 1; + if (lastNonTriviaToken === 23 /* DotToken */) { + token = 71 /* Identifier */; } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 16) { - result.endOfLineState = 5; - } - else if (token === 13) { - result.endOfLineState = 4; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 71 /* Identifier */; } + } + } + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 71 /* Identifier */, + 9 /* StringLiteral */, + 8 /* NumericLiteral */, + 12 /* RegularExpressionLiteral */, + 99 /* ThisKeyword */, + 43 /* PlusPlusToken */, + 44 /* MinusMinusToken */, + 20 /* CloseParenToken */, + 22 /* CloseBracketToken */, + 18 /* CloseBraceToken */, + 101 /* TrueKeyword */, + 86 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 9 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 14) { - result.endOfLineState = 6; + switch (token) { + case 16 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 13 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); } } - } - function addResult(start, end, classification) { - if (classification === 8) { - return; + return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_6 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } - if (start === 0 && offset > 0) { - start += offset; - } - start -= offset; - end -= offset; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); - } - } - } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 39: - case 41: - case 42: - case 37: - case 38: - case 45: - case 46: - case 47: - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - case 32: - case 33: - case 34: - case 35: - case 48: - case 50: - case 49: - case 53: - case 54: - case 69: - case 68: - case 70: - case 65: - case 66: - case 67: - case 59: - case 60: - case 61: - case 63: - case 64: - case 58: - case 26: - return true; - default: - return false; } + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 37: - case 38: - case 52: - case 51: - case 43: - case 44: - return true; - default: - return false; - } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); } - function isKeyword(token) { - return token >= 72 && token <= 142; + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; } - function classFromKind(token) { - if (isKeyword(token)) { - return 3; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5; - } - else if (token >= 17 && token <= 70) { - return 10; - } - switch (token) { - case 8: - return 4; - case 9: - return 6; - case 12: - return 7; - case 7: - case 3: - case 2: - return 1; - case 5: - case 4: - return 8; - case 71: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6; - } - return 2; - } + switch (keyword2) { + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. + } + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + throw ts.Debug.assertNever(lexState); } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; } - ts.createClassifier = createClassifier; + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 48 /* AmpersandToken */: + case 50 /* CaretToken */: + case 49 /* BarToken */: + case 53 /* AmpersandAmpersandToken */: + case 54 /* BarBarToken */: + case 69 /* BarEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 59 /* PlusEqualsToken */: + case 60 /* MinusEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 58 /* EqualsToken */: + case 26 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* StringLiteral */: + return 6 /* stringLiteral */; + case 12 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 71 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + /* @internal */ function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); } ts.getSemanticClassifications = getSemanticClassifications; function checkForClassificationCancellation(cancellationToken, kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. switch (kind) { - case 233: - case 229: - case 230: - case 228: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } + /* @internal */ function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - var result = []; - processNode(sourceFile); - return { spans: result, endOfLineState: 0 }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448) === 0) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (flags & 32) { - return 11; - } - else if (flags & 384) { - return 12; - } - else if (flags & 524288) { - return 16; - } - else if (meaningAtPosition & 2) { - if (flags & 64) { - return 13; - } - else if (flags & 262144) { - return 15; - } - } - else if (flags & 1536) { - if (meaningAtPosition & 4 || - (meaningAtPosition & 1 && hasValueSideModule(symbol))) { - return 14; + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); } } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { return undefined; - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 233 && - ts.getModuleInstanceState(declaration) === 1; - }); - } } - function processNode(node) { - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(cancellationToken, kind); - if (kind === 71 && !ts.nodeIsMissing(node)) { - var identifier = node; - if (classifiableNames.has(identifier.escapedText)) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; } } - ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } function getClassificationTypeName(type) { switch (type) { - case 1: return "comment"; - case 2: return "identifier"; - case 3: return "keyword"; - case 4: return "number"; - case 5: return "operator"; - case 6: return "string"; - case 8: return "whitespace"; - case 9: return "text"; - case 10: return "punctuation"; - case 11: return "class name"; - case 12: return "enum name"; - case 13: return "interface name"; - case 14: return "module name"; - case 15: return "type parameter name"; - case 16: return "type alias name"; - case 17: return "parameter name"; - case 18: return "doc comment tag name"; - case 19: return "jsx open tag name"; - case 20: return "jsx close tag name"; - case 21: return "jsx self closing tag name"; - case 22: return "jsx attribute"; - case 23: return "jsx text"; - case 24: return "jsx attribute string literal value"; - } - } - function convertClassifications(classifications) { + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + } + } + function convertClassificationsToSpans(classifications) { ts.Debug.assert(classifications.spans.length % 3 === 0); var dense = classifications.spans; var result = []; @@ -63004,18 +79782,21 @@ var ts; } return result; } + /* @internal */ function getSyntacticClassifications(cancellationToken, sourceFile, span) { - return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); } ts.getSyntacticClassifications = getSyntacticClassifications; + /* @internal */ function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { var spanStart = span.start; var spanLength = span.length; - var triviaScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(5, false, sourceFile.languageVariant, sourceFile.text); + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); - return { spans: result, endOfLineState: 0 }; + return { spans: result, endOfLineState: 0 /* None */ }; function pushClassification(start, length, type) { result.push(start); result.push(length); @@ -63025,71 +79806,88 @@ var ts; triviaScanner.setTextPos(token.pos); while (true) { var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. if (!ts.couldStartTrivia(sourceFile.text, start)) { return start; } var kind = triviaScanner.scan(); var end = triviaScanner.getTextPos(); var width = end - start; + // The moment we get something that isn't trivia, then stop processing. if (!ts.isTrivia(kind)) { return start; } - if (kind === 4 || kind === 5) { + // Don't bother with newlines/whitespace. + if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { continue; } + // Only bother with the trivia if it at least intersects the span of interest. if (ts.isComment(kind)) { classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. triviaScanner.setTextPos(end); continue; } - if (kind === 7) { + if (kind === 7 /* ConflictMarkerTrivia */) { var text = sourceFile.text; var ch = text.charCodeAt(start); - if (ch === 60 || ch === 62) { - pushClassification(start, width, 1); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); continue; } - ts.Debug.assert(ch === 124 || ch === 61); + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); classifyDisabledMergeCode(text, start, end); } } } function classifyComment(token, kind, start, width) { - if (kind === 3) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` docCommentAndDiagnostics.jsDoc.parent = token; classifyJSDocComment(docCommentAndDiagnostics.jsDoc); return; } } + // Simple comment. Just add as is. pushCommentRange(start, width); } function pushCommentRange(start, width) { - pushClassification(start, width, 1); + pushClassification(start, width, 1 /* comment */); } function classifyJSDocComment(docComment) { var pos = docComment.pos; if (docComment.tags) { for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 279: + case 284 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 282: + case 287 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 281: + case 286 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 280: + case 285 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -63103,7 +79901,7 @@ var ts; function processJSDocParameterTag(tag) { if (tag.isNameFirst) { pushCommentRange(pos, tag.name.pos - pos); - pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); pos = tag.name.end; } if (tag.typeExpression) { @@ -63113,7 +79911,7 @@ var ts; } if (!tag.isNameFirst) { pushCommentRange(pos, tag.name.pos - pos); - pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); pos = tag.name.end; } } @@ -63125,13 +79923,15 @@ var ts; } } function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. var i; for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } } - pushClassification(start, i - start, 1); + pushClassification(start, i - start, 1 /* comment */); mergeConflictScanner.setTextPos(i); while (mergeConflictScanner.getTextPos() < end) { classifyDisabledCodeToken(); @@ -63146,6 +79946,10 @@ var ts; pushClassification(start, end - start, type); } } + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ function tryClassifyNode(node) { if (ts.isJSDoc(node)) { return true; @@ -63154,10 +79958,10 @@ var ts; return true; } var classifiedElementName = tryClassifyJsxElementName(node); - if (!ts.isToken(node) && node.kind !== 10 && classifiedElementName === undefined) { + if (!ts.isToken(node) && node.kind !== 10 /* JsxText */ && classifiedElementName === undefined) { return false; } - var tokenStart = node.kind === 10 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenStart = node.kind === 10 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { @@ -63170,119 +79974,131 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 251: + case 252 /* JsxOpeningElement */: if (token.parent.tagName === token) { - return 19; + return 19 /* jsxOpenTagName */; } break; - case 252: + case 253 /* JsxClosingElement */: if (token.parent.tagName === token) { - return 20; + return 20 /* jsxCloseTagName */; } break; - case 250: + case 251 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { - return 21; + return 21 /* jsxSelfClosingTagName */; } break; - case 253: + case 257 /* JsxAttribute */: if (token.parent.name === token) { - return 22; + return 22 /* jsxAttribute */; } break; } return undefined; } + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. function classifyTokenType(tokenKind, token) { if (ts.isKeyword(tokenKind)) { - return 3; + return 3 /* keyword */; } - if (tokenKind === 27 || tokenKind === 29) { + // Special case < and > If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { + // If the node owning the token has a type argument list or type parameter list, then + // we can effectively assume that a '<' and '>' belong to those lists. if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { - return 10; + return 10 /* punctuation */; } } if (ts.isPunctuation(tokenKind)) { if (token) { - if (tokenKind === 58) { - if (token.parent.kind === 226 || - token.parent.kind === 149 || - token.parent.kind === 146 || - token.parent.kind === 253) { - return 5; - } - } - if (token.parent.kind === 194 || - token.parent.kind === 192 || - token.parent.kind === 193 || - token.parent.kind === 195) { - return 5; + if (tokenKind === 58 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (token.parent.kind === 227 /* VariableDeclaration */ || + token.parent.kind === 150 /* PropertyDeclaration */ || + token.parent.kind === 147 /* Parameter */ || + token.parent.kind === 257 /* JsxAttribute */) { + return 5 /* operator */; + } + } + if (token.parent.kind === 195 /* BinaryExpression */ || + token.parent.kind === 193 /* PrefixUnaryExpression */ || + token.parent.kind === 194 /* PostfixUnaryExpression */ || + token.parent.kind === 196 /* ConditionalExpression */) { + return 5 /* operator */; } } - return 10; + return 10 /* punctuation */; } - else if (tokenKind === 8) { - return 4; + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; } - else if (tokenKind === 9) { - return token.parent.kind === 253 ? 24 : 6; + else if (tokenKind === 9 /* StringLiteral */) { + return token.parent.kind === 257 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } - else if (tokenKind === 12) { - return 6; + else if (tokenKind === 12 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; } else if (ts.isTemplateLiteralKind(tokenKind)) { - return 6; + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; } - else if (tokenKind === 10) { - return 23; + else if (tokenKind === 10 /* JsxText */) { + return 23 /* jsxText */; } - else if (tokenKind === 71) { + else if (tokenKind === 71 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 229: + case 230 /* ClassDeclaration */: if (token.parent.name === token) { - return 11; + return 11 /* className */; } return; - case 145: + case 146 /* TypeParameter */: if (token.parent.name === token) { - return 15; + return 15 /* typeParameterName */; } return; - case 230: + case 231 /* InterfaceDeclaration */: if (token.parent.name === token) { - return 13; + return 13 /* interfaceName */; } return; - case 232: + case 233 /* EnumDeclaration */: if (token.parent.name === token) { - return 12; + return 12 /* enumName */; } return; - case 233: + case 234 /* ModuleDeclaration */: if (token.parent.name === token) { - return 14; + return 14 /* moduleName */; } return; - case 146: + case 147 /* Parameter */: if (token.parent.name === token) { - return ts.isThisIdentifier(token) ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } } - return 2; + return 2 /* identifier */; } } function processElement(element) { if (!element) { return; } + // Ignore nodes that don't intersect the original span to classify. if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { checkForClassificationCancellation(cancellationToken, element.kind); for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; if (!tryClassifyNode(child)) { + // Recurse into our child nodes. processElement(child); } } @@ -63291,44 +80107,46 @@ var ts; } ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications; })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var Completions; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); - var entries; if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); } else { - entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); } } else { - entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + // Check for node modules + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); } - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries - }; } - PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames; + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + /** + * Takes a script path and returns paths for all potential folders that could be merged with its + * containing folder via the "rootDirs" compiler option + */ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { - rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); - var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + // Make all paths absolute/normalized if they are not already + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + // Determine the path to the directory containing the script relative to the root directory it is contained within + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; }); - return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + // Now find a path for each potential directory that is to be merged with the one containing the script + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); @@ -63341,12 +80159,19 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; } fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); if (fragment === "") { fragment = "." + ts.directorySeparator; @@ -63356,13 +80181,20 @@ var ts; var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { - var files = tryReadDirectory(host, baseDirectory, extensions, undefined, ["./*"]); + // Enumerate the available files if possible + var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var filePath = files_2[_i]; filePath = ts.normalizePath(filePath); - if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0) { + if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); @@ -63371,59 +80203,81 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createCompletionEntryForModule(foundFile, "script", span)); + result.push(createCompletionEntryForModule(foundFile, "script" /* scriptElement */, span)); }); } + // If possible, get folder completion as well var directories = tryGetDirectories(host, baseDirectory); if (directories) { - for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { - var directory = directories_2[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var directory = directories_1[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createCompletionEntryForModule(directoryName, "directory", span)); + result.push(createCompletionEntryForModule(directoryName, "directory" /* directory */, span)); } } } return result; } + /** + * Check all of the declared modules and those in node modules. Possible sources of modules: + * Modules that are found by the type checker + * Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option) + * Modules from node_modules (i.e. those listed in package.json) + * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions + */ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result; + var result = []; + var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { - var fileExtensions = ts.getSupportedExtensions(compilerOptions); var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span, host); - if (paths) { - for (var path in paths) { - if (paths.hasOwnProperty(path)) { - if (path === "*") { - if (paths[path]) { - for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { - var pattern = _a[_i]; - for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { - var match = _c[_b]; - result.push(createCompletionEntryForModule(match, "external module name", span)); - } - } - } - } - else if (ts.startsWith(path, fragment)) { - var entry = paths[path] && paths[path].length === 1 && paths[path][0]; - if (entry) { - result.push(createCompletionEntryForModule(path, "external module name", span)); - } + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + var _loop_6 = function (path) { + if (!paths.hasOwnProperty(path)) + return "continue"; + var patterns = paths[path]; + if (!patterns) + return "continue"; + if (path === "*") { + for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { + var pattern = patterns_1[_i]; + var _loop_7 = function (match) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (result.some(function (entry) { return entry.name === match; })) + return "continue"; + result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); + }; + for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { + var match = _b[_a]; + _loop_7(match); } } } + else if (ts.startsWith(path, fragment)) { + if (patterns.length === 1) { + if (result.some(function (entry) { return entry.name === path; })) + return "continue"; + result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); + } + } + }; + for (var path in paths) { + _loop_6(path); } } - else { - result = []; + if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (host.directoryExists(nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + } + }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { - var moduleName = _e[_d]; - result.push(createCompletionEntryForModule(moduleName, "external module name", span)); + for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { + var moduleName = _a[_i]; + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } @@ -63431,18 +80285,25 @@ var ts; if (host.readDirectory) { var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; if (parsed) { + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); if (matches) { var result = []; + // Trim away prefix and suffix for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { var match = matches_1[_i]; var normalizedMatch = ts.normalizePath(match); @@ -63460,10 +80321,15 @@ var ts; return undefined; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + // Check If this is a nested module + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + // Nested modules of the form "module-name/sub" need to be adjusted to only return the string + // after the last '/' that appears in the fragment because that's where the replacement span + // starts if (isNestedModule) { var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { @@ -63477,7 +80343,7 @@ var ts; nonRelativeModuleNames.push(visibleModule.moduleName); } else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { - var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, undefined, ["./*"]); + var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (nestedFiles) { for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { var f = nestedFiles_1[_b]; @@ -63489,52 +80355,45 @@ var ts; } } } - return ts.deduplicate(nonRelativeModuleNames); + return ts.deduplicate(nonRelativeModuleNames, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position, false); - if (!token) { - return undefined; - } + var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - if (!commentRanges || !commentRanges.length) { - return undefined; - } - var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { return undefined; } - var completionInfo = { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: [] - }; - var text = sourceFile.text.substr(range.pos, position - range.pos); + var text = sourceFile.text.slice(range.pos, position); var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - if (kind === "path") { + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + switch (kind) { + case "path": { + // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, host, sourceFile.path); + return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); } - else { - var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + case "types": { + // Give completions based on the typings available + var span_11 = ts.createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); + return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } + default: + return undefined; } - return completionInfo; } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } + // Check for typings specified in compiler options if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name", span)); + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } } else if (host.getDirectories) { @@ -63542,17 +80401,18 @@ var ts; try { typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (e) { } + catch (_b) { } if (typeRoots) { - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; + for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { + var root = typeRoots_2[_c]; getCompletionEntriesFromDirectories(host, root, span, result); } } } if (host.getDirectories) { - for (var _c = 0, _d = findPackageJsons(scriptPath, host); _c < _d.length; _c++) { - var packageJson = _d[_c]; + // Also get all @types typings installed in visible node_modules directories + for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { + var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); getCompletionEntriesFromDirectories(host, typesDir, span, result); } @@ -63563,32 +80423,23 @@ var ts; if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name", span)); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); } } } } - function findPackageJsons(currentDir, host) { + function findPackageJsons(directory, host) { var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_18 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_18) { - break; - } - currentDir = parent_18; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out } - else { - break; - } - } + paths.push(currentConfigPath); + }); return paths; } function enumerateNodeModulesVisibleToScript(host, scriptPath) { @@ -63602,6 +80453,7 @@ var ts; } var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); var foundModuleNames = []; + // Provide completions for all non @types dependencies for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { var key = nodeModulesDependencyKeys_1[_b]; addPotentialPackageNames(contents[key], foundModuleNames); @@ -63637,24 +80489,38 @@ var ts; } } function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: "", sortText: name, replacementSpan: replacementSpan }; + return { name: name, kind: kind, kindModifiers: "" /* none */, sortText: name, replacementSpan: replacementSpan }; } + // Replace everything after the last directory seperator that appears function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); var offset = index !== -1 ? index + 1 : 0; return { start: textStart + offset, length: text.length - offset }; } + // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { - if (path && path.length >= 2 && path.charCodeAt(0) === 46) { - var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 ? 2 : 1; + if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { + var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; var slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === 47 || slashCharCode === 92; + return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; } return false; } function normalizeAndPreserveTrailingSlash(path) { return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); } + /** + * Matches a triple slash reference directive with an incomplete string literal for its path. Used + * to determine if the caret is currently within the string literal and capture the literal fragment + * for completions. + * For example, this matches + * + * /// +/* @internal */ var ts; (function (ts) { var Completions; @@ -63700,49 +80568,60 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries_2 && pathCompletionsInfo(entries_2); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; - if (sourceFile.languageVariant === 1 && - location && location.parent && location.parent.kind === 252) { + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; + if (sourceFile.languageVariant === 1 /* JSX */ && + location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ name: tagName.getFullText(), - kind: "class", + kind: "class" /* classElement */, kindModifiers: undefined, sortText: "0", }] }; } if (request) { - var entries_2 = request.kind === "JsDocTagName" + var entries_3 = request.kind === "JsDocTagName" + // If the current position is a jsDoc tag name, only tag names should be provided for completion ? ts.JsDoc.getJSDocTagNameCompletions() : request.kind === "JsDocTag" + // If the current position is a jsDoc tag, only tags should be provided for completion ? ts.JsDoc.getJSDocTagCompletions() : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { - if ((!symbols || symbols.length === 0) && keywordFilters === 0) { + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); } - if (keywordFilters !== 0 || !isMemberCompletion) { + // TODO add filter for keyword based on type/value/namespace and also location + // Add all keywords if + // - this is not a member completion list (all the keywords) + // - other filters are enabled in required scenario so add those keywords + if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; @@ -63750,91 +80629,174 @@ var ts; Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { + // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName)) { + if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { return; } uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, true, false); + var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); if (displayName) { entries.push({ name: displayName, - kind: "warning", + kind: "warning" /* warning */, kindModifiers: "", sortText: "1" }); } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { + // Try to get a valid display name for this symbol, if we could not find one, then ignore it. + // We would like to only show things that can be added after a dot, so for instance numeric properties can + // not be accessed with a dot (a.1 <- invalid) + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); if (!displayName) { return undefined; } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). return { name: displayName, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(origin !== undefined), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && ts.stripQuotes(origin.moduleSymbol.name); + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); - var uniqueNames = ts.createMap(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); - if (entry) { - var id = entry.name; - if (!uniqueNames.has(id)) { - entries.push(entry); - uniqueNames.set(id, true); - } + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + if (!entry) { + continue; } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); + } + entries.push(entry); } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniqueNames; + return uniques; } function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9) { + if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 261 && - node.parent.parent.kind === 178 && + if (node.parent.kind === 265 /* PropertyAssignment */ && + node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); } - else if (node.parent.kind === 238 || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) { - return Completions.PathCompletions.getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker); + else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ + || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) + || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + return pathCompletionsInfo(entries); } else if (isEqualityExpression(node.parent)) { + // Get completions from the type of the other operand + // i.e. switch (a) { + // case '/*completion position*/' + // } return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); } else if (ts.isCaseOrDefaultClause(node.parent)) { + // Get completions from the type of the switch expression + // i.e. x === '/*completion position' return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.parent.parent.expression), typeChecker); } else { var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); if (argumentInfo) { + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); } + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); } } + function pathCompletionsInfo(entries) { + return { + // We don't want the editor to offer any other completions, such as snippets, inside a comment. + isGlobalCompletion: false, + isMemberCompletion: false, + // The user may type in a path that doesn't yet exist, creating a "new identifier" + // with respect to the collection of identifiers the server is aware of. + isNewIdentifierLocation: true, + entries: entries, + }; + } function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log, true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -63858,7 +80820,7 @@ var ts; var type = typeChecker.getTypeAtLocation(node.expression); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false, typeChecker, target, log, true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -63877,104 +80839,213 @@ var ts; } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } - if (type && type.flags & 16384) { + if (type && type.flags & 32768 /* TypeParameter */) { type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; } - if (type.flags & 65536) { + if (type.flags & 131072 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } - else if (type.flags & 32 && !(type.flags & 256)) { - var name_56 = type.value; - if (!uniques.has(name_56)) { - uniques.set(name_56, true); + else if (type.flags & 32 /* StringLiteral */ && !(type.flags & 256 /* EnumLiteral */)) { + var name = type.value; + if (!uniques.has(name)) { + uniques.set(name, true); result.push({ - name: name_56, - kindModifiers: "", - kind: "var", + name: name, + kindModifiers: "" /* none */, + kind: "var" /* variableElement */, sortText: "0" }); } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location_3 = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral_1) === entryName ? s : undefined; }); - if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; - } + function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { + var name = _a.name, source = _a.source; + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + if (!completionData) { + return { type: "none" }; } - var keywordCompletion = ts.forEach(getKeywordCompletions(0), function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: "keyword", - kindModifiers: "", - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined - }; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; + if (request) { + return { type: "request", request: request }; + } + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + var symbol = ts.find(symbols, function (s) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; + return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name + && getSourceFromOrigin(origin) === source; + }); + return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + } + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var name = entryId.name; + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case "JsDocTagName": + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case "JsDocTag": + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case "JsDocParameterName": + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); + var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; + } + case "none": { + // Didn't find a symbol with this name. See if we can find a keyword instead. + if (ts.some(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; })) { + return { + name: name, + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined, + tags: undefined, + codeActions: undefined, + source: undefined, + }; + } + return undefined; + } } - return undefined; } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (!completionData) { - return undefined; - } - var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral) === entryName ? s : undefined; }); + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); + ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + formatContext: formatContext, + symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), + getCanonicalFileName: getCanonicalFileName, + symbolToken: undefined, + kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + }); + return { sourceDisplay: sourceDisplay, codeActions: codeActions }; + } + function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { + var result = []; + ts.codefix.forEachExternalModule(checker, allSourceFiles, function (module) { + for (var _i = 0, _a = checker.getExportsOfModule(module); _i < _a.length; _i++) { + var exported = _a[_i]; + if (ts.skipAlias(exported, checker) === exportedSymbol) { + result.push(module); + } + } + }); + return result; + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { + var completion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + function getRecommendedCompletion(currentToken, checker /*, symbolToOriginInfoMap: SymbolOriginInfoMap*/) { + var ty = checker.getContextualType(currentToken); + var symbol = ty && ty.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return isModuleSymbol(symbol.parent) ? symbol : symbol.parent && getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); + } + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { var request; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position, false); + var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); + // Completion not allowed inside comments, bail out if this is the case var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { - if (sourceFile.text.charCodeAt(position - 1) === 64) { + if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names request = { kind: "JsDocTagName" }; } else { + // When completion is requested without "@", we will have check to make sure that + // there are no comments prefix the request position. We will only allow "*" and space. + // e.g + // /** |c| /* + // + // /** + // |c| + // */ + // + // /** + // * |c| + // */ + // + // /** + // * |c| + // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { request = { kind: "JsDocTag" }; } } } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267) { - currentToken = ts.getTokenAtPosition(sourceFile, position, true); + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 284 || + (currentToken.parent.kind !== 289 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); } } @@ -63983,66 +81054,95 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; + return { + symbols: ts.emptyArray, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0 /* None */, + symbolToOriginInfoMap: undefined, + recommendedCompletion: undefined, + }; } if (!insideJsDocTagTypeExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, insideJsDocTagTypeExpression); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { var start_4 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, insideJsDocTagTypeExpression); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. var node = currentToken; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { + // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_19 = contextToken.parent; - if (contextToken.kind === 23) { - if (parent_19.kind === 179) { + var parent = contextToken.parent; + if (contextToken.kind === 23 /* DotToken */) { + if (parent.kind === 180 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_19.kind === 143) { + else if (parent.kind === 144 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } else { + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. return undefined; } } - else if (sourceFile.languageVariant === 1) { - if (parent_19 && parent_19.kind === 179) { - contextToken = parent_19; - parent_19 = parent_19.parent; + else if (sourceFile.languageVariant === 1 /* JSX */) { + // + // If the tagname is a property access expression, we will then walk up to the top most of property access expression. + // Then, try to get a JSX container and its associated attributes type. + if (parent && parent.kind === 180 /* PropertyAccessExpression */) { + contextToken = parent; + parent = parent.parent; } - switch (parent_19.kind) { - case 252: - if (contextToken.kind === 41) { + switch (parent.kind) { + case 253 /* JsxClosingElement */: + if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 194: - if (!(parent_19.left.flags & 32768)) { + case 195 /* BinaryExpression */: + if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { + // It has a left-hand side, so we're not in an opening JSX tag. break; } - case 250: - case 249: - case 251: - if (contextToken.kind === 27) { + // falls through + case 251 /* JsxSelfClosingElement */: + case 250 /* JsxElement */: + case 252 /* JsxOpeningElement */: + if (contextToken.kind === 27 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } @@ -64055,15 +81155,16 @@ var ts; var isMemberCompletion; var allowStringLiteral = false; var isNewIdentifierLocation; - var keywordFilters = 0; + var keywordFilters = 0 /* None */; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } else if (isRightOfOpenTag) { var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 2097152)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); })); } else { symbols = tagSymbols; @@ -64081,38 +81182,45 @@ var ts; isNewIdentifierLocation = false; } else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. if (!tryGetGlobalSymbols()) { return undefined; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 277: - case 279: - case 284: - case 280: - case 281: - case 283: + case 284 /* JSDocParameterTag */: + case 289 /* JSDocPropertyTag */: + case 285 /* JSDocReturnTag */: + case 286 /* JSDocTypeTag */: + case 288 /* JSDocTypedefTag */: return true; } } function getTypeScriptMemberSymbols() { + // Right of dot member completion list isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; + // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & (1536 | 384)) { + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members var exportedSymbols = typeChecker.getExportsOfModule(symbol); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; var isValidAccess = isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { @@ -64121,7 +81229,8 @@ var ts; symbols.push(symbol_2); } } - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 && d.kind !== 233 && d.kind !== 232; })) { + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 269 /* SourceFile */ && d.kind !== 234 /* ModuleDeclaration */ && d.kind !== 233 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -64133,17 +81242,21 @@ var ts; } } function addTypeProperties(type) { - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } + if (ts.isSourceFileJavaScript(sourceFile)) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); } - if (isJavaScriptFile && type.flags & 65536) { - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); + else { + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } } } } @@ -64156,21 +81269,28 @@ var ts; return tryGetObjectLikeCompletionSymbols(objectLikeContainer); } if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + // cursor is in an import clause + // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (tryGetConstructorLikeCompletionContainer(contextToken)) { + // no members, only keywords isMemberCompletion = false; + // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = 2; + // Has keywords for constructor parameter + keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { + // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); return true; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 250) || (jsxContainer.kind === 251)) { + if ((jsxContainer.kind === 251 /* JsxSelfClosingElement */) || (jsxContainer.kind === 252 /* JsxOpeningElement */)) { + // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); @@ -64180,80 +81300,174 @@ var ts; } } } + // Get all entities in the current scope. isMemberCompletion = false; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. var adjustedPosition = previousToken !== contextToken ? previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; if (scopeNode) { isGlobalCompletion = - scopeNode.kind === 265 || - scopeNode.kind === 196 || - scopeNode.kind === 256 || + scopeNode.kind === 269 /* SourceFile */ || + scopeNode.kind === 197 /* TemplateExpression */ || + scopeNode.kind === 260 /* JsxExpression */ || + scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions ts.isStatement(scopeNode); } - var symbolMeanings = 793064 | 107455 | 1920 | 2097152; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + if (options.includeExternalModuleExports) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); + } + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { return true; } - if (symbol && symbol.flags & 2097152) { + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 2097152 /* Alias */) { symbol = typeChecker.getAliasedSymbol(symbol); } + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920); + return !!(symbol.flags & 1920 /* Namespace */); } if (insideJsDocTagTypeExpression || (!isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + // Its a type, but you can reach it by namespace.type as well return symbolCanBeReferencedAtTypeLocation(symbol); } } - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455); + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455 /* Value */); }); } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 103 && - contextToken.parent.kind === 162; + contextToken.kind === 103 /* TypeOfKeyword */ && + contextToken.parent.kind === 163 /* TypeQuery */; } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { - case 56: - return parentKind === 149 || - parentKind === 148 || - parentKind === 146 || - parentKind === 226 || + case 56 /* ColonToken */: + return parentKind === 150 /* PropertyDeclaration */ || + parentKind === 149 /* PropertySignature */ || + parentKind === 147 /* Parameter */ || + parentKind === 227 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); - case 58: - return parentKind === 231; - case 118: - return parentKind === 202; + case 58 /* EqualsToken */: + return parentKind === 232 /* TypeAliasDeclaration */; + case 118 /* AsKeyword */: + return parentKind === 203 /* AsExpression */; } } } function symbolCanBeReferencedAtTypeLocation(symbol) { symbol = symbol.exportSymbol || symbol; + // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 793064) { + if (symbol.flags & 793064 /* Type */) { return true; } - if (symbol.flags & 1536) { + if (symbol.flags & 1536 /* Module */) { var exportedSymbols = typeChecker.getExportsOfModule(symbol); + // If the exported symbols contains type, + // symbol can be referenced at locations where type is allowed return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + // Don't add a completion for a re-export, only for the original. + // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + continue; + } + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + else { + name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); + } + } + if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -64271,15 +81485,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 10) { + if (contextToken.kind === 10 /* JsxText */) { return true; } - if (contextToken.kind === 29 && contextToken.parent) { - if (contextToken.parent.kind === 251) { + if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 252 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 252 || contextToken.parent.kind === 250) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 249; + if (contextToken.parent.kind === 253 /* JsxClosingElement */ || contextToken.parent.kind === 251 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 250 /* JsxElement */; } } return false; @@ -64288,42 +81502,43 @@ var ts; if (previousToken) { var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { - case 26: - return containingNodeKind === 181 - || containingNodeKind === 152 - || containingNodeKind === 182 - || containingNodeKind === 177 - || containingNodeKind === 194 - || containingNodeKind === 160; - case 19: - return containingNodeKind === 181 - || containingNodeKind === 152 - || containingNodeKind === 182 - || containingNodeKind === 185 - || containingNodeKind === 168; - case 21: - return containingNodeKind === 177 - || containingNodeKind === 157 - || containingNodeKind === 144; - case 128: - case 129: + case 26 /* CommaToken */: + return containingNodeKind === 182 /* CallExpression */ // func( a, | + || containingNodeKind === 153 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 183 /* NewExpression */ // new C(a, | + || containingNodeKind === 178 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 195 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 161 /* FunctionType */; // var x: (s: string, list| + case 19 /* OpenParenToken */: + return containingNodeKind === 182 /* CallExpression */ // func( | + || containingNodeKind === 153 /* Constructor */ // constructor( | + || containingNodeKind === 183 /* NewExpression */ // new C(a| + || containingNodeKind === 186 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 169 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 21 /* OpenBracketToken */: + return containingNodeKind === 178 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 158 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 145 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 128 /* ModuleKeyword */: // module | + case 129 /* NamespaceKeyword */:// namespace | return true; - case 23: - return containingNodeKind === 233; - case 17: - return containingNodeKind === 229; - case 58: - return containingNodeKind === 226 - || containingNodeKind === 194; - case 14: - return containingNodeKind === 196; - case 15: - return containingNodeKind === 205; - case 114: - case 112: - case 113: - return containingNodeKind === 149; - } + case 23 /* DotToken */: + return containingNodeKind === 234 /* ModuleDeclaration */; // module A.| + case 17 /* OpenBraceToken */: + return containingNodeKind === 230 /* ClassDeclaration */; // class A{ | + case 58 /* EqualsToken */: + return containingNodeKind === 227 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 195 /* BinaryExpression */; // x = a| + case 14 /* TemplateHead */: + return containingNodeKind === 197 /* TemplateExpression */; // `aa ${| + case 15 /* TemplateMiddle */: + return containingNodeKind === 206 /* TemplateSpan */; // `aa ${10} dd ${| + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + return containingNodeKind === 150 /* PropertyDeclaration */; // class A{ public | + } + // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { case "public": case "protected": @@ -64334,46 +81549,65 @@ var ts; return false; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { - if (contextToken.kind === 9 - || contextToken.kind === 12 + if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 12 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { var start_5 = contextToken.getStart(); var end = contextToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). if (start_5 < position && position < end) { return true; } if (position === end) { return !!contextToken.isUnterminated - || contextToken.kind === 12; + || contextToken.kind === 12 /* RegularExpressionLiteral */; } } return false; } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; allowStringLiteral = true; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 178) { + if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { + // We are completing on contextual types, but may also include properties + // other than those within the declared type. isNewIdentifierLocation = true; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 174); + ts.Debug.assert(objectLikeContainer.kind === 175 /* ObjectBindingPattern */); + // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) throw ts.Debug.fail("Root declaration is not variable-like."); - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216; - if (!canGetType && rootDeclaration.kind === 146) { + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 147 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 151 || rootDeclaration.parent.kind === 154) { + else if (rootDeclaration.parent.kind === 152 /* MethodDeclaration */ || rootDeclaration.parent.kind === 155 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -64381,19 +81615,36 @@ var ts; var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24); }); + // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(function (symbol) { return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */); }); existingMembers = objectLikeContainer.elements; } } if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 241 ? - 238 : - 244; + var declarationKind = namedImportsOrExports.kind === 242 /* NamedImports */ ? + 239 /* ImportDeclaration */ : + 245 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -64410,64 +81661,83 @@ var ts; symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements); return true; } + /** + * Aggregates relevant symbols for completion in class declaration + * Relevant symbols are stored in the captured 'symbols' variable. + */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { + // We're looking up possible property names from parent type. isMemberCompletion = true; + // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = 1; + // Has keywords for class elements + keywordFilters = 1 /* ClassElementKeywords */; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); if (baseTypeNode || implementsTypeNodes) { var classElement = contextToken.parent; var classElementModifierFlags = ts.isClassElement(classElement) && ts.getModifierFlags(classElement); - if (contextToken.kind === 71 && !isCurrentlyEditingNode(contextToken)) { + // If this is context token is not something we are editing now, consider if this would lead to be modifier + if (contextToken.kind === 71 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { switch (contextToken.getText()) { case "private": - classElementModifierFlags = classElementModifierFlags | 8; + classElementModifierFlags = classElementModifierFlags | 8 /* Private */; break; case "static": - classElementModifierFlags = classElementModifierFlags | 32; + classElementModifierFlags = classElementModifierFlags | 32 /* Static */; break; } } - if (!(classElementModifierFlags & 8)) { + // No member list for private methods + if (!(classElementModifierFlags & 8 /* Private */)) { var baseClassTypeToGetPropertiesFrom = void 0; if (baseTypeNode) { baseClassTypeToGetPropertiesFrom = typeChecker.getTypeAtLocation(baseTypeNode); - if (classElementModifierFlags & 32) { + if (classElementModifierFlags & 32 /* Static */) { + // Use static class to get property symbols from baseClassTypeToGetPropertiesFrom = typeChecker.getTypeOfSymbolAtLocation(baseClassTypeToGetPropertiesFrom.symbol, classLikeDeclaration); } } - var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? + var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? ts.emptyArray : ts.flatMap(implementsTypeNodes || ts.emptyArray, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + // List of property symbols of base type that are not private and already implemented symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : ts.emptyArray, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); } } } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 17: - case 26: - var parent_20 = contextToken.parent; - if (ts.isObjectLiteralExpression(parent_20) || ts.isObjectBindingPattern(parent_20)) { - return parent_20; + case 17 /* OpenBraceToken */: // const x = { | + case 26 /* CommaToken */:// const x = { a: 0, | + var parent = contextToken.parent; + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { + return parent; } break; } } return undefined; } + /** + * Returns the containing list of named imports or exports of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 17: - case 26: + case 17 /* OpenBraceToken */: // import { | + case 26 /* CommaToken */:// import { a as 0, | switch (contextToken.parent.kind) { - case 241: - case 245: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return contextToken.parent; } } @@ -64485,24 +81755,36 @@ var ts; isParameterOfConstructorDeclaration(node.parent) && (isConstructorParameterCompletionKeyword(node.kind) || ts.isDeclarationName(node)); } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ function tryGetClassLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 17: + case 17 /* OpenBraceToken */:// class c { | if (ts.isClassLike(contextToken.parent)) { return contextToken.parent; } break; - case 26: + // class c {getValue(): number, | } + case 26 /* CommaToken */: if (ts.isClassLike(contextToken.parent)) { return contextToken.parent; } break; - case 25: - case 18: + // class c {getValue(): number; | } + case 25 /* SemicolonToken */: + // class c { method() { } | } + case 18 /* CloseBraceToken */: if (ts.isClassLike(location)) { return location; } + // class c { method() { } b| } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -64512,16 +81794,21 @@ var ts; } } } - if (location && location.kind === 286 && ts.isClassLike(location.parent)) { + // class c { method() { } | method2() { } } + if (location && location.kind === 290 /* SyntaxList */ && ts.isClassLike(location.parent)) { return location.parent; } return undefined; } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ function tryGetConstructorLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 19: - case 26: + case 19 /* OpenParenToken */: + case 26 /* CommaToken */: return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; default: if (isConstructorParameterCompletion(contextToken)) { @@ -64533,122 +81820,155 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_21 = contextToken.parent; + var parent = contextToken.parent; switch (contextToken.kind) { - case 28: - case 41: - case 71: - case 179: - case 254: - case 253: - case 255: - if (parent_21 && (parent_21.kind === 250 || parent_21.kind === 251)) { - return parent_21; + case 28 /* LessThanSlashToken */: + case 41 /* SlashToken */: + case 71 /* Identifier */: + case 180 /* PropertyAccessExpression */: + case 258 /* JsxAttributes */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 251 /* JsxSelfClosingElement */ || parent.kind === 252 /* JsxOpeningElement */)) { + return parent; } - else if (parent_21.kind === 253) { - return parent_21.parent.parent; + else if (parent.kind === 257 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; } break; - case 9: - if (parent_21 && ((parent_21.kind === 253) || (parent_21.kind === 255))) { - return parent_21.parent.parent; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 9 /* StringLiteral */: + if (parent && ((parent.kind === 257 /* JsxAttribute */) || (parent.kind === 259 /* JsxSpreadAttribute */))) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; } break; - case 18: - if (parent_21 && - parent_21.kind === 256 && - parent_21.parent && parent_21.parent.kind === 253) { - return parent_21.parent.parent.parent; + case 18 /* CloseBraceToken */: + if (parent && + parent.kind === 260 /* JsxExpression */ && + parent.parent && parent.parent.kind === 257 /* JsxAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + // each JsxAttribute can have initializer as JsxExpression + return parent.parent.parent.parent; } - if (parent_21 && parent_21.kind === 255) { - return parent_21.parent.parent; + if (parent && parent.kind === 259 /* JsxSpreadAttribute */) { + // Currently we parse JsxOpeningLikeElement as: + // JsxOpeningLikeElement + // attributes: JsxAttributes + // properties: NodeArray + return parent.parent.parent; } break; } } return undefined; } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { - case 26: - return containingNodeKind === 226 || - containingNodeKind === 227 || - containingNodeKind === 208 || - containingNodeKind === 232 || + case 26 /* CommaToken */: + return containingNodeKind === 227 /* VariableDeclaration */ || + containingNodeKind === 228 /* VariableDeclarationList */ || + containingNodeKind === 209 /* VariableStatement */ || + containingNodeKind === 233 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 230 || - containingNodeKind === 175 || - containingNodeKind === 231 || + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface A= contextToken.pos); - case 23: - return containingNodeKind === 175; - case 56: - return containingNodeKind === 176; - case 21: - return containingNodeKind === 175; - case 19: - return containingNodeKind === 260 || + case 23 /* DotToken */: + return containingNodeKind === 176 /* ArrayBindingPattern */; // var [.| + case 56 /* ColonToken */: + return containingNodeKind === 177 /* BindingElement */; // var {x :html| + case 21 /* OpenBracketToken */: + return containingNodeKind === 176 /* ArrayBindingPattern */; // var [x| + case 19 /* OpenParenToken */: + return containingNodeKind === 264 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); - case 17: - return containingNodeKind === 232 || - containingNodeKind === 230 || - containingNodeKind === 163; - case 25: - return containingNodeKind === 148 && + case 17 /* OpenBraceToken */: + return containingNodeKind === 233 /* EnumDeclaration */ || // enum a { | + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface a { | + containingNodeKind === 164 /* TypeLiteral */; // const x : { | + case 25 /* SemicolonToken */: + return containingNodeKind === 149 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 230 || - contextToken.parent.parent.kind === 163); - case 27: - return containingNodeKind === 229 || - containingNodeKind === 199 || - containingNodeKind === 230 || - containingNodeKind === 231 || + (contextToken.parent.parent.kind === 231 /* InterfaceDeclaration */ || // interface a { f; | + contextToken.parent.parent.kind === 164 /* TypeLiteral */); // const x : { a; | + case 27 /* LessThanToken */: + return containingNodeKind === 230 /* ClassDeclaration */ || // class A< | + containingNodeKind === 200 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 232 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); - case 115: - return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); - case 24: - return containingNodeKind === 146 || + case 115 /* StaticKeyword */: + return containingNodeKind === 150 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + case 24 /* DotDotDotToken */: + return containingNodeKind === 147 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 175); - case 114: - case 112: - case 113: - return containingNodeKind === 146 && !ts.isConstructorDeclaration(contextToken.parent.parent); - case 118: - return containingNodeKind === 242 || - containingNodeKind === 246 || - containingNodeKind === 240; - case 125: - case 135: + contextToken.parent.parent.kind === 176 /* ArrayBindingPattern */); // var [...z| + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + return containingNodeKind === 147 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + case 118 /* AsKeyword */: + return containingNodeKind === 243 /* ImportSpecifier */ || + containingNodeKind === 247 /* ExportSpecifier */ || + containingNodeKind === 241 /* NamespaceImport */; + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: if (isFromClassElementDeclaration(contextToken)) { return false; } - case 75: - case 83: - case 109: - case 89: - case 104: - case 91: - case 110: - case 76: - case 116: - case 138: + // falls through + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: + case 109 /* InterfaceKeyword */: + case 89 /* FunctionKeyword */: + case 104 /* VarKeyword */: + case 91 /* ImportKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + case 116 /* YieldKeyword */: + case 138 /* TypeKeyword */:// type htm| return true; } + // If the previous token is keyword correspoding to class member completion keyword + // there will be completion available here if (isClassMemberCompletionKeywordText(contextToken.getText()) && isFromClassElementDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion if (!ts.isIdentifier(contextToken) || isConstructorParameterCompletionKeywordText(contextToken.getText()) || isCurrentlyEditingNode(contextToken)) { return false; } } + // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": case "async": @@ -64670,30 +81990,46 @@ var ts; return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 152; + return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { - if (contextToken.kind === 8) { + if (contextToken.kind === 8 /* NumericLiteral */) { var text = contextToken.getFullText(); return text.charAt(text.length - 1) === "."; } return false; } + /** + * Filters out completion suggestions for named imports or exports. + * + * @param exportsOfModule The list of symbols which a module exposes. + * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. + * + * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports + * do not occur at the current position and have not otherwise been typed. + */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var existingImportsOrExports = ts.createUnderscoreEscapedMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; + // If this is the current item we are editing right now, do not filter it out if (isCurrentlyEditingNode(element)) { continue; } - var name_57 = element.propertyName || element.name; - existingImportsOrExports.set(name_57.escapedText, true); + var name = element.propertyName || element.name; + existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); } return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; @@ -64701,49 +82037,64 @@ var ts; var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; - if (m.kind !== 261 && - m.kind !== 262 && - m.kind !== 176 && - m.kind !== 151 && - m.kind !== 153 && - m.kind !== 154) { + // Ignore omitted expressions for missing members + if (m.kind !== 265 /* PropertyAssignment */ && + m.kind !== 266 /* ShorthandPropertyAssignment */ && + m.kind !== 177 /* BindingElement */ && + m.kind !== 152 /* MethodDeclaration */ && + m.kind !== 154 /* GetAccessor */ && + m.kind !== 155 /* SetAccessor */) { continue; } + // If this is the current item we are editing right now, do not filter it out if (isCurrentlyEditingNode(m)) { continue; } var existingName = void 0; - if (m.kind === 176 && m.propertyName) { - if (m.propertyName.kind === 71) { + if (m.kind === 177 /* BindingElement */ && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; } } else { - var name_58 = ts.getNameOfDeclaration(m); - existingName = ts.getEscapedTextOfIdentifierOrLiteral(name_58); + // TODO: Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + var name = ts.getNameOfDeclaration(m); + existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); } existingMemberNames.set(existingName, true); } return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.escapedName); }); } + /** + * Filters out completion suggestions for class elements. + * + * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags + */ function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; - if (m.kind !== 149 && - m.kind !== 151 && - m.kind !== 153 && - m.kind !== 154) { + // Ignore omitted expressions for missing members + if (m.kind !== 150 /* PropertyDeclaration */ && + m.kind !== 152 /* MethodDeclaration */ && + m.kind !== 154 /* GetAccessor */ && + m.kind !== 155 /* SetAccessor */) { continue; } + // If this is the current item we are editing right now, do not filter it out if (isCurrentlyEditingNode(m)) { continue; } - if (ts.hasModifier(m, 8)) { + // Dont filter member even if the name matches if it is declared private in the list + if (ts.hasModifier(m, 8 /* Private */)) { continue; } - var mIsStatic = ts.hasModifier(m, 32); - var currentElementIsStatic = !!(currentClassElementModifierFlags & 32); + // do not filter it out if the static presence doesnt match + var mIsStatic = ts.hasModifier(m, 32 /* Static */); + var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); if ((mIsStatic && !currentElementIsStatic) || (!mIsStatic && currentElementIsStatic)) { continue; @@ -64754,8 +82105,8 @@ var ts; } } var result = []; - addPropertySymbols(baseSymbols, 8); - addPropertySymbols(implementingTypeSymbols, 24); + addPropertySymbols(baseSymbols, 8 /* Private */); + addPropertySymbols(implementingTypeSymbols, 24 /* NonPublicAccessibilityModifier */); return result; function addPropertySymbols(properties, inValidModifierFlags) { for (var _i = 0, properties_12 = properties; _i < properties_12.length; _i++) { @@ -64771,14 +82122,21 @@ var ts; !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); } } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ function filterJsxAttributes(symbols, attributes) { var seenNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; + // If this is the current item we are editing right now, do not filter it out if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 253) { + if (attr.kind === 257 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -64788,24 +82146,53 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { - var name = symbol.name; + /** + * Get the name to be display in completion from a given symbol. + * + * @return undefined if the name is of external module + */ + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + var name = getSymbolName(symbol, origin, target); if (!name) return undefined; - if (symbol.flags & 1920) { + // First check of the displayName is not external module; if it is an external module, it is not valid entry + if (symbol.flags & 1920 /* Namespace */) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 || firstCharCode === 34) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + return undefined; + } + } + // If the symbol is for a member of an object type and is the internal name of an ES + // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + if (symbol.flags & 106500 /* ClassMember */) { + var escapedName = symbol.escapedName; + if (escapedName.length >= 3 && + escapedName.charCodeAt(0) === 95 /* _ */ && + escapedName.charCodeAt(1) === 95 /* _ */ && + escapedName.charCodeAt(2) === 64 /* at */) { return undefined; } } return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } + /** + * Get a displayName from a given for completion list, performing any necessary quotes stripping + * and checking whether the name is valid identifier name. + */ function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { + // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an + // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. + // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. + // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks && !ts.isIdentifierText(name, target)) { + // TODO: GH#18169 return allowStringLiteral ? JSON.stringify(name) : undefined; } return name; } + // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; function getKeywordCompletions(keywordFilter) { var completions = _keywordCompletions[keywordFilter]; @@ -64815,42 +82202,45 @@ var ts; return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); function generateKeywordCompletions(keywordFilter) { switch (keywordFilter) { - case 0: + case 0 /* None */: return getAllKeywordCompletions(); - case 1: + case 1 /* ClassElementKeywords */: return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); - case 2: + case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); } } function getAllKeywordCompletions() { var allKeywordsCompletions = []; - for (var i = 72; i <= 142; i++) { + for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { + // "undefined" is a global variable, so don't need a keyword completion for it. + if (i === 139 /* UndefinedKeyword */) + continue; allKeywordsCompletions.push({ name: ts.tokenToString(i), - kind: "keyword", - kindModifiers: "", + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, sortText: "0" }); } return allKeywordsCompletions; } function getFilteredKeywordCompletions(filterFn) { - return ts.filter(getKeywordCompletions(0), function (entry) { return filterFn(entry.name); }); + return ts.filter(getKeywordCompletions(0 /* None */), function (entry) { return filterFn(entry.name); }); } } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114: - case 113: - case 112: - case 117: - case 115: - case 123: - case 131: - case 125: - case 135: - case 120: + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 123 /* ConstructorKeyword */: + case 131 /* ReadonlyKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 120 /* AsyncKeyword */: return true; } } @@ -64859,10 +82249,10 @@ var ts; } function isConstructorParameterCompletionKeyword(kind) { switch (kind) { - case 114: - case 112: - case 113: - case 131: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: return true; } } @@ -64873,11 +82263,12 @@ var ts; return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } function isEqualityOperatorKind(kind) { - return kind === 32 || - kind === 33 || - kind === 34 || - kind === 35; + return kind === 32 /* EqualsEqualsToken */ || + kind === 33 /* ExclamationEqualsToken */ || + kind === 34 /* EqualsEqualsEqualsToken */ || + kind === 35 /* ExclamationEqualsEqualsToken */; } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { var jsDoc = getJsDocHavingNode(node).jsDoc; if (!jsDoc) @@ -64898,34 +82289,46 @@ var ts; if (!ts.isToken(node)) return node; switch (node.kind) { - case 104: - case 110: - case 76: + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + // if the current token is var, let or const, skip the VariableDeclarationList return node.parent.parent; default: return node.parent; } } - function getPropertiesForCompletion(type, checker) { - if (!(type.flags & 65536)) { - return checker.getPropertiesOfType(type); + /** + * Gets all properties on a type, but if that type is a union of several types, + * tries to only include those types which declare properties, not methods. + * This ensures that we don't try providing completions for all the methods on e.g. Array. + */ + function getPropertiesForCompletion(type, checker, isForAccess) { + if (!(type.flags & 131072 /* Union */)) { + return type.getApparentProperties(); } var types = type.types; - var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 || checker.isArrayLikeType(memberType)); }); + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + var filteredTypes = isForAccess ? types : types.filter(function (memberType) { + return !(memberType.flags & 16382 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); + }); return checker.getAllPossiblePropertiesOfTypes(filteredTypes); } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position, true); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + // Note that getTouchingWord indicates failure by returning the sourceFile node. if (node === sourceFile) return undefined; ts.Debug.assert(node.parent !== undefined); if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { var tagName = _a.tagName; @@ -64940,7 +82343,7 @@ var ts; return { fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node, sourceFile), - kind: "none" + kind: "none" /* none */ }; } function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { @@ -64970,110 +82373,72 @@ var ts; } return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - function parent(node) { - return node && node.parent; - } function getHighlightSpans(node, sourceFile) { - if (!node) { - return undefined; - } switch (node.kind) { - case 90: - case 82: - if (hasKind(node.parent, 211)) { - return getIfElseOccurrences(node.parent, sourceFile); - } - break; - case 96: - if (hasKind(node.parent, 219)) { - return highlightSpans(getReturnOccurrences(node.parent)); - } - break; - case 100: - if (hasKind(node.parent, 223)) { - return highlightSpans(getThrowOccurrences(node.parent)); - } - break; - case 102: - case 74: - case 87: - var tryStatement = node.kind === 74 ? parent(parent(node)) : parent(node); - if (hasKind(tryStatement, 224)) { - return highlightSpans(getTryCatchFinallyOccurrences(tryStatement, sourceFile)); - } - break; - case 98: - if (hasKind(node.parent, 221)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent)); - } - break; - case 73: - case 79: - if (hasKind(parent(parent(parent(node))), 221)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent.parent.parent)); - } - break; - case 72: - case 77: - if (hasKind(node.parent, 218) || hasKind(node.parent, 217)) { - return highlightSpans(getBreakOrContinueStatementOccurrences(node.parent)); - } - break; - case 88: - if (hasKind(node.parent, 214) || - hasKind(node.parent, 215) || - hasKind(node.parent, 216)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; - case 106: - case 81: - if (hasKind(node.parent, 213) || hasKind(node.parent, 212)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; - case 123: - if (hasKind(node.parent, 152)) { - return highlightSpans(getConstructorOccurrences(node.parent)); - } - break; - case 125: - case 135: - if (hasKind(node.parent, 153) || hasKind(node.parent, 154)) { - return highlightSpans(getGetAndSetOccurrences(node.parent)); - } - break; + case 90 /* IfKeyword */: + case 82 /* ElseKeyword */: + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; + case 96 /* ReturnKeyword */: + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); + case 100 /* ThrowKeyword */: + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); + case 102 /* TryKeyword */: + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: + var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); + case 98 /* SwitchKeyword */: + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 73 /* CaseKeyword */: + case 79 /* DefaultKeyword */: + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 72 /* BreakKeyword */: + case 77 /* ContinueKeyword */: + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); + case 88 /* ForKeyword */: + case 106 /* WhileKeyword */: + case 81 /* DoKeyword */: + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); + case 123 /* ConstructorKeyword */: + return useParent(node.parent, ts.isConstructorDeclaration, getConstructorOccurrences); + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + return useParent(node.parent, ts.isAccessor, getGetAndSetOccurrences); default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 208)) { - return highlightSpans(getModifierOccurrences(node.kind, node.parent)); - } + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; } function highlightSpans(nodes) { return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); } } + /** + * Aggregates all throw-statements within this node *without* crossing + * into function boundaries and try-blocks with catch-clauses. + */ function aggregateOwnedThrowStatements(node) { var statementAccumulator = []; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 223) { + if (ts.isThrowStatement(node)) { statementAccumulator.push(node); } - else if (node.kind === 224) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); + else if (ts.isTryStatement(node)) { + if (node.catchClause) { + aggregate(node.catchClause); } else { - aggregate(tryStatement.tryBlock); + // Exceptions thrown within a try block lacking a catch clause + // are "owned" in the current context. + aggregate(node.tryBlock); } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); + if (node.finallyBlock) { + aggregate(node.finallyBlock); } } else if (!ts.isFunctionLike(node)) { @@ -65081,20 +82446,27 @@ var ts; } } } + /** + * For lack of a better name, this function takes a throw statement and returns the + * nearest ancestor that is a try-block (whose try statement has a catch clause), + * function-block, or source file. + */ function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_22 = child.parent; - if (ts.isFunctionBlock(parent_22) || parent_22.kind === 265) { - return parent_22; - } - if (parent_22.kind === 224) { - var tryStatement = parent_22; + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 269 /* SourceFile */) { + return parent; + } + // A throw-statement is only owned by a try-statement if the try-statement has + // a catch clause, and if the throw-statement occurs within the try block. + if (parent.kind === 225 /* TryStatement */) { + var tryStatement = parent; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_22; + child = parent; } return undefined; } @@ -65103,7 +82475,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 218 || node.kind === 217) { + if (node.kind === 219 /* BreakStatement */ || node.kind === 218 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -65116,116 +82488,100 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node = statement.parent; node; node = node.parent) { + return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 221: - if (statement.kind === 217) { - continue; - } - case 214: - case 215: - case 216: - case 213: - case 212: - if (!statement.label || isLabeledBy(node, statement.label.text)) { - return node; + case 222 /* SwitchStatement */: + if (statement.kind === 218 /* ContinueStatement */) { + return false; } - break; + // falls through + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.text); default: - if (ts.isFunctionLike(node)) { - return undefined; - } - break; + // Don't cross function boundaries. + // TODO: GH#20090 + return (ts.isFunctionLike(node) && "quit"); } - } - return undefined; + }); } function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 229 || - container.kind === 199 || - (declaration.kind === 146 && hasKind(container, 152)))) { - return undefined; - } - } - else if (modifier === 115) { - if (!(container.kind === 229 || container.kind === 199)) { - return undefined; - } - } - else if (modifier === 84 || modifier === 124) { - if (!(container.kind === 234 || container.kind === 265)) { - return undefined; - } - } - else if (modifier === 117) { - if (!(container.kind === 229 || declaration.kind === 229)) { - return undefined; - } - } - else { + // Make sure we only highlight the keyword when it makes sense to do so. + if (!isLegalModifier(modifier, declaration)) { return undefined; } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; + var modifierFlag = ts.modifierToFlag(modifier); + return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { + if (ts.getModifierFlags(node) & modifierFlag) { + var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); + ts.Debug.assert(!!mod); + return mod; + } + }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + var container = declaration.parent; switch (container.kind) { - case 234: - case 265: - if (modifierFlag & 128) { - nodes = declaration.members.concat([declaration]); + case 235 /* ModuleBlock */: + case 269 /* SourceFile */: + case 208 /* Block */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 128 /* Abstract */) { + return declaration.members.concat([declaration]); } else { - nodes = container.statements; - } - break; - case 152: - nodes = container.parameters.concat(container.parent.members); - break; - case 229: - case 199: - nodes = container.members; - if (modifierFlag & 28) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 152 && member; - }); + return container.statements; + } + case 153 /* Constructor */: + return container.parameters.concat(container.parent.members); + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + var nodes = container.members; + // If we're an accessibility modifier, we're in an instance member and should search + // the constructor's parameter list for instance members as well. + if (modifierFlag & 28 /* AccessibilityModifier */) { + var constructor = ts.find(container.members, ts.isConstructorDeclaration); if (constructor) { - nodes = nodes.concat(constructor.parameters); + return nodes.concat(constructor.parameters); } } - else if (modifierFlag & 128) { - nodes = nodes.concat([container]); + else if (modifierFlag & 128 /* Abstract */) { + return nodes.concat([container]); } - break; + return nodes; default: ts.Debug.fail("Invalid container kind."); } - ts.forEach(nodes, function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return keywords; - function getFlagFromModifier(modifier) { - switch (modifier) { - case 114: - return 4; - case 112: - return 8; - case 113: - return 16; - case 115: - return 32; - case 84: - return 1; - case 124: - return 2; - case 117: - return 128; - default: - ts.Debug.fail(); - } + } + function isLegalModifier(modifier, declaration) { + var container = declaration.parent; + switch (modifier) { + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + switch (container.kind) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + return true; + case 153 /* Constructor */: + return declaration.kind === 147 /* Parameter */; + default: + return false; + } + case 115 /* StaticKeyword */: + return container.kind === 230 /* ClassDeclaration */ || container.kind === 200 /* ClassExpression */; + case 84 /* ExportKeyword */: + case 124 /* DeclareKeyword */: + return container.kind === 235 /* ModuleBlock */ || container.kind === 269 /* SourceFile */; + case 117 /* AbstractKeyword */: + return container.kind === 230 /* ClassDeclaration */ || declaration.kind === 230 /* ClassDeclaration */; + default: + return false; } } function pushKeywordIf(keywordList, token) { @@ -65241,13 +82597,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 153); - tryPushAccessorKeyword(accessorDeclaration.symbol, 154); + tryPushAccessorKeyword(accessorDeclaration.symbol, 154 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 155 /* SetAccessor */); return keywords; function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 125, 135); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 125 /* GetKeyword */, 135 /* SetKeyword */); }); } } } @@ -65256,18 +82612,19 @@ var ts; var keywords = []; ts.forEach(declarations, function (declaration) { ts.forEach(declaration.getChildren(), function (token) { - return pushKeywordIf(keywords, token, 123); + return pushKeywordIf(keywords, token, 123 /* ConstructorKeyword */); }); }); return keywords; } function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88, 106, 81)) { - if (loopNode.kind === 212) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { + // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. + if (loopNode.kind === 213 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, loopTokens[i], 106)) { + if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { break; } } @@ -65276,7 +82633,7 @@ var ts; var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72, 77); + pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */, 77 /* ContinueKeyword */); } }); return keywords; @@ -65285,13 +82642,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 214: - case 215: - case 216: - case 212: - case 213: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 221: + case 222 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -65299,13 +82656,14 @@ var ts; } function getSwitchCaseDefaultOccurrences(switchStatement) { var keywords = []; - pushKeywordIf(keywords, switchStatement.getFirstToken(), 98); + pushKeywordIf(keywords, switchStatement.getFirstToken(), 98 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. ts.forEach(switchStatement.caseBlock.clauses, function (clause) { - pushKeywordIf(keywords, clause.getFirstToken(), 73, 79); + pushKeywordIf(keywords, clause.getFirstToken(), 73 /* CaseKeyword */, 79 /* DefaultKeyword */); var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); ts.forEach(breaksAndContinues, function (statement) { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken(), 72); + pushKeywordIf(keywords, statement.getFirstToken(), 72 /* BreakKeyword */); } }); }); @@ -65313,13 +82671,13 @@ var ts; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { var keywords = []; - pushKeywordIf(keywords, tryStatement.getFirstToken(), 102); + pushKeywordIf(keywords, tryStatement.getFirstToken(), 102 /* TryKeyword */); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 74 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87, sourceFile); - pushKeywordIf(keywords, finallyKeyword, 87); + var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 87 /* FinallyKeyword */); } return keywords; } @@ -65330,75 +82688,93 @@ var ts; } var keywords = []; ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 100); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 100 /* ThrowKeyword */); }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. if (ts.isFunctionBlock(owner)) { ts.forEachReturnStatement(owner, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 96); + pushKeywordIf(keywords, returnStatement.getFirstToken(), 96 /* ReturnKeyword */); }); } return keywords; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 207))) { + if (!func) { return undefined; } var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { - pushKeywordIf(keywords, returnStatement.getFirstToken(), 96); + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 96 /* ReturnKeyword */); }); + // Include 'throw' statements that do not occur within a try block. ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { - pushKeywordIf(keywords, throwStatement.getFirstToken(), 100); + pushKeywordIf(keywords, throwStatement.getFirstToken(), 100 /* ThrowKeyword */); }); return keywords; } function getIfElseOccurrences(ifStatement, sourceFile) { - var keywords = []; - while (hasKind(ifStatement.parent, 211) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 90); - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 211)) { - break; - } - ifStatement = ifStatement.elseStatement; - } + var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). for (var i = 0; i < keywords.length; i++) { - if (keywords[i].kind === 82 && i < keywords.length - 1) { + if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; - var ifKeyword = keywords[i + 1]; - var shouldCombindElseAndIf = true; - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombineElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; + shouldCombineElseAndIf = false; break; } } - if (shouldCombindElseAndIf) { + if (shouldCombineElseAndIf) { result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: "reference" + kind: "reference" /* reference */ }); - i++; + i++; // skip the next keyword continue; } } + // Ordinary case: just highlight the keyword. result.push(getHighlightSpanForNode(keywords[i], sourceFile)); } return result; } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 222; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 223 /* LabeledStatement */; owner = owner.parent) { if (owner.label.escapedText === labelName) { return true; } @@ -65411,6 +82787,8 @@ var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { @@ -65448,7 +82826,7 @@ var ts; return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); } function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, true, scriptKind); + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); } function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); @@ -65456,13 +82834,14 @@ var ts; return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); } function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, false, scriptKind); + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = getBucketForCompilationSettings(key, true); + var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); if (!entry) { - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 1, @@ -65471,9 +82850,17 @@ var ts; bucket.set(path, entry); } else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. if (acquiring) { entry.languageServiceRefCount++; } @@ -65486,7 +82873,7 @@ var ts; return releaseDocumentWithKey(path, key); } function releaseDocumentWithKey(path, key) { - var bucket = getBucketForCompilationSettings(key, false); + var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); ts.Debug.assert(bucket !== undefined); var entry = bucket.get(path); entry.languageServiceRefCount--; @@ -65508,10 +82895,13 @@ var ts; } ts.createDocumentRegistry = createDocumentRegistry; })(ts || (ts = {})); +/* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ +/* @internal */ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { + /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ function createImportTracker(sourceFiles, checker, cancellationToken) { var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); return function (exportSymbol, exportInfo, isForRename) { @@ -65531,6 +82921,7 @@ var ts; ImportExport[ImportExport["Import"] = 0] = "Import"; ImportExport[ImportExport["Export"] = 1] = "Export"; })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); + /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ function getImportersForExport(sourceFiles, allDirectImports, _a, checker, cancellationToken) { var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; var markSeenDirectImport = ts.nodeSeenTracker(); @@ -65542,14 +82933,17 @@ var ts; return { directImports: directImports, indirectUsers: getIndirectUsers() }; function getIndirectUsers() { if (isAvailableThroughGlobal) { + // It has `export as namespace`, so anything could potentially use it. return sourceFiles; } + // Module augmentations may use this module's exports without importing it. for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; if (ts.isExternalModuleAugmentation(decl)) { addIndirectUser(decl); } } + // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. return indirectUserDeclarations.map(ts.getSourceFileOfNode); } function handleDirectImports(exportingModuleSymbol) { @@ -65562,36 +82956,39 @@ var ts; } cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 181: + case 182 /* CallExpression */: if (!isAvailableThroughGlobal) { - var parent_23 = direct.parent; - if (exportKind === 2 && parent_23.kind === 226) { - var name_59 = parent_23.name; - if (name_59.kind === 71) { - directImports.push(name_59); + var parent = direct.parent; + if (exportKind === 2 /* ExportEquals */ && parent.kind === 227 /* VariableDeclaration */) { + var name = parent.name; + if (name.kind === 71 /* Identifier */) { + directImports.push(name); break; } } + // Don't support re-exporting 'require()' calls, so just add a single indirect user. addIndirectUser(direct.getSourceFile()); } break; - case 237: - handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1)); + case 238 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); break; - case 238: + case 239 /* ImportDeclaration */: var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { + if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name); } else { directImports.push(direct); } break; - case 244: + case 245 /* ExportDeclaration */: if (!direct.exportClause) { + // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); } else { + // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports. directImports.push(direct); } break; @@ -65600,12 +82997,13 @@ var ts; } } function handleNamespaceImport(importDeclaration, name, isReExport) { - if (exportKind === 2) { + if (exportKind === 2 /* ExportEquals */) { + // This is a direct import, not import-as-namespace. directImports.push(importDeclaration); } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 265 || sourceFileLike.kind === 233); + ts.Debug.assert(sourceFileLike.kind === 269 /* SourceFile */ || sourceFileLike.kind === 234 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -65622,12 +83020,13 @@ var ts; } return isNew; } + /** Adds a module and all of its transitive dependencies as possible indirect users. */ function addIndirectUsers(sourceFileLike) { if (!addIndirectUser(sourceFileLike)) { return; } var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); - ts.Debug.assert(!!(moduleSymbol.flags & 1536)); + ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); var directImports = getDirectImports(moduleSymbol); if (directImports) { for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { @@ -65640,6 +83039,11 @@ var ts; return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); } } + /** + * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol. + * The returned `importSearches` will result in the entire source file being searched. + * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. + */ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { var importSearches = []; var singleReferences = []; @@ -65654,20 +83058,21 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 237) { + if (decl.kind === 238 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } return; } - if (decl.kind === 71) { + if (decl.kind === 71 /* Identifier */) { handleNamespaceImportLike(decl); return; } - if (decl.moduleSpecifier.kind !== 9) { + // Ignore if there's a grammar error + if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { return; } - if (decl.kind === 244) { + if (decl.kind === 245 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } @@ -65676,26 +83081,36 @@ var ts; return; } var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { + if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImportLike(namedBindings.name); return; } - if (exportKind === 0) { + if (exportKind === 0 /* Named */) { searchForNamedImport(namedBindings); } else { - var name_60 = importClause.name; - if (name_60 && (!isForRename || name_60.escapedText === symbolName(exportSymbol))) { - var defaultImportAlias = checker.getSymbolAtLocation(name_60); - addSearch(name_60, defaultImportAlias); - } - if (!isForRename && exportKind === 1) { + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals + var name = importClause.name; + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } + // 'default' might be accessed as a named import `{ default as foo }`. + if (!isForRename && exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); } } } + /** + * `import x = require("./x") or `import * as x from "./x"`. + * An `export =` may be imported by this syntax, so it may be a direct import. + * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here. + */ function handleNamespaceImportLike(importName) { - if (exportKind === 2 && (!isForRename || isNameMatch(importName.escapedText))) { + // Don't rename an import that already has a different name than the export. + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } @@ -65705,32 +83120,36 @@ var ts; } for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; - var name_61 = element.name, propertyName = element.propertyName; - if (!isNameMatch((propertyName || name_61).escapedText)) { + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { continue; } if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. singleReferences.push(propertyName); if (!isForRename) { - addSearch(name_61, checker.getSymbolAtLocation(name_61)); + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); } } else { - var localSymbol = element.kind === 246 && element.propertyName - ? checker.getExportSpecifierLocalTargetSymbol(element) - : checker.getSymbolAtLocation(name_61); - addSearch(name_61, localSymbol); + var localSymbol = element.kind === 247 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); } } } function isNameMatch(name) { - return name === exportSymbol.escapedName || exportKind !== 0 && name === "default"; + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default"; } } + /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 244) + if (statement.kind !== 245 /* ExportDeclaration */) return; var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; if (moduleSpecifier || !exportClause) @@ -65749,7 +83168,7 @@ var ts; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 265) { + if (searchSourceFile.kind === 269 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -65774,6 +83193,7 @@ var ts; return refs; } FindAllReferences.findModuleReferences = findModuleReferences; + /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { @@ -65793,11 +83213,13 @@ var ts; } return map; } + /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 265 ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 269 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } + /** Calls `action` for each import, re-export, or require() in a file. */ function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -65808,19 +83230,19 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 244: - case 238: { + case 245 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: { var decl = statement; - if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9) { + if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9 /* StringLiteral */) { action(decl, decl.moduleSpecifier); } break; } - case 237: { + case 238 /* ImportEqualsDeclaration */: { var decl = statement; var moduleReference = decl.moduleReference; - if (moduleReference.kind === 248 && - moduleReference.expression.kind === 9) { + if (moduleReference.kind === 249 /* ExternalModuleReference */ && + moduleReference.expression.kind === 9 /* StringLiteral */) { action(decl, moduleReference.expression); } break; @@ -65832,24 +83254,33 @@ var ts; function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; switch (decl.kind) { - case 181: - case 238: - case 244: + case 182 /* CallExpression */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return decl; - case 248: + case 249 /* ExternalModuleReference */: return decl.parent; default: ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); } } + /** + * Given a local reference, we might notice that it's an import/export and recursively search for references of that. + * If at an import, look locally for the symbol it imports. + * If an an export, look for all imports of it. + * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. + * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. + */ function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; if (symbol.exportSymbol) { - if (parent.kind === 179) { + if (parent.kind === 180 /* PropertyAccessExpression */) { + // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. + // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, false) + ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) : undefined; } else { @@ -65858,13 +83289,14 @@ var ts; } else { var exportNode = getExportNode(parent, node); - if (exportNode && ts.hasModifier(exportNode, 1)) { + if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { + // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. if (comingFromExport) { return undefined; } var lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { kind: 0, symbol: lhsSymbol, isNamedImport: false }; + return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); @@ -65877,26 +83309,27 @@ var ts; return getExportAssignmentExport(parent.parent); } else if (ts.isBinaryExpression(parent)) { - return getSpecialPropertyExport(parent, true); + return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, true); + return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); } } function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. var exportingModuleSymbol = ex.symbol.parent; ts.Debug.assert(!!exportingModuleSymbol); - var exportKind = ex.isExportEquals ? 2 : 1; - return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 1: - kind = 0; + case 1 /* ExportsProperty */: + kind = 0 /* Named */; break; - case 2: - kind = 2; + case 2 /* ModuleExports */: + kind = 2 /* ExportEquals */; break; default: return undefined; @@ -65909,29 +83342,36 @@ var ts; var isImport = isNodeImport(node); if (!isImport) return undefined; + // A symbol being imported is always an alias. So get what that aliases to find the local symbol. var importedSymbol = checker.getImmediateAliasedSymbol(symbol); if (!importedSymbol) return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); } + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = symbolName(importedSymbol); if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { - return __assign({ kind: 0, symbol: importedSymbol }, isImport); + return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } function exportInfo(symbol, kind) { var exportInfo = getExportInfo(symbol, kind, checker); - return exportInfo && { kind: 1, symbol: symbol, exportInfo: exportInfo }; + return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo }; } + // Not meant for use with export specifiers or export assignment. function getExportKindForDeclaration(node) { - return ts.hasModifier(node, 512) ? 1 : 0; + return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */; } } FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; function getExportEqualsLocalSymbol(importedSymbol, checker) { - if (importedSymbol.flags & 2097152) { + if (importedSymbol.flags & 2097152 /* Alias */) { return checker.getImmediateAliasedSymbol(importedSymbol); } var decl = importedSymbol.valueDeclaration; @@ -65943,11 +83383,13 @@ var ts; } ts.Debug.fail(); } + // If a reference is a class expression, the exported node would be its parent. + // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 226) { + if (parent.kind === 227 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 260 ? undefined : p.parent.parent.kind === 208 ? p.parent.parent : undefined; + p.parent.kind === 264 /* CatchClause */ ? undefined : p.parent.parent.kind === 209 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -65956,14 +83398,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 237: + case 238 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 242: + case 243 /* ImportSpecifier */: + // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return parent.propertyName ? undefined : { isNamedImport: true }; - case 239: - case 240: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -65971,7 +83414,8 @@ var ts; } } function getExportInfo(exportSymbol, exportKind, checker) { - var exportingModuleSymbol = checker.getMergedSymbol(exportSymbol.parent); + var exportingModuleSymbol = checker.getMergedSymbol(exportSymbol.parent); // Need to get merged symbol in case there's an augmentation. + // `export` may appear in a namespace. In that case, just rely on global search. return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; } FindAllReferences.getExportInfo = getExportInfo; @@ -65980,14 +83424,13 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 && name.escapedText; + return name && name.kind === 71 /* Identifier */ && name.escapedText; }); } + /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -66002,25 +83445,27 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 181) { + if (node.kind === 182 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 265) { + if (parent.kind === 269 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 234 && isAmbientModuleDeclaration(parent.parent)); + ts.Debug.assert(parent.kind === 235 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); return parent.parent; } function isAmbientModuleDeclaration(node) { - return node.kind === 233 && node.name.kind === 9; + return node.kind === 234 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; } function isExternalModuleImportEquals(_a) { var moduleReference = _a.moduleReference; - return moduleReference.kind === 248 && moduleReference.expression.kind === 9; + return moduleReference.kind === 249 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { var FindAllReferences; @@ -66038,6 +83483,7 @@ var ts; var checker = program.getTypeChecker(); for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; + // Only include referenced symbols that have a valid definition. if (definition) { out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); } @@ -66046,27 +83492,33 @@ var ts; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position, false); + // A node in a JSDoc comment can't have an implementation anyway. + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { - if (node.kind === 265) { + if (node.kind === 269 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); - if (node.parent.kind === 262) { - var result_5 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); - return result_5; + // If invoked directly on a shorthand property assignment, then return + // the declaration of the symbol being assigned (not the symbol being assigned to). + if (node.parent.kind === 266 /* ShorthandPropertyAssignment */) { + var result_4 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); + return result_4; } - else if (node.kind === 97 || ts.isSuperProperty(node.parent)) { + else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { + // References to and accesses on the super keyword only have one possible implementation, so no + // need to "Find all References" var symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { + // Perform "Find all References" and retrieve only those that are implementations return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); } } @@ -66081,7 +83533,7 @@ var ts; } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, true); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { @@ -66091,29 +83543,29 @@ var ts; var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_2 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_62 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_62, kind: kind_1, displayParts: displayParts_1 }; + var symbol = def.symbol, node_3 = def.node; + var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: "label", displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + var node_4 = def.node; + return { node: node_4, name: node_4.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { - var node_4 = def.node; - var name_63 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_63, kind: "keyword", displayParts: [{ text: name_63, kind: "keyword" }] }; + var node_5 = def.node; + var name_6 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_6, kind: "keyword" /* keyword */, displayParts: [{ text: name_6, kind: "keyword" /* keyword */ }] }; } case "this": { - var node_5 = def.node; - var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: "var", displayParts: displayParts_2 }; + var node_6 = def.node; + var symbol = checker.getSymbolAtLocation(node_6); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts; + return { node: node_6, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { - var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + var node_7 = def.node; + return { node: node_7, name: node_7.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -66123,7 +83575,7 @@ var ts; var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); return { - containerKind: "", + containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, @@ -66145,7 +83597,7 @@ var ts; fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccessForReference(node), - isDefinition: node.kind === 79 + isDefinition: node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString @@ -66158,7 +83610,7 @@ var ts; } else { var textSpan = entry.textSpan, fileName = entry.fileName; - return { textSpan: textSpan, fileName: fileName, kind: "", displayParts: [] }; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; } } function implementationKindDisplayParts(node, checker) { @@ -66166,16 +83618,16 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, node, checker); } - else if (node.kind === 178) { + else if (node.kind === 179 /* ObjectLiteralExpression */) { return { - kind: "interface", - displayParts: [ts.punctuationPart(19), ts.textPart("object literal"), ts.punctuationPart(20)] + kind: "interface" /* interfaceElement */, + displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } - else if (node.kind === 199) { + else if (node.kind === 200 /* ClassExpression */) { return { - kind: "local class", - displayParts: [ts.punctuationPart(19), ts.textPart("anonymous local class"), ts.punctuationPart(20)] + kind: "local class" /* localClassElement */, + displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] }; } else { @@ -66185,14 +83637,14 @@ var ts; function toHighlightSpan(entry) { if (entry.type === "span") { var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" } }; + return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node), - kind: writeAccess ? "writtenReference" : "reference", + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: isInString }; return { fileName: fileName, span: span }; @@ -66201,25 +83653,29 @@ var ts; function getTextSpan(node) { var start = node.getStart(); var end = node.getEnd(); - if (node.kind === 9) { + if (node.kind === 9 /* StringLiteral */) { start += 1; end -= 1; } return ts.createTextSpanFromBounds(start, end); } + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); +/** Encapsulates the core find-all-references algorithm. */ +/* @internal */ (function (ts) { var FindAllReferences; (function (FindAllReferences) { var Core; (function (Core) { + /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 265) { + if (node.kind === 269 /* SourceFile */) { return undefined; } if (!options.implementations) { @@ -66230,30 +83686,33 @@ var ts; } var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); + // Could not find a symbol e.g. unknown identifier if (!symbol) { - if (!options.implementations && node.kind === 9) { + // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. + if (!options.implementations && node.kind === 9 /* StringLiteral */) { return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); } + // Can't have references to something that we have no symbol for. return undefined; } - if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { + if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); } return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleReferenceLocation(node) { - if (node.kind !== 9) { + if (node.kind !== 9 /* StringLiteral */) { return false; } switch (node.parent.kind) { - case 233: - case 248: - case 238: - case 244: + case 234 /* ModuleDeclaration */: + case 249 /* ExternalModuleReference */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return true; - case 181: - return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); + case 182 /* CallExpression */: + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -66275,9 +83734,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 265: + case 269 /* SourceFile */: + // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 233: + case 234 /* ModuleDeclaration */: references.push({ type: "node", node: decl.name }); break; default: @@ -66289,58 +83749,82 @@ var ts; references: references }]; } + /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (ts.isTypeKeyword(node.kind)) { return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken); } + // Labels if (ts.isLabelName(node)) { if (ts.isJumpStatementTarget(node)) { var labelDefinition = ts.getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); } else { + // it is a label definition and not a target, search within the parent labeledStatement return getLabelReferencesInNode(node.parent, node); } } if (ts.isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles, cancellationToken); } - if (node.kind === 97) { + if (node.kind === 97 /* SuperKeyword */) { return getReferencesForSuperKeyword(node); } return undefined; } + /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; - var state = new State(sourceFiles, node.kind === 123, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); + if (node.kind === 79 /* DefaultKeyword */) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; } + /** Handle a few special cases relating to export/import specifiers. */ function skipPastExportOrImportSpecifier(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } if (ts.isImportSpecifier(parent) && parent.propertyName === node) { + // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } return symbol; } - var State = (function () { - function State(sourceFiles, isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = /** @class */ (function () { + function State(sourceFiles, + /** True if we're searching for constructor references. */ + isForConstructor, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.isForConstructor = isForConstructor; this.checker = checker; @@ -66348,20 +83832,43 @@ var ts; this.searchMeaning = searchMeaning; this.options = options; this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ this.markSeenReExportRHS = ts.nodeSeenTracker(); this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. this.sourceFileToSeenSymbols = []; } + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); }; + /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + // Note: if this is an external module symbol, the name doesn't include quotes. + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -66369,6 +83876,10 @@ var ts; includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, }; }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ State.prototype.referenceAdder = function (searchSymbol, searchLocation) { var symbolId = ts.getSymbolId(searchSymbol); var references = this.symbolIdToReferences[symbolId]; @@ -66378,12 +83889,14 @@ var ts; } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; }; + /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, references: [{ type: "span", fileName: fileName, textSpan: textSpan }] }); }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ State.prototype.markSearchedSymbol = function (sourceFile, symbol) { var sourceId = ts.getNodeId(sourceFile); var symbolId = ts.getSymbolId(symbol); @@ -66392,8 +83905,10 @@ var ts; }; return State; }()); + /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; + // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file. if (singleReferences.length) { var addRef = state.referenceAdder(exportSymbol, exportLocation); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { @@ -66401,20 +83916,22 @@ var ts; addRef(singleRef); } } + // For each import, find all references to that import in its source file. for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) { var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1]; - getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1), state); + getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state); } if (indirectUsers.length) { var indirectSearch = void 0; switch (exportInfo.exportKind) { - case 0: - indirectSearch = state.createSearch(exportLocation, exportSymbol, 1); + case 0 /* Named */: + indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */); break; - case 1: - indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1, { text: "default" }); + case 1 /* Default */: + // Search for a property access to '.default'. This can't be renamed. + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); break; - case 2: + case 2 /* ExportEquals */: break; } if (indirectSearch) { @@ -66425,12 +83942,14 @@ var ts; } } } + // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0), state); + getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0 /* Import */), state); } } + /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ function searchForName(sourceFile, search, state) { if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) { getReferencesInSourceFile(sourceFile, search, state); @@ -66441,9 +83960,9 @@ var ts; checker.getPropertySymbolOfDestructuringAssignment(location); } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176); + var bindingElement = ts.getDeclarationOfKind(symbol, 177 /* BindingElement */); if (bindingElement && - bindingElement.parent.kind === 174 && + bindingElement.parent.kind === 175 /* ObjectBindingPattern */ && !bindingElement.propertyName) { return bindingElement; } @@ -66454,32 +83973,54 @@ var ts; return undefined; var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304) { - ts.Debug.assert(!!(propSymbol.flags & 33554432)); + if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { + // See GH#16922 + ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); return propSymbol.target; } return propSymbol; } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 186 || valueDeclaration.kind === 199)) { + if (valueDeclaration && (valueDeclaration.kind === 187 /* FunctionExpression */ || valueDeclaration.kind === 200 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { return undefined; } - if (flags & (4 | 8192)) { - var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8); }); + // If this is private property or method, the scope is the containing class + if (flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 229); + return ts.getAncestor(privateDeclaration, 230 /* ClassDeclaration */); } + // Else this is a public property and could be accessed from anywhere. return undefined; } + // If symbol is of object binding pattern element without property name we would want to + // look for property too and that could be anywhere if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } - var exposedByParent = parent && !(symbol.flags & 262144); - if (exposedByParent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + /* + If the symbol has a parent, it's globally visible unless: + - It's a private property (handled above). + - It's a type parameter. + - The parent is an external module: then we should only search in the module (and recurse on the export later). + - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. + */ + var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); + if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; @@ -66487,18 +84028,30 @@ var ts; var declaration = declarations_9[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { + // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 265 && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 269 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file return undefined; } + // The search scope is the container node scope = container; } + // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.) + // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.: + // declare module "a" { export type T = number; } + // declare module "b" { import { T } from "a"; export const x: T; } + // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) return exposedByParent ? scope.getSourceFile() : scope; } function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name if (!symbolName || !symbolName.length) { return positions; } @@ -66507,11 +84060,15 @@ var ts; var symbolNameLength = symbolName.length; var position = text.indexOf(symbolName, container.pos); while (position >= 0) { + // If we are past the end, stop looking if (position > container.end) break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { + // Found a real match. Keep searching. positions.push(position); } position = text.indexOf(symbolName, position + symbolNameLength + 1); @@ -66525,7 +84082,8 @@ var ts; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) { var position = possiblePositions_1[_i]; - var node = ts.getTouchingWord(sourceFile, position, false); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + // Only pick labels that are either the target label, or have a target that is the target label if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } @@ -66533,15 +84091,16 @@ var ts; return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for switch (node.kind) { - case 71: + case 71 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9: + case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && node.text.length === searchSymbolName.length; - case 8: + case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; - case 79: + case 79 /* DefaultKeyword */: return "default".length === searchSymbolName.length; default: return false; @@ -66560,7 +84119,7 @@ var ts; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -66570,6 +84129,11 @@ var ts; state.cancellationToken.throwIfCancellationRequested(); return getReferencesInContainer(sourceFile, sourceFile, search, state); } + /** + * Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ function getReferencesInContainer(container, sourceFile, search, state) { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; @@ -66580,9 +84144,16 @@ var ts; } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (!isValidReferencePosition(referenceLocation, search.text)) { + // This wasn't the start of a token. Check to see if it might be a + // match in a comment or string if that's what the caller is asking + // for. if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + // In the case where we're looking inside comments/strings, we don't have + // an actual definition. So just use 'undefined' here. Features like + // 'Rename' won't care (as they ignore the definitions), and features like + // 'FindReferences' will just filter out these results. state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); } return; @@ -66596,10 +84167,11 @@ var ts; } var parent = referenceLocation.parent; if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) { + // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again. return; } if (ts.isExportSpecifier(parent)) { - ts.Debug.assert(referenceLocation.kind === 71); + ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); return; } @@ -66627,6 +84199,8 @@ var ts; addRef(); } else if (referenceLocation === propertyName) { + // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. + // For `export { foo as bar };`, where `foo` is a local, so add it now. if (!exportDeclaration.moduleSpecifier) { addRef(); } @@ -66639,13 +84213,15 @@ var ts; addRef(); } } + // For `export { foo as bar }`, rename `foo`, but not `bar`. if (!(referenceLocation === propertyName && state.options.isForRename)) { - var exportKind = referenceLocation.originalKeywordKind === 79 ? 1 : 0; + var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); ts.Debug.assert(!!exportInfo); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } - if (search.comingFrom !== 1 && exportDeclaration.moduleSpecifier && !propertyName) { + // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) { searchForImportedSymbol(state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier), state); } function addRef() { @@ -66659,30 +84235,41 @@ var ts; var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation); if (propertyName) { + // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. return propertyName === referenceLocation; } else { + // `export { foo } from "foo"` is a re-export. + // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. return !parent.parent.moduleSpecifier; } } function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { - var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1); + var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); if (!importOrExport) return; var symbol = importOrExport.symbol; - if (importOrExport.kind === 0) { + if (importOrExport.kind === 0 /* Import */) { if (!state.options.isForRename || importOrExport.isNamedImport) { searchForImportedSymbol(symbol, state); } } else { + // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching. searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } function getReferenceForShorthandProperty(_a, search, state) { var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); - if (!(flags & 33554432) && search.includes(shorthandValueSymbol)) { + /* + * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment + * has two meanings: property name and property value. Therefore when we do findAllReference at the position where + * an identifier is declared, the language service should return the position of the variable declaration as well as + * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the + * position of property accessing, the referenceEntry of such position will be handled in the first case. + */ + if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) { addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } @@ -66695,6 +84282,7 @@ var ts; addRef(referenceLocation); } } + /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ function findConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { addReference(referenceLocation, search.symbol, search.location, state); @@ -66702,9 +84290,11 @@ var ts; var pusher = state.referenceAdder(search.symbol, search.location); if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); + // This is the class declaration containing the constructor. findOwnConstructorReferences(search.symbol, sourceFile, pusher); } else { + // If this class appears in `extends C`, then the extending class' "super" calls are references. var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending && ts.isClassLike(classExtending)) { findSuperConstructorAccesses(classExtending, pusher); @@ -66714,19 +84304,23 @@ var ts; function getPropertyAccessExpressionFromRightHandSide(node) { return ts.isRightSideOfPropertyAccess(node) && node.parent; } + /** + * `classSymbol` is the class where the constructor was defined. + * Reference the constructor and all calls to `new this()`. + */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor").declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 123, sourceFile); - ts.Debug.assert(decl.kind === 152 && !!ctrKeyword); + var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 153 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 151) { + if (decl && decl.kind === 152 /* MethodDeclaration */) { var body = decl.body; if (body) { - forEachDescendantOfKind(body, 99, function (thisKeyword) { + forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { if (ts.isNewExpressionTarget(thisKeyword)) { addNode(thisKeyword); } @@ -66735,18 +84329,19 @@ var ts; } }); } + /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor"); + var ctr = symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 152); + ts.Debug.assert(decl.kind === 153 /* Constructor */); var body = decl.body; if (body) { - forEachDescendantOfKind(body, 97, function (node) { + forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { if (ts.isCallExpressionTarget(node)) { addNode(node); } @@ -66755,30 +84350,34 @@ var ts; } } function addImplementationReferences(refNode, addReference, state) { + // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { addReference(refNode.parent); return; } - if (refNode.kind !== 71) { + if (refNode.kind !== 71 /* Identifier */) { return; } - if (refNode.parent.kind === 262) { + if (refNode.parent.kind === 266 /* ShorthandPropertyAssignment */) { + // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } + // Check if the node is within an extends or implements clause var containingClass = getContainingClassIfInHeritageClause(refNode); if (containingClass) { addReference(containingClass); return; } + // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { - var parent_24 = containingTypeReference.parent; - if (ts.isVariableLike(parent_24) && parent_24.type === containingTypeReference && parent_24.initializer && isImplementationExpression(parent_24.initializer)) { - addReference(parent_24.initializer); + var parent = containingTypeReference.parent; + if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { + addReference(parent.initializer); } - else if (ts.isFunctionLike(parent_24) && parent_24.type === containingTypeReference && parent_24.body) { - var body = parent_24.body; - if (body.kind === 207) { + else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { + var body = parent.body; + if (body.kind === 208 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); @@ -66789,8 +84388,8 @@ var ts; addReference(body); } } - else if (ts.isAssertionExpression(parent_24) && isImplementationExpression(parent_24.expression)) { - addReference(parent_24.expression); + else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { + addReference(parent.expression); } } } @@ -66798,10 +84397,10 @@ var ts; if (result === void 0) { result = []; } for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var componentType = _a[_i]; - if (componentType.symbol && componentType.symbol.getFlags() & (32 | 64)) { + if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 196608) { + if (componentType.getFlags() & 393216 /* UnionOrIntersection */) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -66819,33 +84418,55 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 201 - && node.parent.kind === 259 + if (node.kind === 202 /* ExpressionWithTypeArguments */ + && node.parent.kind === 263 /* HeritageClause */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 71 || node.kind === 179) { + else if (node.kind === 71 /* Identifier */ || node.kind === 180 /* PropertyAccessExpression */) { return getContainingClassIfInHeritageClause(node.parent); } } return undefined; } + /** + * Returns true if this is an expression that can be considered an implementation + */ function isImplementationExpression(node) { switch (node.kind) { - case 185: + case 186 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 187: - case 186: - case 178: - case 199: - case 177: + case 188 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 179 /* ObjectLiteralExpression */: + case 200 /* ClassExpression */: + case 178 /* ArrayLiteralExpression */: return true; default: return false; } } + /** + * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol + * is an interface, determines if some ancestor of the child symbol extends or inherits from it. + * Also takes in a cache of previous results which makes this slightly more efficient and is + * necessary to avoid potential loops like so: + * class A extends B { } + * class B extends A { } + * + * We traverse the AST rather than using the type checker because users are typically only interested + * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling + * implementations of types that share a common ancestor with the type whose implementation we are + * searching for need to be filtered out of the results. The type checker doesn't let us make the + * distinction between structurally compatible implementations and explicit implementations, so we + * must use the AST. + * + * @param child A class or interface Symbol + * @param parent Another class or interface Symbol + * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results + */ function explicitlyInheritsFrom(child, parent, cachedResults, checker) { - var parentIsInterface = parent.getFlags() & 64; + var parentIsInterface = parent.getFlags() & 64 /* Interface */; return searchHierarchy(child); function searchHierarchy(symbol) { if (symbol === parent) { @@ -66856,6 +84477,7 @@ var ts; if (cached !== undefined) { return cached; } + // Set the key so that we don't infinitely recurse cachedResults.set(key, false); var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { if (ts.isClassLike(declaration)) { @@ -66872,7 +84494,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 230) { + else if (declaration.kind === 231 /* InterfaceDeclaration */) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -66893,21 +84515,22 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, false); + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); if (!searchSpaceNode) { return undefined; } - var staticFlag = 32; + // Whether 'super' occurs in a static context within a class. + var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 149: - case 148: - case 151: - case 150: - case 152: - case 153: - case 154: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); - searchSpaceNode = searchSpaceNode.parent; + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; default: return undefined; @@ -66917,47 +84540,55 @@ var ts; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode); for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) { var position = possiblePositions_3[_i]; - var node = ts.getTouchingWord(sourceFile, position, false); - if (!node || node.kind !== 97) { + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + if (!node || node.kind !== 97 /* SuperKeyword */) { continue; } - var container = ts.getSuperContainer(node, false); - if (container && (32 & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(FindAllReferences.nodeEntry(node)); } } return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol, node: superKeyword }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { - var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); - var staticFlag = 32; + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 151: - case 150: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } - case 149: - case 148: - case 152: - case 153: - case 154: + // falls through + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); - searchSpaceNode = searchSpaceNode.parent; + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 265: + case 269 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 228: - case 186: + // falls through + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 265) { + if (searchSpaceNode.kind === 269 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); @@ -66975,32 +84606,34 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position, false); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !ts.isThis(node)) { return; } - var container = ts.getThisContainer(node, false); + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 186: - case 228: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 151: - case 150: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 199: - case 229: - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32) === staticFlag) { + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 265: - if (container.kind === 265 && !ts.isExternalModule(container)) { + case 269 /* SourceFile */: + if (container.kind === 269 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(FindAllReferences.nodeEntry(node)); } break; @@ -67023,35 +84656,58 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position, false); - if (node_7 && node_7.kind === 9 && node_7.text === searchText) { - references.push(FindAllReferences.nodeEntry(node_7, true)); + var node_8 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + if (node_8 && node_8.kind === 9 /* StringLiteral */ && node_8.text === searchText) { + references.push(FindAllReferences.nodeEntry(node_8, /*isInString*/ true)); } } } } + // For certain symbol kinds, we need to include other symbols in the search set. + // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol, location, checker, implementations) { + // The search set contains at least the current symbol var result = [symbol]; var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - if (containingObjectLiteralElement.kind !== 262) { + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + if (containingObjectLiteralElement.kind !== 266 /* ShorthandPropertyAssignment */) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); if (propertySymbol) { result.push(propertySymbol); } } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { ts.addRange(result, checker.getRootSymbols(contextualSymbol)); }); + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * const name = "Foo"; + * const obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); if (shorthandValueSymbol) { result.push(shorthandValueSymbol); } } - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 146 && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - ts.addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + ts.addRange(result, getParameterPropertySymbols(symbol, checker)); + // If this is symbol of binding element without propertyName declaration in Object binding pattern + // Include the property in the search var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); if (bindingElementPropertySymbol) { result.push(bindingElementPropertySymbol); @@ -67060,31 +84716,58 @@ var ts; addRootSymbols(symbol); return result; function addRootSymbols(sym) { + // If this is a union property, add all the symbols from all its source symbols in all unioned types. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { var rootSymbol = _a[_i]; if (rootSymbol !== sym) { result.push(rootSymbol); } - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); } } } } + function getParameterPropertySymbols(symbol, checker) { + return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isParameterPropertyDeclaration(symbol.valueDeclaration) + ? checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name) + : undefined; + } + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { if (!symbol) { return; } + // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited + // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. + // For example: + // interface C extends C { + // /*findRef*/propName: string; + // } + // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, + // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, + // the function will add any found symbol of the property-name, then its sub-routine will call + // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already + // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. if (previousIterationSymbolsCache.has(symbol.escapedName)) { return; } - if (symbol.flags & (32 | 64)) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { if (ts.isClassLike(declaration)) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 230) { + else if (declaration.kind === 231 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -67098,6 +84781,7 @@ var ts; if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); } + // Visit the typeReference as well to see if it directly or indirectly use that property previousIterationSymbolsCache.set(symbol.escapedName, symbol); getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); } @@ -67105,23 +84789,41 @@ var ts; } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; if (search.includes(referenceSymbol)) { return referenceSymbol; } + if (referenceSymbol.flags & 1 /* FunctionScopedVariable */) { + ts.Debug.assert(!(referenceSymbol.flags & 4 /* Property */)); + var paramProps = getParameterPropertySymbols(referenceSymbol, checker); + if (paramProps) { + return getRelatedSymbol(search, ts.find(paramProps, function (x) { return !!(x.flags & 4 /* Property */); }), referenceLocation, state); + } + } + // If the reference location is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this symbol to + // compare to our searchSymbol var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, state.checker), function (contextualSymbol) { - return ts.find(state.checker.getRootSymbols(contextualSymbol), search.includes); + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { + return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); }); if (contextualSymbol) { return contextualSymbol; } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, state.checker); + // If the reference location is the name of property from object literal destructuring pattern + // Get the property symbol from the object literal's type and look if thats the search symbol + // In below eg. get 'property' from type of elems iterating type + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, checker); if (propertySymbol && search.includes(propertySymbol)) { return propertySymbol; } } - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); + // If the reference location is the binding element and doesn't have property name + // then include the binding element in the related symbols + // let { a } : { a }; + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, checker); if (bindingElementPropertySymbol) { var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); if (fromBindingElement) @@ -67129,16 +84831,23 @@ var ts; } return findRootSymbol(referenceSymbol); function findRootSymbol(sym) { + // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) + // Or a union property, use its underlying unioned symbols return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + // if it is in the list, then we are done if (search.includes(rootSymbol)) { return rootSymbol; } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + // Finally, try all properties with the same name in any type the containing type extended or implemented, and + // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the + // parent symbol + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + // Parents will only be defined if implementations is true if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); return ts.find(result, search.includes); } return undefined; @@ -67146,8 +84855,9 @@ var ts; } } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 144) { + if (node.name.kind === 145 /* ComputedPropertyName */) { var nameExpression = node.name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } @@ -67155,32 +84865,46 @@ var ts; } return ts.getTextOfIdentifierOrLiteral(node.name); } + /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { var objectLiteral = node.parent; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; + var result_5 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } - if (contextualType.flags & 65536) { + if (contextualType.flags & 131072 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } + /** + * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { var lastIterationMeaning = void 0; do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning lastIterationMeaning = meaning; for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var declaration = declarations_10[_i]; @@ -67201,28 +84925,28 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 226) { + else if (node.kind === 227 /* VariableDeclaration */) { var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2); + return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } } else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2); + return !!node.body || ts.hasModifier(node, 2 /* Ambient */); } else { switch (node.kind) { - case 229: - case 199: - case 232: - case 233: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 208) { - ts.Debug.assert(node.parent.kind === 227); + if (node.parent && node.parent.parent && node.parent.parent.kind === 209 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 228 /* VariableDeclarationList */); return node.parent.parent; } } @@ -67232,7 +84956,7 @@ var ts; if (shorthandSymbol) { for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.getMeaningFromDeclaration(declaration) & 1) { + if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) { addReference(declaration); } } @@ -67247,15 +84971,22 @@ var ts; forEachDescendantOfKind(child, kind, action); }); } + /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */ function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9) { + if (node.kind === 9 /* StringLiteral */) { return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); } return false; } + /** + * If we are just looking for implementations and this is a property access expression, we need to get the + * symbol of the local type of the symbol the property is being accessed on. This is because our search + * symbol may have a different parent symbol if the local type's symbol does not declare the property + * being accessed (i.e. it is declared in some parent class or interface) + */ function getParentSymbolsOfPropertyAccess(location, symbol, checker) { var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(location); if (!propertyAccessExpression) { @@ -67265,42 +84996,47 @@ var ts; if (!localParentType) { return undefined; } - if (localParentType.symbol && localParentType.symbol.flags & (32 | 64) && localParentType.symbol !== symbol.parent) { + if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== symbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 196608) { + else if (localParentType.flags & 393216 /* UnionOrIntersection */) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { + /// Triple slash reference comments var comment = findReferenceInPosition(sourceFile.referencedFiles, position); if (comment) { var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); if (referenceFile) { return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; } + // Might still be on jsdoc, so keep looking. } + // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position, true); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } + // Labels if (ts.isJumpStatementTarget(node)) { var labelName = node.text; var label = ts.getTargetLabel(node.parent, labelName); - return label ? [createDefinitionInfoFromName(label, "label", labelName, undefined)] : undefined; + return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -67308,16 +85044,27 @@ var ts; return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; } var symbol = typeChecker.getSymbolAtLocation(node); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { return undefined; } - if (symbol.flags & 2097152 && shouldSkipAlias(node, symbol.declarations[0])) { + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = typeChecker.getAliasedSymbol(symbol); if (aliased.declarations) { symbol = aliased; } } - if (node.parent.kind === 262) { + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 266 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -67328,6 +85075,17 @@ var ts; var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } + // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the + // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern + // and return the property declaration for the referenced property. + // For example: + // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo" + // + // function bar(onfulfilled: (value: T) => void) { //....} + // interface Test { + // pr/*destination*/op1: number + // } + // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(node.parent) && ts.isObjectBindingPattern(node.parent.parent) && (node === (node.parent.propertyName || node.parent.name))) { var type = typeChecker.getTypeAtLocation(node.parent.parent); @@ -67338,6 +85096,15 @@ var ts; } } } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); if (element && typeChecker.getContextualType(element.parent)) { return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { @@ -67347,8 +85114,9 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position, true); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -67360,14 +85128,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 65536 && !(type.flags & 16)) { - var result_7 = []; + if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_7, getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_7; + return result_6; } if (!type.symbol) { return undefined; @@ -67375,19 +85143,42 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (comment) { + return { + definitions: definitions, + textSpan: ts.createTextSpanFromBounds(comment.pos, comment.end) + }; + } + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from an import. + // function shouldSkipAlias(node, declaration) { - if (node.kind !== 71) { + if (node.kind !== 71 /* Identifier */) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { - case 239: - case 237: + case 240 /* ImportClause */: + case 238 /* ImportEqualsDeclaration */: return true; - case 242: - return declaration.parent.kind === 241; + case 243 /* ImportSpecifier */: + return declaration.parent.kind === 242 /* NamedImports */; default: return false; } @@ -67398,18 +85189,22 @@ var ts; var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. ts.forEach(declarations, function (declaration) { result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); }); } return result; function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isNewExpressionTarget(location) || location.kind === 123) { - if (symbol.flags & 32) { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { + if (symbol.flags & 32 /* Class */) { + // Find the first class-like declaration and try to get the construct signature. for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); + return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); } } ts.Debug.fail("Expected declaration to have at least one class-like declaration"); @@ -67419,7 +85214,7 @@ var ts; } function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); + return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); } return false; } @@ -67431,7 +85226,7 @@ var ts; var definition; for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 152 : isSignatureDeclaration(d)) { + if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { declarations.push(d); if (d.body) definition = d; @@ -67446,18 +85241,20 @@ var ts; } function isSignatureDeclaration(node) { switch (node.kind) { - case 152: - case 228: - case 151: - case 150: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return true; default: return false; } } + /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } + /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); return { @@ -67493,12 +85290,13 @@ var ts; return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), - kind: "script", + kind: "script" /* scriptElement */, name: name, containerName: undefined, containerKind: undefined }; } + /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; @@ -67516,14 +85314,17 @@ var ts; return decl; } } + // Don't go to a function type, go to the value having that type. return undefined; } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var JsDoc; (function (JsDoc) { + var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -67543,6 +85344,7 @@ var ts; "fileOverview", "function", "ignore", + "inheritDoc", "inner", "lends", "link", @@ -67568,6 +85370,12 @@ var ts; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; function getJsDocCommentsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once: + // In case of a union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. const a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { ts.forEach(ts.getAllJSDocs(declaration), function (doc) { @@ -67583,18 +85391,46 @@ var ts; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. var tags = []; forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - if (tag.kind === 276) { - tags.push({ name: tag.tagName.text, text: tag.comment }); - } + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 282 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 287 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 286 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 288 /* JSDocTypedefTag */: + case 289 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return node.getText() + " " + comment; + } + function withList(list) { + return list.map(function (x) { return x.getText(); }) + " " + 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++) { @@ -67612,24 +85448,37 @@ var ts; return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: tagName, - kind: "keyword", + kind: "keyword" /* keyword */, kindModifiers: "", sortText: "0", }; })); } JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; function getJSDocTagCompletions() { return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: "@" + tagName, - kind: "keyword", + kind: "keyword" /* keyword */, kindModifiers: "", sortText: "0" }; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; function getJSDocParameterNameCompletions(tag) { if (!ts.isIdentifier(tag.name)) { return ts.emptyArray; @@ -67647,46 +85496,80 @@ var ts; || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { return undefined; } - return { name: name, kind: "parameter", kindModifiers: "", sortText: "0" }; + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; }); } JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Invalid positions are + * - within comments, strings (including template literals and regex), and JSXText + * - within a token + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, false); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - return undefined; + // if climbing the tree did not find a declaration with parameters, complete to a single line comment + return singleLineTemplate; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.getStart() < position) { + if (commentOwner.kind === 10 /* JsxText */) { return undefined; } + if (commentOwner.getStart() < position || parameters.length === 0) { + // if climbing the tree found a declaration with parameters but the request was made inside it + // or if there are no parameters, complete to a single line comment + return singleLineTemplate; + } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; + // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = ""; - if (parameters) { - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; - } - } - } + var docParams = parameters.map(function (_a, i) { + var name = _a.name; + var nameText = ts.isIdentifier(name) ? name.text : "param" + i; + var type = isJavaScriptFile ? "{any} " : ""; + return indentationStr + " * @param " + type + nameText + newLine; + }).join(""); + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + @@ -67699,48 +85582,57 @@ var ts; function getCommentOwnerInfo(tokenAtPos) { for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 228: - case 151: - case 152: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 151 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 229: - return { commentOwner: commentOwner }; - case 208: { + case 209 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return { commentOwner: commentOwner, parameters: parameters_1 }; + return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; } - case 265: + case 269 /* SourceFile */: return undefined; - case 233: - return commentOwner.parent.kind === 233 ? undefined : { commentOwner: commentOwner }; - case 194: { + case 195 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0) { + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { return undefined; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } + case 10 /* JsxText */: { + var parameters_3 = ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_3 }; + } } } } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 185) { + while (rightHandSide.kind === 186 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 186: - case 187: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return rightHandSide.parameters; - case 199: + case 200 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152) { + if (member.kind === 153 /* Constructor */) { return member.parameters; } } @@ -67750,10 +85642,17 @@ var ts; } })(JsDoc = ts.JsDoc || (ts.JsDoc = {})); })(ts || (ts = {})); +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +/// +/// +/* @internal */ var ts; (function (ts) { var JsTyping; (function (JsTyping) { + /* @internal */ JsTyping.nodeCoreModuleList = [ "buffer", "querystring", "events", "http", "cluster", "zlib", "os", "https", "punycode", "repl", "readline", @@ -67776,11 +85675,22 @@ var ts; return undefined; } JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } + // A typing name to typing file path mapping var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); if (ts.hasJavaScriptFileExtension(path)) { @@ -67791,6 +85701,7 @@ var ts; if (typeAcquisition.include) addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); possibleSearchDirs.set(projectRootPath, true); possibleSearchDirs.forEach(function (_true, searchDir) { @@ -67804,15 +85715,18 @@ var ts; getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); }); getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); addInferredTypings(module, "Inferred typings from unresolved imports"); } + // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typingLocation, name) { if (inferredTypings.has(name) && inferredTypings.get(name) === undefined) { inferredTypings.set(name, typingLocation); } }); + // Remove typings that the user has added to the exclude list for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { var excludeTypingName = exclude_1[_i]; var didDelete = inferredTypings.delete(excludeTypingName); @@ -67843,6 +85757,9 @@ var ts; log(message + ": " + JSON.stringify(typingNames)); ts.forEach(typingNames, addInferredTyping); } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ function getTypingNamesFromJson(jsonPath, filesToWatch) { if (!host.fileExists(jsonPath)) { return; @@ -67852,46 +85769,63 @@ var ts; var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { if (!ts.hasJavaScriptFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); }); if (fromFileNames.length) { addInferredTypings(fromFileNames, "Inferred typings from file names"); } - var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx"); }); + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); if (hasJsxFile) { if (log) log("Inferred 'react' typings due to presence of '.jsx' extension"); addInferredTyping("react"); } } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too if (!host.directoryExists(packagesFolderPath)) { return; } - var fileNames = host.readDirectory(packagesFolderPath, [".json"], undefined, undefined, 2); + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); if (log) log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); var packageNames = []; - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; var normalizedFileName = ts.normalizePath(fileName); var baseFileName = ts.getBaseFileName(normalizedFileName); if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_8.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped if (!packageJson.name) { continue; } @@ -67910,8 +85844,69 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + throw ts.Debug.fail(); // Shouldn't have called this. + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var NavigateTo; @@ -67919,18 +85914,19 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_8 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; + // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_6(sourceFile); + _loop_8(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -67940,15 +85936,19 @@ var ts; } NavigateTo.getNavigateToItems = getNavigateToItems; function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); if (!matches) { - return; + return; // continue to next named declarations } for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { var declaration = declarations_11[_i]; if (!shouldKeepItem(declaration, checker)) { continue; } + // It was a match! If the pattern has dots in it, then also see if the + // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { containerMatches = patternMatcher.getMatches(getContainers(declaration), name); @@ -67963,9 +85963,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 239: - case 242: - case 237: + case 240 /* ImportClause */: + case 243 /* ImportSpecifier */: + case 238 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -67975,6 +85975,7 @@ var ts; } function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); + // This is a case sensitive match, only if all the submatches were case sensitive. for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { var match = matches_2[_i]; if (!match.isCaseSensitive) { @@ -67985,22 +85986,26 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { if (declaration) { - var name_64 = ts.getNameOfDeclaration(declaration); - if (name_64) { - var text = ts.getTextOfIdentifierOrLiteral(name_64); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = ts.getTextOfIdentifierOrLiteral(name); if (text !== undefined) { containers.unshift(text); } - else if (name_64.kind === 144) { - return tryAddComputedPropertyName(name_64.expression, containers, true); + else if (name.kind === 145 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); } else { + // Don't know how to add this. return false; } } } return true; } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } function tryAddComputedPropertyName(expression, containers, includeLastPortion) { var text = ts.getTextOfIdentifierOrLiteral(expression); if (text !== undefined) { @@ -68009,23 +86014,26 @@ var ts; } return true; } - if (expression.kind === 179) { + if (expression.kind === 180 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, true); + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } return false; } function getContainers(declaration) { var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144) { - if (!tryAddComputedPropertyName(name.expression, containers, false)) { + if (name.kind === 145 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } + // Now, walk up our containers, adding all their names to the container array. declaration = ts.getContainerNode(declaration); while (declaration) { if (!tryAddSingleDeclarationName(declaration, containers)) { @@ -68048,9 +86056,9 @@ var ts; return bestMatchKind; } function compareNavigateToItems(i1, i2) { - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -68064,21 +86072,44 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { + /** + * Matches all whitespace characters in a string. Eg: + * + * "app. + * + * onactivated" + * + * matches because of the newline, whereas + * + * "app.onactivated" + * + * does not match. + */ var whiteSpaceRegex = /\s+/g; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curCancellationToken; var curSourceFile; + /** + * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + * `parent` is the current parent and is *not* stored in parentsStack. + * `startNode` sets a new parent and `endNode` returns to the previous parent. + */ var parentsStack = []; var parent; + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; function getNavigationBarItems(sourceFile, cancellationToken) { curCancellationToken = cancellationToken; @@ -68147,12 +86178,18 @@ var ts; indent: parent.indent + 1 }; } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ function startNode(node) { var navNode = emptyNavigationBarNode(node); pushChild(parent, navNode); + // Save the old parent parentsStack.push(parent); parent = navNode; } + /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { mergeChildren(parent.children); @@ -68165,15 +86202,18 @@ var ts; addChildrenRecursively(child); endNode(); } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { curCancellationToken.throwIfCancellationRequested(); if (!node || ts.isToken(node)) { return; } switch (node.kind) { - case 152: + case 153 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { var param = _a[_i]; if (ts.isParameterPropertyDeclaration(param)) { @@ -68181,28 +86221,33 @@ var ts; } } break; - case 151: - case 153: - case 154: - case 150: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 151 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 149: - case 148: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 239: + case 240 /* ImportClause */: var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; if (importClause.name) { addLeafNode(importClause); } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 240) { + if (namedBindings.kind === 241 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -68213,17 +86258,19 @@ var ts; } } break; - case 176: - case 226: - var _d = node, name_65 = _d.name, initializer = _d.initializer; - if (ts.isBindingPattern(name_65)) { - addChildrenRecursively(name_65); + case 177 /* BindingElement */: + case 227 /* VariableDeclaration */: + var _d = node, name = _d.name, initializer = _d.initializer; + if (ts.isBindingPattern(name)) { + addChildrenRecursively(name); } else if (initializer && isFunctionOrClassExpression(initializer)) { if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. addChildrenRecursively(initializer); } else { + // Add a node for the VariableDeclaration, but not for the initializer. startNode(node); ts.forEachChild(initializer, addChildrenRecursively); endNode(); @@ -68233,12 +86280,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 187: - case 228: - case 186: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 232: + case 233 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -68248,9 +86295,9 @@ var ts; } endNode(); break; - case 229: - case 199: - case 230: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -68258,22 +86305,39 @@ var ts; } endNode(); break; - case 233: + case 234 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 246: - case 237: - case 157: - case 155: - case 156: - case 231: + case 247 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 158 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 232 /* TypeAliasDeclaration */: addLeafNode(node); break; + case 195 /* BinaryExpression */: { + var special = ts.getSpecialPropertyAssignmentKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + addNodeWithRecursiveChild(node, node.right); + break; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through default: if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283) { + if (tag.kind === 288 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -68282,12 +86346,14 @@ var ts; ts.forEachChild(node, addChildrenRecursively); } } + /** Merge declarations of the same kind. */ function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); var name = declName && nodeText(declName); if (!name) { + // Anonymous items are never merged. return true; } var itemsWithSameName = nameToItems.get(name); @@ -68313,55 +86379,66 @@ var ts; nameToItems.set(name, [itemWithSameName, child]); return true; } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { - merge(a, b); - return true; - } - return false; - } }); - function shouldReallyMerge(a, b) { - return a.kind === b.kind && (a.kind !== 233 || areSameModule(a, b)); - function areSameModule(a, b) { - if (a.body.kind !== b.body.kind) { - return false; - } - if (a.body.kind !== 233) { - return true; - } - return areSameModule(a.body, b.body); - } + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); + return true; } - function merge(target, source) { - target.additionalNodes = target.additionalNodes || []; - target.additionalNodes.push(source.node); - if (source.additionalNodes) { - (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); - } - target.children = ts.concatenate(target.children, source.children); - if (target.children) { - mergeChildren(target.children); - sortChildren(target.children); - } - var _a; + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + if (a.kind !== b.kind) { + return false; + } + switch (a.kind) { + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 234 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; } } - function sortChildren(children) { - children.sort(compareChildren); + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + return a.body.kind === b.body.kind && (a.body.kind !== 234 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } - function compareChildren(child1, child2) { - var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); - if (name1 && name2) { - var cmp = ts.compareStringsCaseInsensitive(name1, name2); - return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); } - else { - return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); } + var _a; + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); } + function compareChildren(child1, child2) { + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); + } + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ function tryGetName(node) { - if (node.kind === 233) { + if (node.kind === 234 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -68369,18 +86446,18 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { - case 186: - case 187: - case 199: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 200 /* ClassExpression */: return getFunctionOrClassName(node); - case 283: + case 288 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 233) { + if (node.kind === 234 /* ModuleDeclaration */) { return getModuleName(node); } var name = ts.getNameOfDeclaration(node); @@ -68391,29 +86468,32 @@ var ts; } } switch (node.kind) { - case 265: + case 269 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 187: - case 228: - case 186: - case 229: - case 199: - if (ts.getModifierFlags(node) & 512) { + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + // We may get a string with newlines or other whitespace in the case of an object dereference + // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the + // navigation bar. return getFunctionOrClassName(node); - case 152: + case 153 /* Constructor */: return "constructor"; - case 156: + case 157 /* ConstructSignature */: return "new()"; - case 155: + case 156 /* CallSignature */: return "()"; - case 157: + case 158 /* IndexSignature */: return "[]"; - case 283: + case 288 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -68425,10 +86505,10 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 208) { + if (parentNode && parentNode.kind === 209 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71) { + if (nameIdentifier.kind === 71 /* Identifier */) { return nameIdentifier.text; } } @@ -68436,6 +86516,7 @@ var ts; return ""; } } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ function topLevelItems(root) { var topLevel = []; function recur(item) { @@ -68453,24 +86534,24 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 229: - case 199: - case 232: - case 230: - case 233: - case 265: - case 231: - case 283: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 232 /* TypeAliasDeclaration */: + case 288 /* JSDocTypedefTag */: return true; - case 152: - case 151: - case 153: - case 154: - case 226: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 227 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 187: - case 228: - case 186: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -68480,10 +86561,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 234: - case 265: - case 151: - case 152: + case 235 /* ModuleBlock */: + case 269 /* SourceFile */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -68492,7 +86573,7 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 226 && childKind !== 176; + return childKind !== 227 /* VariableDeclaration */ && childKind !== 177 /* BindingElement */; }); } } @@ -68541,30 +86622,36 @@ var ts; return spans; } function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); } + // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 233) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 234 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } return result.join("."); } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ function getInteriorModule(decl) { - return decl.body.kind === 233 ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 234 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 144; + return !member.name || member.name.kind === 145 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 265 + return node.kind === 269 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 226) { + if (node.parent && node.parent.kind === 227 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -68573,17 +86660,17 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 226) { + else if (node.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } - else if (node.parent.kind === 194 && - node.parent.operatorToken.kind === 58) { + else if (node.parent.kind === 195 /* BinaryExpression */ && + node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 261 && node.parent.name) { + else if (node.parent.kind === 265 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } - else if (ts.getModifierFlags(node) & 512) { + else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } else { @@ -68592,9 +86679,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 187: - case 186: - case 199: + case 188 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: return true; default: return false; @@ -68602,199 +86689,179 @@ var ts; } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { - var collapseText = "..."; - var maxDepth = 20; - var defaultLabel = "#region"; - var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { - var elements = []; - var depth = 0; + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + sourceFile.forEachChild(function walk(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + n.forEachChild(walk); + depthRemaining++; + }); + } + function addRegionOutliningSpans(sourceFile, out) { var regions = []; - walk(sourceFile); - gatherRegions(); - return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { - if (hintSpanNode && startElement && endElement) { - var span_13 = { - textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), - hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_13); + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?$/); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; } - } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span_14 = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_14); - } - } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var currentComment = comments_3[_i]; - cancellationToken.throwIfCancellationRequested(); - if (currentComment.kind === 2) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; - } - else if (currentComment.kind === 3) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; - } - } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + if (!result[1]) { + var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span_13, span_13, /*autoCollapse*/ false, result[2] || "#region")); } - } - function combineAndAddMultipleSingleLineComments(count, start, end) { - if (count > 1) { - var multipleSingleLineComments = { - kind: 2, - pos: start, - end: end, - }; - addOutliningSpanComments(multipleSingleLineComments, false); - } - } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 187; - } - function gatherRegions() { - var lineStarts = sourceFile.getLineStarts(); - for (var i = 0; i < lineStarts.length; i++) { - var currentLineStart = lineStarts[i]; - var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); - var comment = sourceFile.text.substring(currentLineStart, lineEnd); - var result = comment.match(regionMatch); - if (result && !ts.isInComment(sourceFile, currentLineStart)) { - if (!result[1]) { - var start = sourceFile.getFullText().indexOf("//", currentLineStart); - var textSpan = ts.createTextSpanFromBounds(start, lineEnd); - var region = { - textSpan: textSpan, - hintSpan: textSpan, - bannerText: result[2] || defaultLabel, - autoCollapse: false - }; - regions.push(region); - } - else { - var region = regions.pop(); - if (region) { - region.textSpan.length = lineEnd - region.textSpan.start; - region.hintSpan.length = lineEnd - region.textSpan.start; - elements.push(region); - } - } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); } } } - function walk(n) { + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var _a = comments_3[_i], kind = _a.kind, pos = _a.pos, end = _a.end; cancellationToken.throwIfCancellationRequested(); - if (depth > maxDepth) { - return; - } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); - } - switch (n.kind) { - case 207: - if (!ts.isFunctionBlock(n)) { - var parent_25 = n.parent; - var openBrace_1 = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace_1 = ts.findChildOfKind(n, 18, sourceFile); - if (parent_25.kind === 212 || - parent_25.kind === 215 || - parent_25.kind === 216 || - parent_25.kind === 214 || - parent_25.kind === 211 || - parent_25.kind === 213 || - parent_25.kind === 220 || - parent_25.kind === 260) { - addOutliningSpan(parent_25, openBrace_1, closeBrace_1, autoCollapse(n), true); - break; - } - if (parent_25.kind === 224) { - var tryStatement = parent_25; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_25, openBrace_1, closeBrace_1, autoCollapse(n), true); - break; - } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), true); - break; - } - } - } - var span_15 = ts.createTextSpanFromNode(n); - elements.push({ - textSpan: span_15, - hintSpan: span_15, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); - break; - } - case 234: { - var openBrace_2 = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace_2 = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), true); - break; - } - case 229: - case 230: - case 232: - case 235: { - var openBrace_3 = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace_3 = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), true); - break; - } - case 178: - var openBrace = ts.findChildOfKind(n, 17, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; + } + lastSingleLineCommentEnd = end; + singleLineCommentCount++; break; - case 177: - var openBracket = ts.findChildOfKind(n, 21, sourceFile); - var closeBracket = ts.findChildOfKind(n, 22, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), !ts.isArrayLiteralExpression(n.parent)); + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end)); + singleLineCommentCount = 0; break; + default: + ts.Debug.assertNever(kind); + } + } + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { + // Only outline spans of two or more consecutive single line comments + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + } + } + } + function createOutliningSpanFromBounds(pos, end) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 208 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 188 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 213 /* DoStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 212 /* IfStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 264 /* CatchClause */: + return spanForNode(n.parent); + case 225 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); + } + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); + } + // falls through + default: + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + } + case 235 /* ModuleBlock */: + return spanForNode(n.parent); + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 236 /* CaseBlock */: + return spanForNode(n); + case 179 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 178 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 17 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 17 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; } - depth++; - ts.forEachChild(n, walk); - depth--; + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - OutliningElementsCollector.collectElements = collectElements; + function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. var PatternMatchKind; (function (PatternMatchKind) { PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; @@ -68811,6 +86878,10 @@ var ts; }; } function createPatternMatcher(pattern) { + // We'll often see the same candidate string many times when searching (For example, when + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this + // pattern matcher so we don't have to compute it multiple times. var stringToWordSpans = ts.createMap(); pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); @@ -68820,6 +86891,7 @@ var ts; getMatchesForLastSegmentOfPattern: getMatchesForLastSegmentOfPattern, patternContainsDots: dotSeparatedSegments.length > 1 }; + // Quick checks so we can bail out when asked to match a candidate. function skipMatch(candidate) { return invalidPattern || !candidate; } @@ -68833,24 +86905,36 @@ var ts; if (skipMatch(candidate)) { return undefined; } + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); if (!candidateMatch) { return undefined; } candidateContainers = candidateContainers || []; + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. return undefined; } + // So far so good. Now break up the container for the candidate and check if all + // the dotted parts match up correctly. var totalMatch = candidateMatch; for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); if (!containerMatch) { + // This container didn't match the pattern piece. So there's no match at all. return undefined; } ts.addRange(totalMatch, containerMatch); } + // Success, this symbol's full name matched against the dotted name the user was asking + // about. return totalMatch; } function getWordSpans(word) { @@ -68864,46 +86948,68 @@ var ts; var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); if (index === 0) { if (chunk.text.length === candidate.length) { - return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text); + // a) Check if the part matches the candidate entirely, in an case insensitive or + // sensitive manner. If it does, return that there was an exact match. + return createPatternMatch(PatternMatchKind.exact, punctuationStripped, /*isCaseSensitive:*/ candidate === chunk.text); } else { - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text)); + // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive + // manner. If it does, return that there was a prefix match. + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; if (isLowercase) { if (index > 0) { + // c) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span_16 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_16, chunk.text, true)) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span_16, chunk.text, false)); + var span_14 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, + /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false)); } } } } else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. if (candidate.indexOf(chunk.text) > 0) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, true); + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ true); } } if (!isLowercase) { + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. if (chunk.characterSpans.length > 0) { var candidateParts = getWordSpans(candidate); - var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, false); + var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false); if (camelCaseWeight !== undefined) { - return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, true, camelCaseWeight); + return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight); } - camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, true); + camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true); if (camelCaseWeight !== undefined) { - return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, false, camelCaseWeight); + return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ false, /*camelCaseWeight:*/ camelCaseWeight); } } } if (isLowercase) { + // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.text.length < candidate.length) { if (index > 0 && isUpperCaseLetter(candidate.charCodeAt(index))) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, false); + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ false); } } } @@ -68912,24 +87018,68 @@ var ts; function containsSpaceOrAsterisk(text) { for (var i = 0; i < text.length; i++) { var ch = text.charCodeAt(i); - if (ch === 32 || ch === 42) { + if (ch === 32 /* space */ || ch === 42 /* asterisk */) { return true; } } return false; } function matchSegment(candidate, segment) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) { - var match = matchTextChunk(candidate, segment.totalTextChunk, false); + var match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false); if (match) { return [match]; } } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word matches the candidate entirely, in an case insensitive or + // sensitive manner. If it does, return that there was an exact match. + // + // b) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was a prefix match. + // + // c) If the word is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // f) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.subWordTextChunks; var matches = undefined; for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { var subWordTextChunk = subWordTextChunks_1[_i]; - var result = matchTextChunk(candidate, subWordTextChunk, true); + // Try to match the candidate with this word + var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); if (!result) { return undefined; } @@ -68942,6 +87092,7 @@ var ts; var patternPartStart = patternSpan ? patternSpan.start : 0; var patternPartLength = patternSpan ? patternSpan.length : pattern.length; if (patternPartLength > candidateSpan.length) { + // Pattern part is longer than the candidate part. There can never be a match. return false; } if (ignoreCase) { @@ -68966,29 +87117,45 @@ var ts; } function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; var firstMatch = undefined; var contiguous = undefined; while (true) { + // Let's consider our termination cases if (currentChunkSpan === chunkCharacterSpans.length) { + // We did match! We shall assign a weight to this var weight = 0; + // Was this contiguous? if (contiguous) { weight += 1; } + // Did we start at the beginning of the candidate? if (firstMatch === 0) { weight += 2; } return weight; } else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit return undefined; } var candidatePart = candidateParts[currentCandidate]; var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { break; @@ -68999,12 +87166,20 @@ var ts; } gotOneMatchThisCandidate = true; firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. contiguous = contiguous === undefined ? true : contiguous; candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. if (!gotOneMatchThisCandidate && contiguous !== undefined) { contiguous = false; } + // Move onto the next candidate. currentCandidate++; } } @@ -69016,41 +87191,50 @@ var ts; subWordTextChunks: breakPatternIntoTextChunks(text) }; } + // A segment is considered invalid if we couldn't find any words in it. function segmentIsInvalid(segment) { return segment.subWordTextChunks.length === 0; } function isUpperCaseLetter(ch) { - if (ch >= 65 && ch <= 90) { + // Fast check for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { return false; } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toUpperCase(); } function isLowerCaseLetter(ch) { - if (ch >= 97 && ch <= 122) { + // Fast check for the ascii range. + if (ch >= 97 /* a */ && ch <= 122 /* z */) { return true; } - if (ch < 127 || !ts.isUnicodeIdentifierStart(ch, 5)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { return false; } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function indexOfIgnoringCase(string, value) { - var n = string.length - value.length; + // Assumes 'value' is already lowercase. + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; for (var i = 0; i <= n; i++) { - if (startsWithIgnoringCase(string, value, i)) { + if (startsWithIgnoringCase(str, value, i)) { return i; } } return -1; } - function startsWithIgnoringCase(string, value, start) { + // Assumes 'value' is already lowercase. + function startsWithIgnoringCase(str, value, start) { for (var i = 0; i < value.length; i++) { - var ch1 = toLowerCase(string.charCodeAt(i + start)); + var ch1 = toLowerCase(str.charCodeAt(i + start)); var ch2 = value.charCodeAt(i); if (ch1 !== ch2) { return false; @@ -69059,19 +87243,23 @@ var ts; return true; } function toLowerCase(ch) { - if (ch >= 65 && ch <= 90) { - return 97 + (ch - 65); + // Fast convert for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return 97 /* a */ + (ch - 65 /* A */); } - if (ch < 127) { + if (ch < 127 /* maxAsciiCharacter */) { return ch; } + // TODO: find a way to compute this for any unicode characters in a + // non-allocating manner. return String.fromCharCode(ch).toLowerCase().charCodeAt(0); } function isDigit(ch) { - return ch >= 48 && ch <= 57; + // TODO(cyrusn): Find a way to support this for unicode digits. + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; } function isWordChar(ch) { - return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 || ch === 36; + return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; } function breakPatternIntoTextChunks(pattern) { var result = []; @@ -69106,12 +87294,12 @@ var ts; characterSpans: breakIntoCharacterSpans(text) }; } - function breakIntoCharacterSpans(identifier) { - return breakIntoSpans(identifier, false); + /* @internal */ function breakIntoCharacterSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ false); } ts.breakIntoCharacterSpans = breakIntoCharacterSpans; - function breakIntoWordSpans(identifier) { - return breakIntoSpans(identifier, true); + /* @internal */ function breakIntoWordSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ true); } ts.breakIntoWordSpans = breakIntoWordSpans; function breakIntoSpans(identifier, word) { @@ -69140,29 +87328,29 @@ var ts; } function charIsPunctuation(ch) { switch (ch) { - case 33: - case 34: - case 35: - case 37: - case 38: - case 39: - case 40: - case 41: - case 42: - case 44: - case 45: - case 46: - case 47: - case 58: - case 59: - case 63: - case 64: - case 91: - case 92: - case 93: - case 95: - case 123: - case 125: + case 33 /* exclamation */: + case 34 /* doubleQuote */: + case 35 /* hash */: + case 37 /* percent */: + case 38 /* ampersand */: + case 39 /* singleQuote */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 42 /* asterisk */: + case 44 /* comma */: + case 45 /* minus */: + case 46 /* dot */: + case 47 /* slash */: + case 58 /* colon */: + case 59 /* semicolon */: + case 63 /* question */: + case 64 /* at */: + case 91 /* openBracket */: + case 92 /* backslash */: + case 93 /* closeBracket */: + case 95 /* _ */: + case 123 /* openBrace */: + case 125 /* closeBrace */: return true; } return false; @@ -69170,7 +87358,8 @@ var ts; function isAllPunctuation(identifier, start, end) { for (var i = start; i < end; i++) { var ch = identifier.charCodeAt(i); - if (!charIsPunctuation(ch) || ch === 95 || ch === 36) { + // We don't consider _ or $ as punctuation as there may be things with that name. + if (!charIsPunctuation(ch) || ch === 95 /* _ */ || ch === 36 /* $ */) { return false; } } @@ -69178,11 +87367,25 @@ var ts; } function transitionFromUpperToLower(identifier, word, index, wordStart) { if (word) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. if (index !== wordStart && index + 1 < identifier.length) { var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); if (currentIsUpper && nextIsLower) { + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. for (var i = wordStart; i < index; i++) { if (!isUpperCaseLetter(identifier.charCodeAt(i))) { return false; @@ -69197,6 +87400,19 @@ var ts; function transitionFromLowerToUpper(identifier, word, index) { var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + // See if the casing indicates we're starting a new word. Note: if we're breaking on + // words, then just seeing an upper case character isn't enough. Instead, it has to + // be uppercase and the previous character can't be uppercase. + // + // For example, breaking "AddMetadata" on words would make: Add Metadata + // + // on characters would be: A dd M etadata + // + // Break "AM" on words would be: AM + // + // on characters would be: A M + // + // We break the search string on characters. But we break the symbol name on words. var transition = word ? (currentIsUpper && !lastIsUpper) : currentIsUpper; @@ -69214,13 +87430,15 @@ var ts; var ambientExternalModules; var isNoDefaultLib = false; var braceNesting = 0; + // assume that text represent an external module if it contains at least one top level import/export + // ambient modules that are found inside external modules are interpreted as module augmentations var externalModule = false; function nextToken() { var token = ts.scanner.scan(); - if (token === 17) { + if (token === 17 /* OpenBraceToken */) { braceNesting++; } - else if (token === 18) { + else if (token === 18 /* CloseBraceToken */) { braceNesting--; } return token; @@ -69262,13 +87480,17 @@ var ts; externalModule = true; } } + /** + * Returns true if at least one token was consumed from the stream + */ function tryConsumeDeclare() { var token = ts.scanner.getToken(); - if (token === 124) { + if (token === 124 /* DeclareKeyword */) { + // declare module "mod" token = nextToken(); - if (token === 128) { + if (token === 128 /* ModuleKeyword */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { recordAmbientExternalModule(); } } @@ -69276,67 +87498,81 @@ var ts; } return false; } + /** + * Returns true if at least one token was consumed from the stream + */ function tryConsumeImport() { var token = ts.scanner.getToken(); - if (token === 91) { + if (token === 91 /* ImportKeyword */) { token = nextToken(); - if (token === 19) { + if (token === 19 /* OpenParenToken */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // import("mod"); recordModuleName(); return true; } } - else if (token === 9) { + else if (token === 9 /* StringLiteral */) { + // import "mod"; recordModuleName(); return true; } else { - if (token === 71 || ts.isKeyword(token)) { + if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 140) { + if (token === 141 /* FromKeyword */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // import d from "mod"; recordModuleName(); return true; } } - else if (token === 58) { - if (tryConsumeRequireCall(true)) { + else if (token === 58 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } - else if (token === 26) { + else if (token === 26 /* CommaToken */) { + // consume comma and keep going token = nextToken(); } else { + // unknown syntax return true; } } - if (token === 17) { + if (token === 17 /* OpenBraceToken */) { token = nextToken(); - while (token !== 18 && token !== 1) { + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18) { + if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 140) { + if (token === 141 /* FromKeyword */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" recordModuleName(); } } } } - else if (token === 39) { + else if (token === 39 /* AsteriskToken */) { token = nextToken(); - if (token === 118) { + if (token === 118 /* AsKeyword */) { token = nextToken(); - if (token === 71 || ts.isKeyword(token)) { + if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 140) { + if (token === 141 /* FromKeyword */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" recordModuleName(); } } @@ -69350,39 +87586,44 @@ var ts; } function tryConsumeExport() { var token = ts.scanner.getToken(); - if (token === 84) { + if (token === 84 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); - if (token === 17) { + if (token === 17 /* OpenBraceToken */) { token = nextToken(); - while (token !== 18 && token !== 1) { + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 18 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = nextToken(); } - if (token === 18) { + if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 140) { + if (token === 141 /* FromKeyword */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" recordModuleName(); } } } } - else if (token === 39) { + else if (token === 39 /* AsteriskToken */) { token = nextToken(); - if (token === 140) { + if (token === 141 /* FromKeyword */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // export * from "mod" recordModuleName(); } } } - else if (token === 91) { + else if (token === 91 /* ImportKeyword */) { token = nextToken(); - if (token === 71 || ts.isKeyword(token)) { + if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 58) { - if (tryConsumeRequireCall(true)) { + if (token === 58 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } @@ -69394,11 +87635,12 @@ var ts; } function tryConsumeRequireCall(skipCurrentToken) { var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); - if (token === 132) { + if (token === 132 /* RequireKeyword */) { token = nextToken(); - if (token === 19) { + if (token === 19 /* OpenParenToken */) { token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // require("mod"); recordModuleName(); } } @@ -69408,27 +87650,33 @@ var ts; } function tryConsumeDefine() { var token = ts.scanner.getToken(); - if (token === 71 && ts.scanner.getTokenValue() === "define") { + if (token === 71 /* Identifier */ && ts.scanner.getTokenValue() === "define") { token = nextToken(); - if (token !== 19) { + if (token !== 19 /* OpenParenToken */) { return true; } token = nextToken(); - if (token === 9) { + if (token === 9 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma token = nextToken(); - if (token === 26) { + if (token === 26 /* CommaToken */) { token = nextToken(); } else { + // unexpected token return true; } } - if (token !== 21) { + // should be start of dependency list + if (token !== 21 /* OpenBracketToken */) { return true; } + // skip open bracket token = nextToken(); - while (token !== 22 && token !== 1) { - if (token === 9) { + // scan until ']' or EOF + while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 9 /* StringLiteral */) { recordModuleName(); } token = nextToken(); @@ -69440,14 +87688,27 @@ var ts; function processImports() { ts.scanner.setText(sourceText); nextToken(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // import("mod"); + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + // (for JavaScript files) require("mod") while (true) { - if (ts.scanner.getToken() === 1) { + if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { break; } + // check if at least one of alternative have moved scanner forward if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) { + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { continue; } else { @@ -69461,7 +87722,9 @@ var ts; } processTripleSlashDirectives(); if (externalModule) { + // for external modules module all nested ambient modules are augmentations if (ambientExternalModules) { + // move all detected ambient modules to imported files since they need to be resolved for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) { var decl = ambientExternalModules_1[_i]; importedFiles.push(decl.ref); @@ -69470,6 +87733,7 @@ var ts; return { referencedFiles: referencedFiles, typeReferenceDirectives: typeReferenceDirectives, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined }; } else { + // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 var ambientModuleNames = void 0; if (ambientExternalModules) { for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) { @@ -69490,13 +87754,14 @@ var ts; } ts.preProcessFile = preProcessFile; })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var Rename; (function (Rename) { function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); }); - var node = ts.getTouchingWord(sourceFile, position, true); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); var renameInfo = node && nodeIsEligibleForRename(node) ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) : undefined; @@ -69513,15 +87778,18 @@ var ts; Rename.getRenameInfo = getRenameInfo; function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { var symbol = typeChecker.getSymbolAtLocation(node); + // Only allow a symbol to be renamed if it actually has at least one declaration. if (symbol) { var declarations = symbol.getDeclarations(); if (declarations && declarations.length > 0) { + // Disallow rename for elements that are defined in the standard TypeScript library. if (ts.some(declarations, isDefinedInLibraryFile)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } - if (node.kind === 71 && - node.originalKeywordKind === 79 && - symbol.parent.flags & 1536) { + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (node.kind === 71 /* Identifier */ && + node.originalKeywordKind === 79 /* DefaultKeyword */ && + symbol.parent.flags & 1536 /* Module */) { return undefined; } var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); @@ -69529,12 +87797,12 @@ var ts; return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; } } - else if (node.kind === 9) { + else if (node.kind === 9 /* StringLiteral */) { if (isDefinedInLibraryFile(node)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } var displayName = ts.stripQuotes(node.text); - return getRenameInfoSuccess(displayName, displayName, "var", "", node, sourceFile); + return getRenameInfoSuccess(displayName, displayName, "var" /* variableElement */, "" /* none */, node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -69562,7 +87830,8 @@ var ts; function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); var width = node.getWidth(sourceFile); - if (node.kind === 9) { + if (node.kind === 9 /* StringLiteral */) { + // Exclude the quotes start += 1; width -= 2; } @@ -69570,11 +87839,11 @@ var ts; } function nodeIsEligibleForRename(node) { switch (node.kind) { - case 71: - case 9: - case 99: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 99 /* ThisKeyword */: return true; - case 8: + case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); default: return false; @@ -69582,6 +87851,8 @@ var ts; } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { var SignatureHelp; @@ -69595,19 +87866,24 @@ var ts; })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { var typeChecker = program.getTypeChecker(); + // Decide whether to show signature help var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); if (!startingToken) { + // We are at the beginning of the file return undefined; } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); + // Semantic filtering of signature help var call = argumentInfo.invocation; var candidates = []; var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { + // We didn't have any sig help items produced by the TS compiler. If this is a JS + // file, then see if we can figure out anything better. if (ts.isSourceFileJavaScript(sourceFile)) { return createJavaScriptSignatureHelpItems(argumentInfo, program); } @@ -69617,14 +87893,15 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 181) { + if (argumentInfo.invocation.kind !== 182 /* CallExpression */) { return undefined; } + // See if we can find some symbol with the call expression name that has call signatures. var callExpression = argumentInfo.invocation; var expression = callExpression.expression; - var name = expression.kind === 71 + var name = expression.kind === 71 /* Identifier */ ? expression - : expression.kind === 179 + : expression.kind === 180 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.escapedText) { @@ -69652,23 +87929,49 @@ var ts; } } } + /** + * Returns relevant information for the argument list and the current argument if we are + * in the argument of an invocation; returns undefined otherwise. + */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { if (ts.isCallOrNewExpression(node.parent)) { var invocation = node.parent; var list = void 0; var argumentIndex = void 0; - if (node.kind === 27 || node.kind === 19) { + // There are 3 cases to handle: + // 1. The token introduces a list, and should begin a signature help session + // 2. The token is either not associated with a list, or ends a list, so the session should end + // 3. The token is buried inside a list, and should give signature help + // + // The following are examples of each: + // + // Case 1: + // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session + // Case 2: + // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end + // Case 3: + // foo(a#, #b#) -> The token is buried inside a list, and should give signature help + // Find out if 'node' is an argument, a type argument, or neither + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression list = ts.findContainingList(node); if (!list) return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 : 1; + var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); @@ -69676,24 +87979,27 @@ var ts; var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 && node.parent.kind === 183) { + else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 184 /* TaggedTemplateExpression */) { + // Check if we're actually inside the template; + // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, 0, sourceFile); + return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 && node.parent.parent.kind === 183) { + else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 184 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196); + ts.Debug.assert(templateExpression.kind === 197 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 205 && node.parent.parent.parent.kind === 183) { + else if (node.parent.kind === 206 /* TemplateSpan */ && node.parent.parent.parent.kind === 184 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196); - if (node.kind === 16 && !ts.isInsideTemplateLiteral(node, position)) { + ts.Debug.assert(templateExpression.kind === 197 /* TemplateExpression */); + // If we're just after a template tail, don't show signature help. + if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); @@ -69701,10 +88007,15 @@ var ts; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { + // Provide a signature help for JSX opening element or JSX self-closing element. + // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") + // i.e + // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } + // ' 'b'. So, in this case the arg count will be 2. However, there + // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // 'a' ''. So, in the case where the last child is a comma, we increase the + // arg count by one to compensate. + // + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' + // That will give us 2 non-commas. We then add one for the last comma, giving us an + // arg count of 3. var listChildren = argumentsList.getChildren(); - var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26; }); - if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 26) { + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 26 /* CommaToken */; }); + if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 26 /* CommaToken */) { argumentCount++; } return argumentCount; } + // spanIndex is either the index for a given template span. + // This does not give appropriate results for a NoSubstitutionTemplateLiteral function getArgumentIndexForTemplatePiece(spanIndex, node, position) { + // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. + // There are three cases we can encounter: + // 1. We are precisely in the template literal (argIndex = 0). + // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). + // 3. We are directly to the right of the template literal, but because we look for the token on the left, + // not enough to put us in the substitution expression; we should consider ourselves part of + // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). + // + // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` + // ^ ^ ^ ^ ^ ^ ^ ^ ^ + // Case: 1 1 3 2 1 3 2 2 1 ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -69747,14 +88093,15 @@ var ts; return spanIndex + 1; } function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) { - var argumentCount = tagExpression.template.kind === 13 + // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. + var argumentCount = tagExpression.template.kind === 13 /* NoSubstitutionTemplateLiteral */ ? 1 : tagExpression.template.templateSpans.length + 1; if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } return { - kind: 2, + kind: 2 /* TaggedTemplateArguments */, invocation: tagExpression, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, @@ -69762,27 +88109,46 @@ var ts; }; } function getApplicableSpanForArguments(argumentsList, sourceFile) { + // We use full start and skip trivia on the end because we want to include trivia on + // both sides. For example, + // + // foo( /*comment */ a, b, c /*comment*/ ) + // | | + // + // The applicable span is from the first bar to the second bar (inclusive, + // but not including parentheses) var applicableSpanStart = argumentsList.getFullStart(); - var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), false); + var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) { var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 196) { + // We need to adjust the end position for the case where the template does not have a tail. + // Otherwise, we will not show signature help past the expression. + // For example, + // + // ` ${ 1 + 1 foo(10) + // | | + // + // This is because a Missing node has no width. However, what we actually want is to include trivia + // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. + if (template.kind === 197 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { - applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); + applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 265; n = n.parent) { + for (var n = node; n.kind !== 269 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } + // If the node is not a subspan of its parent, this is a big problem. + // There have been crashes that might be caused by this violation. if (n.pos < n.parent.pos || n.end > n.parent.end) { ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); } @@ -69790,6 +88156,7 @@ var ts; if (argumentInfo) { return argumentInfo; } + // TODO: Handle generic call with incomplete syntax } return undefined; } @@ -69802,10 +88169,10 @@ var ts; } function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; - var isTypeParameterList = argumentListInfo.kind === 0; + var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); - var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, undefined, undefined); + var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -69815,11 +88182,11 @@ var ts; } var isVariadic; if (isTypeParameterList) { - isVariadic = false; - prefixDisplayParts.push(ts.punctuationPart(27)); + isVariadic = false; // type parameter lists are not variadic + prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; - suffixDisplayParts.push(ts.punctuationPart(29)); + suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); }); @@ -69831,9 +88198,9 @@ var ts; return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); }); ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(19)); + prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); - suffixDisplayParts.push(ts.punctuationPart(20)); + suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); @@ -69843,9 +88210,9 @@ var ts; isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(26), ts.spacePart()], + separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(), + documentation: candidateSignature.getDocumentationComment(typeChecker), tags: candidateSignature.getJsDocTags() }; }); @@ -69853,7 +88220,7 @@ var ts; ts.Debug.assertLessThan(argumentIndex, argumentCount); } var selectedItemIndex = candidates.indexOf(resolvedSignature); - ts.Debug.assert(selectedItemIndex !== -1); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { @@ -69861,7 +88228,7 @@ var ts; }); return { name: parameter.name, - documentation: parameter.getDocumentationComment(), + documentation: parameter.getDocumentationComment(typeChecker), displayParts: displayParts, isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) }; @@ -69880,102 +88247,115 @@ var ts; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { + // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - if (flags & 32) { - return ts.getDeclarationOfKind(symbol, 199) ? - "local class" : "class"; - } - if (flags & 384) - return "enum"; - if (flags & 524288) - return "type"; - if (flags & 64) - return "interface"; - if (flags & 262144) - return "type parameter"; + if (flags & 32 /* Class */) { + return ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */) ? + "local class" /* localClassElement */ : "class" /* classElement */; + } + if (flags & 384 /* Enum */) + return "enum" /* enumElement */; + if (flags & 524288 /* TypeAlias */) + return "type" /* typeElement */; + if (flags & 64 /* Interface */) + return "interface" /* interfaceElement */; + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - if (result === "") { - if (flags & 262144) - return "type parameter"; - if (flags & 8) - return "enum member"; - if (flags & 2097152) - return "alias"; - if (flags & 1536) - return "module"; + if (result === "" /* unknown */) { + if (flags & 262144 /* TypeParameter */) + return "type parameter" /* typeParameterElement */; + if (flags & 8 /* EnumMember */) + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; + if (flags & 1536 /* Module */) + return "module" /* moduleElement */; } return result; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { if (typeChecker.isUndefinedSymbol(symbol)) { - return "var"; + return "var" /* variableElement */; } if (typeChecker.isArgumentsSymbol(symbol)) { - return "local var"; + return "local var" /* localVariableElement */; } - if (location.kind === 99 && ts.isExpression(location)) { - return "parameter"; + if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { + return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - if (flags & 3) { + if (flags & 3 /* Variable */) { if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return "parameter"; + return "parameter" /* parameterElement */; } else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return "const"; + return "const" /* constElement */; } else if (ts.forEach(symbol.declarations, ts.isLet)) { - return "let"; - } - return isLocalVariableOrFunction(symbol) ? "local var" : "var"; - } - if (flags & 16) - return isLocalVariableOrFunction(symbol) ? "local function" : "function"; - if (flags & 32768) - return "getter"; - if (flags & 65536) - return "setter"; - if (flags & 8192) - return "method"; - if (flags & 16384) - return "constructor"; - if (flags & 4) { - if (flags & 33554432 && symbol.checkFlags & 6) { + return "let" /* letElement */; + } + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + if (flags & 32768 /* GetAccessor */) + return "getter" /* memberGetAccessorElement */; + if (flags & 65536 /* SetAccessor */) + return "setter" /* memberSetAccessorElement */; + if (flags & 8192 /* Method */) + return "method" /* memberFunctionElement */; + if (flags & 16384 /* Constructor */) + return "constructor" /* constructorImplementationElement */; + if (flags & 4 /* Property */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); - if (rootSymbolFlags & (98308 | 3)) { - return "property"; + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return "property" /* memberVariableElement */; } - ts.Debug.assert(!!(rootSymbolFlags & (8192 | 16))); + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); }); if (!unionPropertyKind) { + // If this was union of all methods, + // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { - return "method"; + return "method" /* memberFunctionElement */; } - return "property"; + return "property" /* memberVariableElement */; } return unionPropertyKind; } - if (location.parent && ts.isJsxAttribute(location.parent)) { - return "JSX attribute"; + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 252 /* JsxOpeningElement */: + return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 257 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; } - return "property"; } - return ""; + return "" /* unknown */; } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) - : ""; + : "" /* none */; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; @@ -69984,20 +88364,24 @@ var ts; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); var hasAddedSymbolInfo; - var isThisExpression = location.kind === 99 && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; - if (symbolKind !== "" || symbolFlags & 32 || symbolFlags & 2097152) { - if (symbolKind === "getter" || symbolKind === "setter") { - symbolKind = "property"; + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 179) { + if (location.parent && location.parent.kind === 180 /* PropertyAccessExpression */) { var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } + // try get the call/construct signature from the type if it matches var callExpressionLike = void 0; if (ts.isCallOrNewExpression(location)) { callExpressionLike = location; @@ -70011,25 +88395,25 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97); + var useConstructSignatures = callExpressionLike.kind === 183 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either signature = allSignatures.length ? allSignatures[0] : undefined; } if (signature) { - if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = "constructor"; + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - else if (symbolFlags & 2097152) { - symbolKind = "alias"; + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94)); + displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } addFullSymbolName(symbol); @@ -70038,136 +88422,152 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } switch (symbolKind) { - case "JSX attribute": - case "property": - case "var": - case "const": - case "let": - case "parameter": - case "local var": - displayParts.push(ts.punctuationPart(56)); + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); + if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } if (useConstructSignatures) { - displayParts.push(ts.keywordPart(94)); + displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); - } - addSignatureDisplayParts(signature, allSignatures, 16); + addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); break; default: + // Just signature addSignatureDisplayParts(signature, allSignatures); } hasAddedSymbolInfo = true; } } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || - (location.kind === 123 && location.parent.kind === 152)) { + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 153 /* Constructor */)) { + // 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) { - return declaration === (location.kind === 123 ? functionDeclaration_1.parent : functionDeclaration_1); + return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 152 ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 153 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 152) { - symbolKind = "constructor"; + if (functionDeclaration_1.kind === 153 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 && - !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 156 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); hasAddedSymbolInfo = true; } } } - if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 199)) { - pushTypePart("local class"); + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushTypePart("local class" /* localClassElement */); } else { - displayParts.push(ts.keywordPart(75)); + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(75 /* ClassKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if ((symbolFlags & 64) && (semanticMeaning & 2)) { + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(109)); + displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288) { + if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(138)); + displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58)); + displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); } - if (symbolFlags & 384) { + if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { - displayParts.push(ts.keywordPart(76)); + displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } - displayParts.push(ts.keywordPart(83)); + displayParts.push(ts.keywordPart(83 /* EnumKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } - if (symbolFlags & 1536) { + if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 233); - var isNamespace = declaration && declaration.name && declaration.name.kind === 71; - displayParts.push(ts.keywordPart(isNamespace ? 129 : 128)); + var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } - if ((symbolFlags & 262144) && (semanticMeaning & 2)) { + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.punctuationPart(19)); + displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); - displayParts.push(ts.punctuationPart(20)); + displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); if (symbol.parent) { + // Class/Interface type parameter addInPrefix(); addFullSymbolName(symbol.parent, enclosingDeclaration); writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var decl = ts.getDeclarationOfKind(symbol, 145); + // Method/function type parameter + var decl = ts.getDeclarationOfKind(symbol, 146 /* TypeParameter */); ts.Debug.assert(decl !== undefined); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 156) { - displayParts.push(ts.keywordPart(94)); + if (declaration.kind === 157 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 155 && declaration.name) { + else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 231) { + else if (declaration.kind === 232 /* TypeAliasDeclaration */) { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path addInPrefix(); - displayParts.push(ts.keywordPart(138)); + displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(declaration.symbol); writeTypeParametersOfSymbol(declaration.symbol, sourceFile); @@ -70175,49 +88575,55 @@ var ts; } } } - if (symbolFlags & 8) { - symbolKind = "enum member"; + if (symbolFlags & 8 /* EnumMember */) { + symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 264) { + if (declaration.kind === 268 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58)); + displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral)); } } } - if (symbolFlags & 2097152) { + if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236) { - displayParts.push(ts.keywordPart(84)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129)); - } - else { - displayParts.push(ts.keywordPart(91)); + switch (symbol.declarations[0].kind) { + case 237 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); + break; + case 244 /* ExportAssignment */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 237) { + if (declaration.kind === 238 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58)); + displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(132)); - displayParts.push(ts.punctuationPart(19)); + displayParts.push(ts.keywordPart(132 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral)); - displayParts.push(ts.punctuationPart(20)); + displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } else { var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(ts.spacePart()); - displayParts.push(ts.operatorPart(58)); + displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); addFullSymbolName(internalAliasSymbol, enclosingDeclaration); } @@ -70227,23 +88633,25 @@ var ts; }); } if (!hasAddedSymbolInfo) { - if (symbolKind !== "") { + if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(99)); + displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); } - if (symbolKind === "property" || - symbolKind === "JSX attribute" || - symbolFlags & 3 || - symbolKind === "local var" || + // For properties, variables and local vars: show the type + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || + symbolFlags & 3 /* Variable */ || + symbolKind === "local var" /* localVariableElement */ || isThisExpression) { - displayParts.push(ts.punctuationPart(56)); + displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); - if (type.symbol && type.symbol.flags & 262144) { + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); }); @@ -70253,12 +88661,12 @@ var ts; ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); } } - else if (symbolFlags & 16 || - symbolFlags & 8192 || - symbolFlags & 16384 || - symbolFlags & 131072 || - symbolFlags & 98304 || - symbolKind === "method") { + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === "method" /* memberFunctionElement */) { var allSignatures = type.getNonNullableType().getCallSignatures(); if (allSignatures.length) { addSignatureDisplayParts(allSignatures[0], allSignatures); @@ -70271,20 +88679,23 @@ var ts; } } if (!documentation) { - documentation = symbol.getDocumentationComment(); + documentation = symbol.getDocumentationComment(typeChecker); tags = symbol.getJsDocTags(); - if (documentation.length === 0 && symbolFlags & 4) { - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 265; })) { + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { + // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` + // there documentation comments might be attached to the right hand side symbol of their declarations. + // The pattern of such special property access is that the parent symbol is the symbol of the file. + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 269 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 194) { + if (!declaration.parent || declaration.parent.kind !== 195 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); if (!rhsSymbol) { continue; } - documentation = rhsSymbol.getDocumentationComment(); + documentation = rhsSymbol.getDocumentationComment(typeChecker); tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; @@ -70301,49 +88712,51 @@ var ts; } function addInPrefix() { displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { addNewLineIfDisplayPartsExist(); if (symbolKind) { pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); + if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } } } function pushTypePart(symbolKind) { switch (symbolKind) { - case "var": - case "function": - case "let": - case "const": - case "constructor": + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: - displayParts.push(ts.punctuationPart(19)); + displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textOrKeywordPart(symbolKind)); - displayParts.push(ts.punctuationPart(20)); + displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); return; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); - displayParts.push(ts.punctuationPart(19)); - displayParts.push(ts.operatorPart(37)); + displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(37 /* PlusToken */)); displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral)); displayParts.push(ts.spacePart()); displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); - displayParts.push(ts.punctuationPart(20)); + displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(); + documentation = signature.getDocumentationComment(typeChecker); tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -70356,20 +88769,24 @@ var ts; SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind; function isLocalVariableOrFunction(symbol) { if (symbol.parent) { - return false; + return false; // This is exported symbol } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 186) { + // Function expressions are local + if (declaration.kind === 187 /* FunctionExpression */) { return true; } - if (declaration.kind !== 226 && declaration.kind !== 228) { + if (declaration.kind !== 227 /* VariableDeclaration */ && declaration.kind !== 229 /* FunctionDeclaration */) { return false; } - for (var parent_26 = declaration.parent; !ts.isFunctionBlock(parent_26); parent_26 = parent_26.parent) { - if (parent_26.kind === 265 || parent_26.kind === 234) { + // If the parent is not sourceFile or module block it is local variable + for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { + // Reached source file or module block + if (parent.kind === 269 /* SourceFile */ || parent.kind === 235 /* ModuleBlock */) { return false; } } + // parent is in function block return true; }); } @@ -70377,13 +88794,27 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true + */ function transpileModule(input, transpileOptions) { var diagnostics = []; var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : ts.getDefaultCompilerOptions(); options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. options.suppressOutputPathCheck = true; + // Filename can be non-ts file. options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. options.noLib = true; + // Clear out other settings that would not be used in transpiling this module options.lib = undefined; options.types = undefined; options.noEmit = undefined; @@ -70394,7 +88825,10 @@ var ts; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. options.noResolve = true; + // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); var sourceFile = ts.createSourceFile(inputFileName, input, options.target); if (transpileOptions.moduleName) { @@ -70404,8 +88838,10 @@ var ts; sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies); } var newLine = ts.getNewLineCharacter(options); + // Output var outputText; var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files var compilerHost = { getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; }, writeFile: function (name, text) { @@ -70430,268 +88866,74 @@ var ts; }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { - ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); - ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); } - program.emit(undefined, undefined, undefined, undefined, transpileOptions.transformers); + // Emit + program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing ts.addRange(diagnostics, output.diagnostics); return output.outputText; } ts.transpile = transpile; var commandLineOptionsStringToEnum; + /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ + /*@internal*/ function fixupCompilerOptions(options, diagnostics) { + // Lazily create this value to fix module loading errors. commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_7 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } var value = options[opt.name]; - if (typeof value === "string") { + // Value should be a key of opt.type + if (ts.isString(value)) { + // If value is not a string, this will fail options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } else { if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) { + // Supplied value isn't a valid enum value. diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } } }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_7(opt); + _loop_9(opt); } return options; } ts.fixupCompilerOptions = fixupCompilerOptions; })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(5, false, 0); - var jsxScanner = ts.createScanner(5, false, 1); - var ScanAction; - (function (ScanAction) { - ScanAction[ScanAction["Scan"] = 0] = "Scan"; - ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; - ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; - ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; - ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; - ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; - })(ScanAction || (ScanAction = {})); - function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { - var scanner = languageVariant === 1 ? jsxScanner : standardScanner; - scanner.setText(text); - scanner.setTextPos(startPos); - var wasNewLine = true; - var leadingTrivia; - var trailingTrivia; - var savedPos; - var lastScanAction; - var lastTokenInfo; - var res = cb({ - advance: advance, - readTokenInfo: readTokenInfo, - isOnToken: isOnToken, - getCurrentLeadingTrivia: function () { return leadingTrivia; }, - lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, - skipToEndOf: skipToEndOf, - }); - lastTokenInfo = undefined; - scanner.setText(undefined); - return res; - function advance() { - lastTokenInfo = undefined; - var isStarted = scanner.getStartPos() !== startPos; - if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4; - } - else { - scanner.scan(); - } - leadingTrivia = undefined; - trailingTrivia = undefined; - var pos = scanner.getStartPos(); - while (pos < endPos) { - var t = scanner.getToken(); - if (!ts.isTrivia(t)) { - break; - } - scanner.scan(); - var item = { - pos: pos, - end: scanner.getStartPos(), - kind: t - }; - pos = scanner.getStartPos(); - leadingTrivia = ts.append(leadingTrivia, item); - } - savedPos = scanner.getStartPos(); - } - function shouldRescanGreaterThanToken(node) { - switch (node.kind) { - case 31: - case 66: - case 67: - case 47: - case 46: - return true; - } - return false; - } - function shouldRescanJsxIdentifier(node) { - if (node.parent) { - switch (node.parent.kind) { - case 253: - case 251: - case 252: - case 250: - return ts.isKeyword(node.kind) || node.kind === 71; - } - } - return false; - } - function shouldRescanJsxText(node) { - return node.kind === 10; - } - function shouldRescanSlashToken(container) { - return container.kind === 12; - } - function shouldRescanTemplateToken(container) { - return container.kind === 15 || - container.kind === 16; - } - function startsWithSlashToken(t) { - return t === 41 || t === 63; - } - function readTokenInfo(n) { - ts.Debug.assert(isOnToken()); - var expectedScanAction = shouldRescanGreaterThanToken(n) - ? 1 - : shouldRescanSlashToken(n) - ? 2 - : shouldRescanTemplateToken(n) - ? 3 - : shouldRescanJsxIdentifier(n) - ? 4 - : shouldRescanJsxText(n) - ? 5 - : 0; - if (lastTokenInfo && expectedScanAction === lastScanAction) { - return fixTokenKind(lastTokenInfo, n); - } - if (scanner.getStartPos() !== savedPos) { - ts.Debug.assert(lastTokenInfo !== undefined); - scanner.setTextPos(savedPos); - scanner.scan(); - } - var currentToken = getNextToken(n, expectedScanAction); - var token = { - pos: scanner.getStartPos(), - end: scanner.getTextPos(), - kind: currentToken - }; - if (trailingTrivia) { - trailingTrivia = undefined; - } - while (scanner.getStartPos() < endPos) { - currentToken = scanner.scan(); - if (!ts.isTrivia(currentToken)) { - break; - } - var trivia = { - pos: scanner.getStartPos(), - end: scanner.getTextPos(), - kind: currentToken - }; - if (!trailingTrivia) { - trailingTrivia = []; - } - trailingTrivia.push(trivia); - if (currentToken === 4) { - scanner.scan(); - break; - } - } - lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; - return fixTokenKind(lastTokenInfo, n); - } - function getNextToken(n, expectedScanAction) { - var token = scanner.getToken(); - lastScanAction = 0; - switch (expectedScanAction) { - case 1: - if (token === 29) { - lastScanAction = 1; - var newToken = scanner.reScanGreaterToken(); - ts.Debug.assert(n.kind === newToken); - return newToken; - } - break; - case 2: - if (startsWithSlashToken(token)) { - lastScanAction = 2; - var newToken = scanner.reScanSlashToken(); - ts.Debug.assert(n.kind === newToken); - return newToken; - } - break; - case 3: - if (token === 18) { - lastScanAction = 3; - return scanner.reScanTemplateToken(); - } - break; - case 4: - lastScanAction = 4; - return scanner.scanJsxIdentifier(); - case 5: - lastScanAction = 5; - return scanner.reScanJsxToken(); - case 0: - break; - default: - ts.Debug.assertNever(expectedScanAction); - } - return token; - } - function isOnToken() { - var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); - var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); - return startPos < endPos && current !== 1 && !ts.isTrivia(current); - } - function fixTokenKind(tokenInfo, container) { - if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { - tokenInfo.token.kind = container.kind; - } - return tokenInfo; - } - function skipToEndOf(node) { - scanner.setTextPos(node.end); - savedPos = scanner.getStartPos(); - lastScanAction = undefined; - lastTokenInfo = undefined; - wasNewLine = false; - leadingTrivia = undefined; - trailingTrivia = undefined; - } - } - formatting.getFormattingScanner = getFormattingScanner; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var FormattingContext = (function () { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { function FormattingContext(sourceFile, formattingRequestKind, options) { this.sourceFile = sourceFile; this.formattingRequestKind = formattingRequestKind; @@ -70708,6 +88950,7 @@ var ts; this.nextTokenSpan = nextRange; this.nextTokenParent = nextTokenParent; this.contextNode = commonParent; + // drop cached results this.contextNodeAllOnSameLine = undefined; this.nextNodeAllOnSameLine = undefined; this.tokensAreOnSameLine = undefined; @@ -70752,8 +88995,8 @@ var ts; return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18, this.sourceFile); + var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); if (openBrace && closeBrace) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; @@ -70766,41 +89009,248 @@ var ts; formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/// +/// +/* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var FormattingRequestKind; - (function (FormattingRequestKind) { - FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; - FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; - FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; - FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; - })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rule = (function () { - function Rule(Descriptor, Operation, Flag) { - if (Flag === void 0) { Flag = 0; } - this.Descriptor = Descriptor; - this.Operation = Operation; - this.Flag = Flag; - } - return Rule; - }()); - formatting.Rule = Rule; + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; + })(ScanAction || (ScanAction = {})); + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + scanner.setText(text); + scanner.setTextPos(startPos); + var wasNewLine = true; + var leadingTrivia; + var trailingTrivia; + var savedPos; + var lastScanAction; + var lastTokenInfo; + var res = cb({ + advance: advance, + readTokenInfo: readTokenInfo, + isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, + lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, + skipToEndOf: skipToEndOf, + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; + function advance() { + lastTokenInfo = undefined; + var isStarted = scanner.getStartPos() !== startPos; + if (isStarted) { + wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + } + else { + scanner.scan(); + } + leadingTrivia = undefined; + trailingTrivia = undefined; + var pos = scanner.getStartPos(); + // Read leading trivia and token + while (pos < endPos) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { + break; + } + // consume leading trivia + scanner.scan(); + var item = { + pos: pos, + end: scanner.getStartPos(), + kind: t + }; + pos = scanner.getStartPos(); + leadingTrivia = ts.append(leadingTrivia, item); + } + savedPos = scanner.getStartPos(); + } + function shouldRescanGreaterThanToken(node) { + switch (node.kind) { + case 31 /* GreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + return true; + } + return false; + } + function shouldRescanJsxIdentifier(node) { + if (node.parent) { + switch (node.parent.kind) { + case 257 /* JsxAttribute */: + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; + } + } + return false; + } + function shouldRescanJsxText(node) { + return node.kind === 10 /* JsxText */; + } + function shouldRescanSlashToken(container) { + return container.kind === 12 /* RegularExpressionLiteral */; + } + function shouldRescanTemplateToken(container) { + return container.kind === 15 /* TemplateMiddle */ || + container.kind === 16 /* TemplateTail */; + } + function startsWithSlashToken(t) { + return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; + } + function readTokenInfo(n) { + ts.Debug.assert(isOnToken()); + // normally scanner returns the smallest available token + // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. + var expectedScanAction = shouldRescanGreaterThanToken(n) + ? 1 /* RescanGreaterThanToken */ + : shouldRescanSlashToken(n) + ? 2 /* RescanSlashToken */ + : shouldRescanTemplateToken(n) + ? 3 /* RescanTemplateToken */ + : shouldRescanJsxIdentifier(n) + ? 4 /* RescanJsxIdentifier */ + : shouldRescanJsxText(n) + ? 5 /* RescanJsxText */ + : 0 /* Scan */; + if (lastTokenInfo && expectedScanAction === lastScanAction) { + // readTokenInfo was called before with the same expected scan action. + // No need to re-scan text, return existing 'lastTokenInfo' + // it is ok to call fixTokenKind here since it does not affect + // what portion of text is consumed. In contrast rescanning can change it, + // i.e. for '>=' when originally scanner eats just one character + // and rescanning forces it to consume more. + return fixTokenKind(lastTokenInfo, n); + } + if (scanner.getStartPos() !== savedPos) { + ts.Debug.assert(lastTokenInfo !== undefined); + // readTokenInfo was called before but scan action differs - rescan text + scanner.setTextPos(savedPos); + scanner.scan(); + } + var currentToken = getNextToken(n, expectedScanAction); + var token = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + // consume trailing trivia + if (trailingTrivia) { + trailingTrivia = undefined; + } + while (scanner.getStartPos() < endPos) { + currentToken = scanner.scan(); + if (!ts.isTrivia(currentToken)) { + break; + } + var trivia = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + if (!trailingTrivia) { + trailingTrivia = []; + } + trailingTrivia.push(trivia); + if (currentToken === 4 /* NewLineTrivia */) { + // move past new line + scanner.scan(); + break; + } + } + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; + return fixTokenKind(lastTokenInfo, n); + } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 29 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 18 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } + function isOnToken() { + var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); + var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); + return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + } + // when containing node in the tree is token + // but its kind differs from the kind that was returned by the scanner, + // then kind needs to be fixed. This might happen in cases + // when parser interprets token differently, i.e keyword treated as identifier + function fixTokenKind(tokenInfo, container) { + if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { + tokenInfo.token.kind = container.kind; + } + return tokenInfo; + } + function skipToEndOf(node) { + scanner.setTextPos(node.end); + savedPos = scanner.getStartPos(); + lastScanAction = undefined; + lastTokenInfo = undefined; + wasNewLine = false; + leadingTrivia = undefined; + trailingTrivia = undefined; + } + } + formatting.getFormattingScanner = getFormattingScanner; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { + formatting.anyContext = ts.emptyArray; var RuleAction; (function (RuleAction) { RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; @@ -70808,42 +89258,6 @@ var ts; RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; RuleAction[RuleAction["Delete"] = 8] = "Delete"; })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleDescriptor = (function () { - function RuleDescriptor(LeftTokenRange, RightTokenRange) { - this.LeftTokenRange = LeftTokenRange; - this.RightTokenRange = RightTokenRange; - } - RuleDescriptor.prototype.toString = function () { - return "[leftRange=" + this.LeftTokenRange + "," + - "rightRange=" + this.RightTokenRange + "]"; - }; - RuleDescriptor.create1 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create2 = function (left, right) { - return RuleDescriptor.create4(left, formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create3 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), right); - }; - RuleDescriptor.create4 = function (left, right) { - return new RuleDescriptor(left, right); - }; - return RuleDescriptor; - }()); - formatting.RuleDescriptor = RuleDescriptor; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { var RuleFlags; (function (RuleFlags) { RuleFlags[RuleFlags["None"] = 0] = "None"; @@ -70851,842 +89265,692 @@ var ts; })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperation = (function () { - function RuleOperation(Context, Action) { - this.Context = Context; - this.Action = Action; + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { + allTokens.push(token); } - RuleOperation.prototype.toString = function () { - return "[context=" + this.Context + "," + - "action=" + this.Action + "]"; - }; - RuleOperation.create1 = function (action) { - return RuleOperation.create2(formatting.RuleOperationContext.Any, action); - }; - RuleOperation.create2 = function (context, action) { - return new RuleOperation(context, action); - }; - return RuleOperation; - }()); - formatting.RuleOperation = RuleOperation; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleOperationContext = (function () { - function RuleOperationContext() { - var funcs = []; - for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i] = arguments[_i]; + function anyTokenExcept(token) { + return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 143 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 143 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]; + var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; + var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; + var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ + // Leave comments alone + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: + // get x() {} + // set x(val) {} + rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 135 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // template string + rule("NoSpaceBetweenTagAndTemplateString", 71 /* Identifier */, [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules + // Use of module as a function call. e.g.: import m2 = module("m2"); + rule("NoSpaceAfterModuleImport", [128 /* ModuleKeyword */, 132 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Add a space around certain TypeScript keywords + rule("SpaceAfterCertainTypeScriptKeywords", [ + 117 /* AbstractKeyword */, + 75 /* ClassKeyword */, + 124 /* DeclareKeyword */, + 79 /* DefaultKeyword */, + 83 /* EnumKeyword */, + 84 /* ExportKeyword */, + 85 /* ExtendsKeyword */, + 125 /* GetKeyword */, + 108 /* ImplementsKeyword */, + 91 /* ImportKeyword */, + 109 /* InterfaceKeyword */, + 128 /* ModuleKeyword */, + 129 /* NamespaceKeyword */, + 112 /* PrivateKeyword */, + 114 /* PublicKeyword */, + 113 /* ProtectedKeyword */, + 131 /* ReadonlyKeyword */, + 135 /* SetKeyword */, + 115 /* StaticKeyword */, + 138 /* TypeKeyword */, + 141 /* FromKeyword */, + 127 /* KeyOfKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 141 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), + // Lambda expressions + rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Optional parameters and let args + rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // Remove spaces in empty interface literals. e.g.: x: {} + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + // decorators + rule("SpaceBeforeAt", anyToken, 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 117 /* AbstractKeyword */, + 71 /* Identifier */, + 84 /* ExportKeyword */, + 79 /* DefaultKeyword */, + 75 /* ClassKeyword */, + 115 /* StaticKeyword */, + 114 /* PublicKeyword */, + 112 /* PrivateKeyword */, + 113 /* ProtectedKeyword */, + 125 /* GetKeyword */, + 135 /* SetKeyword */, + 21 /* OpenBracketToken */, + 39 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), + // Insert space after keywords in control flow statements + rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty parenthesis + rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing nonempty brackets + rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after opening and before closing template string braces + rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space after { and before } in JSX expression + rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); } - this.customContextChecks = funcs; } - RuleOperationContext.prototype.IsAny = function () { - return this === RuleOperationContext.Any; - }; - RuleOperationContext.prototype.InContext = function (context) { - if (this.IsAny()) { + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 215 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 195 /* BinaryExpression */: + case 196 /* ConditionalExpression */: + case 203 /* AsExpression */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 159 /* TypePredicate */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return true; - } - for (var _i = 0, _a = this.customContextChecks; _i < _a.length; _i++) { - var check = _a[_i]; - if (!check(context)) { - return false; - } - } + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 177 /* BindingElement */: + // equals in type X = ... + case 232 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 238 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 227 /* VariableDeclaration */: + // equal in p = 0; + case 147 /* Parameter */: + case 268 /* EnumMember */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 216 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 146 /* TypeParameter */: + return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 217 /* ForOfStatement */: + return context.currentTokenSpan.kind === 143 /* OfKeyword */ || context.nextTokenSpan.kind === 143 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 196 /* ConditionalExpression */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 175 /* ObjectBindingPattern */ || isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). return true; - }; - RuleOperationContext.Any = new RuleOperationContext(); - return RuleOperationContext; - }()); - formatting.RuleOperationContext = RuleOperationContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rules = (function () { - function Rules() { - this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1)); - this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1)); - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromRange(0, 142, [20])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(18, 82), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(18, 106), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.FromTokens([22, 26, 25])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120), 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); - this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71, 3, 75, 84, 91]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20, 3, 81, 102, 87, 82]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(44, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(43, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(37, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(37, 43), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(44, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(38, 38), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38, 44), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104, 100, 94, 80, 96, 103, 121]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 76]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20, 81, 82, 73]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([102, 87]), 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 135]), 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128, 132]), 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117, 75, 124, 79, 83, 84, 85, 125, 108, 91, 109, 128, 129, 112, 114, 113, 131, 135, 115, 138, 140, 127]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85, 108, 140])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(36, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(24, 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.FromTokens([20, 26])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(20, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 29), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.FromTokens([19, 21, 29, 26])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(57, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([117, 71, 84, 79, 75, 115, 114, 112, 113, 125, 135, 21, 39])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(89, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(39, formatting.Shared.TokenRange.FromTokens([71, 19])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(116, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116, 39]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(120, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(120, 89), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(71, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 71), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(41, 29), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8)); - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8)); - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14, 15]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2)); - this.HighPriorityCommonRules = [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, - this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceBeforeArrow, this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator, - this.NoSpaceAfterNewKeywordOnConstructorSignature - ]; - this.UserConfigurableRules = [ - this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, - this.SpaceAfterComma, this.NoSpaceAfterComma, - this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, - this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, - this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, - this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, - this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, - this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, - this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, - this.NewLineBeforeOpenBraceInControl, - this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, - this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion - ]; - this.LowPriorityCommonRules = [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; - if (ts.Debug.isDebugging) { - var o = this; - for (var name_66 in o) { - var rule = o[name_66]; - if (rule instanceof formatting.Rule) { - rule.debugName = name_66; - } - } - } } - Rules.IsOptionEnabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; - }; - Rules.IsOptionDisabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; - }; - Rules.IsOptionDisabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; - }; - Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; - }; - Rules.IsOptionEnabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; - }; - Rules.IsForContext = function (context) { - return context.contextNode.kind === 214; - }; - Rules.IsNotForContext = function (context) { - return !Rules.IsForContext(context); - }; - Rules.IsBinaryOpContext = function (context) { - switch (context.contextNode.kind) { - case 194: - case 195: - case 202: - case 246: - case 242: - case 158: - case 166: - case 167: - return true; - case 176: - case 231: - case 237: - case 226: - case 146: - case 264: - case 149: - case 148: - return context.currentTokenSpan.kind === 58 || context.nextTokenSpan.kind === 58; - case 215: - case 145: - return context.currentTokenSpan.kind === 92 || context.nextTokenSpan.kind === 92; - case 216: - return context.currentTokenSpan.kind === 142 || context.nextTokenSpan.kind === 142; - } - return false; - }; - Rules.IsNotBinaryOpContext = function (context) { - return !Rules.IsBinaryOpContext(context); - }; - Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 195; - }; - Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { - return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); - }; - Rules.IsBraceWrappedContext = function (context) { - return context.contextNode.kind === 174 || Rules.IsSingleLineBlockContext(context); - }; - Rules.IsBeforeMultilineBlockContext = function (context) { - return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); - }; - Rules.IsMultilineBlockContext = function (context) { - return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsSingleLineBlockContext = function (context) { - return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.contextNode); - }; - Rules.IsBeforeBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.nextTokenParent); - }; - Rules.NodeIsBlockContext = function (node) { - if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) { + switch (node.kind) { + case 208 /* Block */: + case 236 /* CaseBlock */: + case 179 /* ObjectLiteralExpression */: + case 235 /* ModuleBlock */: return true; - } - switch (node.kind) { - case 207: - case 235: - case 178: - case 234: - return true; - } - return false; - }; - Rules.IsFunctionDeclContext = function (context) { - switch (context.contextNode.kind) { - case 228: - case 151: - case 150: - case 153: - case 154: - case 155: - case 186: - case 152: - case 187: - case 230: - return true; - } - return false; - }; - Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 228 || context.contextNode.kind === 186; - }; - Rules.IsTypeScriptDeclWithBlockContext = function (context) { - return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); - }; - Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { - switch (node.kind) { - case 229: - case 199: - case 230: - case 232: - case 163: - case 233: - case 244: - case 245: - case 238: - case 241: - return true; - } - return false; - }; - Rules.IsAfterCodeBlockContext = function (context) { - switch (context.currentTokenParent.kind) { - case 229: - case 233: - case 232: - case 260: - case 234: - case 221: + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 156 /* CallSignature */: + case 187 /* FunctionExpression */: + case 153 /* Constructor */: + case 188 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 231 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 229 /* FunctionDeclaration */ || context.contextNode.kind === 187 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 164 /* TypeLiteral */: + case 234 /* ModuleDeclaration */: + case 245 /* ExportDeclaration */: + case 246 /* NamedExports */: + case 239 /* ImportDeclaration */: + case 242 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 230 /* ClassDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 264 /* CatchClause */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + return true; + case 208 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 188 /* ArrowFunction */ && blockParent.kind !== 187 /* FunctionExpression */) { return true; - case 207: { - var blockParent = context.currentTokenParent.parent; - if (!blockParent || blockParent.kind !== 187 && blockParent.kind !== 186) { - return true; - } } } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 221 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 264 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 179 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 182 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 183 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 26 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 188 /* ArrowFunction */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + } + function isNonJsxElementContext(context) { + return context.contextNode.kind !== 250 /* JsxElement */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 260 /* JsxExpression */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 257 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 257 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 251 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 148 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 228 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 234 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 164 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 157 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { return false; - }; - Rules.IsControlDeclContext = function (context) { - switch (context.contextNode.kind) { - case 211: - case 221: - case 214: - case 215: - case 216: - case 213: - case 224: - case 212: - case 220: - case 260: - return true; - default: - return false; - } - }; - Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 178; - }; - Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 181; - }; - Rules.IsNewContext = function (context) { - return context.contextNode.kind === 182; - }; - Rules.IsFunctionCallOrNewContext = function (context) { - return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); - }; - Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 26; - }; - Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 22; - }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 187; - }; - Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; - }; - Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 249; - }; - Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 256; - }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 253; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 253; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 250; - }; - Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { - return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); - }; - Rules.IsEndOfDecoratorContextOnSameLine = function (context) { - return context.TokensAreOnSameLine() && - context.contextNode.decorators && - Rules.NodeIsInDecoratorContext(context.currentTokenParent) && - !Rules.NodeIsInDecoratorContext(context.nextTokenParent); - }; - Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isPartOfExpression(node)) { - node = node.parent; - } - return node.kind === 147; - }; - Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 227 && - context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; - }; - Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind !== 2; - }; - Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 233; - }; - Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 163; - }; - Rules.IsConstructorSignatureContext = function (context) { - return context.contextNode.kind === 156; - }; - Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 27 && token.kind !== 29) { + } + switch (parent.kind) { + case 160 /* TypeReference */: + case 185 /* TypeAssertionExpression */: + case 232 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 202 /* ExpressionWithTypeArguments */: + return true; + default: return false; - } - switch (parent.kind) { - case 159: - case 184: - case 231: - case 229: - case 199: - case 230: - case 228: - case 186: - case 187: - case 151: - case 150: - case 155: - case 156: - case 181: - case 182: - case 201: - return true; - default: - return false; - } - }; - Rules.IsTypeArgumentOrParameterOrAssertionContext = function (context) { - return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || - Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); - }; - Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 184; - }; - Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 105 && context.currentTokenParent.kind === 190; - }; - Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 197 && context.contextNode.expression !== undefined; - }; - Rules.IsNonNullAssertionContext = function (context) { - return context.contextNode.kind === 203; - }; - return Rules; - }()); - formatting.Rules = Rules; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 185 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 191 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 198 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 204 /* NonNullExpression */; + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesMap = (function () { - function RulesMap() { - this.map = []; - this.mapRowLength = 0; - } - RulesMap.create = function (rules) { - var result = new RulesMap(); - result.Initialize(rules); - return result; - }; - RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 142 + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength); - var rulesBucketConstructionStateList = new Array(this.map.length); - this.FillRules(rules, rulesBucketConstructionStateList); - return this.map; - }; - RulesMap.prototype.FillRules = function (rules, rulesBucketConstructionStateList) { - var _this = this; - rules.forEach(function (rule) { - _this.FillRule(rule, rulesBucketConstructionStateList); - }); - }; - RulesMap.prototype.GetRuleBucketIndex = function (row, column) { - ts.Debug.assert(row <= 142 && column <= 142, "Must compute formatting context from tokens"); - var rulesBucketIndex = (row * this.mapRowLength) + column; - return rulesBucketIndex; - }; - RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { - var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); - rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { - rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { - var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); - var rulesBucket = _this.map[rulesBucketIndex]; + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); + }; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; if (rulesBucket === undefined) { - rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); - } - rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); - }); - }); - }; - RulesMap.prototype.GetRule = function (context) { - var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); - var bucket = this.map[bucketIndex]; - if (bucket) { - for (var _i = 0, _a = bucket.Rules(); _i < _a.length; _i++) { - var rule = _a[_i]; - if (rule.Operation.Context.InContext(context)) { - return rule; + rulesBucket = map[index] = []; } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); } } - return undefined; - }; - return RulesMap; - }()); - formatting.RulesMap = RulesMap; - var MaskBitSize = 5; - var Mask = 0x1f; + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 143 /* LastKeyword */ && column <= 143 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 143 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; - RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; - RulesPosition[RulesPosition["ContextRulesSpecific"] = MaskBitSize * 2] = "ContextRulesSpecific"; - RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; - RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; - RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesBucketConstructionState = (function () { - function RulesBucketConstructionState() { - this.rulesInsertionIndexBitmap = 0; - } - RulesBucketConstructionState.prototype.GetInsertionIndex = function (maskPosition) { - var index = 0; - var pos = 0; - var indexBitmap = this.rulesInsertionIndexBitmap; - while (pos <= maskPosition) { - index += (indexBitmap & Mask); - indexBitmap >>= MaskBitSize; - pos += MaskBitSize; - } - return index; - }; - RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { - var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; - value++; - ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); - var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); - temp |= value << maskPosition; - this.rulesInsertionIndexBitmap = temp; - }; - return RulesBucketConstructionState; - }()); - formatting.RulesBucketConstructionState = RulesBucketConstructionState; - var RulesBucket = (function () { - function RulesBucket() { - this.rules = []; - } - RulesBucket.prototype.Rules = function () { - return this.rules; - }; - RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { - var position; - if (rule.Operation.Action === 1) { - position = specificTokens ? - RulesPosition.IgnoreRulesSpecific : - RulesPosition.IgnoreRulesAny; - } - else if (!rule.Operation.Context.IsAny()) { - position = specificTokens ? - RulesPosition.ContextRulesSpecific : - RulesPosition.ContextRulesAny; - } - else { - position = specificTokens ? - RulesPosition.NoContextRulesSpecific : - RulesPosition.NoContextRulesAny; - } - var state = constructionState[rulesBucketIndex]; - if (state === undefined) { - state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); - } - var index = state.GetInsertionIndex(position); - this.rules.splice(index, 0, rule); - state.IncreaseInsertionIndex(position); - }; - return RulesBucket; - }()); - formatting.RulesBucket = RulesBucket; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Shared; - (function (Shared) { - var allTokens = []; - for (var token = 0; token <= 142; token++) { - allTokens.push(token); - } - var TokenValuesAccess = (function () { - function TokenValuesAccess(tokens) { - if (tokens === void 0) { tokens = []; } - this.tokens = tokens; - } - TokenValuesAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenValuesAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - TokenValuesAccess.prototype.isSpecific = function () { return true; }; - return TokenValuesAccess; - }()); - var TokenSingleValueAccess = (function () { - function TokenSingleValueAccess(token) { - this.token = token; - } - TokenSingleValueAccess.prototype.GetTokens = function () { - return [this.token]; - }; - TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue === this.token; - }; - TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; - return TokenSingleValueAccess; - }()); - var TokenAllAccess = (function () { - function TokenAllAccess() { - } - TokenAllAccess.prototype.GetTokens = function () { - return allTokens; - }; - TokenAllAccess.prototype.Contains = function () { - return true; - }; - TokenAllAccess.prototype.toString = function () { - return "[allTokens]"; - }; - TokenAllAccess.prototype.isSpecific = function () { return false; }; - return TokenAllAccess; - }()); - var TokenAllExceptAccess = (function () { - function TokenAllExceptAccess(except) { - this.except = except; - } - TokenAllExceptAccess.prototype.GetTokens = function () { - var _this = this; - return allTokens.filter(function (t) { return t !== _this.except; }); - }; - TokenAllExceptAccess.prototype.Contains = function (token) { - return token !== this.except; - }; - TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; - return TokenAllExceptAccess; - }()); - var TokenRange; - (function (TokenRange) { - function FromToken(token) { - return new TokenSingleValueAccess(token); - } - TokenRange.FromToken = FromToken; - function FromTokens(tokens) { - return new TokenValuesAccess(tokens); - } - TokenRange.FromTokens = FromTokens; - function FromRange(from, to, except) { - if (except === void 0) { except = []; } - var tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - tokens.push(token); - } - } - return new TokenValuesAccess(tokens); - } - TokenRange.FromRange = FromRange; - function AnyExcept(token) { - return new TokenAllExceptAccess(token); - } - TokenRange.AnyExcept = AnyExcept; - TokenRange.Any = new TokenAllAccess(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3])); - TokenRange.Keywords = TokenRange.FromRange(72, 142); - TokenRange.BinaryOperators = TokenRange.FromRange(27, 70); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ - 92, 93, 142, 118, 126 - ]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ - 43, 44, 52, 51 - ]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ - 8, 71, 19, 21, - 17, 99, 94 - ]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ - 71, 19, 99, 94 - ]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ - 71, 20, 22, 94 - ]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ - 71, 19, 99, 94 - ]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ - 71, 20, 22, 94 - ]); - TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([ - 71, 133, 136, 122, - 137, 105, 119 - ]); - })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); - })(Shared = formatting.Shared || (formatting.Shared = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RulesProvider = (function () { - function RulesProvider() { - this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); - this.rulesMap = formatting.RulesMap.create(activeRules); + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; } - RulesProvider.prototype.getRulesMap = function () { - return this.rulesMap; - }; - RulesProvider.prototype.getFormatOptions = function () { - return this.options; - }; - RulesProvider.prototype.ensureUpToDate = function (options) { - if (!this.options || !ts.compareDataObjects(this.options, options)) { - this.options = ts.clone(options); - } - }; - return RulesProvider; - }()); - formatting.RulesProvider = RulesProvider; + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/// +/// +/// +/// +/* @internal */ var ts; (function (ts) { var formatting; @@ -71695,71 +89959,111 @@ var ts; (function (Constants) { Constants[Constants["Unknown"] = -1] = "Unknown"; })(Constants || (Constants = {})); - function formatOnEnter(position, sourceFile, rulesProvider, options) { + function formatOnEnter(position, sourceFile, formatContext) { var line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { return []; } + // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters. + // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as + // trailing whitespaces. So the end of the formatting span should be the later one between: + // 1. the end of the previous line + // 2. the last non-whitespace character in the current line var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile); while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) { endOfFormatSpan--; } + // if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to + // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the + // previous character before the end of format span is line break character as well. if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) { endOfFormatSpan--; } var span = { + // get start position for the previous line pos: ts.getStartPositionOfLine(line - 1, sourceFile), + // end value is exclusive so add 1 to the result end: endOfFormatSpan + 1 }; - return formatSpan(span, sourceFile, options, rulesProvider, 2); + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); } formatting.formatOnEnter = formatOnEnter; - function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3); + function formatOnSemicolon(position, sourceFile, formatContext) { + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; - function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { - var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17, sourceFile); + function formatOnOpeningCurly(position, sourceFile, formatContext) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; } var curlyBraceRange = openingCurly.parent; var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ var textRange = { pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), end: position }; - return formatSpan(textRange, sourceFile, options, rulesProvider, 4); + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); } formatting.formatOnOpeningCurly = formatOnOpeningCurly; - function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5); + function formatOnClosingCurly(position, sourceFile, formatContext) { + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; - function formatDocument(sourceFile, rulesProvider, options) { + function formatDocument(sourceFile, formatContext) { var span = { pos: 0, end: sourceFile.text.length }; - return formatSpan(span, sourceFile, options, rulesProvider, 0); + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); } formatting.formatDocument = formatDocument; - function formatSelection(start, end, sourceFile, rulesProvider, options) { + function formatSelection(start, end, sourceFile, formatContext) { + // format from the beginning of the line var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), end: end, }; - return formatSpan(span, sourceFile, options, rulesProvider, 1); + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); } formatting.formatSelection = formatSelection; + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { var precedingToken = ts.findPrecedingToken(end, sourceFile); return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? precedingToken : undefined; } + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ function findOutermostNodeWithinListLevel(node) { var current = node; while (current && @@ -71770,23 +90074,26 @@ var ts; } return current; } + // Returns true if node is a element in some list in parent + // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 229: - case 230: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 233: + case 234 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 234 && ts.rangeContainsRange(body.statements, node); - case 265: - case 207: - case 234: + return body && body.kind === 235 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 269 /* SourceFile */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 260: + case 264 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; } + /** find node that fully contains given text range */ function findEnclosingNode(range, sourceFile) { return find(sourceFile); function find(n) { @@ -71800,10 +90107,15 @@ var ts; return n; } } + /** formatting is not applied to ranges that contain parse errors. + * This function will return a predicate that for a given text range will tell + * if there are any parse errors that overlap with the range. + */ function prepareRangeContainsErrorFunction(errors, originalRange) { if (!errors.length) { return rangeHasNoErrors; } + // pick only errors that fall in range var sorted = errors .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) .sort(function (e1, e2) { return e1.start - e2.start; }); @@ -71812,15 +90124,20 @@ var ts; } var index = 0; return function (r) { + // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. + // 'index' tracks the index of the most recent error that was checked. while (true) { if (index >= sorted.length) { + // all errors in the range were already checked -> no error in specified range return false; } var error = sorted[index]; if (r.end <= error.start) { + // specified range ends before the error refered by 'index' - no error in range return false; } if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { + // specified range overlaps with error range return true; } index++; @@ -71830,6 +90147,11 @@ var ts; return false; } } + /** + * Start of the original range might fall inside the comment - scanner will not yield appropriate results + * This function will look for token that is located before the start of target range + * and return its end as start position for the scanner. + */ function getScanStartPosition(enclosingNode, originalRange, sourceFile) { var start = enclosingNode.getStart(sourceFile); if (start === originalRange.pos && enclosingNode.end === originalRange.end) { @@ -71837,19 +90159,37 @@ var ts; } var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); if (!precedingToken) { + // no preceding token found - start from the beginning of enclosing node return enclosingNode.pos; } + // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal) + // start from the beginning of enclosingNode to handle the entire 'originalRange' if (precedingToken.end >= originalRange.pos) { return enclosingNode.pos; } return precedingToken.end; } + /* + * For cases like + * if (a || + * b ||$ + * c) {...} + * If we hit Enter at $ we want line ' b ||' to be indented. + * Formatting will be applied to the last two lines. + * Node that fully encloses these lines is binary expression 'a ||...'. + * Initial indentation for this node will be 0. + * Binary expressions don't introduce new indentation scopes, however it is possible + * that some parent node on the same line does - like if statement in this case. + * Note that we are considering parents only from the same line with initial node - + * if parent is on the different line - its delta was already contributed + * to the initial indentation. + */ function getOwnOrInheritedDelta(n, options, sourceFile) { - var previousLine = -1; + var previousLine = -1 /* Unknown */; var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; - if (previousLine !== -1 && line !== previousLine) { + if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { @@ -71861,12 +90201,14 @@ var ts; } return 0; } - function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + /* @internal */ + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); }); + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; - function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + function formatNodeLines(node, sourceFile, formatContext, requestKind) { if (!node) { return []; } @@ -71874,13 +90216,16 @@ var ts; pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), end: node.end }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + return formatSpan(span, sourceFile, formatContext, requestKind); } - function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { + // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } - function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; + // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRange; var previousParent; @@ -71900,15 +90245,23 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); trimTrailingWhitespacesForRemainingRange(); } } return edits; + // local functions + /** Tries to compute the indentation for a list element. + * If list element is not in range then + * function will pick its actual indentation + * so it can be pushed downstream as inherited indentation. + * If list element is in the range - its indentation will be equal + * to inherited indentation from its predecessors. + */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || - ts.rangeContainsStartEnd(range, startPos, endPos)) { - if (inheritedIndentation !== -1) { + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { + if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } } @@ -71917,22 +90270,27 @@ var ts; var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { + // Use the base indent size if it is greater than + // the indentation of the inherited predecessor. var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options); return baseIndentSize > column ? baseIndentSize : column; } } - return -1; + return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { + // if node is located on the same line with the parent + // - inherit indentation from the parent + // - push children if either parent of node itself has non-zero delta indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } - else if (indentation === -1) { + else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { indentation = parentDynamicIndentation.getIndentation(); } @@ -71950,18 +90308,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 229: return 75; - case 230: return 109; - case 228: return 89; - case 232: return 232; - case 153: return 125; - case 154: return 135; - case 151: + case 230 /* ClassDeclaration */: return 75 /* ClassKeyword */; + case 231 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; + case 229 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; + case 233 /* EnumDeclaration */: return 233 /* EnumDeclaration */; + case 154 /* GetAccessor */: return 125 /* GetKeyword */; + case 155 /* SetAccessor */: return 135 /* SetKeyword */; + case 152 /* MethodDeclaration */: if (node.asteriskToken) { - return 39; + return 39 /* AsteriskToken */; } - case 149: - case 146: + // falls through + case 150 /* PropertyDeclaration */: + case 147 /* Parameter */: return ts.getNameOfDeclaration(node).kind; } } @@ -71969,45 +90328,52 @@ var ts; return { getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { - case 18: - case 22: - case 20: + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } + case 18 /* CloseBraceToken */: + case 22 /* CloseBracketToken */: + case 20 /* CloseParenToken */: return indentation + getEffectiveDelta(delta, container); } - return tokenIndentation !== -1 ? tokenIndentation : indentation; + return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { + // if this token is the first token following the list of decorators, we do not need to indent return indentation; } } switch (kind) { - case 17: - case 18: - case 19: - case 20: - case 82: - case 106: - case 57: + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: return indentation; - case 41: - case 29: { - if (container.kind === 251 || - container.kind === 252 || - container.kind === 250) { + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: { + if (container.kind === 252 /* JsxOpeningElement */ || + container.kind === 253 /* JsxClosingElement */ || + container.kind === 251 /* JsxSelfClosingElement */) { return indentation; } break; } - case 21: - case 22: { - if (container.kind !== 172) { + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: { + if (container.kind !== 173 /* MappedType */) { return indentation; } break; } } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; }, getIndentation: function () { return indentation; }, @@ -72030,7 +90396,8 @@ var ts; } }; function getEffectiveDelta(delta, child) { - return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { @@ -72038,12 +90405,26 @@ var ts; return; } var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + // a useful observations when tracking context node + // / + // [a] + // / | \ + // [b] [c] [d] + // node 'a' is a context node for nodes 'b', 'c', 'd' + // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' + // this rule can be applied recursively to child nodes of 'a'. + // + // context node is set to parent node value after processing every child node + // context node is set to parent of the token after processing every token var childContextNode = contextNode; + // if there are any tokens that logically belong to node and interleave child nodes + // such tokens will be consumed in processChildNode for for the child that follows them ts.forEachChild(node, function (child) { - processChildNode(child, -1, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, false); + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); + // proceed any tokens in the node that are located after child nodes while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > node.end) { @@ -72058,13 +90439,15 @@ var ts; if (child.decorators) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } - var childIndentationAmount = -1; - if (isListItem) { + // if child is a list item - try to get its indentation, only if parent is within the original range. + var childIndentationAmount = -1 /* Unknown */; + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); - if (childIndentationAmount !== -1) { + if (childIndentationAmount !== -1 /* Unknown */) { inheritedIndentation = childIndentationAmount; } } + // child node is outside the target range - do not dive inside if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { if (child.end < originalRange.pos) { formattingScanner.skipToEndOf(child); @@ -72075,8 +90458,10 @@ var ts; return inheritedIndentation; } while (formattingScanner.isOnToken()) { + // proceed any parent tokens that are located prior to child.getStart() var tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > childStartPos) { + // stop when formatting scanner advances past the beginning of the child break; } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); @@ -72084,17 +90469,23 @@ var ts; if (!formattingScanner.isOnToken()) { return inheritedIndentation; } - if (ts.isToken(child) && child.kind !== 10) { + // JSX text shouldn't affect indenting + if (ts.isToken(child) && child.kind !== 10 /* JsxText */) { + // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end"); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 147 ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 148 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 10 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } childContextNode = node; - if (isFirstListItem && parent.kind === 177 && inheritedIndentation === -1) { + if (isFirstListItem && parent.kind === 178 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -72105,32 +90496,41 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; - if (listStartToken !== 0) { + if (listStartToken !== 0 /* Unknown */) { + // introduce a new indentation scope for lists (including list start and end tokens) while (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { + // stop when formatting scanner moves past the beginning of node list break; } else if (tokenInfo.token.kind === listStartToken) { + // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1, parent, parentDynamicIndentation, parentStartLine); + var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { + // consume any tokens that precede the list as child elements of 'node' using its indentation scope consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent); } } } - var inheritedIndentation = -1; + var inheritedIndentation = -1 /* Unknown */; for (var i = 0; i < nodes.length; i++) { var child = nodes[i]; - inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, true, i === 0); + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0) { + if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } @@ -72143,24 +90543,24 @@ var ts; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } - var lineAdded; + var lineAction = 0 /* None */; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); + // save previousRange since processRange will overwrite this value with current one var savePreviousRange = previousRange; - lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); - if (rangeHasError) { - indentToken = false; - } - else { - if (lineAdded !== undefined) { - indentToken = lineAdded; - } - else { + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { + // indent token only if end line of previous range does not match start line of the token var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } + else { + indentToken = lineAction === 1 /* LineAdded */; + } } } if (currentTokenInfo.trailingTrivia) { @@ -72169,7 +90569,7 @@ var ts; if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : - -1; + -1 /* Unknown */; var indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); @@ -72177,26 +90577,27 @@ var ts; var triviaItem = _a[_i]; var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem); switch (triviaItem.kind) { - case 3: + case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineComment(triviaItem, commentIndentation, !indentNextTokenOrTrivia); + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; - case 2: + case 2 /* SingleLineCommentTrivia */: if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, false); + insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); } indentNextTokenOrTrivia = false; break; - case 4: + case 4 /* NewLineTrivia */: indentNextTokenOrTrivia = true; break; } } } - if (tokenIndentation !== -1 && indentNextTokenOrTrivia) { - insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + // indent token only if is it is in target range and does not overlap with any error ranges + if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } @@ -72216,54 +90617,64 @@ var ts; } function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); - var lineAdded; + var lineAction = 0 /* None */; if (!rangeHasError) { if (!previousRange) { + // trim whitespaces starting from the beginning of the span up to the current line var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { - lineAdded = + lineAction = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - return lineAdded; + return lineAction; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); - var rule = rulesProvider.getRulesMap().GetRule(formattingContext); + var rule = getRule(formattingContext); var trimTrailingWhitespaces; - var lineAdded; + var lineAction = 0 /* None */; if (rule) { applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.Operation.Action & (2 | 8) && currentStartLine !== previousStartLine) { - lineAdded = false; + if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { + lineAction = 2 /* LineRemoved */; + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(false); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); } } - else if (rule.Operation.Action & 4 && currentStartLine === previousStartLine) { - lineAdded = true; + else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { + lineAction = 1 /* LineAdded */; + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(true); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); } } - trimTrailingWhitespaces = !(rule.Operation.Action & 8) && rule.Flag !== 1; + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; } if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } - return lineAdded; + return lineAction; } function insertIndentation(pos, indentation, lineAdded) { var indentationString = getIndentationString(indentation, options); if (lineAdded) { + // new line is added before the token by the formatting rules + // insert indentation string at the very beginning of the token recordReplace(pos, 0, indentationString); } else { @@ -72277,7 +90688,7 @@ var ts; function characterToColumn(startLinePosition, characterInLine) { var column = 0; for (var i = 0; i < characterInLine; i++) { - if (sourceFile.text.charCodeAt(startLinePosition + i) === 9) { + if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) { column += options.tabSize - column % options.tabSize; } else { @@ -72289,13 +90700,16 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } + // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; var parts; if (startLine === endLine) { if (!firstLineIsIndented) { - insertIndentation(commentRange.pos, indentation, false); + // treat as single line comment + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); } return; } @@ -72307,7 +90721,9 @@ var ts; parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } - parts.push({ pos: startPos, end: commentRange.end }); + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } } var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); @@ -72319,6 +90735,7 @@ var ts; startIndex = 1; startLine++; } + // shift all parts on the delta size var delta = indentation - nonWhitespaceColumnInFirstPart.column; for (var i = startIndex; i < parts.length; i++, startLine++) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); @@ -72339,6 +90756,7 @@ var ts; for (var line = line1; line < line2; line++) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); + // do not trim whitespaces in comments or template expression if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } @@ -72349,6 +90767,10 @@ var ts; } } } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ function getTrailingWhitespaceStartPosition(start, end) { var pos = end; while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) { @@ -72359,6 +90781,9 @@ var ts; } return -1; } + /** + * Trimming will be done for lines after the previous range + */ function trimTrailingWhitespacesForRemainingRange() { var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; @@ -72379,37 +90804,54 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - switch (rule.Operation.Action) { - case 1: + switch (rule.action) { + case 1 /* Ignore */: + // no action required return; - case 8: + case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { + // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); } break; - case 4: - if (rule.Flag !== 1 && previousStartLine !== currentStartLine) { + case 4 /* NewLine */: + // exit early if we on different lines and rule cannot change number of newlines + // if line1 and line2 are on subsequent lines then no edits are required - ok to exit + // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } + // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; - case 2: - if (rule.Flag !== 1 && previousStartLine !== currentStartLine) { + case 2 /* Space */: + // exit early if we on different lines and rule cannot change number of newlines + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } var posDelta = currentRange.pos - previousRange.end; - if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32) { + if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); } break; } } } - function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, false); } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); + /** + * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. + */ + function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition, predicate) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { return undefined; @@ -72417,6 +90859,8 @@ var ts; if (precedingToken === undefined) { precedingToken = ts.findPrecedingToken(position, sourceFile); } + // Between two consecutive tokens, all comments are either trailing on the former + // or leading on the latter (and none are in both lists). var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ? @@ -72425,9 +90869,22 @@ var ts; if (commentRanges) { for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) { var range = commentRanges_1[_i]; + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // if ((range.pos < position && position < range.end || - position === range.end && (range.kind === 2 || position === sourceFile.getFullWidth()))) { - return (range.kind === 3 || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()))) { + return (range.kind === 3 /* MultiLineCommentTrivia */ || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; } } } @@ -72436,48 +90893,49 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 152: - case 228: - case 186: - case 151: - case 150: - case 187: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 188 /* ArrowFunction */: if (node.typeParameters === list) { - return 27; + return 27 /* LessThanToken */; } else if (node.parameters === list) { - return 19; + return 19 /* OpenParenToken */; } break; - case 181: - case 182: + case 182 /* CallExpression */: + case 183 /* NewExpression */: if (node.typeArguments === list) { - return 27; + return 27 /* LessThanToken */; } else if (node.arguments === list) { - return 19; + return 19 /* OpenParenToken */; } break; - case 159: + case 160 /* TypeReference */: if (node.typeArguments === list) { - return 27; + return 27 /* LessThanToken */; } } - return 0; + return 0 /* Unknown */; } function getCloseTokenForOpenToken(kind) { switch (kind) { - case 19: - return 20; - case 27: - return 29; + case 19 /* OpenParenToken */: + return 20 /* CloseParenToken */; + case 27 /* LessThanToken */: + return 29 /* GreaterThanToken */; } - return 0; + return 0 /* Unknown */; } var internedSizes; var internedTabsIndentation; var internedSpacesIndentation; function getIndentationString(indentation, options) { + // reset interned strings if FormatCodeOptions were changed var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; @@ -72525,6 +90983,7 @@ var ts; formatting.getIndentationString = getIndentationString; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var formatting; @@ -72535,102 +90994,134 @@ var ts; (function (Value) { Value[Value["Unknown"] = -1] = "Unknown"; })(Value || (Value = {})); + /** + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` + * function f() { + * |} + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. + */ function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } if (position > sourceFile.text.length) { - return getBaseIndentation(options); + return getBaseIndentation(options); // past EOF } + // no indentation when the indent style is set to none, + // so we can return fast if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); - var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, true, precedingToken || null); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword if (enclosingCommentRange) { - var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; - var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; - ts.Debug.assert(commentStartLine >= 0); - if (previousLine <= commentStartLine) { - return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); - } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; - if (column === 0) { - return column; - } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); - return firstNonWhitespaceCharacterCode === 42 ? column - 1 : column; + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { return getBaseIndentation(options); } + // no indentation in string \regex\template literals var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + // indentation is first non-whitespace character in a previous line + // for block indentation, we should look for a line which contains something that's not + // whitespace. if (options.indentStyle === ts.IndentStyle.Block) { - var current_1 = position; - while (current_1 > 0) { - var char = sourceFile.text.charCodeAt(current_1); - if (!ts.isWhiteSpaceLike(char)) { - break; - } - current_1--; - } - var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); - return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); + return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 && precedingToken.parent.kind !== 194) { + if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 195 /* BinaryExpression */) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); - if (actualIndentation !== -1) { + if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { + // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' + // if such node is found - compute initial indentation for 'position' inside this node var previous; var current = precedingToken; - var currentStart; - var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { - currentStart = getStartLineAndCharacterForNode(current, sourceFile); + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); - if (nextTokenKind !== 0) { - indentationDelta = assumeNewLineBeforeCloseBrace && nextTokenKind === 2 ? options.indentSize : 0; - } - else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; - } - break; + var indentationDelta = nextTokenKind !== 0 /* Unknown */ + // handle cases when codefix is about to be inserted before the close brace + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); } + // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== -1) { + if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== -1) { + if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + options.indentSize; } previous = current; current = current.parent; } - if (!current) { - return getBaseIndentation(options); - } - return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); } - SmartIndenter.getIndentation = getIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); - return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; function getBaseIndentation(options) { return options.baseIndentSize || 0; } SmartIndenter.getBaseIndentation = getBaseIndentation; - function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { var parent = current.parent; - var parentStart; + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. while (parent) { var useActualIndentation = true; if (ignoreActualIndentationRange) { @@ -72638,54 +91129,75 @@ var ts; useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } if (useActualIndentation) { + // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); - if (actualIndentation !== -1) { + if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } } - parentStart = getParentStart(parent, current, sourceFile); - var parentAndChildShareLine = parentStart.line === currentStart.line || + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { + // try to fetch actual indentation for current node from source text var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); - if (actualIndentation !== -1) { + if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); - if (actualIndentation !== -1) { + if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } } - if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { + // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line + if (shouldIndentChildNode(parent, current, isNextChild) && !parentAndChildShareLine) { indentationDelta += options.indentSize; } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); current = parent; - currentStart = parentStart; parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; } return indentationDelta + getBaseIndentation(options); } - function getParentStart(parent, child, sourceFile) { + function getContainingListOrParentStart(parent, child, sourceFile) { var containingList = getContainingList(child, sourceFile); - if (containingList) { - return sourceFile.getLineAndCharacterOfPosition(containingList.pos); - } - return sourceFile.getLineAndCharacterOfPosition(parent.getStart(sourceFile)); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); } + /* + * Function returns Value.Unknown if indentation cannot be determined + */ function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var commaItemInfo = ts.findListItemInfo(commaToken); if (commaItemInfo && commaItemInfo.listItemIndex > 0) { return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); } else { - return -1; + // handle broken code gracefully + return -1 /* Unknown */; } } + /* + * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) + */ function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { + // actual indentation is used for statements\declarations if one of cases below is true: + // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually + // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 265 || !parentAndChildShareLine); + (parent.kind === 269 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { - return -1; + return -1 /* Unknown */; } return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); } @@ -72698,23 +91210,41 @@ var ts; function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { var nextToken = ts.findNextToken(precedingToken, current); if (!nextToken) { - return 0; - } - if (nextToken.kind === 17) { - return 1; - } - else if (nextToken.kind === 18) { + return 0 /* Unknown */; + } + if (nextToken.kind === 17 /* OpenBraceToken */) { + // open braces are always indented at the parent level + return 1 /* OpenBrace */; + } + else if (nextToken.kind === 18 /* CloseBraceToken */) { + // close braces are indented at the parent level if they are located on the same line with cursor + // this means that if new line will be added at $ position, this case will be indented + // class A { + // $ + // } + /// and this one - not + // class A { + // $} var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; - return lineAtPosition === nextTokenStartLine ? 2 : 0; + return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */; } - return 0; + return 0 /* Unknown */; } function getStartLineAndCharacterForNode(n, sourceFile) { return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 211 && parent.elseStatement === child) { - var elseKeyword = ts.findChildOfKind(parent, 82, sourceFile); + if (parent.kind === 212 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; @@ -72728,37 +91258,37 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 159: + case 160 /* TypeReference */: return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); - case 178: + case 179 /* ObjectLiteralExpression */: return node.parent.properties; - case 177: + case 178 /* ArrayLiteralExpression */: return node.parent.elements; - case 228: - case 186: - case 187: - case 151: - case 150: - case 155: - case 152: - case 161: - case 156: { + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 153 /* Constructor */: + case 162 /* ConstructorType */: + case 157 /* ConstructSignature */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); } - case 229: + case 230 /* ClassDeclaration */: return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); - case 182: - case 181: { + case 183 /* NewExpression */: + case 182 /* CallExpression */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); } - case 227: + case 228 /* VariableDeclarationList */: return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); - case 241: - case 245: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); } } @@ -72767,37 +91297,39 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1; + return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; function getActualIndentationFromList(list) { var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1; + return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; } } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { - if (node.kind === 20) { - return -1; + // actual indentation should not be used when: + // - node is close parenthesis - this is the end of the expression + if (node.kind === 20 /* CloseParenToken */) { + return -1 /* Unknown */; } if (node.parent && ts.isCallOrNewExpression(node.parent) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { - return -1; + return -1 /* Unknown */; } var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { - return -1; + return -1 /* Unknown */; } return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); } - return -1; + return -1 /* Unknown */; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 181: - case 182: - case 179: - case 180: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: node = node.expression; break; default: @@ -72809,23 +91341,33 @@ var ts; function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; + // walk toward the start of the list starting from current node and check if the line is the same for all items. + // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); for (var i = index - 1; i >= 0; i--) { - if (list[i].kind === 26) { + if (list[i].kind === 26 /* CommaToken */) { continue; } + // skip list items that ends on the same line with the current list element var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; if (prevEndLine !== lineAndCharacter.line) { return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); } lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); } - return -1; + return -1 /* Unknown */; } function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); } + /** + * Character is the actual index of the character since the beginning of the line. + * Column - position of the character after expanding tabs to spaces. + * "0\t2$" + * value of 'character' for '$' is 3 + * value of 'column' for '$' is 6 (assuming that tab size is 4) + */ function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; @@ -72834,7 +91376,7 @@ var ts; if (!ts.isWhiteSpaceSingleLine(ch)) { break; } - if (ch === 9) { + if (ch === 9 /* tab */) { column += options.tabSize + (column % options.tabSize); } else { @@ -72851,111 +91393,153 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 210: - case 229: - case 199: - case 230: - case 232: - case 231: - case 177: - case 207: - case 234: - case 178: - case 163: - case 172: - case 165: - case 235: - case 258: - case 257: - case 185: - case 179: - case 181: - case 182: - case 208: - case 226: - case 243: - case 219: - case 195: - case 175: - case 174: - case 251: - case 250: - case 256: - case 150: - case 155: - case 156: - case 146: - case 160: - case 161: - case 168: - case 183: - case 191: - case 245: - case 241: - case 246: - case 242: - case 261: - case 149: + case 211 /* ExpressionStatement */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 178 /* ArrayLiteralExpression */: + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 179 /* ObjectLiteralExpression */: + case 164 /* TypeLiteral */: + case 173 /* MappedType */: + case 166 /* TupleType */: + case 236 /* CaseBlock */: + case 262 /* DefaultClause */: + case 261 /* CaseClause */: + case 186 /* ParenthesizedExpression */: + case 180 /* PropertyAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 209 /* VariableStatement */: + case 227 /* VariableDeclaration */: + case 244 /* ExportAssignment */: + case 220 /* ReturnStatement */: + case 196 /* ConditionalExpression */: + case 176 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 260 /* JsxExpression */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 147 /* Parameter */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 169 /* ParenthesizedType */: + case 184 /* TaggedTemplateExpression */: + case 192 /* AwaitExpression */: + case 246 /* NamedExports */: + case 242 /* NamedImports */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: return true; } return false; } function nodeWillIndentChild(parent, child, indentByDefault) { - var childKind = child ? child.kind : 0; + var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 212: - case 213: - case 215: - case 216: - case 214: - case 211: - case 228: - case 186: - case 151: - case 187: - case 152: - case 153: - case 154: - return childKind !== 207; - case 244: - return childKind !== 245; - case 238: - return childKind !== 239 || - (child.namedBindings && child.namedBindings.kind !== 241); - case 249: - return childKind !== 252; - } + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 212 /* IfStatement */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 188 /* ArrowFunction */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return childKind !== 208 /* Block */; + case 245 /* ExportDeclaration */: + return childKind !== 246 /* NamedExports */; + case 239 /* ImportDeclaration */: + return childKind !== 240 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 242 /* NamedImports */); + case 250 /* JsxElement */: + return childKind !== 253 /* JsxClosingElement */; + } + // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; } SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; - function shouldIndentChildNode(parent, child) { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: + switch (parent.kind) { + case 208 /* Block */: + var grandParent = parent.parent; + switch (grandParent && grandParent.kind) { + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + // We may want to write inner functions after this. + return false; + default: + return true; + } + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 269 /* SourceFile */: + case 235 /* ModuleBlock */: + return true; + default: + throw ts.Debug.fail(); + } + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: + return true; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(parent, child, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false)) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var textChanges; (function (textChanges) { + /** + * Currently for simplicity we store recovered positions on the node itself. + * It can be changed to side-table later if we decide that current design is too invasive. + */ function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -72963,7 +91547,7 @@ var ts; Position[Position["Start"] = 1] = "Start"; })(Position = textChanges.Position || (textChanges.Position = {})); function skipWhitespacesAndLineBreaks(text, start) { - return ts.skipTrivia(text, start, false, true); + return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } function hasCommentsBeforeLineBreak(text, start) { var i = start; @@ -72973,7 +91557,7 @@ var ts; i++; continue; } - return ch === 47; + return ch === 47 /* slash */; } return false; } @@ -72999,10 +91583,20 @@ var ts; var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile); var startLine = ts.getLineStartPositionForPosition(start, sourceFile); if (startLine === fullStartLine) { + // full start and start of the node are on the same line + // a, b; + // ^ ^ + // | start + // fullstart + // when b is replaced - we usually want to keep the leading trvia + // when b is deleted - we delete it return position === Position.Start ? start : fullStart; } + // get start position of the line following the line that contains fullstart position + // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); + // skip whitespaces/newlines adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } @@ -73012,14 +91606,17 @@ var ts; return node.getEnd(); } var end = node.getEnd(); - var newEnd = ts.skipTrivia(sourceFile.text, end, true); + var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd : end; } textChanges.getAdjustedEndPosition = getAdjustedEndPosition; + /** + * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element + */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 || (candidate.kind === 25 && node.parent.kind === 178)); + return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 179 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -73028,16 +91625,21 @@ var ts; } return s; } - var ChangeTracker = (function () { - function ChangeTracker(newLine, rulesProvider, validator) { + var ChangeTracker = /** @class */ (function () { + function ChangeTracker(newLine, formatContext, validator) { this.newLine = newLine; - this.rulesProvider = rulesProvider; + this.formatContext = formatContext; this.validator = validator; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -73072,16 +91674,19 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); + // find first non-whitespace position in the leading trivia of the node + var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); var nextElement = containingList[index + 1]; - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), false, true); + /// find first non-whitespace position in the leading trivia of the next node + var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -73156,22 +91761,29 @@ var ts; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } if ((ts.isStatementButNotDeclaration(after)) || - after.kind === 149 || - after.kind === 148 || - after.kind === 150) { - if (sourceFile.text.charCodeAt(after.end - 1) !== 59) { + after.kind === 150 /* PropertyDeclaration */ || + after.kind === 149 /* PropertySignature */ || + after.kind === 151 /* MethodSignature */) { + // check if previous statement ends with semicolon + // if not - insert semicolon to preserve the code from changing the meaning due to ASI + if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: {}, range: { pos: after.end, end: after.end }, - node: ts.createToken(25) + node: ts.createToken(25 /* SemicolonToken */) }); } } var endPosition = getAdjustedEndPosition(sourceFile, after, options); return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); }; + /** + * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, + * i.e. arguments in arguments lists, parameters in parameter lists etc. + * Note that separators are part of the node in statements and class elements. + */ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); if (!containingList) { @@ -73184,17 +91796,50 @@ var ts; } var end = after.getEnd(); if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, after.end, false); + // any element except the last one + // use next sibling as an anchor + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { + // for list + // a, b, c + // create change for adding 'e' after 'a' as + // - find start of next element after a (it is b) + // - use this start as start and end position in final change + // - build text of change by formatting the text of node + separator + whitespace trivia of b + // in multiline case it will work as + // a, + // b, + // c, + // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') + // a,* + // ***insertedtext# + // ###b, + // c, + // find line and character of the next element var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); + // find line and character of the token that precedes next element (usually it is separator) var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); var prefix = void 0; var startPos = void 0; if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { + // next element is located on the same line with separator: + // a,$$$$b + // ^ ^ + // | |-next element + // |-separator + // where $$$ is some leading trivia + // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces + // a, x,$$$$b + // ^ ^ ^ + // | | |-next element + // | |-new inserted node padded with spaces + // |-separator startPos = nextToken.end; prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); } else { + // next element is located on different line that separator + // let insert position be the beginning of the line that contains next element startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); } this.changes.push({ @@ -73204,6 +91849,7 @@ var ts; node: newNode, options: { prefix: prefix, + // write separator and leading trivia of the next element as suffix suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)) } }); @@ -73214,19 +91860,30 @@ var ts; var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile); var separator = void 0; var multilineList = false; + // insert element after the last element in the list that has more than one item + // pick the element preceding the after element to: + // - pick the separator + // - determine if list is a multiline if (containingList.length === 1) { - separator = 26; + // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise + // i.e. var x = 1 // this is x + // | new element will be inserted at this position + separator = 26 /* CommaToken */; } else { + // element has more than one element, pick separator from the list var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile); - separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26; + separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 26 /* CommaToken */; + // determine if list is multiline by checking lines of after element and element that precedes it. var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile); multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition; } if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) { + // in this case we'll always treat containing list as multiline multilineList = true; } if (multilineList) { + // insert separator immediately following the 'after' node to preserve comments in trailing trivia this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, @@ -73234,8 +91891,10 @@ var ts; node: ts.createToken(separator), options: {} }); - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.rulesProvider.getFormatOptions()); - var insertPos = ts.skipTrivia(sourceFile.text, end, true, false); + // use the same indentation as 'after' item + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); + // insert element before the line break on the line that contains 'after' element + var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } @@ -73262,6 +91921,7 @@ var ts; ChangeTracker.prototype.getChanges = function () { var _this = this; var changesPerFile = ts.createMap(); + // group changes per file for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { var c = _a[_i]; var changesInFile = changesPerFile.get(c.sourceFile.path); @@ -73270,6 +91930,7 @@ var ts; } changesInFile.push(c); } + // convert changes var fileChangesList = []; changesPerFile.forEach(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; @@ -73291,6 +91952,7 @@ var ts; ChangeTracker.prototype.computeNewText = function (change, sourceFile) { var _this = this; if (change.kind === ChangeKind.Remove) { + // deletion case return ""; } var options = change.options || {}; @@ -73305,6 +91967,7 @@ var ts; ts.Debug.assert(change.kind === ChangeKind.ReplaceWithSingleNode, "change.kind === ReplaceWithSingleNode"); text = this.getFormattedTextOfNode(change.node, sourceFile, pos, options); } + // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line text = (posStartsLine || options.indentation !== undefined) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + text + (options.suffix || ""); }; @@ -73313,7 +91976,7 @@ var ts; if (this.validator) { this.validator(nonformattedText); } - var formatOptions = this.rulesProvider.getFormatOptions(); + var formatOptions = this.formatContext.options; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; var initialIndentation = options.indentation !== undefined ? options.indentation @@ -73325,10 +91988,12 @@ var ts; : ts.formatting.SmartIndenter.shouldIndentChildNode(node) ? (formatOptions.indentSize || 0) : 0; - return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext); }; ChangeTracker.normalize = function (changes) { + // order changes by start position var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; }); + // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 2; i++) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos); } @@ -73341,17 +92006,17 @@ var ts; var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); - printer.writeNode(4, node, sourceFile, writer); + printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { + function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { text: nonFormattedText.text, lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(nonFormattedText.text, changes); } function applyChanges(text, changes) { @@ -73367,6 +92032,7 @@ var ts; } function assignPositionsToNode(node) { var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); newNode.end = getEnd(node); @@ -73377,12 +92043,13 @@ var ts; if (!visited) { return visited; } + // clone nodearray if necessary var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited; nodeArray.pos = getPos(nodes); nodeArray.end = getEnd(nodes); return nodeArray; } - var Writer = (function () { + var Writer = /** @class */ (function () { function Writer(newLine) { var _this = this; this.lastNonTriviaPosition = 0; @@ -73424,12 +92091,13 @@ var ts; while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) { i++; } + // trim trailing whitespaces this.lastNonTriviaPosition -= i; } }; Writer.prototype.write = function (s) { this.writer.write(s); - this.setLastNonTriviaPosition(s, false); + this.setLastNonTriviaPosition(s, /*force*/ false); }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); @@ -73448,11 +92116,11 @@ var ts; }; Writer.prototype.rawWrite = function (s) { this.writer.rawWrite(s); - this.setLastNonTriviaPosition(s, false); + this.setLastNonTriviaPosition(s, /*force*/ false); }; Writer.prototype.writeLiteral = function (s) { this.writer.writeLiteral(s); - this.setLastNonTriviaPosition(s, true); + this.setLastNonTriviaPosition(s, /*force*/ true); }; Writer.prototype.getTextPos = function () { return this.writer.getTextPos(); @@ -73477,6 +92145,7 @@ var ts; }()); })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73519,10 +92188,13 @@ var ts; codefix.getFixes = getFixes; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var refactor; (function (refactor_1) { + // A map with the refactor code as key, the refactor itself as value + // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); function registerRefactor(refactor) { refactors.set(refactor.name, refactor); @@ -73530,7 +92202,7 @@ var ts; refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { return ts.flatMapIter(refactors.values(), function (refactor) { - return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); }); } refactor_1.getApplicableRefactors = getApplicableRefactors; @@ -73545,6 +92217,30 @@ var ts; } ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decorator = ts.getAncestor(token, 148 /* Decorator */); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73553,15 +92249,15 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var qualifiedName = ts.getAncestor(token, 143); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var qualifiedName = ts.getAncestor(token, 144 /* QualifiedName */); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); if (!ts.isIdentifier(qualifiedName.left)) { return undefined; } var leftText = qualifiedName.left.getText(sourceFile); var rightText = qualifiedName.right.getText(sourceFile); - var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); return [{ @@ -73572,6 +92268,7 @@ var ts; }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73583,7 +92280,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -73592,17 +92289,19 @@ var ts; var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); var classType = checker.getTypeAtLocation(classDeclaration); var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(classDeclaration); - var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1); - var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0); + var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1 /* Number */); + var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0 /* String */); var result = []; for (var _i = 0, implementedTypeNodes_2 = implementedTypeNodes; _i < implementedTypeNodes_2.length; _i++) { var implementedTypeNode = implementedTypeNodes_2[_i]; + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. var implementedType = checker.getTypeAtLocation(implementedTypeNode); var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8); }); + var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); var newNodes = []; - createAndAddMissingIndexSignatureDeclaration(implementedType, 1, hasNumericIndexSignature, newNodes); - createAndAddMissingIndexSignatureDeclaration(implementedType, 0, hasStringIndexSignature, newNodes); + createAndAddMissingIndexSignatureDeclaration(implementedType, 1 /* Number */, hasNumericIndexSignature, newNodes); + createAndAddMissingIndexSignatureDeclaration(implementedType, 0 /* String */, hasStringIndexSignature, newNodes); newNodes = newNodes.concat(codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); var message = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); if (newNodes.length > 0) { @@ -73627,6 +92326,7 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73639,8 +92339,11 @@ var ts; function getActionsForAddMissingMember(context) { var tokenSourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(tokenSourceFile, start, false); - if (token.kind !== 71) { + // The identifier of the missing property. eg: + // this.missing = 1; + // ^^^^^^^ + var token = ts.getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); + if (token.kind !== 71 /* Identifier */) { return undefined; } if (!ts.isPropertyAccessExpression(token.parent)) { @@ -73649,23 +92352,25 @@ var ts; var tokenName = token.getText(tokenSourceFile); var makeStatic = false; var classDeclaration; - if (token.parent.expression.kind === 99) { - var containingClassMemberDeclaration = ts.getThisContainer(token, false); + if (token.parent.expression.kind === 99 /* ThisKeyword */) { + var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); if (!ts.isClassElement(containingClassMemberDeclaration)) { return undefined; } classDeclaration = containingClassMemberDeclaration.parent; - makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32); + // Property accesses on `this` in a static method are accesses of a static member. + makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */); } else { var checker = context.program.getTypeChecker(); var leftExpression = token.parent.expression; var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 32768) { + if (leftExpressionType.flags & 65536 /* Object */) { var symbol = leftExpressionType.symbol; - if (symbol.flags & 32) { + if (symbol.flags & 32 /* Class */) { classDeclaration = symbol.declarations && symbol.declarations[0]; if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { + // The expression is a class symbol but the type is not the instance-side. makeStatic = true; } } @@ -73681,18 +92386,18 @@ var ts; getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { var actions; - var methodCodeAction = getActionForMethodDeclaration(false); + var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); if (methodCodeAction) { actions = [methodCodeAction]; } if (makeStatic) { - if (classDeclaration.kind === 199) { + if (classDeclaration.kind === 200 /* ClassExpression */) { return actions; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -73707,7 +92412,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -73718,30 +92423,43 @@ var ts; } function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { var actions; - var methodCodeAction = getActionForMethodDeclaration(true); + var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); if (methodCodeAction) { actions = [methodCodeAction]; } var typeNode; - if (token.parent.parent.kind === 194) { + if (token.parent.parent.kind === 195 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } - typeNode = typeNode || ts.createKeywordTypeNode(119); - var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); + typeNode = typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - (actions || (actions = [])).push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; + actions = ts.append(actions, { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: propertyChangeTracker.getChanges() }); if (!makeStatic) { - var stringTypeNode = ts.createKeywordTypeNode(136); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ @@ -73752,15 +92470,14 @@ var ts; return actions; } function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 181) { + if (token.parent.parent.kind === 182 /* CallExpression */) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? - ts.Diagnostics.Declare_method_0 : - ts.Diagnostics.Declare_static_method_0), [tokenName]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: methodDeclarationChangeTracker.getChanges() }; } @@ -73768,6 +92485,7 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73779,17 +92497,22 @@ var ts; }); function getActionsForCorrectSpelling(context) { var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 var checker = context.program.getTypeChecker(); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71); + ts.Debug.assert(node.kind === 71 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } else { var meaning = ts.getMeaningFromLocation(node); - suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } if (suggestion) { return [{ @@ -73806,19 +92529,55 @@ var ts; } function convertSemanticMeaningToSymbolFlags(meaning) { var flags = 0; - if (meaning & 4) { - flags |= 1920; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; } - if (meaning & 2) { - flags |= 793064; + if (meaning & 2 /* Type */) { + flags |= 793064 /* Type */; } - if (meaning & 1) { - flags |= 107455; + if (meaning & 1 /* Value */) { + flags |= 107455 /* Value */; } return flags; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); // These errors should only happen on the module name. + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, sourceFile.fileName, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + // If !registry, registry not available yet, can't do anything. + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + changes: [], + commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73834,12 +92593,16 @@ var ts; function getActionForClassLikeMissingAbstractMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); + // This is the identifier in the case of a class declaration + // or the class keyword token in the case of a class expression. + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. var extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); var abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); var newNodes = codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); @@ -73857,10 +92620,11 @@ var ts; var decls = symbol.getDeclarations(); ts.Debug.assert(!!(decls && decls.length > 0)); var flags = ts.getModifierFlags(decls[0]); - return !(flags & 8) && !!(flags & 128); + return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73869,8 +92633,8 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - if (token.kind !== 99) { + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + if (token.kind !== 99 /* ThisKeyword */) { return undefined; } var constructor = ts.getContainingFunction(token); @@ -73878,10 +92642,13 @@ var ts; if (!superCall) { return undefined; } - if (superCall.expression && superCall.expression.kind === 181) { + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind === 182 /* CallExpression */) { var expressionArguments = superCall.expression.arguments; - for (var i = 0; i < expressionArguments.length; i++) { - if (expressionArguments[i].expression === token) { + for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { + var arg = expressionArguments_1[_i]; + if (arg.expression === token) { return undefined; } } @@ -73894,7 +92661,7 @@ var ts; changes: changeTracker.getChanges() }]; function findSuperCall(n) { - if (n.kind === 210 && ts.isSuperCall(n.expression)) { + if (n.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { return n; } if (ts.isFunctionLike(n)) { @@ -73906,6 +92673,7 @@ var ts; }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73914,12 +92682,12 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - if (token.kind !== 123) { + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var superCall = ts.createStatement(ts.createCall(ts.createSuper(), undefined, ts.emptyArray)); + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), @@ -73929,6 +92697,7 @@ var ts; }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73938,9 +92707,9 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var classDeclNode = ts.getContainingClass(token); - if (!(token.kind === 71 && ts.isClassLike(classDeclNode))) { + if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { return undefined; } var heritageClauses = classDeclNode.heritageClauses; @@ -73948,15 +92717,16 @@ var ts; return undefined; } var extendsToken = heritageClauses[0].getFirstToken(); - if (!(extendsToken && extendsToken.kind === 85)) { + if (!(extendsToken && extendsToken.kind === 85 /* ExtendsKeyword */)) { return undefined; } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108)); + changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); + // We replace existing keywords with commas. for (var i = 1; i < heritageClauses.length; i++) { var keywordToken = heritageClauses[i].getFirstToken(); if (keywordToken) { - changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(26)); + changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(26 /* CommaToken */)); } } var result = [{ @@ -73968,6 +92738,7 @@ var ts; }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -73976,8 +92747,8 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - if (token.kind !== 71) { + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + if (token.kind !== 71 /* Identifier */) { return undefined; } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -73990,6 +92761,7 @@ var ts; }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -74002,15 +92774,16 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); - if (token.kind === 21) { - token = ts.getTokenAtPosition(sourceFile, start + 1, false); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + // this handles var ["computed"] = 12; + if (token.kind === 21 /* OpenBracketToken */) { + token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { - case 71: - return deleteIdentifierOrPrefixWithUnderscore(token); - case 149: - case 240: + case 71 /* Identifier */: + return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); + case 150 /* PropertyDeclaration */: + case 241 /* NamespaceImport */: return [deleteNode(token.parent)]; default: return deleteDefault(); @@ -74027,7 +92800,7 @@ var ts; } } function prefixIdentifierWithUnderscore(identifier) { - var startPosition = identifier.getStart(sourceFile, false); + var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), changes: [{ @@ -74039,55 +92812,61 @@ var ts; }] }; } - function deleteIdentifierOrPrefixWithUnderscore(identifier) { + function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { var parent = identifier.parent; switch (parent.kind) { - case 226: + case 227 /* VariableDeclaration */: return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 145: + case 146 /* TypeParameter */: var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); - ts.Debug.assert(previousToken.kind === 27); - ts.Debug.assert(nextToken.kind === 29); + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); return [deleteNodeRange(previousToken, nextToken)]; } else { return [deleteNodeInList(parent)]; } - case 146: + case 147 /* Parameter */: var functionDeclaration = parent.parent; - return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), - prefixIdentifierWithUnderscore(identifier)]; - case 237: - var importEquals = ts.getAncestor(identifier, 237); + var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); + return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code + ? [deleteAction] + : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; + // handle case where 'import a = A;' + case 238 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); return [deleteNode(importEquals)]; - case 242: + case 243 /* ImportSpecifier */: var namedImports = parent.parent; if (namedImports.elements.length === 1) { return deleteNamedImportBinding(namedImports); } else { + // delete import specifier return [deleteNodeInList(parent)]; } - case 239: + case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' var importClause = parent; if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238); + var importDecl = ts.getAncestor(importClause, 239 /* ImportDeclaration */); return [deleteNode(importDecl)]; } else { + // import |d,| * as ns from './file' var start_6 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); - if (nextToken && nextToken.kind === 26) { - return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) })]; + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; } else { return [deleteNode(importClause.name)]; } } - case 240: + case 241 /* NamespaceImport */: return deleteNamedImportBinding(parent); default: return deleteDefault(); @@ -74095,32 +92874,41 @@ var ts; } function deleteNamedImportBinding(namedBindings) { if (namedBindings.parent.name) { - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, false); - if (previousToken && previousToken.kind === 26) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; } return undefined; } else { - var importDecl = ts.getAncestor(namedBindings, 238); + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); return [deleteNode(importDecl)]; } } + // token.parent is a variableDeclaration function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { - case 214: + case 215 /* ForStatement */: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 216: + case 217 /* ForOfStatement */: var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 227); + ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; return [ replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), prefixIdentifierWithUnderscore(identifier) ]; - case 215: + case 216 /* ForInStatement */: + // There is no valid fix in the case of: + // for .. in return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; @@ -74157,6 +92945,7 @@ var ts; }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -74167,24 +92956,26 @@ var ts; }); function getActionsForJSDocTypes(context) { var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments var decl = ts.findAncestor(node, function (n) { - return n.kind === 202 || - n.kind === 155 || - n.kind === 156 || - n.kind === 228 || - n.kind === 153 || - n.kind === 157 || - n.kind === 172 || - n.kind === 151 || - n.kind === 150 || - n.kind === 146 || - n.kind === 149 || - n.kind === 148 || - n.kind === 154 || - n.kind === 231 || - n.kind === 184 || - n.kind === 226; + return n.kind === 203 /* AsExpression */ || + n.kind === 156 /* CallSignature */ || + n.kind === 157 /* ConstructSignature */ || + n.kind === 229 /* FunctionDeclaration */ || + n.kind === 154 /* GetAccessor */ || + n.kind === 158 /* IndexSignature */ || + n.kind === 173 /* MappedType */ || + n.kind === 152 /* MethodDeclaration */ || + n.kind === 151 /* MethodSignature */ || + n.kind === 147 /* Parameter */ || + n.kind === 150 /* PropertyDeclaration */ || + n.kind === 149 /* PropertySignature */ || + n.kind === 155 /* SetAccessor */ || + n.kind === 232 /* TypeAliasDeclaration */ || + n.kind === 185 /* TypeAssertionExpression */ || + n.kind === 227 /* VariableDeclaration */; }); if (!decl) return; @@ -74194,9 +92985,11 @@ var ts; return; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); - var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; - if (jsdocType.kind === 270) { - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048), undefined, 8); + var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; + if (jsdocType.kind === 274 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); } return actions; @@ -74215,10 +93008,12 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -74234,14 +93029,11 @@ var ts; ModuleSpecifierComparison[ModuleSpecifierComparison["Equal"] = 1] = "Equal"; ModuleSpecifierComparison[ModuleSpecifierComparison["Worse"] = 2] = "Worse"; })(ModuleSpecifierComparison || (ModuleSpecifierComparison = {})); - var ImportCodeActionMap = (function () { + var ImportCodeActionMap = /** @class */ (function () { function ImportCodeActionMap() { this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -74255,21 +93047,33 @@ var ts; for (var _i = 0, _a = this.symbolIdToActionMap[symbolId]; _i < _a.length; _i++) { var existingAction = _a[_i]; if (existingAction.kind === "CodeChange") { + // only import actions should compare updatedNewImports.push(existingAction); continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0 /* Better */: + // the new one is not worth considering if it is a new import. + // However if it is instead a insertion into existing import, the user might want to use + // the module specifier even it is worse by our standards. So keep it. if (newAction.kind === "NewImport") { return; } - case ModuleSpecifierComparison.Equal: + // falls through + case 1 /* Equal */: + // the current one is safe. But it is still possible that the new one is worse + // than another existing one. For example, you may have new imports from "./foo/bar" + // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new + // one and the current one are not comparable (one relative path and one absolute path), + // but the new one is worse than the other one, so should not add to the list. updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2 /* Worse */: + // the existing one is worse, remove from the list. continue; } } + // if we reach here, it means the new one is better or equal to all of the existing ones. updatedNewImports.push(newAction); this.symbolIdToActionMap[symbolId] = updatedNewImports; }; @@ -74288,457 +93092,624 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; } + // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0 /* Better */; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2 /* Worse */; } + // if both are relative paths, and ms1 has fewer levels, then it is better if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { var regex = new RegExp(ts.directorySeparator, "g"); var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 /* Better */ : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 /* Equal */ + : 2 /* Worse */; } - return ModuleSpecifierComparison.Equal; + // the equal cases include when the two specifiers are not comparable. + return 1 /* Equal */; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName = void 0; - if (umdSymbol.flags & 2097152) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455)); - symbolName = symbol.name; + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + formatContext: context.formatContext, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbols, context) { + moduleSymbols = ts.toArray(moduleSymbols); + var declarations = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + }); + var actions = []; + if (context.symbolToken) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } + } + } + return actions.concat(getCodeActionsForAddImport(moduleSymbols, context, declarations)); + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 239 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 241 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { + return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; + }); + } + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 239 /* ImportDeclaration */: + return parent; + case 249 /* ExternalModuleReference */: + return parent.parent; + case 245 /* ExportDeclaration */: + case 182 /* CallExpression */:// For "require()" calls + // Ignore these, can't add imports to them. + return undefined; + default: + ts.Debug.fail(); + } + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var importDecl = kind !== 3 /* Equals */ + ? ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createImportClauseOfKind(kind, symbolName), quotedModuleSpecifier) + : ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - return getCodeActionForImport(symbol, symbolName, false, true); + }); + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + var id = ts.createIdentifier(symbolName); + switch (kind) { + case 1 /* Default */: + return ts.createImportClause(id, /*namedBindings*/ undefined); + case 2 /* Namespace */: + return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id)); + case 0 /* Named */: + return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) + return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + } + codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + function getRelativePathNParents(relativePath) { + var count = 0; + for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { + count++; } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); - } + return count; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, true)); + } + function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); + } + } + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } - } - ts.Debug.assert(name !== "default"); - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); } } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { - return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238: - return parent; - case 248: - return parent.parent; - default: - return undefined; - } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options); } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); } else { - return [getCodeActionForNewImport()]; - } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; } - } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); - } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); - } - else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); - } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; } else { - namespacePrefix = declaration.name.getText(); + state = 3 /* PackageContent */; } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); - } + break; } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } - } - } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSourceFileImportLocation(node) { - var text = node.text; - var ranges = ts.getLeadingCommentRanges(text, 0); - if (!ranges) - return 0; - var position = 0; - if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end + 1; - ranges = ranges.slice(1); - } - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { - position = range.end + 1; - continue; - } - break; - } - return position; + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName, options) { + var noExtension = ts.removeFileExtension(fileName); + return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionsForAddImport(moduleSymbols, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 239 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } + } + }); + if (fromExistingImport) { + return [fromExistingImport]; + } + var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 239 /* ImportDeclaration */ + ? node.moduleSpecifier + : node.moduleReference.kind === 249 /* ExternalModuleReference */ + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile, kind = context.kind; + var name = importClause.name; + var namedBindings = (importClause.kind !== 238 /* ImportEqualsDeclaration */ && importClause).namedBindings; + switch (kind) { + case 1 /* Default */: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0 /* Named */: { + var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 242 /* NamedImports */ && namedBindings.elements.length !== 0) { + // There are already named imports; add another. + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 242 /* NamedImports */ && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } - return undefined; - } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } - } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } - } - } - function getNodeModulePathParts(fullPath) { - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1; - } - break; - case 1: - case 2: - if (state === 1 && fullPath.charAt(partStart + 1) === "@") { - state = 2; - } - else { - packageRootIndex = partEnd; - state = 3; - } - break; - case 3: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1; - } - else { - state = 3; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } - } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6); - } - return fileName; - } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + return undefined; + } + case 2 /* Namespace */: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + case 3 /* Equals */: + return undefined; + default: + ts.Debug.assertNever(kind); + } + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", + /*moduleSpecifier*/ undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken, compilerOptions = context.compilerOptions; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; + } + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbolName = symbol.name; + } + else { + throw ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: getUmdImportKind(compilerOptions) })); + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + throw ts.Debug.assertNever(moduleKind); + } + } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) + && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); } } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol, sourceFile); + } } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + } + codefix.forEachExternalModule = forEachExternalModule; + /** + * 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) { + // 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)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var res = ""; + var lastCharWasValid = true; + var firstCharCode = moduleSpecifier.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < moduleSpecifier.length; i++) { + var ch = moduleSpecifier.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -74757,8 +93728,12 @@ var ts; var line = ts.getLineAndCharacterOfPosition(sourceFile, position).line; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the '// @ts-ignore' on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // We also want to check if the previous line holds a comment for a node on the next line + // if so, we do not want to separate the node from its comment if we can. if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition, false); + var token = ts.getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -74767,6 +93742,7 @@ var ts; }; } } + // If all fails, add an extra new line immediately before the error span. return { span: { start: position, length: 0 }, newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter @@ -74800,6 +93776,7 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var codefix; @@ -74826,6 +93803,12 @@ var ts; return consolidatedChanges; } codefix.newNodesToChanges = newNodesToChanges; + /** + * Finds members of the resolved type that are missing in the class pointed to by class decl + * and generates source code for the missing members. + * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. + * @returns Empty string iff there are no member insertions. + */ function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { var classMembers = classDeclaration.symbol.members; var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); @@ -74845,28 +93828,41 @@ var ts; return newNodes; } codefix.createMissingMemberNodes = createMissingMemberNodes; + /** + * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. + */ function createNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; + // Clone name to remove leading trivia. var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - var optional = !!(symbol.flags & 16777216); + var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 153: - case 154: - case 148: - case 149: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 149 /* PropertySignature */: + case 150 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); - var property = ts.createProperty(undefined, modifiers, name, optional ? ts.createToken(55) : undefined, typeNode, undefined); + var property = ts.createProperty( + /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, + /*initializer*/ undefined); return property; - case 150: - case 151: - var signatures = checker.getSignaturesOfType(type, 0); + case 151 /* MethodSignature */: + case 152 /* MethodDeclaration */: + // The signature for the implementation appears as an entry in `signatures` iff + // there is only one signature. + // If there are overloads and an implementation signature, it appears as an + // extra declaration that isn't a signature for `type`. + // If there is more than one overload but no implementation signature + // (eg: an abstract method or interface declaration), there is a 1-1 + // correspondence of declarations and signatures. + var signatures = checker.getSignaturesOfType(type, 0 /* Call */); if (!ts.some(signatures)) { return undefined; } @@ -74876,8 +93872,8 @@ var ts; return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); } var signatureDeclarations = []; - for (var i = 0; i < signatures.length; i++) { - var signature = signatures[i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); if (methodDeclaration) { signatureDeclarations.push(methodDeclaration); @@ -74900,46 +93896,62 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55) : undefined; + signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; signatureDeclaration.body = body; } return signatureDeclaration; } } function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { - var parameters = createDummyParameters(callExpression.arguments.length, undefined, undefined, includeTypeScriptSyntax); + var parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); var typeParameters; if (includeTypeScriptSyntax) { var typeArgCount = ts.length(callExpression.typeArguments); for (var i = 0; i < typeArgCount; i++) { - var name_67 = typeArgCount < 8 ? String.fromCharCode(84 + i) : "T" + i; - var typeParameter = ts.createTypeParameterDeclaration(name_67, undefined, undefined); + var name = typeArgCount < 8 ? String.fromCharCode(84 /* T */ + i) : "T" + i; + var typeParameter = ts.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); } } - var newMethod = ts.createMethod(undefined, makeStatic ? [ts.createToken(115)] : undefined, undefined, methodName, undefined, typeParameters, parameters, includeTypeScriptSyntax ? ts.createKeywordTypeNode(119) : undefined, createStubbedMethodBody()); + var newMethod = ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ undefined, methodName, + /*questionToken*/ undefined, typeParameters, parameters, + /*type*/ includeTypeScriptSyntax ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, createStubbedMethodBody()); return newMethod; } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { var parameters = []; for (var i = 0; i < argCount; i++) { - var newParameter = ts.createParameter(undefined, undefined, undefined, names && names[i] || "arg" + i, minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55) : undefined, addAnyType ? ts.createKeywordTypeNode(119) : undefined, undefined); + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, + /*type*/ addAnyType ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, + /*initializer*/ undefined); parameters.push(newParameter); } return parameters; } function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + /** This is *a* signature with the maximal number of arguments, + * such that if there is a "maximal" signature without rest arguments, + * this is one of them. + */ var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var i = 0; i < signatures.length; i++) { - var sig = signatures[i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -74950,32 +93962,858 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, true); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); if (someSigHasRestParameter) { - var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119)); - var restParameter = ts.createParameter(undefined, undefined, ts.createToken(24), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", maxNonRestArgs >= minArgumentCount ? ts.createToken(55) : undefined, anyArrayType, undefined); + var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); + var restParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", + /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyArrayType, + /*initializer*/ undefined); parameters.push(restParameter); } - return createStubbedMethod(modifiers, name, optional, undefined, parameters, undefined); + return createStubbedMethod(modifiers, name, optional, + /*typeParameters*/ undefined, parameters, + /*returnType*/ undefined); } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { - return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + return ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { - return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), undefined, [ts.createLiteral("Method not implemented.")]))], true); + return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], + /*multiline*/ true); } function createVisibilityModifier(flags) { - if (flags & 4) { - return ts.createToken(114); + if (flags & 4 /* Public */) { + return ts.createToken(114 /* PublicKeyword */); } - else if (flags & 16) { - return ts.createToken(113); + else if (flags & 16 /* Protected */) { + return ts.createToken(113 /* ProtectedKeyword */); } return undefined; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + // Allowed + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + // Get Accessor declarations + 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + return true; + case 187 /* FunctionExpression */: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 153 /* Constructor */; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 153 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 194 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 193 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 195 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 180 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 181 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + usageContext.isNumber = true; + break; + case 37 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 40 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + // ShiftOperator + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 48 /* AmpersandToken */: + case 49 /* BarToken */: + case 50 /* CaretToken */: + // CompoundAssignmentOperator + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 69 /* BarEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 38 /* MinusToken */: + // RelationalOperator + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59 /* PlusEqualsToken */: + case 37 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 524322 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 58 /* EqualsToken */: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 54 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 227 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + case 93 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 182 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + var members_5 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + var numberIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + members_5.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + } + return checker.createAnonymousType(/*symbol*/ undefined, members_5, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 16384 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var annotateWithTypeFromJSDoc; + (function (annotateWithTypeFromJSDoc) { + var actionName = "annotate"; + var annotateTypeFromJSDoc = { + name: "Annotate with type from JSDoc", + description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(annotateTypeFromJSDoc); + function getAvailableActions(context) { + if (ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { + return [{ + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, + actions: [ + { + description: annotateTypeFromJSDoc.description, + name: actionName + } + ] + }]; + } + } + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { + if (actionName !== action) { + return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 147 /* Parameter */) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(token, isDeclarationWithType); + var jsdocType = ts.getJSDocType(decl); + if (!decl || !jsdocType || decl.type) { + return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var declarationWithType = addType(decl, transformJSDocType(jsdocType)); + ts.suppressLeadingAndTrailingTrivia(declarationWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, declarationWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function getEditsForFunctionAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var functionWithType = addTypesToFunctionLike(decl); + ts.suppressLeadingAndTrailingTrivia(functionWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, functionWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 227 /* VariableDeclaration */ || + node.kind === 147 /* Parameter */ || + node.kind === 149 /* PropertySignature */ || + node.kind === 150 /* PropertyDeclaration */; + } + function addTypesToFunctionLike(decl) { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true); + var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); }); + var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true)); + switch (decl.kind) { + case 229 /* FunctionDeclaration */: + return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 153 /* Constructor */: + return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); + case 187 /* FunctionExpression */: + return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 188 /* ArrowFunction */: + return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); + case 152 /* MethodDeclaration */: + return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); + case 154 /* GetAccessor */: + return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); + case 155 /* SetAccessor */: + return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body); + default: + return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind); + } + } + function addType(decl, jsdocType) { + switch (decl.kind) { + case 227 /* VariableDeclaration */: + return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); + case 149 /* PropertySignature */: + return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + case 150 /* PropertyDeclaration */: + return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + default: + return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind); + } + } + function transformJSDocType(node) { + if (node === undefined) { + return undefined; + } + switch (node.kind) { + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 276 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 275 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 274 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 278 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 277 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 147 /* Parameter */: + return transformJSDocParameter(node); + case 160 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + var parameters = node.parameters && node.parameters.map(transformJSDocType); + return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 278 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { var refactor; @@ -74994,14 +94832,14 @@ var ts; if (!ts.isInJavaScriptFile(context.file)) { return undefined; } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + var symbol = getConstructorSymbol(context); + if (!symbol) { + return undefined; + } + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { symbol = symbol.valueDeclaration.initializer.symbol; } - if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { + if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { name: convertFunctionToES6Class.name, @@ -75017,18 +94855,16 @@ var ts; } } function getEditsForAction(context, action) { + // Somehow wrong action got invoked? if (actionName !== action) { return undefined; } - var start = context.startPosition; var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var ctorSymbol = getConstructorSymbol(context); + var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; - if (!(ctorSymbol.flags & (16 | 3))) { + if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; @@ -75036,18 +94872,18 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 228: + case 229 /* FunctionDeclaration */: precedingNode = ctorDeclaration; deleteNode(ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 226: + case 227 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; if (ctorDeclaration.parent.declarations.length === 1) { deleteNode(precedingNode); } else { - deleteNode(ctorDeclaration, true); + deleteNode(ctorDeclaration, /*inList*/ true); } newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); break; @@ -75055,6 +94891,7 @@ var ts; if (!newClassDeclaration) { return undefined; } + // Because the preceding node could be touched, we need to insert nodes before delete nodes. changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { var deleteCallback = deletes_1[_i]; @@ -75068,6 +94905,7 @@ var ts; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { + // Parent node has already been deleted; do nothing return; } deletedNodes.push(node); @@ -75080,17 +94918,19 @@ var ts; } function createClassElementsFromSymbol(symbol) { var memberElements = []; + // all instance members are stored in the "member" array of symbol if (symbol.members) { symbol.members.forEach(function (member) { - var memberElement = createClassElement(member, undefined); + var memberElement = createClassElement(member, /*modifiers*/ undefined); if (memberElement) { memberElements.push(memberElement); } }); } + // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(115)]); + var memberElement = createClassElement(member, [ts.createToken(115 /* StaticKeyword */)]); if (memberElement) { memberElements.push(memberElement); } @@ -75098,10 +94938,13 @@ var ts; } return memberElements; function shouldConvertDeclaration(_target, source) { + // Right now the only thing we can convert are function expressions - other values shouldn't get + // transformed. We can update this once ES public class properties are available. return ts.isFunctionLike(source); } function createClassElement(symbol, modifiers) { - if (!(symbol.flags & 4)) { + // both properties and methods are bound as property symbols + if (!(symbol.flags & 4 /* Property */)) { return; } var memberDeclaration = symbol.valueDeclaration; @@ -75109,39 +94952,48 @@ var ts; if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { return; } - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 + // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 211 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; deleteNode(nodeToDelete); if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); + return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186: { + case 187 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; } - case 187: { + case 188 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; - if (arrowFunctionBody.kind === 207) { + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 208 /* Block */) { bodyBlock = arrowFunctionBody; } else { var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; } default: { + // Don't try to declare members in JavaScript files if (ts.isSourceFileJavaScript(sourceFile)) { return; } - var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, + /*type*/ undefined, assignmentBinaryExpression.right); copyComments(assignmentBinaryExpression.parent, prop); return prop; } @@ -75150,11 +95002,14 @@ var ts; } function copyComments(sourceNode, targetNode) { ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { - if (kind === 3) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* pos += 2; + // Remove trailing */ end -= 2; } else { + // Remove leading // pos += 2; } ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); @@ -75162,44 +95017,66 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 186) { + if (!initializer || initializer.kind !== 187 /* FunctionExpression */) { return undefined; } - if (node.name.kind !== 71) { + if (node.name.kind !== 71 /* Identifier */) { return undefined; } var memberElements = createClassElementsFromSymbol(initializer.symbol); if (initializer.body) { - memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place return cls; } function createClassFromFunctionDeclaration(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(ts.createConstructor(undefined, undefined, node.parameters, node.body)); + memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + } + function getConstructorSymbol(_a) { + var startPosition = _a.startPosition, file = _a.file, program = _a.program; + var checker = program.getTypeChecker(); + var token = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return checker.getSymbolAtLocation(token); } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/// +/// +/* @internal */ var ts; (function (ts) { var refactor; (function (refactor) { - var extractMethod; - (function (extractMethod_1) { - var extractMethod = { - name: "Extract Method", - description: ts.Diagnostics.Extract_function.message, + var extractSymbol; + (function (extractSymbol_1) { + var extractSymbol = { + name: "Extract Symbol", + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction, }; - refactor.registerRefactor(extractMethod); + refactor.registerRefactor(extractSymbol); + /** + * Compute the associated code actions + * Exported for tests. + */ function getAvailableActions(context) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -75208,64 +95085,114 @@ var ts; } var extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { + // No extractions possible return undefined; } - var actions = []; - var usedNames = ts.createMap(); + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; - if (errors.length) { - continue; + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; + // Skip these since we don't have a way to report errors yet + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } } - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); - if (!usedNames.has(description)) { - usedNames.set(description, true); - actions.push({ - description: description, - name: "scope_" + i - }); + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } } + // *do* increment i anyway because we'll look for the i-th scope + // later when actually doing the refactoring if the user requests it i++; } - if (actions.length === 0) { - return undefined; + var infos = []; + if (functionActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); } - return [{ - name: extractMethod.name, - description: extractMethod.description, - inlineable: true, - actions: actions - }]; + if (constantActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : undefined; } + extractSymbol_1.getAvailableActions = getAvailableActions; + /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; - var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); - ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); - var index = +parsedIndexMatch[1]; - ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - return getExtractionAtIndex(targetRange, context, index); - } + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); + } + extractSymbol_1.getEditsForAction = getEditsForAction; + // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { function createMessage(message) { return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; } - Messages.CannotExtractFunction = createMessage("Cannot extract function."); - Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages.InsufficientSelection = createMessage("Select more than a single identifier."); - Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); - Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - })(Messages || (Messages = {})); + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -75273,41 +95200,52 @@ var ts; RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator"; RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; + /** + * The range is in a function which needs the 'static' modifier in a class + */ RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; })(RangeFacts || (RangeFacts = {})); + /** + * getRangeToExtract takes a span inside a text file and returns either an expression or an array + * of statements representing the minimum set of nodes needed to extract the entire span. This + * process may fail, in which case a set of errors is returned instead (these are currently + * not shown to the user, but can be used by us diagnostically) + */ + // exported only for tests function getRangeToExtract(sourceFile, span) { var length = span.length; if (length === 0) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } - var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, false), sourceFile, span); + // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. + // This may fail (e.g. you select two statements in the root of a source file) + var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span); + // Do the same for the ending position var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); var declarations = []; + // We'll modify these flags as we walk the tree to collect data + // about what things need to be done as part of the extraction. var rangeFacts = RangeFacts.None; if (!start || !end) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + // cannot find either start or end node + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start.parent !== end.parent) { - var startParent = ts.skipParentheses(start.parent); - var endParent = ts.skipParentheses(end.parent); - if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { - start = end = endParent; - } - else { - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); - } + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start !== end) { + // start and end should be statements and parent should be either block or a source file if (!isBlockLike(start.parent)) { - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { - var errors = checkNode(statement); - if (errors) { - return { errors: errors }; + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; } statements.push(statement); } @@ -75317,46 +95255,80 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - else { - var errors = checkRootNode(start) || checkNode(start); - if (errors) { - return { errors: errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - function createErrorResult(sourceFile, start, length, message) { - return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = undefined; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; } function checkRootNode(node) { if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { - return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; } return undefined; } function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 149) { - if (ts.hasModifier(current, 32)) { + if (current.kind === 150 /* PropertyDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 146) { + else if (current.kind === 147 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 152) { + if (ctorOrMethod.kind === 153 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 151) { - if (ts.hasModifier(current, 32)) { + else if (current.kind === 152 /* MethodDeclaration */) { + if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } } current = current.parent; } } + // Verifies whether we can actually extract this node or not. function checkNode(nodeToCheck) { var PermittedJumps; (function (PermittedJumps) { @@ -75365,42 +95337,48 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; } - if (ts.isInAmbientContext(nodeToCheck)) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + if (nodeToCheck.flags & 2097152 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; } + // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) var containingClass = ts.getContainingClass(nodeToCheck); if (containingClass) { checkForStaticContext(nodeToCheck, containingClass); } var errors; - var permittedJumps = 4; + var permittedJumps = 4 /* Return */; var seenLabels; visit(nodeToCheck); return errors; function visit(node) { if (errors) { + // already found an error - can stop now return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 226) ? node.parent.parent : node; - if (ts.hasModifier(declaringNode, 1)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + var declaringNode = (node.kind === 227 /* VariableDeclaration */) ? node.parent.parent : node; + if (ts.hasModifier(declaringNode, 1 /* Export */)) { + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } declarations.push(node.symbol); } + // Some things can't be extracted in certain situations switch (node.kind) { - case 238: - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + case 239 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 97: - if (node.parent.kind === 181) { + case 97 /* SuperKeyword */: + // For a super *constructor call*, we have to be extracting the entire class, + // but a super *method call* simply implies a 'this' reference + if (node.parent.kind === 182 /* CallExpression */) { + // Super constructor call var containingClass_1 = ts.getContainingClass(node); if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; } } @@ -75409,45 +95387,51 @@ var ts; } break; } - if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 228: - case 229: - if (node.parent.kind === 265 && node.parent.externalModuleIndicator === undefined) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + if (node.parent.kind === 269 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + // You cannot extract global declarations + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } break; } + // do not dive into functions or classes return false; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 211: - permittedJumps = 0; + case 212 /* IfStatement */: + permittedJumps = 0 /* None */; break; - case 224: - permittedJumps = 0; + case 225 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; break; - case 207: - if (node.parent && node.parent.kind === 224 && node.finallyBlock === node) { - permittedJumps = 4; + case 208 /* Block */: + if (node.parent && node.parent.kind === 225 /* TryStatement */ && node.parent.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; } break; - case 257: - permittedJumps |= 1; + case 261 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; break; default: - if (ts.isIterationStatement(node, false)) { - permittedJumps |= 1 | 2; + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; } break; } switch (node.kind) { - case 169: - case 99: + case 170 /* ThisType */: + case 99 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 222: + case 223 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -75455,34 +95439,36 @@ var ts; seenLabels.pop(); break; } - case 218: - case 217: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } } else { - if (!(permittedJumps & (node.kind === 218 ? 1 : 2))) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + if (!(permittedJumps & (node.kind === 219 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 191: + case 192 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 197: + case 198 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 219: - if (permittedJumps & 4) { + case 220 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } else { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); } break; default: @@ -75493,120 +95479,197 @@ var ts; } } } - extractMethod_1.getRangeToExtract = getRangeToExtract; + extractSymbol_1.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; } - else if (ts.isPartOfExpression(node)) { + else if (ts.isExpressionNode(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) return ts.isExpressionStatement(node.parent) ? [node.parent] : node; } return undefined; } - function isValidExtractionTarget(node) { - return (node.kind === 228) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); } + /** + * Computes possible places we could extract the function into. For example, + * you may be able to extract into a class method *or* local closure *or* namespace function, + * depending on what's in the extracted body. + */ function collectEnclosingScopes(range) { - var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; if (range.facts & RangeFacts.UsesThis) { + // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { - if (current !== start && isValidExtractionTarget(current)) { - (scopes = scopes || []).push(current); - } - if (current && current.parent && current.parent.kind === 146) { - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 147 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } - else { - current = current.parent; + // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. + // Walk up to the closest parent of a place where we can logically put a sibling: + // * Function declaration + // * Class declaration or expression + // * Module/namespace or source file + if (isScope(current)) { + scopes.push(current); + if (current.kind === 269 /* SourceFile */) { + return scopes; + } } } - return scopes; } - function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; - ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } - extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + /** + * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. + * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes + * or an error explaining why we can't extract into that scope. + */ function getPossibleExtractions(targetRange, context) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; - return scopes.map(function (scope, i) { - return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; }); + return extractions; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; } - function getDescriptionForScope(scope) { + function getDescriptionForFunctionInScope(scope) { return ts.isFunctionLikeDeclaration(scope) - ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + ? "inner function" : ts.isClassLike(scope) - ? "method in " + getDescriptionForClassLikeDeclaration(scope) - : "function in " + getDescriptionForModuleLikeDeclaration(scope); + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 152: + case 153 /* Constructor */: return "constructor"; - case 186: + case 187 /* FunctionExpression */: return scope.name ? "function expression '" + scope.name.text + "'" : "anonymous function expression"; - case 228: + case 229 /* FunctionDeclaration */: return "function '" + scope.name.text + "'"; - case 187: + case 188 /* ArrowFunction */: return "arrow function"; - case 151: + case 152 /* MethodDeclaration */: return "method '" + scope.name.getText(); - case 153: + case 154 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 154: + case 155 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 229 + return scope.kind === 230 /* ClassDeclaration */ ? "class '" + scope.name.text + "'" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 234 + return scope.kind === 235 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" - : scope.externalModuleIndicator ? "module scope" : "global scope"; - } - function getUniqueName(fileText) { - var functionNameText = "newFunction"; - for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { - functionNameText = "newFunction_" + i; - } - return functionNameText; - } - function extractFunctionInScope(node, scope, _a, range, context) { + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + function getUniqueName(baseName, fileText) { + var nameText = baseName; + for (var i = 1; ts.stringContains(fileText, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(file.text); + var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType = undefined; @@ -75617,12 +95680,18 @@ var ts; var typeNode = undefined; if (!isJS) { var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); - } - var paramDecl = ts.createParameter(undefined, undefined, undefined, name, undefined, typeNode); + typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + } + var paramDecl = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ name, + /*questionToken*/ undefined, typeNode); parameters.push(paramDecl); - if (usage.usage === 2) { + if (usage.usage === 2 /* Write */) { (writes || (writes = [])).push(usage); } callArguments.push(ts.createIdentifier(name)); @@ -75632,67 +95701,143 @@ var ts; var typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? undefined : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. var callTypeArguments = typeParameters !== undefined - ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, undefined); }) + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) : undefined; + // Provide explicit return types for contextually-typed functions + // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { - var modifiers = isJS ? [] : [ts.createToken(112)]; + // always create private method in TypeScript files + var modifiers = isJS ? [] : [ts.createToken(112 /* PrivateKeyword */)]; if (range.facts & RangeFacts.InStaticRegion) { - modifiers.push(ts.createToken(115)); + modifiers.push(ts.createToken(115 /* StaticKeyword */)); } if (range.facts & RangeFacts.IsAsyncFunction) { - modifiers.push(ts.createToken(120)); + modifiers.push(ts.createToken(120 /* AsyncKeyword */)); } - newFunction = ts.createMethod(undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, typeParameters, parameters, returnType, body); + newFunction = ts.createMethod( + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { - newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.createFunctionDeclaration( + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; - var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; + // replace range with function call var called = getCalledExpression(scope, range, functionNameText); - var call = ts.createCall(called, callTypeArguments, callArguments); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); if (range.facts & RangeFacts.IsGenerator) { - call = ts.createYield(ts.createToken(39), call); + call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); } if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { - newNodes.push(ts.createVariableStatement(undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119))])); + // has both writes and return, need to create variable declaration to hold return value; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } + // propagate writes back if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58, call))); + // emit e.g. + // { a, b, __return } = newFunction(a, b); + // return __return; + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -75709,37 +95854,165 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter - }); + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var isJS = ts.isInJavaScriptFile(scope); + var variableType = isJS + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(131 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + // Consume + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line + changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + else if (node.parent.kind === 211 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + // If we're at the beginning of the file, we need to take care not to insert before header comments + // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved + // for imports. + var insertionPos = ts.getSourceFileImportLocation(file); + changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { + prefix: insertionPos === 0 ? undefined : context.newLineCharacter, + suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter + }); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + // Consume + if (node.parent.kind === 211 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.deleteRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + } } var edits = changeTracker.getChanges(); - var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; - var renameFilename = renameRange.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function getRenameLocation(edits, renameFilename, functionNameText) { + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode = undefined; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, functionNameText, isDeclaredBeforeUse) { var delta = 0; + var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { var change = textChanges_2[_b]; - var span_17 = change.span, newText = change.newText; + var span_15 = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - return span_17.start + delta + index; + lastPos = span_15.start + delta + index; + // If the reference comes first, return immediately. + if (!isDeclaredBeforeUse) { + return lastPos; + } } - delta += newText.length - span_17.length; + delta += newText.length - span_15.length; } } - throw new Error(); + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(lastPos >= 0); + return lastPos; } function getFirstDeclaration(type) { var firstDeclaration = undefined; @@ -75757,27 +96030,9 @@ var ts; function compareTypesByDeclarationOrder(_a, _b) { var type1 = _a.type, declaration1 = _a.declaration; var type2 = _b.type, declaration2 = _b.declaration; - if (declaration1) { - if (declaration2) { - var positionDiff = declaration1.pos - declaration2.pos; - if (positionDiff !== 0) { - return positionDiff; - } - } - else { - return 1; - } - } - else if (declaration2) { - return -1; - } - var name1 = type1.symbol ? type1.symbol.getName() : ""; - var name2 = type2.symbol ? type2.symbol.getName() : ""; - var nameDiff = ts.compareStrings(name1, name2); - if (nameDiff !== 0) { - return nameDiff; - } - return type1.id - type2.id; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); } function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); @@ -75789,17 +96044,22 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - if (writes || substitutions.size) { + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -75807,14 +96067,14 @@ var ts; rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); } } - return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; } else { - return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 220 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -75830,16 +96090,25 @@ var ts; } else { var oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } } } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } function getStatementsOrClassElements(scope) { - if (ts.isFunctionLike(scope)) { + if (ts.isFunctionLikeDeclaration(scope)) { var body = scope.body; if (ts.isBlock(body)) { return body.statements; @@ -75856,59 +96125,169 @@ var ts; } return ts.emptyArray; } - function getNodeToInsertBefore(minPos, scope) { + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertFunctionBefore(minPos, scope) { return ts.find(getStatementsOrClassElements(scope), function (child) { - return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); }); } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember = undefined; + var allProperties = true; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope = undefined; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = undefined; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + // There must be at least one statement since we started in one. + ts.Debug.assert(prevStatement !== undefined); + return prevStatement; + } + if (curr === scope) { + ts.Debug.fail("Didn't encounter a block-like before encountering scope"); + break; + } + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); } + /** + * Produces a range that spans the entirety of nodes, given a selection + * that might start/end in the middle of nodes. + * + * For example, when the user makes a selection like this + * v---v + * var someThing = foo + bar; + * this returns ^-------^ + */ function getEnclosingTextRange(targetRange, sourceFile) { return isReadonlyArray(targetRange.range) - ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } : targetRange.range; } var Usage; (function (Usage) { + // value should be passed to extracted method Usage[Usage["Read"] = 1] = "Read"; + // value should be passed to extracted method and propagated back Usage[Usage["Write"] = 2] = "Write"; })(Usage || (Usage = {})); function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { - var allTypeParameterUsages = ts.createMap(); + var allTypeParameterUsages = ts.createMap(); // Key is type ID var usagesPerScope = []; var substitutionsPerScope = []; - var errorsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic = undefined; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } + // initialize results for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { - var _ = scopes_1[_i]; + var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - errorsPerScope.push([]); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 229 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); - var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). if (inGenericContext && !isReadonlyArray(targetRange.range)) { var contextualType = checker.getContextualType(targetRange.range); recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { - var seenTypeParameterUsages = ts.createMap(); + var seenTypeParameterUsages = ts.createMap(); // Key is type ID var i_1 = 0; for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. seenTypeParameterUsages.forEach(function (typeParameter, id) { usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); }); i_1++; } + // Note that we add the current node's type parameters *after* updating the corresponding scope. if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; @@ -75919,35 +96298,62 @@ var ts; } } } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. ts.Debug.assert(i_1 === scopes.length); } - var _loop_8 = function (i) { + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_10 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } var hasWrite = false; var readonlyClassPropertyWrite = undefined; usagesPerScope[i].usages.forEach(function (value) { - if (value.usage === 2) { + if (value.usage === 2 /* Write */) { hasWrite = true; - if (value.symbol.flags & 106500 && + if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && - ts.hasModifier(value.symbol.valueDeclaration, 64)) { + ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { readonlyClassPropertyWrite = value.symbol.valueDeclaration; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } }; for (var i = 0; i < scopes.length; i++) { - _loop_8(i); - } - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + _loop_10(i); } - return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -75962,32 +96368,37 @@ var ts; return false; } function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); var visitedTypes = symbolWalker.walkType(type).visitedTypes; for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { var visitedType = visitedTypes_1[_i]; - if (visitedType.flags & 16384) { + if (visitedType.flags & 32768 /* TypeParameter */) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); } } } function collectUsages(node, valueUsage) { - if (valueUsage === void 0) { valueUsage = 1; } + if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { var type = checker.getTypeAtLocation(node); recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { - collectUsages(node.left, 2); + // use 'write' as default usage for values + collectUsages(node.left, 2 /* Write */); collectUsages(node.right); } else if (ts.isUnaryExpressionWithWrite(node)) { - collectUsages(node.operand, 2); + collectUsages(node.operand, 2 /* Write */); } else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { + // use 'write' as default usage for values ts.forEachChild(node, collectUsages); } else if (ts.isIdentifier(node)) { @@ -76000,7 +96411,7 @@ var ts; if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { return; } - recordUsage(node, valueUsage, ts.isPartOfTypeNode(node)); + recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node)); } else { ts.forEachChild(node, collectUsages); @@ -76010,27 +96421,35 @@ var ts; var symbolId = recordUsagebySymbol(n, usage, isTypeNode); if (symbolId) { for (var i = 0; i < scopes.length; i++) { - var substitition = substitutionsPerScope[i].get(symbolId); - if (substitition) { - usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + // push substitution from map to map to simplify rewriting + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); } } } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { + // cannot find symbol - do nothing return undefined; } var symbolId = ts.getSymbolId(symbol).toString(); var lastUsage = seenUsages.get(symbolId); + // there are two kinds of value usages + // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter + // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and + // returned as a return value + // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read' + // since all information is already recorded if (lastUsage && lastUsage >= usage) { return symbolId; } seenUsages.set(symbolId, usage); if (lastUsage) { + // if we get here this means that we are trying to handle 'write' and 'read' was already processed + // walk scopes and update existing records. for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) { var perScope = usagesPerScope_1[_i]; var prevEntry = perScope.usages.get(identifier.text); @@ -76040,17 +96459,26 @@ var ts; } return symbolId; } + // find first declaration in this file var declInFile = ts.find(symbol.getDeclarations(), function (d) { return d.getSourceFile() === sourceFile; }); if (!declInFile) { return undefined; } if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + // declaration is located in range to be extracted - do nothing return undefined; } - if (targetRange.facts & RangeFacts.IsGenerator && usage === 2) { - for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { - var errors = errorsPerScope_1[_a]; - errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { + // this is write to a reference located outside of the target scope and range is extracted into generator + // currently this is unsupported scenario + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); } } for (var i = 0; i < scopes.length; i++) { @@ -76065,8 +96493,12 @@ var ts; substitutionsPerScope[i].set(symbolId, substitution); } else if (isTypeName) { - if (!(symbol.flags & 262144)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } } else { @@ -76077,20 +96509,42 @@ var ts; return symbolId; } function checkForUsedDeclarations(node) { + // If this node is entirely within the original extraction range, we don't need to do anything. if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) { return; } - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { - var scope = errorsPerScope_2[_i]; - scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + // Otherwise check and recurse. + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { @@ -76103,7 +96557,9 @@ var ts; if (prefix === undefined) { return undefined; } - return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -76120,85 +96576,301 @@ var ts; return ts.textSpanContainsPosition(span, node.getStart(file)) && node.getEnd() <= ts.textSpanEnd(span); } + /** + * Computes whether or not a node represents an expression in a position where it could + * be extracted. + * The isExpression() in utilities.ts returns some false positives we need to handle, + * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression + * in the sense of something that you could extract on + */ function isExtractableExpression(node) { switch (node.parent.kind) { - case 264: + case 268 /* EnumMember */: return false; } switch (node.kind) { - case 9: - return node.parent.kind !== 238 && - node.parent.kind !== 242; - case 198: - case 174: - case 176: + case 9 /* StringLiteral */: + return node.parent.kind !== 239 /* ImportDeclaration */ && + node.parent.kind !== 243 /* ImportSpecifier */; + case 199 /* SpreadElement */: + case 175 /* ObjectBindingPattern */: + case 177 /* BindingElement */: return false; - case 71: - return node.parent.kind !== 176 && - node.parent.kind !== 242 && - node.parent.kind !== 246; + case 71 /* Identifier */: + return node.parent.kind !== 177 /* BindingElement */ && + node.parent.kind !== 243 /* ImportSpecifier */ && + node.parent.kind !== 247 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 207: - case 265: - case 234: - case 257: + case 208 /* Block */: + case 269 /* SourceFile */: + case 235 /* ModuleBlock */: + case 261 /* CaseClause */: return true; default: return false; } } - })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ var ts; (function (ts) { - ts.servicesVersion = "0.5"; - var ruleProvider; + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { + // Then it will be available via `fixCannotFindModule`. + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); // Should be defined if we said there was an action available. + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) { + return undefined; + } + var resolvedTo = ts.getResolvedModule(file, node.text); + // Still offer to install types if it resolved to e.g. a ".js" file. + // `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name, + // so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings. + if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) { + return undefined; + } + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text); + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 239 /* ImportDeclaration */: + case 249 /* ExternalModuleReference */: + return true; + default: + return false; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage) { + var actionName = "Convert to default import"; + var useDefaultImport = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(useDefaultImport); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition, program = context.program; + if (!program.getCompilerOptions().allowSyntheticDefaultImports) { + return undefined; + } + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); + var resolvedFile = program.getSourceFile(module.resolvedFileName); + if (!(resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { + return undefined; + } + return [ + { + name: useDefaultImport.name, + description: useDefaultImport.description, + actions: [ + { + description: useDefaultImport.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + var file = context.file, startPosition = context.startPosition; + ts.Debug.assertEqual(actionName, _actionName); + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier; + var newImportClause = ts.createImportClause(name, /*namedBindings*/ undefined); + var newImportStatement = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newImportClause, moduleSpecifier); + return { + edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }), + renameFilename: undefined, + renameLocation: undefined, + }; + } + function getConvertibleImportAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + while (true) { + switch (node.kind) { + case 238 /* ImportEqualsDeclaration */: + var eq = node; + var moduleReference = eq.moduleReference; + return moduleReference.kind === 249 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression) + ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } + : undefined; + case 239 /* ImportDeclaration */: + var d = node; + var importClause = d.importClause; + return !importClause.name && importClause.namedBindings.kind === 241 /* NamespaceImport */ && ts.isStringLiteral(d.moduleSpecifier) + ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier } + : undefined; + // For known child node kinds of convertible imports, try again with parent node. + case 241 /* NamespaceImport */: + case 249 /* ExternalModuleReference */: + case 91 /* ImportKeyword */: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 39 /* AsteriskToken */: + break; + default: + return undefined; + } + node = node.parent; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +var ts; +(function (ts) { + /** The version of the language service API */ + ts.servicesVersion = "0.7"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : - kind === 71 ? new IdentifierObject(71, pos, end) : + kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; + node.flags = parent.flags & 6387712 /* ContextFlags */; return node; } - var NodeObject = (function () { + var NodeObject = /** @class */ (function () { function NodeObject(kind, pos, end) { this.pos = pos; this.end = end; - this.flags = 0; + this.flags = 0 /* None */; this.transformFlags = undefined; this.parent = undefined; this.kind = kind; } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); }; NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); }; NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); return this.pos; }; NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); return this.end; }; NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getStart(sourceFile) - this.pos; }; NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); if (!sourceFile) { sourceFile = this.getSourceFile(); } @@ -76213,14 +96885,14 @@ var ts; nodes.push(createNode(token, pos, textPos, this)); } pos = textPos; - if (token === 1) { + if (token === 1 /* EndOfFileToken */) { break; } } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286, nodes.pos, nodes.end, this); + var list = createNode(290 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -76243,9 +96915,10 @@ var ts; return; } if (ts.isJSDocCommentContainingNode(this)) { - var children_3 = []; - this.forEachChild(function (child) { children_3.push(child); }); - this._children = children_3; + /** Don't add trivia for "tokens" since this is in a comment. */ + var children_4 = []; + this.forEachChild(function (child) { children_4.push(child); }); + this._children = children_4; return; } var children = []; @@ -76263,12 +96936,16 @@ var ts; children.push(_this.createSyntaxList(nodes)); pos = nodes.end; }; + // jsDocComments need to be the first children if (this.jsDoc) { for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; processNode(jsDocComment); } } + // For syntactic classifications, all trivia are classcified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. pos = this.pos; ts.forEachChild(this, processNode, processNodes); if (pos < this.end) { @@ -76278,48 +96955,54 @@ var ts; this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children.length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children[index]; }; NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); if (!this._children) this.createChildren(sourceFile); return this._children; }; NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 || kid.kind > 285; }); - return child.kind < 143 ? + var child = ts.find(children, function (kid) { return kid.kind < 271 /* FirstJSDocNode */ || kid.kind > 289 /* LastJSDocNode */; }); + return child.kind < 144 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); var child = ts.lastOrUndefined(children); if (!child) { return undefined; } - return child.kind < 143 ? child : child.getLastToken(sourceFile); + return child.kind < 144 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { + var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { + // Set properties in same order as NodeObject this.pos = pos; this.end = end; - this.flags = 0; + this.flags = 0 /* None */; this.parent = undefined; } TokenOrIdentifierObject.prototype.getSourceFile = function () { @@ -76347,7 +97030,10 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; @@ -76369,7 +97055,7 @@ var ts; }; return TokenOrIdentifierObject; }()); - var SymbolObject = (function () { + var SymbolObject = /** @class */ (function () { function SymbolObject(flags, name) { this.flags = flags; this.escapedName = name; @@ -76379,7 +97065,7 @@ var ts; }; Object.defineProperty(SymbolObject.prototype, "name", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedName); + return ts.symbolName(this); }, enumerable: true, configurable: true @@ -76393,9 +97079,29 @@ var ts; SymbolObject.prototype.getDeclarations = function () { return this.declarations; }; - SymbolObject.prototype.getDocumentationComment = function () { + SymbolObject.prototype.getDocumentationComment = function (checker) { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.declarations) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.documentationComment.length === 0 || this.declarations.some(hasJSDocInheritDocTag)) { + if (checker) { + for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); + if (inheritedDocs.length > 0) { + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + break; + } + } + } + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -76407,7 +97113,7 @@ var ts; }; return SymbolObject; }()); - var TokenObject = (function (_super) { + var TokenObject = /** @class */ (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { var _this = _super.call(this, pos, end) || this; @@ -76416,22 +97122,22 @@ var ts; } return TokenObject; }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { + var IdentifierObject = /** @class */ (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; } Object.defineProperty(IdentifierObject.prototype, "text", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedText); + return ts.idText(this); }, enumerable: true, configurable: true }); return IdentifierObject; }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 71; - var TypeObject = (function () { + IdentifierObject.prototype.kind = 71 /* Identifier */; + var TypeObject = /** @class */ (function () { function TypeObject(checker, flags) { this.checker = checker; this.flags = flags; @@ -76452,28 +97158,34 @@ var ts; return this.checker.getAugmentedPropertiesOfType(this); }; TypeObject.prototype.getCallSignatures = function () { - return this.checker.getSignaturesOfType(this, 0); + return this.checker.getSignaturesOfType(this, 0 /* Call */); }; TypeObject.prototype.getConstructSignatures = function () { - return this.checker.getSignaturesOfType(this, 1); + return this.checker.getSignaturesOfType(this, 1 /* Construct */); }; TypeObject.prototype.getStringIndexType = function () { - return this.checker.getIndexTypeOfType(this, 0); + return this.checker.getIndexTypeOfType(this, 0 /* String */); }; TypeObject.prototype.getNumberIndexType = function () { - return this.checker.getIndexTypeOfType(this, 1); + return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & 32768 && this.objectFlags & (1 | 2) + return this.flags & 65536 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; TypeObject.prototype.getNonNullableType = function () { return this.checker.getNonNullableType(this); }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; return TypeObject; }()); - var SignatureObject = (function () { + var SignatureObject = /** @class */ (function () { function SignatureObject(checker) { this.checker = checker; } @@ -76491,7 +97203,19 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; + if (this.declaration) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]); + if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { + var inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -76503,7 +97227,56 @@ var ts; }; return SignatureObject; }()); - var SourceFileObject = (function (_super) { + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + var foundDocs = false; + return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + if (foundDocs) { + return ts.emptyArray; + } + var superType = typeChecker.getTypeAtLocation(superTypeNode); + if (!superType) { + return ts.emptyArray; + } + var baseProperty = typeChecker.getPropertyOfType(superType, propertyName); + if (!baseProperty) { + return ts.emptyArray; + } + var inheritedDocs = baseProperty.getDocumentationComment(typeChecker); + foundDocs = inheritedDocs.length > 0; + return inheritedDocs; + }); + } + /** + * Finds and returns the `TypeNode` for all super classes and implemented interfaces given a declaration. + * @param declaration The possibly-inherited declaration. + * @returns A filled array of `TypeNode`s containing all super classes and implemented interfaces if any exist, otherwise an empty array. + */ + function getAllSuperTypeNodes(declaration) { + var container = declaration.parent; + if (!container || (!ts.isClassDeclaration(container) && !ts.isInterfaceDeclaration(container))) { + return ts.emptyArray; + } + var extended = ts.getClassExtendsHeritageClauseElement(container); + var types = extended ? [extended] : ts.emptyArray; + return ts.isClassLike(container) ? ts.concatenate(types, ts.getClassImplementsHeritageClauseElements(container)) : types; + } + var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { return _super.call(this, kind, pos, end) || this; @@ -76531,6 +97304,7 @@ var ts; lastCharPos = lineStarts[line + 1] - 1; } var fullText = this.getFullText(); + // if the new line is "\r\n", we should return the last non-new-line-character position return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; }; SourceFileObject.prototype.getNamedDeclarations = function () { @@ -76559,13 +97333,13 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_9 = ts.getTextOfIdentifierOrLiteral(name); - if (result_9 !== undefined) { - return result_9; + var result_8 = ts.getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (name.kind === 144) { + if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; - if (expr.kind === 179) { + if (expr.kind === 180 /* PropertyAccessExpression */) { return expr.name.text; } return ts.getTextOfIdentifierOrLiteral(expr); @@ -76575,16 +97349,19 @@ var ts; } function visit(node) { switch (node.kind) { - case 228: - case 186: - case 151: - case 150: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { var declarations = getDeclarations(declarationName); var lastDeclaration = ts.lastOrUndefined(declarations); + // Check whether this declaration belongs to an "overload group". if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + // Overwrite the last declaration if it was an overload + // and this one is an implementation. if (functionDeclaration.body && !lastDeclaration.body) { declarations[declarations.length - 1] = functionDeclaration; } @@ -76595,29 +97372,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 229: - case 199: - case 230: - case 231: - case 232: - case 233: - case 237: - case 246: - case 242: - case 239: - case 240: - case 153: - case 154: - case 163: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 164 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 146: - if (!ts.hasModifier(node, 92)) { + case 147 /* Parameter */: + // Only consider parameter properties + if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } - case 226: - case 176: { + // falls through + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -76627,24 +97406,32 @@ var ts; visit(decl.initializer); } } - case 264: - case 149: - case 148: + // falls through + case 268 /* EnumMember */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: addDeclaration(node); break; - case 244: + case 245 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 238: + case 239 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; if (importClause.name) { addDeclaration(importClause); } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { + if (importClause.namedBindings.kind === 241 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -76653,10 +97440,11 @@ var ts; } } break; - case 194: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0) { + case 195 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { addDeclaration(node); } + // falls through default: ts.forEachChild(node, visit); } @@ -76664,7 +97452,7 @@ var ts; }; return SourceFileObject; }(NodeObject)); - var SourceMapSourceObject = (function () { + var SourceMapSourceObject = /** @class */ (function () { function SourceMapSourceObject(fileName, text, skipTrivia) { this.fileName = fileName; this.text = text; @@ -76719,9 +97507,10 @@ var ts; } ts.displayPartsToString = displayPartsToString; function getDefaultCompilerOptions() { + // Always default to "ScriptTarget.ES5" for the language service return { - target: 1, - jsx: 1 + target: 1 /* ES5 */, + jsx: 1 /* Preserve */ }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; @@ -76729,16 +97518,22 @@ var ts; return ts.codefix.getSupportedErrorCodes(); } ts.getSupportedCodeFixes = getSupportedCodeFixes; - var HostCache = (function () { + // Cache host information about script Should be refreshed + // at each language service public entry point, since we don't know when + // the set of scripts handled by the host changes. + var HostCache = /** @class */ (function () { function HostCache(host, getCanonicalFileName) { this.host = host; + // script id => script index this.currentDirectory = host.getCurrentDirectory(); this.fileNameToEntry = ts.createMap(); + // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { var fileName = rootFileNames_1[_i]; this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } + // store the compilation settings this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); } HostCache.prototype.compilationSettings = function () { @@ -76755,59 +97550,62 @@ var ts; scriptKind: ts.getScriptKind(fileName, this.host) }; } + else { + entry = fileName; + } this.fileNameToEntry.set(path, entry); return entry; }; HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.containsEntryByPath = function (path) { - return this.fileNameToEntry.has(path); + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.containsEntryByPath(path) - ? this.getEntryByPath(path) - : this.createEntry(fileName, path); + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - var fileNames = []; - this.fileNameToEntry.forEach(function (value) { - if (value) { - fileNames.push(value.hostFileName); - } + return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { + return ts.isString(entry) ? entry : entry.hostFileName; }); - return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.scriptSnapshot; }; return HostCache; }()); - var SyntaxTreeCache = (function () { + var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; } SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (!scriptSnapshot) { + // The host does not know about this file. throw new Error("Could not find file: '" + fileName + "'."); } var scriptKind = ts.getScriptKind(fileName, this.host); var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5, version, true, scriptKind); + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); } if (sourceFile) { + // All done, ensure state is up to date this.currentFileVersion = version; this.currentFileName = fileName; this.currentFileScriptSnapshot = scriptSnapshot; @@ -76830,21 +97628,29 @@ var ts; ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; ts.disableIncrementalParsing = false; function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) { + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. if (textChangeRange) { if (version !== sourceFile.version) { + // Once incremental parsing is ready, then just call into this function. if (!ts.disableIncrementalParsing) { var newText = void 0; + // grab the fragment from the beginning of the original text to the beginning of the span var prefix = textChangeRange.span.start !== 0 ? sourceFile.text.substr(0, textChangeRange.span.start) : ""; + // grab the fragment from the end of the span till the end of the original text var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) : ""; if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix newText = prefix && suffix ? prefix + suffix : prefix || suffix; } else { + // it was actual edit, fetch the fragment of new text that correspond to new span var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix newText = prefix && suffix ? prefix + changedText + suffix : prefix @@ -76853,7 +97659,10 @@ var ts; } var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); setSourceFileFields(newSourceFile, scriptSnapshot, version); + // after incremental parsing nameTable might not be up-to-date + // drop it so it can be lazily recreated later newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { if (sourceFile.scriptSnapshot.dispose) { sourceFile.scriptSnapshot.dispose(); @@ -76864,10 +97673,11 @@ var ts; } } } - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true, sourceFile.scriptKind); + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - var CancellationTokenObject = (function () { + var CancellationTokenObject = /** @class */ (function () { function CancellationTokenObject(cancellationToken) { this.cancellationToken = cancellationToken; } @@ -76881,17 +97691,23 @@ var ts; }; return CancellationTokenObject; }()); - var ThrottledCancellationToken = (function () { + /* @internal */ + /** A cancellation that throttles calls to the host */ + var ThrottledCancellationToken = /** @class */ (function () { function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) { if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; } this.hostCancellationToken = hostCancellationToken; this.throttleWaitMilliseconds = throttleWaitMilliseconds; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { var time = ts.timestamp(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration >= this.throttleWaitMilliseconds) { + // Check no more than once every throttle wait milliseconds this.lastCancellationCheckTime = time; return this.hostCancellationToken.isCancellationRequested(); } @@ -76908,13 +97724,13 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); + // Check if the localized messages json is set, otherwise query the host for it if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } @@ -76931,15 +97747,12 @@ var ts; } return sourceFile; } - function getRuleProvider(options) { - ruleProvider.ensureUpToDate(options); - return ruleProvider; - } function synchronizeHostData() { + // perform fast check if host supports it if (host.getProjectVersion) { var hostProjectVersion = host.getProjectVersion(); if (hostProjectVersion) { - if (lastProjectVersion === hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { return; } lastProjectVersion = hostProjectVersion; @@ -76951,43 +97764,38 @@ var ts; program = undefined; lastTypesRootVersion = typeRootsVersion; } + // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); - if (programUpToDate()) { + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { return; } - var oldSettings = program && program.getCompilerOptions(); + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. var newSettings = hostCache.compilationSettings(); - var shouldCreateNewSourceFiles = oldSettings && - (oldSettings.target !== newSettings.target || - oldSettings.module !== newSettings.module || - oldSettings.moduleResolution !== newSettings.moduleResolution || - oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || - oldSettings.baseUrl !== newSettings.baseUrl || - !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); + // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: function (fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - return hostCache.containsEntryByPath(path) ? - !!hostCache.getEntryByPath(path) : - (host.fileExists && host.fileExists(fileName)); - }, + fileExists: fileExists, readFile: function (fileName) { + // stub missing host functionality var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - if (hostCache.containsEntryByPath(path)) { - var entry = hostCache.getEntryByPath(path); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var entry = hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); } return host.readFile && host.readFile(fileName); }, @@ -76996,13 +97804,16 @@ var ts; }, getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; - } + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames }; if (host.trace) { compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; } if (host.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { @@ -77010,70 +97821,78 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - var newProgram = ts.createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program); - if (program) { - var oldSourceFiles = program.getSourceFiles(); - var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { - var oldSourceFile = oldSourceFiles_2[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); - } - } - } + program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; - program = newProgram; + // Make sure all the nodes in the program are both bound, and have their parent + // pointers set property. program.getTypeChecker(); return; - function getOrCreateSourceFile(fileName) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName)); - } - function getOrCreateSourceFileByPath(fileName, path) { + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + } + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { ts.Debug.assert(hostCache !== undefined); + // The program is asking for this file, check first if the host can locate it. + // If the host can not locate the file, then it does not exist. return undefined + // to the program to allow reporting of errors for missing files. var hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path); if (!hostFileInformation) { return undefined; } - if (!shouldCreateNewSourceFiles) { + // Check if the language version has changed since we last created a program; if they are the same, + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // can not be reused. we have to dump all syntax trees and create new ones. + if (!shouldCreateNewSourceFile) { + // Check if the old program had this file already var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { + // We already had a source file for this file name. Go to the registry to + // ensure that we get the right up to date version of it. We need this to + // address the following race-condition. Specifically, say we have the following: + // + // LS1 + // \ + // DocumentRegistry + // / + // LS2 + // + // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates + // it's version of 'foo.ts' to version 2. This will cause LS2 and the + // DocumentRegistry to have version 2 of the document. HOwever, LS1 will + // have version 1. And *importantly* this source file will be *corrupt*. + // The act of creating version 2 of the file irrevocably damages the version + // 1 file. + // + // So, later when we call into LS1, we need to make sure that it doesn't use + // it's source file any more, and instead defers to DocumentRegistry to get + // either version 1, version 2 (or some other version) depending on what the + // host says should be used. + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } + // We didn't already have the file. Fall through and acquire it from the registry. } + // Could not find this file in the old program, create a new SourceFile for it. return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } - function sourceFileUpToDate(sourceFile) { - if (!sourceFile) { - return false; - } - var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile.version === hostCache.getVersion(path); - } - function programUpToDate() { - if (!program) { - return false; - } - var rootFileNames = hostCache.getRootFileNames(); - if (program.getSourceFiles().length !== rootFileNames.length) { - return false; - } - for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { - var fileName = rootFileNames_2[_i]; - if (!sourceFileUpToDate(program.getSourceFile(fileName))) { - return false; - } - } - var currentOptions = program.getCompilerOptions(); - var newOptions = hostCache.compilationSettings(); - if (!ts.compareDataObjects(currentOptions, newOptions)) { - return false; - } - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } - return true; - } } function getProgram() { synchronizeHostData(); @@ -77091,17 +97910,25 @@ var ts; } host = undefined; } + /// Diagnostics function getSyntacticDiagnostics(fileName) { synchronizeHostData(); return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); } + /** + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * If '-d' enabled, report both semantic and emitter errors + */ function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); + // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. + // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { return semanticDiagnostics.slice(); } + // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return semanticDiagnostics.concat(declarationDiagnostics); } @@ -77109,22 +97936,23 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - function getCompletionsAtPosition(fileName, position) { + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = { includeExternalModuleExports: false }; } synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } - function getCompletionEntrySymbol(fileName, position, entryName) { + function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, true); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -77134,21 +97962,23 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { + // Try getting just type at this position and show switch (node.kind) { - case 71: - case 179: - case 143: - case 99: - case 169: - case 97: + case 71 /* Identifier */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: + case 99 /* ThisKeyword */: + case 170 /* ThisType */: + case 97 /* SuperKeyword */: + // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: "", - kindModifiers: "", + kind: "" /* unknown */, + kindModifiers: "" /* none */, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } @@ -77179,22 +98009,31 @@ var ts; } return checker.getSymbolAtLocation(node); } + /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } + /// Goto implementation function getImplementationAtPosition(fileName, position) { synchronizeHostData(); return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } + /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + // Get occurrences only supports reporting occurrences for the file queried. So + // filter down to that list. results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); } return results; @@ -77219,7 +98058,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === "writtenReference", + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, isDefinition: false, isInString: highlightSpan.isInString, }); @@ -77236,6 +98075,7 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = []; if (options && options.isForRename) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { @@ -77254,6 +98094,7 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } + /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); @@ -77262,22 +98103,19 @@ var ts; function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var outputFiles = []; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { - outputFiles: outputFiles, - emitSkipped: emitOutput.emitSkipped - }; + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } + // Signature help + /** + * This is a semantic operation. + */ function getSignatureHelpItems(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken); } + /// Syntactic features function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } @@ -77286,46 +98124,56 @@ var ts; } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, startPos, false); + // Get node at the location + var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; } switch (node.kind) { - case 179: - case 143: - case 9: - case 86: - case 101: - case 95: - case 97: - case 99: - case 169: - case 71: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: + case 9 /* StringLiteral */: + case 86 /* FalseKeyword */: + case 101 /* TrueKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 99 /* ThisKeyword */: + case 170 /* ThisType */: + case 71 /* Identifier */: break; + // Cant create the text span default: return; } var nodeForStartPos = node; while (true) { if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) { + // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node nodeForStartPos = nodeForStartPos.parent; } else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 233 && + // If this is name of a module declarations, check if this is right side of dotted module name + // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of + // Then this name is name from dotted module + if (nodeForStartPos.parent.parent.kind === 234 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { + // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; } else { + // We have to use this name for start pos break; } } else { + // Is not a member expression so we have found the node for start pos break; } } return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); } function getBreakpointStatementAtPosition(fileName, position) { + // doesn't use compiler - no need to synchronize with host var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } @@ -77337,10 +98185,11 @@ var ts; } function isTsOrTsxFile(fileName) { var kind = ts.getScriptKind(fileName, host); - return kind === 3 || kind === 4; + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files return []; } synchronizeHostData(); @@ -77348,27 +98197,32 @@ var ts; } function getEncodedSemanticClassifications(fileName, span) { if (!isTsOrTsxFile(fileName)) { - return { spans: [], endOfLineState: 0 }; + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getEncodedSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span); } function getOutliningSpans(fileName) { + // doesn't use compiler - no need to synchronize with host var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken); } function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position, false); + var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); + // Ensure that there is a corresponding token to match ours. if (matchKind) { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); @@ -77377,6 +98231,7 @@ var ts; if (current.kind === matchKind) { var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); + // We want to order the braces when we return the result. if (range1.start < range2.start) { result.push(range1, range2); } @@ -77391,14 +98246,14 @@ var ts; return result; function getMatchingTokenKind(token) { switch (token.kind) { - case 17: return 18; - case 19: return 20; - case 21: return 22; - case 27: return 29; - case 18: return 17; - case 20: return 19; - case 22: return 21; - case 29: return 27; + case 17 /* OpenBraceToken */: return 18 /* CloseBraceToken */; + case 19 /* OpenParenToken */: return 20 /* CloseParenToken */; + case 21 /* OpenBracketToken */: return 22 /* CloseBracketToken */; + case 27 /* LessThanToken */: return 29 /* GreaterThanToken */; + case 18 /* CloseBraceToken */: return 17 /* OpenBraceToken */; + case 20 /* CloseParenToken */: return 19 /* OpenParenToken */; + case 22 /* CloseBracketToken */: return 21 /* OpenBracketToken */; + case 29 /* GreaterThanToken */: return 27 /* LessThanToken */; } return undefined; } @@ -77415,29 +98270,24 @@ var ts; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsForDocument(fileName, options) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); if (!ts.isInComment(sourceFile, position)) { - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); } } return []; @@ -77447,33 +98297,54 @@ var ts; var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); - var rulesProvider = getRuleProvider(formatOptions); - return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function applyCodeActionCommand(fileName, actionOrUndefined) { + var action = typeof fileName === "string" ? actionOrUndefined : fileName; + return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + } + function applySingleCodeActionCommand(action) { + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { - if (openingBrace === 60) { + // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too + // expensive to do during typing scenarios + // i.e. whether we're dealing with: + // var x = new foo<| ( with class foo{} ) + // or + // var y = 3 <| + if (openingBrace === 60 /* lessThan */) { return false; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { - return openingBrace === 123; + return openingBrace === 123 /* openBrace */; } if (ts.isInTemplateString(sourceFile, position)) { return false; } switch (openingBrace) { - case 39: - case 34: - case 96: + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: return !ts.isInComment(sourceFile, position); } return true; @@ -77484,20 +98355,46 @@ var ts; return range && ts.createTextSpanFromRange(range); } function getTodoComments(fileName, descriptors) { + // Note: while getting todo comments seems like a syntactic operation, we actually + // treat it as a semantic operation here. This is because we expect our host to call + // this on every single file. If we treat this syntactically, then that will cause + // us to populate and throw away the tree in our syntax tree cache for each file. By + // treating this as a semantic operation, we can access any tree without throwing + // anything away. synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); cancellationToken.throwIfCancellationRequested(); var fileContents = sourceFile.text; var result = []; + // Exclude node_modules files as we don't want to show the todos of external libraries. if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { var regExp = getTodoCommentsRegExp(); var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { cancellationToken.throwIfCancellationRequested(); + // If we got a match, here is what the match array will look like. Say the source text is: + // + // " // hack 1" + // + // The result array with the regexp: will be: + // + // ["// hack 1", "// ", "hack 1", undefined, "hack"] + // + // Here are the relevant capture groups: + // 0) The full match for the entire regexp. + // 1) The preamble to the message portion. + // 2) The message portion. + // 3...N) The descriptor that was matched - by index. 'undefined' for each + // descriptor that didn't match. an actual value if it did match. + // + // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. + // "hack" in position 4 means HACK did match. var firstDescriptorCaptureIndex = 3; ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; + // OK, we have found a match in the file. This is only an acceptable match if + // it is contained within a comment. if (!ts.isInComment(sourceFile, matchPosition)) { continue; } @@ -77508,6 +98405,8 @@ var ts; } } ts.Debug.assert(descriptor !== undefined); + // We don't want to match something like 'TODOBY', so we make sure a non + // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { continue; } @@ -77520,25 +98419,62 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { + // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // filter them out later in the final result array. + // TODO comments can appear in one of the following forms: + // + // 1) // TODO or /////////// TODO + // + // 2) /* TODO or /********** TODO + // + // 3) /* + // * TODO + // */ + // + // The following three regexps are used to match the start of the text up to the TODO + // comment portion. var singleLineCommentStart = /(?:\/\/+\s*)/.source; var multiLineCommentStart = /(?:\/\*+\s*)/.source; var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + // Match any of the above three TODO comment start regexps. + // Note that the outermost group *is* a capture group. We want to capture the preamble + // so that we can determine the starting position of the TODO comment match. var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + // Takes the descriptors and forms a regexp that matches them as if they were literals. + // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: + // + // (?:(TODO\(jason\))|(HACK)) + // + // Note that the outermost group is *not* a capture group, but the innermost groups + // *are* capture groups. By capturing the inner literals we can determine after + // matching which descriptor we are dealing with. var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; + // After matching a descriptor literal, the following regexp matches the rest of the + // text up to the end of the line (or */). var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; var messageRemainder = /(?:.*?)/.source; + // This is the portion of the match we'll return as part of the TODO comment result. We + // match the literal portion up to the end of the line or end of comment. var messagePortion = "(" + literals + messageRemainder + ")"; var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + // The final regexp will look like this: + // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim + // The flags of the regexp are important here. + // 'g' is so that we are doing a global search and can find matches several times + // in the input. + // + // 'i' is for case insensitivity (We do this to match C# TODO comment code). + // + // 'm' is so we can find matches in a multi-line input. return new RegExp(regExpString, "gim"); } function isLetterOrDigit(char) { - return (char >= 97 && char <= 122) || - (char >= 65 && char <= 90) || - (char >= 48 && char <= 57); + return (char >= 97 /* a */ && char <= 122 /* z */) || + (char >= 65 /* A */ && char <= 90 /* Z */) || + (char >= 48 /* _0 */ && char <= 57 /* _9 */); } function isNodeModulesFile(path) { - var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, "/node_modules/"); } } function getRenameInfo(fileName, position) { @@ -77554,8 +98490,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), - rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -77584,6 +98521,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, @@ -77608,6 +98546,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -77617,6 +98556,8 @@ var ts; }; } ts.createLanguageService = createLanguageService; + /* @internal */ + /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */ function getNameTable(sourceFile) { if (!sourceFile.nameTable) { initializeNameTable(sourceFile); @@ -77640,63 +98581,76 @@ var ts; } }); } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 248 || + node.parent.kind === 249 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { - case 253: - case 255: - case 261: - case 262: - case 151: - case 153: - case 154: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return true; } return false; } + /** + * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } + */ + /* @internal */ function getContainingObjectLiteralElement(node) { switch (node.kind) { - case 9: - case 8: - if (node.parent.kind === 144) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (node.parent.kind === 145 /* ComputedPropertyName */) { return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } - case 71: + // falls through + case 71 /* Identifier */: return isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 178 || node.parent.parent.kind === 254) && + (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; } ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + /* @internal */ function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); return getPropertySymbolsFromType(contextualType, node.name); } ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /* @internal */ function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_10 = []; + var result_9 = []; var symbol = type.getProperty(name); - if (type.flags & 65536) { + if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_10.push(symbol); + result_9.push(symbol); } }); - return result_10; + return result_9; } if (symbol) { - result_10.push(symbol); - return result_10; + result_9.push(symbol); + return result_9; } } return undefined; @@ -77705,10 +98659,16 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 180 && + node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ function getDefaultLibFilePath(options) { + // Check __dirname is defined and that we are on a node.js system. if (typeof __dirname !== "undefined") { return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); } @@ -77717,12 +98677,19 @@ var ts; ts.getDefaultLibFilePath = getDefaultLibFilePath; ts.objectAllocator = getServicesObjectAllocator(); })(ts || (ts = {})); +/// +/// +/// +/// var ts; (function (ts) { var server; (function (server) { + // tslint:disable variable-name server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; server.EventInitializationFailed = "event::initializationFailed"; @@ -77733,6 +98700,10 @@ var ts; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { @@ -77748,6 +98719,8 @@ var ts; server.findArgument = findArgument; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/// var ts; (function (ts) { var server; @@ -77760,28 +98733,30 @@ var ts; LogLevel[LogLevel["verbose"] = 3] = "verbose"; })(LogLevel = server.LogLevel || (server.LogLevel = {})); server.emptyArray = createSortedArray(); + // TODO: Use a const enum (https://github.com/Microsoft/TypeScript/issues/16804) var Msg; (function (Msg) { - Msg.Err = "Err"; - Msg.Info = "Info"; - Msg.Perf = "Perf"; + Msg["Err"] = "Err"; + Msg["Info"] = "Info"; + Msg["Perf"] = "Perf"; })(Msg = server.Msg || (server.Msg = {})); function getProjectRootPath(project) { switch (project.projectKind) { case server.ProjectKind.Configured: return ts.getDirectoryPath(project.getProjectName()); case server.ProjectKind.Inferred: + // TODO: fixme return ""; case server.ProjectKind.External: var projectName = ts.normalizeSlashes(project.getProjectName()); - return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + return ts.getDirectoryPath(projectName); } } function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()), - compilerOptions: project.getCompilerOptions(), + fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true, /*excludeConfigFiles*/ true).concat(project.getExcludedFiles()), + compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, projectRootPath: getProjectRootPath(project), @@ -77869,6 +98844,7 @@ var ts; } server.createNormalizedPathMap = createNormalizedPathMap; function isInferredProjectName(name) { + // POSIX defines /dev/null as a device - there should be no file with this prefix return /dev\/null\/inferredProject\d+\*/.test(name); } server.isInferredProjectName = isInferredProjectName; @@ -77880,26 +98856,47 @@ var ts; return []; } server.createSortedArray = createSortedArray; - var ThrottledOperations = (function () { - function ThrottledOperations(host) { + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + var server; + (function (server) { + var ThrottledOperations = /** @class */ (function () { + function ThrottledOperations(host, logger) { this.host = host; this.pendingTimeouts = ts.createMap(); - } + this.logger = logger.hasLevel(server.LogLevel.verbose) && logger; + } + /** + * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule + * is called again with the same `operationId`, cancel this operation in favor + * of the new one. (Note that the amount of time the canceled operation had been + * waiting does not affect the amount of time that the new operation waits.) + */ ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { var pendingTimeout = this.pendingTimeouts.get(operationId); if (pendingTimeout) { + // another operation was already scheduled for this id - cancel it this.host.clearTimeout(pendingTimeout); } + // schedule new operation, pass arguments this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); + if (this.logger) { + this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : "")); + } }; ThrottledOperations.run = function (self, operationId, cb) { self.pendingTimeouts.delete(operationId); + if (self.logger) { + self.logger.info("Running: " + operationId); + } cb(); }; return ThrottledOperations; }()); server.ThrottledOperations = ThrottledOperations; - var GcTimer = (function () { + var GcTimer = /** @class */ (function () { function GcTimer(host, delay, logger) { this.host = host; this.delay = delay; @@ -77907,13 +98904,14 @@ var ts; } GcTimer.prototype.scheduleCollect = function () { if (!this.host.gc || this.timerId !== undefined) { + // no global.gc or collection was already scheduled - skip this request return; } this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); }; GcTimer.run = function (self) { self.timerId = undefined; - var log = self.logger.hasLevel(LogLevel.requestTime); + var log = self.logger.hasLevel(server.LogLevel.requestTime); var before = log && self.host.getMemoryUsage(); self.host.gc(); if (log) { @@ -77924,17 +98922,17 @@ var ts; return GcTimer; }()); server.GcTimer = GcTimer; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -(function (ts) { - var server; - (function (server) { + function getBaseConfigFileName(configFilePath) { + var base = ts.getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : undefined; + } + server.getBaseConfigFileName = getBaseConfigFileName; function insertSorted(array, insert, compare) { if (array.length === 0) { array.push(insert); return; } - var insertIndex = ts.binarySearch(array, insert, compare); + var insertIndex = ts.binarySearch(array, insert, ts.identity, compare); if (insertIndex < 0) { array.splice(~insertIndex, 0, insert); } @@ -77948,7 +98946,7 @@ var ts; array.splice(0, 1); return; } - var removeIndex = ts.binarySearch(array, remove, compare); + var removeIndex = ts.binarySearch(array, remove, ts.identity, compare); if (removeIndex >= 0) { array.splice(removeIndex, 1); } @@ -77968,8 +98966,7 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } - function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { - compare = compare || ts.compareValues; + function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, comparer) { var newIndex = 0; var oldIndex = 0; var newLen = newItems.length; @@ -77977,12 +98974,12 @@ var ts; while (newIndex < newLen && oldIndex < oldLen) { var newItem = newItems[newIndex]; var oldItem = oldItems[oldIndex]; - var compareResult = compare(newItem, oldItem); - if (compareResult === -1) { + var compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { inserted(newItem); newIndex++; } - else if (compareResult === 1) { + else if (compareResult === 1 /* GreaterThan */) { deleted(oldItem); oldIndex++; } @@ -77999,62 +98996,97 @@ var ts; } } server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + /* @internal */ + function indent(str) { + return "\n " + str; + } + server.indent = indent; + /** Put stringified JSON on the next line, indented. */ + /* @internal */ + function stringifyIndented(json) { + return "\n " + JSON.stringify(json); + } + server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/** + * Declaration module describing the TypeScript Server protocol + */ var ts; (function (ts) { var server; (function (server) { var protocol; (function (protocol) { + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. var CommandTypes; (function (CommandTypes) { CommandTypes["Brace"] = "brace"; + /* @internal */ CommandTypes["BraceFull"] = "brace-full"; CommandTypes["BraceCompletion"] = "braceCompletion"; CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; CommandTypes["Change"] = "change"; CommandTypes["Close"] = "close"; CommandTypes["Completions"] = "completions"; + /* @internal */ CommandTypes["CompletionsFull"] = "completions-full"; CommandTypes["CompletionDetails"] = "completionEntryDetails"; + /* @internal */ + CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full"; CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; CommandTypes["Configure"] = "configure"; CommandTypes["Definition"] = "definition"; + /* @internal */ CommandTypes["DefinitionFull"] = "definition-full"; + CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; + /* @internal */ + CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; CommandTypes["Implementation"] = "implementation"; + /* @internal */ CommandTypes["ImplementationFull"] = "implementation-full"; CommandTypes["Exit"] = "exit"; CommandTypes["Format"] = "format"; CommandTypes["Formatonkey"] = "formatonkey"; + /* @internal */ CommandTypes["FormatFull"] = "format-full"; + /* @internal */ CommandTypes["FormatonkeyFull"] = "formatonkey-full"; + /* @internal */ CommandTypes["FormatRangeFull"] = "formatRange-full"; CommandTypes["Geterr"] = "geterr"; CommandTypes["GeterrForProject"] = "geterrForProject"; CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; CommandTypes["NavBar"] = "navbar"; + /* @internal */ CommandTypes["NavBarFull"] = "navbar-full"; CommandTypes["Navto"] = "navto"; + /* @internal */ CommandTypes["NavtoFull"] = "navto-full"; CommandTypes["NavTree"] = "navtree"; CommandTypes["NavTreeFull"] = "navtree-full"; CommandTypes["Occurrences"] = "occurrences"; CommandTypes["DocumentHighlights"] = "documentHighlights"; + /* @internal */ CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full"; CommandTypes["Open"] = "open"; CommandTypes["Quickinfo"] = "quickinfo"; + /* @internal */ CommandTypes["QuickinfoFull"] = "quickinfo-full"; CommandTypes["References"] = "references"; + /* @internal */ CommandTypes["ReferencesFull"] = "references-full"; CommandTypes["Reload"] = "reload"; CommandTypes["Rename"] = "rename"; + /* @internal */ CommandTypes["RenameInfoFull"] = "rename-full"; + /* @internal */ CommandTypes["RenameLocationsFull"] = "renameLocations-full"; CommandTypes["Saveto"] = "saveto"; CommandTypes["SignatureHelp"] = "signatureHelp"; + /* @internal */ CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; CommandTypes["TypeDefinition"] = "typeDefinition"; CommandTypes["ProjectInfo"] = "projectInfo"; @@ -78063,24 +99095,36 @@ var ts; CommandTypes["OpenExternalProject"] = "openExternalProject"; CommandTypes["OpenExternalProjects"] = "openExternalProjects"; CommandTypes["CloseExternalProject"] = "closeExternalProject"; + /* @internal */ CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList"; + /* @internal */ CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + /* @internal */ CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + /* @internal */ CommandTypes["Cleanup"] = "cleanup"; + /* @internal */ CommandTypes["OutliningSpans"] = "outliningSpans"; CommandTypes["TodoComments"] = "todoComments"; CommandTypes["Indentation"] = "indentation"; CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; + /* @internal */ CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + /* @internal */ CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + /* @internal */ CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; + /* @internal */ CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; + /* @internal */ CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); var IndentStyle; (function (IndentStyle) { @@ -78129,6 +99173,10 @@ var ts; })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/// +/// +/// var ts; (function (ts) { var server; @@ -78144,6 +99192,18 @@ var ts; return ((1e9 * seconds) + nanoseconds) / 1000000.0; } function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) { + // Checking for semantic diagnostics is an expensive process. We want to avoid it if we + // know for sure it is not needed. + // For instance, .d.ts files injected by ATA automatically do not produce any relevant + // errors to a JS- only project. + // + // Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to + // disable checking for declaration files. We only need to verify for inferred projects (e.g. + // miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS + // files. + // + // We still want to check .js files in a JS-only inferred or external project (e.g. if the + // file has '// @ts-check'). if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { var scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -78202,18 +99262,22 @@ var ts; } return true; } - server.CommandNames = server.protocol.CommandTypes; + server.CommandNames = server.protocol.CommandTypes; // tslint:disable-line variable-name function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); if (verboseLogging) { - logger.info(msg.type + ": " + json); + logger.info(msg.type + ":" + server.indent(json)); } var len = byteLength(json, "utf8"); return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; } server.formatMessage = formatMessage; - var MultistepOperation = (function () { + /** + * Represents operation that can schedule its next step to be executed later. + * Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed. + */ + var MultistepOperation = /** @class */ (function () { function MultistepOperation(operationHost) { this.operationHost = operationHost; } @@ -78260,6 +99324,7 @@ var ts; } catch (e) { stop = true; + // ignore cancellation request if (!(e instanceof ts.OperationCanceledException)) { this.operationHost.logError(e, "delayed processing of request " + this.requestId); } @@ -78285,22 +99350,35 @@ var ts; }; return MultistepOperation; }()); - var Session = (function () { + /** @internal */ + function toEvent(eventName, body) { + return { + seq: 0, + type: "event", + event: eventName, + body: body + }; + } + server.toEvent = toEvent; + var Session = /** @class */ (function () { function Session(opts) { var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, _a[server.CommandNames.OpenExternalProject] = function (request) { - _this.projectService.openExternalProject(request.arguments, false); - return _this.requiredResponse(true); + _this.projectService.openExternalProject(request.arguments, /*suppressRefreshOfInferredProjects*/ false); + // TODO: report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.OpenExternalProjects] = function (request) { _this.projectService.openExternalProjects(request.arguments.projects); - return _this.requiredResponse(true); + // TODO: report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.CloseExternalProject] = function (request) { _this.projectService.closeExternalProject(request.arguments.projectFileName); - return _this.requiredResponse(true); + // TODO: report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.SynchronizeProjectList] = function (request) { var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); @@ -78315,46 +99393,53 @@ var ts; info: p.info, changes: p.changes, files: p.files, - projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined) }; }); return _this.requiredResponse(converted); }, _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { - _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); _this.changeSeq++; - return _this.requiredResponse(true); + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + // TODO: report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.Exit] = function () { _this.exit(); return _this.notRequired(); }, _a[server.CommandNames.Definition] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.DefinitionFull] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, false)); + return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.DefinitionAndBoundSpan] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) { + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.TypeDefinition] = function (request) { return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[server.CommandNames.Implementation] = function (request) { - return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.ImplementationFull] = function (request) { - return _this.requiredResponse(_this.getImplementation(request.arguments, false)); + return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.References] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, true)); + return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.ReferencesFull] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, false)); + return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.Rename] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.RenameLocationsFull] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.RenameInfoFull] = function (request) { return _this.requiredResponse(_this.getRenameInfo(request.arguments)); @@ -78364,10 +99449,10 @@ var ts; return _this.notRequired(); }, _a[server.CommandNames.Quickinfo] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.QuickinfoFull] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.OutliningSpans] = function (request) { return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); @@ -78409,13 +99494,16 @@ var ts; return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[server.CommandNames.Completions] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + return _this.requiredResponse(_this.getCompletions(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.CompletionsFull] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, false)); + return _this.requiredResponse(_this.getCompletions(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.CompletionDetailsFull] = function (request) { + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); @@ -78424,10 +99512,10 @@ var ts; return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[server.CommandNames.SignatureHelp] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.SignatureHelpFull] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); @@ -78437,7 +99525,7 @@ var ts; }, _a[server.CommandNames.Cleanup] = function () { _this.cleanup(); - return _this.requiredResponse(true); + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -78459,7 +99547,7 @@ var ts; }, _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.output(undefined, server.CommandNames.Configure, request.seq); + _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true); return _this.notRequired(); }, _a[server.CommandNames.Reload] = function (request) { @@ -78477,41 +99565,41 @@ var ts; return _this.notRequired(); }, _a[server.CommandNames.Navto] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.NavtoFull] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.Brace] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.BraceFull] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); + return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.NavBar] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.NavBarFull] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.NavTree] = function (request) { - return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.NavTreeFull] = function (request) { - return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); + return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.Occurrences] = function (request) { return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[server.CommandNames.DocumentHighlights] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.DocumentHighlightsFull] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) { _this.setCompilerOptionsForInferredProjects(request.arguments); - return _this.requiredResponse(true); + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.ProjectInfo] = function (request) { return _this.requiredResponse(_this.getProjectInfo(request.arguments)); @@ -78521,10 +99609,14 @@ var ts; return _this.notRequired(); }, _a[server.CommandNames.GetCodeFixes] = function (request) { - return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetCodeFixesFull] = function (request) { - return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { + _this.applyCodeActionCommand(request.command, request.seq, request.arguments); + return _this.notRequired(); // Response will come asynchronously. }, _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); @@ -78533,10 +99625,10 @@ var ts; return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); }, _a[server.CommandNames.GetEditsForRefactor] = function (request) { - return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true)); + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetEditsForRefactorFull] = function (request) { - return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false)); + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ false)); }, _a)); this.host = opts.host; @@ -78573,29 +99665,26 @@ var ts; allowLocalPluginLoads: opts.allowLocalPluginLoads }; this.projectService = new server.ProjectService(settings); - this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); + this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger); var _a; } Session.prototype.sendRequestCompletedEvent = function (requestId) { - var event = { - seq: 0, - type: "event", - event: "requestCompleted", - body: { request_seq: requestId } - }; - this.send(event); + this.event({ request_seq: requestId }, "requestCompleted"); }; Session.prototype.defaultEventHandler = function (event) { - var _this = this; switch (event.eventName) { - case server.ContextEvent: - var _a = event.data, project_1 = _a.project, fileName_2 = _a.fileName; - this.projectService.logger.info("got context event, updating diagnostics for " + fileName_2); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_2, project: project_1 }], 100); }); + case server.ProjectsUpdatedInBackgroundEvent: + var openFiles = event.data.openFiles; + this.projectsUpdatedInBackgroundEvent(openFiles); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; - this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + var _a = event.data, triggerFile = _a.triggerFile, configFile = _a.configFileName, diagnostics = _a.diagnostics; + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); }); + this.event({ + triggerFile: triggerFile, + configFile: configFile, + diagnostics: bakedDiags + }, "configFileDiag"); break; case server.ProjectLanguageServiceStateEvent: { var eventName = "projectLanguageServiceState"; @@ -78615,12 +99704,25 @@ var ts; } } }; + Session.prototype.projectsUpdatedInBackgroundEvent = function (openFiles) { + var _this = this; + this.projectService.logger.info("got projects updated in background, updating diagnostics for " + openFiles); + if (openFiles.length) { + var checkList_1 = this.createCheckList(openFiles); + // For now only queue error checking for open files. We can change this to include non open files as well + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); }); + // Send project changed event + this.event({ + openFiles: openFiles + }, "projectsUpdatedInBackground"); + } + }; Session.prototype.logError = function (err, cmd) { var msg = "Exception on executing command " + cmd; if (err.message) { - msg += ":\n" + err.message; + msg += ":\n" + server.indent(err.message); if (err.stack) { - msg += "\n" + err.stack; + msg += "\n" + server.indent(err.stack); } } this.logger.msg(msg, server.Msg.Err); @@ -78634,43 +99736,30 @@ var ts; } this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; - Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { - var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); - var ev = { - seq: 0, - type: "event", - event: "configFileDiag", - body: { - triggerFile: triggerFile, - configFile: configFile, - diagnostics: bakedDiags - } - }; - this.send(ev); - }; - Session.prototype.event = function (info, eventName) { - var ev = { - seq: 0, - type: "event", - event: eventName, - body: info - }; - this.send(ev); + Session.prototype.event = function (body, eventName) { + this.send(toEvent(eventName, body)); }; + // For backwards-compatibility only. + /** @deprecated */ Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { - if (reqSeq === void 0) { reqSeq = 0; } + this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); + }; + Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { var res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, - success: !errorMsg, + success: success, }; - if (!errorMsg) { + if (success) { res.body = info; } else { - res.message = errorMsg; + ts.Debug.assert(info === undefined); + } + if (message) { + res.message = message; } this.send(res); }; @@ -78699,16 +99788,6 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.updateProjectStructure = function () { - var _this = this; - var ms = 1500; - var seq = this.changeSeq; - this.host.setTimeout(function () { - if (_this.changeSeq === seq) { - _this.projectService.refreshInferredProjects(); - } - }, ms); - }; Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; if (requireOpen === void 0) { requireOpen = true; } @@ -78721,12 +99800,14 @@ var ts; index++; if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - next.immediate(function () { - _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); - if (checkList.length > index) { - next.delay(followMs, checkOne); - } - }); + if (_this.changeSeq === seq) { + next.immediate(function () { + _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); + if (checkList.length > index) { + next.delay(followMs, checkOne); + } + }); + } } } }; @@ -78741,12 +99822,12 @@ var ts; this.logger.info("cleaning " + caption); for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { var p = projects_1[_i]; - p.getLanguageService(false).cleanupSemanticCache(); + p.getLanguageService(/*ensureSynchronized*/ false).cleanupSemanticCache(); } }; Session.prototype.cleanup = function () { this.cleanProjects("inferred projects", this.projectService.inferredProjects); - this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("configured projects", ts.arrayFrom(this.projectService.configuredProjects.values())); this.cleanProjects("external projects", this.projectService.externalProjects); if (this.host.gc) { this.logger.info("host.gc()"); @@ -78774,7 +99855,7 @@ var ts; var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return diagnostic.file && diagnostic.file.fileName === configFile; }); return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : - ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); }); + ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ false); }); }; Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) { var _this = this; @@ -78790,7 +99871,11 @@ var ts; }; Session.prototype.getCompilerOptionsDiagnostics = function (args) { var project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined); + // Get diagnostics that dont have associated file with them + // The diagnostics which have file would be in config file and + // would be reported as part of configFileDiagnostics + return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), + /*scriptInfo*/ undefined); }; Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { var _this = this; @@ -78818,46 +99903,62 @@ var ts; }; Session.prototype.getDefinition = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return server.emptyArray; } if (simplifiedResult) { - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); + return this.mapDefinitionInfo(definitions, project); } else { return definitions; } }; + Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var position = this.getPositionInFile(args, file); + var scriptInfo = project.getScriptInfo(file); + var definitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!definitionAndBoundSpan || !definitionAndBoundSpan.definitions) { + return { + definitions: server.emptyArray, + textSpan: undefined + }; + } + if (simplifiedResult) { + return { + definitions: this.mapDefinitionInfo(definitionAndBoundSpan.definitions, project), + textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo) + }; + } + return definitionAndBoundSpan; + }; + Session.prototype.mapDefinitionInfo = function (definitions, project) { + var _this = this; + return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); + }; + Session.prototype.toFileSpan = function (fileName, textSpan, project) { + var scriptInfo = project.getScriptInfo(fileName); + return { + file: fileName, + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) + }; + }; Session.prototype.getTypeDefinition = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return server.emptyArray; } - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); + return this.mapDefinitionInfo(definitions, project); }; Session.prototype.getImplementation = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var position = this.getPositionInFile(args, file); var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { return server.emptyArray; @@ -78865,12 +99966,7 @@ var ts; if (simplifiedResult) { return implementations.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan; - var scriptInfo = project.getScriptInfo(fileName); - return { - file: fileName, - start: scriptInfo.positionToLineOffset(textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) - }; + return _this.toFileSpan(fileName, textSpan, project); }); } else { @@ -78879,8 +99975,7 @@ var ts; }; Session.prototype.getOccurrences = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return server.emptyArray; @@ -78888,14 +99983,13 @@ var ts; return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan, isInString = occurrence.isInString; var scriptInfo = project.getScriptInfo(fileName); - var start = scriptInfo.positionToLineOffset(textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); var result = { - start: start, - end: end, + start: scriptInfo.positionToLineOffset(textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)), file: fileName, isWriteAccess: isWriteAccess, }; + // no need to serialize the property if it is not true if (isInString) { result.isInString = isInString; } @@ -78905,21 +99999,21 @@ var ts; Session.prototype.getSyntacticDiagnosticsSync = function (args) { var configFile = this.getConfigFileAndProject(args).configFile; if (configFile) { + // all the config file errors are reported as part of semantic check so nothing to report here return server.emptyArray; } - return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; if (configFile) { return this.getConfigFileDiagnostics(configFile, project, args.includeLinePosition); } - return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return server.emptyArray; @@ -78949,21 +100043,21 @@ var ts; this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); }; Session.prototype.getProjectInfo = function (args) { - return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ false); }; Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { - var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project; + project.updateGraph(); var projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined + fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined }; return projectInfo; }; Session.prototype.getRenameInfo = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); return project.getLanguageService().getRenameInfo(file, position); }; Session.prototype.getProjects = function (args) { @@ -78978,6 +100072,7 @@ var ts; var scriptInfo = this.projectService.getScriptInfo(args.file); projects = scriptInfo.containingProjects; } + // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); if (!projects || !projects.length) { return server.Errors.ThrowNoProject(); @@ -78996,11 +100091,11 @@ var ts; }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { var file = server.toNormalizedPath(args.file); - var info = this.projectService.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, info); + var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); if (simplifiedResult) { var defaultProject = this.getDefaultProject(args); + // The rename info should be the same for every project var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); if (!renameInfo) { return undefined; @@ -79044,7 +100139,8 @@ var ts; return { info: renameInfo, locs: locs }; } else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, + /*comparer*/ undefined, renameLocationIsEqualTo); } function renameLocationIsEqualTo(a, b) { if (a === b) { @@ -79065,6 +100161,7 @@ var ts; return 1; } else { + // reverse sort assuming no overlap if (a.start.line < b.start.line) { return 1; } @@ -79081,7 +100178,7 @@ var ts; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); - var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); if (simplifiedResult) { var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); @@ -79120,7 +100217,8 @@ var ts; }; } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, + /*comparer*/ undefined, ts.equateValues); } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { @@ -79131,80 +100229,85 @@ var ts; return false; } }; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (this.eventHandler) { - this.eventHandler({ - eventName: "configFileDiag", - data: { triggerFile: fileName, configFileName: configFileName, diagnostics: configFileErrors || server.emptyArray } - }); - } + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath); }; Session.prototype.getPosition = function (args, scriptInfo) { return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); }; - Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + Session.prototype.getPositionInFile = function (args, file) { + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + return this.getPosition(args, scriptInfo); }; - Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + Session.prototype.getFileAndProject = function (args) { + return this.getFileAndProjectWorker(args.file, args.projectFileName); }; - Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { - var file = server.toNormalizedPath(uncheckedFileName); - var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); - if (!project && errorOnMissingProject) { + Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { + // Since this is syntactic operation, there should always be project for the file + // we wouldnt have to ensure project but rather throw if we dont get project + var file = server.toNormalizedPath(args.file); + var project = this.getProject(args.projectFileName) || this.projectService.getDefaultProjectForFile(file, /*ensureProject*/ false); + if (!project) { return server.Errors.ThrowNoProject(); } + return { + file: file, + languageService: project.getLanguageService(/*ensureSynchronized*/ false) + }; + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, /*ensureProject*/ true); return { file: file, project: project }; }; Session.prototype.getOutliningSpans = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - return project.getLanguageService(false).getOutliningSpans(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + return languageService.getOutliningSpans(file); }; Session.prototype.getTodoComments = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; return project.getLanguageService().getTodoComments(file, args.descriptors); }; Session.prototype.getDocCommentTemplate = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getDocCommentTemplateAtPosition(file, position); }; Session.prototype.getSpanOfEnclosingComment = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var onlyMultiLine = args.onlyMultiLine; - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService(false).getSpanOfEnclosingComment(file, position, onlyMultiLine); + var position = this.getPositionInFile(args, file); + return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); }; Session.prototype.getIndentation = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + var indentation = languageService.getIndentationAtPosition(file, position, options); return { position: position, indentation: indentation }; }; Session.prototype.getBreakpointStatement = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getBreakpointStatementAtPosition(file, position); }; Session.prototype.getNameOrDottedNameSpan = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.getNameOrDottedNameSpan(file, position, position); }; Session.prototype.isValidBraceCompletion = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var position = this.getPositionInFile(args, file); + return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); }; Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; @@ -79228,41 +100331,48 @@ var ts; }; Session.prototype.getFormattingEditsForRange = function (args) { var _this = this; - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + // TODO: avoid duplicate code (with formatonkey) + var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; Session.prototype.getFormattingEditsForRangeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + return languageService.getFormattingEditsForDocument(file, options); }; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + // Check whether we should auto-indent. This will be when + // the position is on a line containing only whitespace. + // This should leave the edits returned from + // getFormattingEditsAfterKeystroke either empty or pertaining + // only to the previous line. If all this is true, then + // add edits necessary to properly indent the current line. if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; if (lineText && lineText.search("\\S") < 0) { - var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); var hasIndent = 0; var i = void 0, len = void 0; for (i = 0, len = lineText.length; i < len; i++) { @@ -79276,6 +100386,7 @@ var ts; break; } } + // i points to the first non whitespace character if (preferredIndent !== hasIndent) { var firstNoWhiteSpacePosition = absolutePosition + i; edits.push({ @@ -79300,44 +100411,52 @@ var ts; var _this = this; var prefix = args.prefix || ""; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, args); if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_68 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - return { name: name_68, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; + if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; + // Use `hasAction || undefined` to avoid serializing `false`. + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } - }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); + }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } else { return completions; } }; - Session.prototype.getCompletionEntryDetails = function (args) { + Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - return ts.mapDefined(args.entryNames, function (entryName) { - return project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + var formattingOptions = project.projectService.getFormatCodeOptions(file); + var result = ts.mapDefined(args.entryNames, function (entryName) { + var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source); }); + return simplifiedResult + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action, scriptInfo); }) })); }) + : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { - var info = this.projectService.getScriptInfo(args.file); - var result = []; + var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); if (!info) { return server.emptyArray; } + var result = []; + // if specified a project, we only return affected file list in this project var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { var project = projectsToSearch_1[_i]; - if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { result.push({ projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), - projectUsesOutFile: !!project.getCompilerOptions().outFile || !!project.getCompilerOptions().out + projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out }); } } @@ -79353,23 +100472,23 @@ var ts; return false; } var scriptInfo = project.getScriptInfo(file); - return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + return project.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); }; Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } if (simplifiedResult) { - var span_18 = helpItems.applicableSpan; + var span_16 = helpItems.applicableSpan; return { items: helpItems.items, applicableSpan: { - start: scriptInfo.positionToLineOffset(span_18.start), - end: scriptInfo.positionToLineOffset(span_18.start + span_18.length) + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, @@ -79380,38 +100499,42 @@ var ts; return helpItems; } }; - Session.prototype.getDiagnostics = function (next, delay, fileNames) { + Session.prototype.createCheckList = function (fileNames, defaultProject) { var _this = this; - var checkList = ts.mapDefined(fileNames, function (uncheckedFileName) { + return ts.mapDefined(fileNames, function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); - var project = _this.projectService.getDefaultProjectForFile(fileName, true); + var project = defaultProject || _this.projectService.getDefaultProjectForFile(fileName, /*ensureProject*/ false); return project && { fileName: fileName, project: project }; }); + }; + Session.prototype.getDiagnostics = function (next, delay, fileNames) { + var checkList = this.createCheckList(fileNames); if (checkList.length > 0) { this.updateErrorCheck(next, checkList, delay); } }; Session.prototype.change = function (args) { - var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; - if (project) { - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); - var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - if (start >= 0) { - scriptInfo.editContent(start, end, args.insertString); - this.changeSeq++; - } - this.updateProjectStructure(); + var scriptInfo = this.projectService.getScriptInfo(args.file); + ts.Debug.assert(!!scriptInfo); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + if (start >= 0) { + this.changeSeq++; + this.projectService.applyChangesToFile(scriptInfo, [{ + span: { start: start, length: end - start }, + newText: args.insertString + }]); } }; Session.prototype.reload = function (args, reqSeq) { var file = server.toNormalizedPath(args.file); var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); - var project = this.projectService.getDefaultProjectForFile(file, true); - if (project) { + var info = this.projectService.getScriptInfoForNormalizedPath(file); + if (info) { this.changeSeq++; - if (project.reloadScript(file, tempFileName)) { - this.output(undefined, server.CommandNames.Reload, reqSeq); + // make sure no changes happen before this one is finished + if (info.reloadFromFile(tempFileName)) { + this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true); } } }; @@ -79428,49 +100551,49 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { + Session.prototype.mapLocationNavigationBarItems = function (items, scriptInfo) { var _this = this; return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), - childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), + spans: item.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + childItems: _this.mapLocationNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var items = project.getLanguageService(false).getNavigationBarItems(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var items = languageService.getNavigationBarItems(file); return !items ? undefined : simplifiedResult - ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items; }; - Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + Session.prototype.toLocationNavigationTree = function (tree, scriptInfo) { var _this = this; return { text: tree.text, kind: tree.kind, kindModifiers: tree.kindModifiers, - spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), - childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + spans: tree.spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.toLocationNavigationTree(item, scriptInfo); }) }; }; - Session.prototype.decorateSpan = function (span, scriptInfo) { + Session.prototype.toLocationTextSpan = function (span, scriptInfo) { return { start: scriptInfo.positionToLineOffset(span.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) }; }; Session.prototype.getNavigationTree = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var tree = project.getLanguageService(false).getNavigationTree(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var tree = languageService.getNavigationTree(file); return !tree ? undefined : simplifiedResult - ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree; }; Session.prototype.getNavigateToItems = function (args, simplifiedResult) { @@ -79478,20 +100601,18 @@ var ts; var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; if (simplifiedResult) { return server.combineProjectOutput(projects, function (project) { - var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); if (!navItems) { return server.emptyArray; } return navItems.map(function (navItem) { var scriptInfo = project.getScriptInfo(navItem.fileName); - var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); var bakedItem = { name: navItem.name, kind: navItem.kind, file: navItem.fileName, - start: start, - end: end, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) }; if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { bakedItem.kindModifiers = navItem.kindModifiers; @@ -79507,10 +100628,12 @@ var ts; } return bakedItem; }); - }, undefined, areNavToItemsForTheSameLocation); + }, + /*comparer*/ undefined, areNavToItemsForTheSameLocation); } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); }, + /*comparer*/ undefined, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { if (a === b) { @@ -79561,33 +100684,35 @@ var ts; } }; Session.prototype.getApplicableRefactors = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; return project.getLanguageService().getApplicableRefactors(file, position || textRange); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { var _this = this; - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - var result = project.getLanguageService().getEditsForRefactor(file, args.formatOptions ? server.convertFormatOptions(args.formatOptions) : this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); + var result = project.getLanguageService().getEditsForRefactor(file, this.projectService.getFormatCodeOptions(file), position || textRange, args.refactor, args.action); if (result === undefined) { return { edits: [] }; } if (simplifiedResult) { - var file_2 = result.renameFilename; - var location_4; - if (file_2 !== undefined && result.renameLocation !== undefined) { - var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(file_2)); - location_4 = renameScriptInfo.positionToLineOffset(result.renameLocation); + var renameFilename = result.renameFilename, renameLocation = result.renameLocation, edits = result.edits; + var mappedRenameLocation = void 0; + if (renameFilename !== undefined && renameLocation !== undefined) { + var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); + var snapshot = renameScriptInfo.getSnapshot(); + var oldText = snapshot.getText(0, snapshot.getLength()); + mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); } return { - renameLocation: location_4, - renameFilename: file_2, - edits: result.edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) + renameLocation: mappedRenameLocation, + renameFilename: renameFilename, + edits: edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) }; } else { @@ -79599,7 +100724,7 @@ var ts; if (args.errorCodes.length === 0) { return undefined; } - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var formatOptions = this.projectService.getFormatCodeOptions(file); @@ -79614,6 +100739,20 @@ var ts; return codeActions; } }; + Session.prototype.applyCodeActionCommand = function (commandName, requestSeq, args) { + var _this = this; + var commands = args.command; // They should be sending back the command we sent them. + var _loop_11 = function (command) { + var project = this_1.getFileAndProject(command).project; + var output = function (success, message) { return _this.doOutput({}, commandName, requestSeq, success, message); }; + project.getLanguageService().applyCodeActionCommand(command).then(function (result) { output(/*success*/ true, result.successMessage); }, function (error) { output(/*success*/ false, error); }); + }; + var this_1 = this; + for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { + var command = _a[_i]; + _loop_11(command); + } + }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { var startPosition = undefined, endPosition = undefined; if (args.startPosition !== undefined) { @@ -79621,6 +100760,7 @@ var ts; } else { startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + // save the result so we don't always recompute args.startPosition = startPosition; } if (args.endPosition !== undefined) { @@ -79632,15 +100772,14 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + Session.prototype.mapCodeAction = function (_a, scriptInfo) { var _this = this; - return { - description: codeAction.description, - changes: codeAction.changes.map(function (change) { return ({ - fileName: change.fileName, - textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) - }); }) - }; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands; + var changes = unmappedChanges.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }); + return { description: description, changes: changes, commands: commands }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -79659,31 +100798,33 @@ var ts; }; Session.prototype.getBraceMatching = function (args, simplifiedResult) { var _this = this; - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + var spans = languageService.getBraceMatchingAtPosition(file, position); return !spans ? undefined : simplifiedResult - ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + ? spans.map(function (span) { return _this.toLocationTextSpan(span, scriptInfo); }) : spans; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { - var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } - var fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); + // No need to analyze lib.d.ts + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); if (fileNamesInProject.length === 0) { return; } + // Sort the file name list to make the recently touched files come first var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; var normalizedFileName = server.toNormalizedPath(fileName); - var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, /*ensureProject*/ true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { @@ -79692,7 +100833,7 @@ var ts; else { var info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isScriptOpen()) { - if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) { + if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) { veryLowPriorityFiles.push(fileNameInProject); } else { @@ -79706,14 +100847,15 @@ var ts; } var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles); var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); - this.updateErrorCheck(next, checkList, delay, false); + // Project level error analysis runs on background files too, therefore + // doesn't require the file to be opened + this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false); }; Session.prototype.getCanonicalFileName = function (fileName) { var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return ts.normalizePath(name); }; - Session.prototype.exit = function () { - }; + Session.prototype.exit = function () { }; Session.prototype.notRequired = function () { return { responseRequired: false }; }; @@ -79751,8 +100893,8 @@ var ts; return this.executeWithRequestId(request.seq, function () { return handler(request); }); } else { - this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); - this.output(undefined, server.CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); + this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -79762,7 +100904,7 @@ var ts; if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("request: " + message); + this.logger.info("request:" + server.indent(message)); } } var request; @@ -79779,26 +100921,53 @@ var ts; } } if (response) { - this.output(response, request.command, request.seq); + this.doOutput(response, request.command, request.seq, /*success*/ true); } else if (responseRequired) { - this.output(undefined, request.command, request.seq, "No content available."); + this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available."); } } catch (err) { if (err instanceof ts.OperationCanceledException) { - this.output({ canceled: true }, request.command, request.seq); + // Handle cancellation exceptions + this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logError(err, message); - this.output(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); + this.doOutput( + /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, + /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); } }; return Session; }()); server.Session = Session; + /* @internal */ // Exported only for tests + function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { + var newText = applyEdits(oldText, renameFilename, edits); + var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + server.getLocationInNewDocument = getLocationInNewDocument; + function applyEdits(text, textFilename, edits) { + for (var _i = 0, edits_3 = edits; _i < edits_3.length; _i++) { + var _a = edits_3[_i], fileName = _a.fileName, textChanges_3 = _a.textChanges; + if (fileName !== textFilename) { + continue; + } + for (var i = textChanges_3.length - 1; i >= 0; i--) { + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_8 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_8); + } + } + return text; + } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/// +/// +/*@internal*/ var ts; (function (ts) { var server; @@ -79813,12 +100982,12 @@ var ts; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; })(CharRangeSection || (CharRangeSection = {})); - var EditWalker = (function () { + var EditWalker = /** @class */ (function () { function EditWalker() { this.goSubtree = true; this.lineIndex = new LineIndex(); this.endBranch = []; - this.state = 2; + this.state = 2 /* Entire */; this.initialText = ""; this.trailingText = ""; this.lineIndex.root = new LineNode(); @@ -79864,6 +101033,7 @@ var ts; if (lastZeroCount) { branchParent.remove(lastZeroCount); } + // path at least length two (root and leaf) var leafNode = this.startPath[this.startPath.length - 1]; if (lines.length > 0) { leafNode.text = lines[0]; @@ -79898,6 +101068,7 @@ var ts; } else { var insertionNode = this.startPath[this.startPath.length - 2]; + // no content for leaf node, so delete it insertionNode.remove(leafNode); for (var j = this.startPath.length - 2; j >= 0; j--) { this.startPath[j].updateCounts(); @@ -79906,15 +101077,20 @@ var ts; return this.lineIndex; }; EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { + // have visited the path for start of range, now looking for end + // if range is on single line, we will never make this state transition if (lineCollection === this.lineCollectionAtBranch) { - this.state = 4; + this.state = 4 /* End */; } + // always pop stack because post only called when child has been visited this.stack.pop(); }; EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { + // currentNode corresponds to parent, but in the new tree var currentNode = this.stack[this.stack.length - 1]; - if ((this.state === 2) && (nodeType === 1)) { - this.state = 1; + if ((this.state === 2 /* Entire */) && (nodeType === 1 /* Start */)) { + // if range is on single line, we will never make this state transition + this.state = 1 /* Start */; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; } @@ -79927,14 +101103,14 @@ var ts; return new LineNode(); } switch (nodeType) { - case 0: + case 0 /* PreStart */: this.goSubtree = false; - if (this.state !== 4) { + if (this.state !== 4 /* End */) { currentNode.add(lineCollection); } break; - case 1: - if (this.state === 4) { + case 1 /* Start */: + if (this.state === 4 /* End */) { this.goSubtree = false; } else { @@ -79943,8 +101119,8 @@ var ts; this.startPath.push(child); } break; - case 2: - if (this.state !== 4) { + case 2 /* Entire */: + if (this.state !== 4 /* End */) { child = fresh(lineCollection); currentNode.add(child); this.startPath.push(child); @@ -79957,11 +101133,11 @@ var ts; } } break; - case 3: + case 3 /* Mid */: this.goSubtree = false; break; - case 4: - if (this.state !== 4) { + case 4 /* End */: + if (this.state !== 4 /* End */) { this.goSubtree = false; } else { @@ -79972,9 +101148,9 @@ var ts; } } break; - case 5: + case 5 /* PostEnd */: this.goSubtree = false; - if (this.state !== 1) { + if (this.state !== 1 /* Start */) { currentNode.add(lineCollection); } break; @@ -79983,21 +101159,24 @@ var ts; this.stack.push(child); } }; + // just gather text from the leaves EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { - if (this.state === 1) { + if (this.state === 1 /* Start */) { this.initialText = ll.text.substring(0, relativeStart); } - else if (this.state === 2) { + else if (this.state === 2 /* Entire */) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } else { + // state is CharRangeSection.End this.trailingText = ll.text.substring(relativeStart + relativeLength); } }; return EditWalker; }()); - var TextChange = (function () { + // text change information + var TextChange = /** @class */ (function () { function TextChange(pos, deleteLen, insertedText) { this.pos = pos; this.deleteLen = deleteLen; @@ -80008,11 +101187,11 @@ var ts; }; return TextChange; }()); - var ScriptVersionCache = (function () { + var ScriptVersionCache = /** @class */ (function () { function ScriptVersionCache() { this.changes = []; this.versions = new Array(ScriptVersionCache.maxVersions); - this.minVersion = 0; + this.minVersion = 0; // no versions earlier than min version will maintain change history this.currentVersion = 0; } ScriptVersionCache.prototype.versionToIndex = function (version) { @@ -80024,6 +101203,7 @@ var ts; ScriptVersionCache.prototype.currentVersionToIndex = function () { return this.currentVersion % ScriptVersionCache.maxVersions; }; + // REVIEW: can optimize by coalescing simple edits ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes.push(new TextChange(pos, deleteLen, insertedText)); if (this.changes.length > ScriptVersionCache.changeNumberThreshold || @@ -80032,18 +101212,6 @@ var ts; this.getSnapshot(); } }; - ScriptVersionCache.prototype.reload = function (script) { - this.currentVersion++; - this.changes = []; - var snap = new LineIndexSnapshot(this.currentVersion, this, new LineIndex()); - for (var i = 0; i < this.versions.length; i++) { - this.versions[i] = undefined; - } - this.versions[this.currentVersionToIndex()] = snap; - var lm = LineIndex.linesFromText(script); - snap.index.load(lm.lines); - this.minVersion = this.currentVersion; - }; ScriptVersionCache.prototype.getSnapshot = function () { return this._getSnapshot(); }; ScriptVersionCache.prototype._getSnapshot = function () { var snap = this.versions[this.currentVersionToIndex()]; @@ -80116,7 +101284,7 @@ var ts; return ScriptVersionCache; }()); server.ScriptVersionCache = ScriptVersionCache; - var LineIndexSnapshot = (function () { + var LineIndexSnapshot = /** @class */ (function () { function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) { if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; } this.version = version; @@ -80142,8 +101310,10 @@ var ts; }; return LineIndexSnapshot; }()); - var LineIndex = (function () { + /* @internal */ + var LineIndex = /** @class */ (function () { function LineIndex() { + // set this to true to check each edit for accuracy this.checkEdits = false; } LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) { @@ -80215,7 +101385,7 @@ var ts; }; LineIndex.prototype.edit = function (pos, deleteLength, newText) { if (this.root.charCount() === 0) { - ts.Debug.assert(deleteLength === 0); + ts.Debug.assert(deleteLength === 0); // Can't delete from empty document if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; @@ -80230,6 +101400,7 @@ var ts; var walker = new EditWalker(); var suppressTrailingText = false; if (pos >= this.root.charCount()) { + // insert at end pos = this.root.charCount() - 1; var endString = this.getText(pos, 1); if (newText) { @@ -80242,10 +101413,13 @@ var ts; suppressTrailingText = true; } else if (deleteLength > 0) { + // check whether last characters deleted are line break var e = pos + deleteLength; var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; if (zeroBasedColumn === 0) { + // move range end just past line that will merge with previous line deleteLength += lineText.length; + // store text by appending to end of insertedText newText = newText ? newText + lineText : lineText; } } @@ -80293,7 +101467,7 @@ var ts; return LineIndex; }()); server.LineIndex = LineIndex; - var LineNode = (function () { + var LineNode = /** @class */ (function () { function LineNode(children) { if (children === void 0) { children = []; } this.children = children; @@ -80336,22 +101510,26 @@ var ts; } }; LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) { + // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) var childIndex = 0; var childCharCount = this.children[childIndex].charCount(); + // find sub-tree containing start var adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { - this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0); + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */); adjustedStart -= childCharCount; childIndex++; childCharCount = this.children[childIndex].charCount(); } + // Case I: both start and end of range in same subtree if ((adjustedStart + rangeLength) <= childCharCount) { - if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) { return; } } else { - if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) { + // Case II: start and end of range in different subtrees (possibly with subtrees in the middle) + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) { return; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); @@ -80359,7 +101537,7 @@ var ts; var child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { - if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) { return; } adjustedLength -= childCharCount; @@ -80367,22 +101545,26 @@ var ts; childCharCount = this.children[childIndex].charCount(); } if (adjustedLength > 0) { - if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) { return; } } } + // Process any subtrees after the one containing range end if (walkFns.pre) { var clen = this.children.length; if (childIndex < (clen - 1)) { for (var ej = childIndex + 1; ej < clen; ej++) { - this.skipChild(0, 0, ej, walkFns, 5); + this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */); } } } }; + // Input position is relative to the start of this node. + // Output line number is absolute. LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { if (this.children.length === 0) { + // Root node might have no children if this is an empty document. return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; } for (var _i = 0, _a = this.children; _i < _a.length; _i++) { @@ -80400,9 +101582,15 @@ var ts; lineNumberAccumulator += child.lineCount(); } } + // Skipped all children var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf; return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf.charCount(), lineText: undefined }; }; + /** + * Input line number is relative to the start of this node. + * Output line number is relative to the child. + * positionAccumulator will be an absolute position once relativeLineNumber reaches 0. + */ LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; @@ -80452,6 +101640,7 @@ var ts; var childIndex = this.findChildIndex(child); var clen = this.children.length; var nodeCount = nodes.length; + // if child is last and there is more room and only one node to place, place it if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { this.add(nodes[0]); this.updateCounts(); @@ -80500,6 +101689,7 @@ var ts; return splitNodes; } }; + // assume there is room for the item; return true if more room LineNode.prototype.add = function (collection) { this.children.push(collection); ts.Debug.assert(this.children.length <= lineCollectionCapacity); @@ -80512,7 +101702,7 @@ var ts; }; return LineNode; }()); - var LineLeaf = (function () { + var LineLeaf = /** @class */ (function () { function LineLeaf(text) { this.text = text; } @@ -80532,11 +101722,13 @@ var ts; }()); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// var ts; (function (ts) { var server; (function (server) { - var TextStorage = (function () { + /* @internal */ + var TextStorage = /** @class */ (function () { function TextStorage(host, fileName) { this.host = host; this.fileName = fileName; @@ -80548,60 +101740,99 @@ var ts; ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshotVersion() : "Text-" + this.textVersion; }; - TextStorage.prototype.hasScriptVersionCache = function () { + TextStorage.prototype.hasScriptVersionCache_TestOnly = function () { return this.svc !== undefined; }; - TextStorage.prototype.useScriptVersionCache = function (newText) { - this.switchToScriptVersionCache(newText); + TextStorage.prototype.useScriptVersionCache_TestOnly = function () { + this.switchToScriptVersionCache(); }; TextStorage.prototype.useText = function (newText) { this.svc = undefined; - this.setText(newText); + this.text = newText; + this.lineMap = undefined; + this.textVersion++; }; TextStorage.prototype.edit = function (start, end, newText) { this.switchToScriptVersionCache().edit(start, end - start, newText); - }; - TextStorage.prototype.reload = function (text) { - if (this.svc) { - this.svc.reload(text); - } - else { - this.setText(text); + this.ownFileText = false; + this.text = undefined; + this.lineMap = undefined; + }; + /** + * Set the contents as newText + * returns true if text changed + */ + TextStorage.prototype.reload = function (newText) { + ts.Debug.assert(newText !== undefined); + // Reload always has fresh content + this.pendingReloadFromDisk = false; + // If text changed set the text + // This also ensures that if we had switched to version cache, + // we are switching back to text. + // The change to version cache will happen when needed + // Thus avoiding the computation if there are no changes + if (this.text !== newText) { + this.useText(newText); + // We cant guarantee new text is own file text + this.ownFileText = false; + return true; } }; - TextStorage.prototype.reloadFromFile = function (tempFileName) { - if (this.svc || (tempFileName !== this.fileName)) { - this.reload(this.getFileText(tempFileName)); - } - else { - this.setText(undefined); + /** + * Reads the contents from tempFile(if supplied) or own file and sets it as contents + * returns true if text changed + */ + TextStorage.prototype.reloadWithFileText = function (tempFileName) { + var reloaded = this.reload(this.getFileText(tempFileName)); + this.ownFileText = !tempFileName || tempFileName === this.fileName; + return reloaded; + }; + /** + * Reloads the contents from the file if there is no pending reload from disk or the contents of file are same as file text + * returns true if text changed + */ + TextStorage.prototype.reloadFromDisk = function () { + if (!this.pendingReloadFromDisk && !this.ownFileText) { + return this.reloadWithFileText(); } + return false; + }; + TextStorage.prototype.delayReloadFromFileIntoText = function () { + this.pendingReloadFromDisk = true; }; TextStorage.prototype.getSnapshot = function () { - return this.svc + return this.useScriptVersionCacheIfValidOrOpen() ? this.svc.getSnapshot() : ts.ScriptSnapshot.fromString(this.getOrLoadText()); }; TextStorage.prototype.getLineInfo = function (line) { return this.switchToScriptVersionCache().getLineInfo(line); }; + /** + * @param line 0 based index + */ TextStorage.prototype.lineToTextSpan = function (line) { - if (!this.svc) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { var lineMap = this.getLineMap(); - var start = lineMap[line]; + var start = lineMap[line]; // -1 since line is 1-based var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; return ts.createTextSpanFromBounds(start, end); } return this.svc.lineToTextSpan(line); }; + /** + * @param line 1 based index + * @param offset 1 based index + */ TextStorage.prototype.lineOffsetToPosition = function (line, offset) { - if (!this.svc) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } + // TODO: assert this offset is actually on the line return this.svc.lineOffsetToPosition(line, offset); }; TextStorage.prototype.positionToLineOffset = function (position) { - if (!this.svc) { + if (!this.useScriptVersionCacheIfValidOrOpen()) { var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; return { line: line + 1, offset: character + 1 }; } @@ -80610,70 +101841,86 @@ var ts; TextStorage.prototype.getFileText = function (tempFileName) { return this.host.readFile(tempFileName || this.fileName) || ""; }; - TextStorage.prototype.ensureNoScriptVersionCache = function () { - ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); - }; - TextStorage.prototype.switchToScriptVersionCache = function (newText) { - if (!this.svc) { - this.svc = server.ScriptVersionCache.fromString(newText !== undefined ? newText : this.getOrLoadText()); + TextStorage.prototype.switchToScriptVersionCache = function () { + if (!this.svc || this.pendingReloadFromDisk) { + this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText()); this.svcVersion++; - this.text = undefined; } return this.svc; }; + TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () { + // If this is open script, use the cache + if (this.isOpen) { + return this.switchToScriptVersionCache(); + } + // Else if the svc is uptodate with the text, we are good + return !this.pendingReloadFromDisk && this.svc; + }; TextStorage.prototype.getOrLoadText = function () { - this.ensureNoScriptVersionCache(); - if (this.text === undefined) { - this.setText(this.getFileText()); + if (this.text === undefined || this.pendingReloadFromDisk) { + ts.Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk"); + this.reloadWithFileText(); } return this.text; }; TextStorage.prototype.getLineMap = function () { - this.ensureNoScriptVersionCache(); + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); }; - TextStorage.prototype.setText = function (newText) { - this.ensureNoScriptVersionCache(); - if (newText === undefined || this.text !== newText) { - this.text = newText; - this.lineMap = undefined; - this.textVersion++; - } - }; return TextStorage; }()); server.TextStorage = TextStorage; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, scriptKind, hasMixedContent, isDynamic) { - if (hasMixedContent === void 0) { hasMixedContent = false; } - if (isDynamic === void 0) { isDynamic = false; } + /*@internal*/ + function isDynamicFileName(fileName) { + return ts.getBaseFileName(fileName)[0] === "^"; + } + server.isDynamicFileName = isDynamicFileName; + var ScriptInfo = /** @class */ (function () { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path) { this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; this.hasMixedContent = hasMixedContent; - this.isDynamic = isDynamic; + this.path = path; + /** + * All projects that include this file + */ this.containingProjects = []; - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.isDynamic = isDynamicFileName(fileName); this.textStorage = new TextStorage(host, fileName); - if (hasMixedContent || isDynamic) { + if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); } this.scriptKind = scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName); } + /*@internal*/ + ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { + return this.hasMixedContent || this.isDynamic; + }; ScriptInfo.prototype.isScriptOpen = function () { - return this.isOpen; + return this.textStorage.isOpen; }; ScriptInfo.prototype.open = function (newText) { - this.isOpen = true; - this.textStorage.useScriptVersionCache(newText); - this.markContainingProjectsAsDirty(); + this.textStorage.isOpen = true; + if (newText !== undefined && + this.textStorage.reload(newText)) { + // reload new contents only if the existing contents changed + this.markContainingProjectsAsDirty(); + } }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - this.textStorage.useText(this.hasMixedContent || this.isDynamic ? "" : undefined); - this.markContainingProjectsAsDirty(); + ScriptInfo.prototype.close = function (fileExists) { + if (fileExists === void 0) { fileExists = true; } + this.textStorage.isOpen = false; + if (this.isDynamicOrHasMixedContent() || !fileExists) { + if (this.textStorage.reload("")) { + this.markContainingProjectsAsDirty(); + } + } + else if (this.textStorage.reloadFromDisk()) { + this.markContainingProjectsAsDirty(); + } }; ScriptInfo.prototype.getSnapshot = function () { return this.textStorage.getSnapshot(); @@ -80689,6 +101936,7 @@ var ts; return isNew; }; ScriptInfo.prototype.isAttached = function (project) { + // unrolled for common cases switch (this.containingProjects.length) { case 0: return false; case 1: return this.containingProjects[0] === project; @@ -80697,6 +101945,7 @@ var ts; } }; ScriptInfo.prototype.detachFromProject = function (project) { + // unrolled for common cases switch (this.containingProjects.length) { case 0: return; @@ -80721,7 +101970,17 @@ var ts; ScriptInfo.prototype.detachAllProjects = function () { for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; - p.removeFile(this, false); + if (p.projectKind === server.ProjectKind.Configured) { + p.directoryStructureHost.addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + } + var isInfoRoot = p.isRoot(this); + // detach is unnecessary since we'll clean the list of containing projects anyways + p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false); + // If the info was for the external or configured project's root, + // add missing file as the root + if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) { + p.addMissingFileRoot(this.fileName); + } } ts.clear(this.containingProjects); }; @@ -80732,6 +101991,9 @@ 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. var firstExternalProject = void 0; for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; @@ -80759,36 +102021,31 @@ var ts; server.mergeMapLikes(this.formatCodeSettings, formatSettings); } }; - ScriptInfo.prototype.setWatcher = function (watcher) { - this.stopWatcher(); - this.fileWatcher = watcher; - }; - ScriptInfo.prototype.stopWatcher = function () { - if (this.fileWatcher) { - this.fileWatcher.close(); - this.fileWatcher = undefined; - } - }; ScriptInfo.prototype.getLatestVersion = function () { return this.textStorage.getVersion(); }; - ScriptInfo.prototype.reload = function (script) { - this.textStorage.reload(script); - this.markContainingProjectsAsDirty(); - }; ScriptInfo.prototype.saveTo = function (fileName) { var snap = this.textStorage.getSnapshot(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; + /*@internal*/ + ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { + ts.Debug.assert(!this.isDynamicOrHasMixedContent()); + this.textStorage.delayReloadFromFileIntoText(); + this.markContainingProjectsAsDirty(); + }; ScriptInfo.prototype.reloadFromFile = function (tempFileName) { - if (this.hasMixedContent || this.isDynamic) { - this.reload(""); + if (this.isDynamicOrHasMixedContent()) { + this.textStorage.reload(""); + this.markContainingProjectsAsDirty(); } else { - this.textStorage.reloadFromFile(tempFileName); - this.markContainingProjectsAsDirty(); + if (this.textStorage.reloadWithFileText(tempFileName)) { + this.markContainingProjectsAsDirty(); + } } }; + /*@internal*/ ScriptInfo.prototype.getLineInfo = function (line) { return this.textStorage.getLineInfo(line); }; @@ -80802,9 +102059,19 @@ var ts; p.markAsDirty(); } }; + ScriptInfo.prototype.isOrphan = function () { + return this.containingProjects.length === 0; + }; + /** + * @param line 1 based index + */ ScriptInfo.prototype.lineToTextSpan = function (line) { return this.textStorage.lineToTextSpan(line); }; + /** + * @param line 1 based index + * @param offset 1 based index + */ ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { return this.textStorage.lineOffsetToPosition(line, offset); }; @@ -80812,210 +102079,662 @@ var ts; return this.textStorage.positionToLineOffset(position); }; ScriptInfo.prototype.isJavaScript = function () { - return this.scriptKind === 1 || this.scriptKind === 2; + return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */; }; return ScriptInfo; }()); server.ScriptInfo = ScriptInfo; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/* @internal */ var ts; (function (ts) { - var server; - (function (server) { - var LSHost = (function () { - function LSHost(host, project, cancellationToken) { - var _this = this; - this.host = host; - this.project = project; - this.cancellationToken = cancellationToken; - this.resolvedModuleNames = ts.createMap(); - this.resolvedTypeReferenceDirectives = ts.createMap(); - this.cancellationToken = new ts.ThrottledCancellationToken(cancellationToken, project.projectService.throttleWaitMilliseconds); - this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - if (host.trace) { - this.trace = function (s) { return host.trace(s); }; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1 /* Recursive */) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); } - this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { - var globalCache = _this.project.getTypeAcquisition().enable - ? _this.project.projectService.typingsInstaller.globalTypingsCacheLocation - : undefined; - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (!ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { - var _a = ts.loadModuleFromGlobalCache(moduleName, _this.project.getProjectName(), compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; - if (resolvedModule) { - return { resolvedModule: resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; - } + watcher.close(); + } + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution() { + if (allFilesHaveInvalidatedResolution) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; } - return primaryResult; - }; - if (this.host.realpath) { - this.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.dispose = function () { - this.project = undefined; - this.resolveModuleName = undefined; - }; - LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { - this.filesWithChangedSetOfUnresolvedImports = []; - }; - LSHost.prototype.finishRecordingFilesWithChangedResolutions = function () { - var collected = this.filesWithChangedSetOfUnresolvedImports; - this.filesWithChangedSetOfUnresolvedImports = undefined; - return collected; - }; - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult, getResultFileName, logChanges) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_69 = names_2[_i]; - var resolution = newResolutions.get(name_69); - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile.get(name_69); - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); } else { - resolution = loader(name_69, containingFile, compilerOptions, this); - newResolutions.set(name_69, resolution); - } - if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { - this.filesWithChangedSetOfUnresolvedImports.push(path); - logChanges = false; + watchFailedLookupLocationOfResolution(resolution, 0); } } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function resolutionIsEqualTo(oldResolution, newResolution) { - if (oldResolution === newResolution) { - return true; + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); } - if (!oldResolution || !newResolution) { - return false; + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; } - var oldResult = getResult(oldResolution); - var newResult = getResult(newResolution); - if (oldResult === newResult) { - return true; + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, + // When root is "/" do not watch directories like: + // "/", "/user", "/user/username", "/user/username/folderAtRoot" + // When root is "c:/" do not watch directories like: + // "c:/", "c:/folderAtRoot" + dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + return { dir: rootDir, dirPath: rootPath }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + // Use some ancestor of the root directory + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; } - if (!oldResult || !newResult) { - return false; + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + // Additional failed lookup locations, watch from this index + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + // Different failed lookup locations, + // Watch new resolution failed lookup locations from this index and + // stop watching existing resolutions from this index + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + // All new failed lookup locations are already watched (and are same), + // Stop watching failed lookup locations of existing resolution after failed lookup locations length + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); } - return getResultFileName(oldResult) === getResultFileName(newResult); } - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); } - var result = getResult(resolution); - if (result) { - return getResultFileName(result) !== lastDeletedFileName; + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); } - return resolution.failedLookupLocations.length === 0; } - }; - LSHost.prototype.getNewLine = function () { - return this.host.newLine; - }; - LSHost.prototype.getProjectVersion = function () { - return this.project.getProjectVersion(); - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.useCaseSensitiveFileNames = function () { - return this.host.useCaseSensitiveFileNames; - }; - LSHost.prototype.getCancellationToken = function () { - return this.cancellationToken; - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }, function (r) { return r.resolvedFileName; }, false); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }, function (r) { return r.resolvedFileName; }, true); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.project.getScriptInfoLSHost(filename); - if (scriptInfo) { - return scriptInfo.getSnapshot(); + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; } - }; - LSHost.prototype.getScriptFileNames = function () { - return this.project.getRootFilesLSHost(); - }; - LSHost.prototype.getTypeRootsVersion = function () { - return this.project.typesVersion; - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.project.getScriptInfoLSHost(fileName); - return info && info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - var info = this.project.getScriptInfoLSHost(filename); - return info && info.getLatestVersion(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return this.host.getCurrentDirectory(); - }; - LSHost.prototype.resolvePath = function (path) { - return this.host.resolvePath(path); - }; - LSHost.prototype.fileExists = function (file) { - var path = ts.toPath(file, this.host.getCurrentDirectory(), this.getCanonicalFileName); - return !this.project.isWatchedMissingFile(path) && this.host.fileExists(file); - }; - LSHost.prototype.readFile = function (fileName) { - return this.host.readFile(fileName); - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - return this.host.readDirectory(path, extensions, exclude, include, depth); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.notifyFileRemoved = function (info) { - this.resolvedModuleNames.delete(info.path); - this.resolvedTypeReferenceDirectives.delete(info.path); - }; - LSHost.prototype.setCompilationSettings = function (opt) { - if (ts.changesAffectModuleResolution(this.compilationSettings, opt)) { - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); + } + } + function createDirectoryWatcher(directory, dirPath) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (resolutionHost.getCachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } - this.compilationSettings = opt; - }; - return LSHost; - }()); - server.LSHost = LSHost; - })(server = ts.server || (ts.server = {})); + // If the files are added to project root or node_modules directory, always run through the invalidation process + // Otherwise run through invalidation only if adding to the immediate directory + if (!allFilesHaveInvalidatedResolution && + dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + } + }, 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (resolutionHost.getCachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); +/// var ts; (function (ts) { var server; (function (server) { server.nullTypingsInstaller = { + isKnownTypesPackageName: ts.returnFalse, + // Should never be called because we never provide a types registry. + installPackage: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, globalTypingsCacheLocation: undefined }; - var TypingsCacheEntry = (function () { + var TypingsCacheEntry = /** @class */ (function () { function TypingsCacheEntry() { } return TypingsCacheEntry; @@ -81055,6 +102774,7 @@ var ts; !setIsEqualTo(opt1.exclude, opt2.exclude); } function compilerOptionsChanged(opt1, opt2) { + // TODO: add more relevant properties return opt1.allowJs !== opt2.allowJs; } function unresolvedImportsChanged(imports1, imports2) { @@ -81063,11 +102783,17 @@ var ts; } return !ts.arrayIsEqualTo(imports1, imports2); } - var TypingsCache = (function () { + var TypingsCache = /** @class */ (function () { function TypingsCache(installer) { this.installer = installer; this.perProjectCache = ts.createMap(); } + TypingsCache.prototype.isKnownTypesPackageName = function (name) { + return this.installer.isKnownTypesPackageName(name); + }; + TypingsCache.prototype.installPackage = function (options) { + return this.installer.installPackage(options); + }; TypingsCache.prototype.getTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -81078,15 +102804,18 @@ var ts; if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || - compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) || + compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options. + // instead it acts as a placeholder to prevent issuing multiple requests this.perProjectCache.set(project.getProjectName(), { - compilerOptions: project.getCompilerOptions(), + compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, typings: result, unresolvedImports: unresolvedImports, poisoned: true }); + // something has been changed, issue a request to update typings this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } return result; @@ -81112,285 +102841,12 @@ var ts; server.TypingsCache = TypingsCache; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - function shouldEmitFile(scriptInfo) { - return !scriptInfo.hasMixedContent && !scriptInfo.isDynamic; - } - server.shouldEmitFile = shouldEmitFile; - var BuilderFileInfo = (function () { - function BuilderFileInfo(scriptInfo, project) { - this.scriptInfo = scriptInfo; - this.project = project; - } - BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { - var sourceFile = this.getSourceFile(); - return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); - }; - BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (statement.kind !== 233 || statement.name.kind !== 9) { - return false; - } - } - return true; - }; - BuilderFileInfo.prototype.computeHash = function (text) { - return this.project.projectService.host.createHash(text); - }; - BuilderFileInfo.prototype.getSourceFile = function () { - return this.project.getSourceFile(this.scriptInfo.path); - }; - BuilderFileInfo.prototype.updateShapeSignature = function () { - var sourceFile = this.getSourceFile(); - if (!sourceFile) { - return true; - } - var lastSignature = this.lastCheckedShapeSignature; - if (sourceFile.isDeclarationFile) { - this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); - } - else { - var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); - } - } - return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; - }; - return BuilderFileInfo; - }()); - server.BuilderFileInfo = BuilderFileInfo; - var AbstractBuilder = (function () { - function AbstractBuilder(project, ctor) { - this.project = project; - this.ctor = ctor; - } - AbstractBuilder.prototype.getFileInfos = function () { - return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createMap()); - }; - AbstractBuilder.prototype.hasFileInfos = function () { - return !!this.fileInfos_doNotAccessDirectly; - }; - AbstractBuilder.prototype.clear = function () { - this.fileInfos_doNotAccessDirectly = undefined; - }; - AbstractBuilder.prototype.getFileInfo = function (path) { - return this.getFileInfos().get(path); - }; - AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { - var fileInfo = this.getFileInfo(path); - if (!fileInfo) { - var scriptInfo = this.project.getScriptInfo(path); - fileInfo = new this.ctor(scriptInfo, this.project); - this.setFileInfo(path, fileInfo); - } - return fileInfo; - }; - AbstractBuilder.prototype.getFileInfoPaths = function () { - return ts.arrayFrom(this.getFileInfos().keys()); - }; - AbstractBuilder.prototype.setFileInfo = function (path, info) { - this.getFileInfos().set(path, info); - }; - AbstractBuilder.prototype.removeFileInfo = function (path) { - this.getFileInfos().delete(path); - }; - AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.getFileInfos().forEach(action); - }; - AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { - this.ensureFileInfoIfInProject(scriptInfo); - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo) { - return false; - } - var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; - if (!emitSkipped) { - var projectRootPath = this.project.getProjectRootPath(); - for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { - var outputFile = outputFiles_1[_i]; - var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); - writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); - } - } - return !emitSkipped; - }; - return AbstractBuilder; - }()); - var NonModuleBuilder = (function (_super) { - __extends(NonModuleBuilder, _super); - function NonModuleBuilder(project) { - var _this = _super.call(this, project, BuilderFileInfo) || this; - _this.project = project; - return _this; - } - NonModuleBuilder.prototype.ensureFileInfoIfInProject = function (scriptInfo) { - if (this.project.containsScriptInfo(scriptInfo)) { - this.getOrCreateFileInfo(scriptInfo.path); - } - }; - NonModuleBuilder.prototype.onProjectUpdateGraph = function () { - var _this = this; - if (this.hasFileInfos()) { - this.forEachFileInfo(function (fileInfo) { - if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { - _this.removeFileInfo(fileInfo.scriptInfo.path); - } - }); - } - }; - NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - var info = this.getOrCreateFileInfo(scriptInfo.path); - var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; - if (info.updateShapeSignature()) { - var options = this.project.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return singleFileResult; - } - return this.project.getAllEmittableFiles(); - } - return singleFileResult; - }; - return NonModuleBuilder; - }(AbstractBuilder)); - var ModuleBuilderFileInfo = (function (_super) { - __extends(ModuleBuilderFileInfo, _super); - function ModuleBuilderFileInfo() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.references = server.createSortedArray(); - _this.referencedBy = server.createSortedArray(); - return _this; - } - ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { - return ts.compareStrings(lf.scriptInfo.fileName, rf.scriptInfo.fileName); - }; - ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { - server.insertSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - }; - ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { - server.removeSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - }; - ModuleBuilderFileInfo.prototype.removeFileReferences = function () { - for (var _i = 0, _a = this.references; _i < _a.length; _i++) { - var reference = _a[_i]; - reference.removeReferencedBy(this); - } - ts.clear(this.references); - }; - return ModuleBuilderFileInfo; - }(BuilderFileInfo)); - var ModuleBuilder = (function (_super) { - __extends(ModuleBuilder, _super); - function ModuleBuilder(project) { - var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; - _this.project = project; - return _this; - } - ModuleBuilder.prototype.clear = function () { - this.projectVersionForDependencyGraph = undefined; - _super.prototype.clear.call(this); - }; - ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { - var _this = this; - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return server.createSortedArray(); - } - var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); - return server.toSortedArray(referencedFilePaths.map(function (f) { return _this.getOrCreateFileInfo(f); }), ModuleBuilderFileInfo.compareFileInfos); - }; - ModuleBuilder.prototype.ensureFileInfoIfInProject = function (_scriptInfo) { - this.ensureProjectDependencyGraphUpToDate(); - }; - ModuleBuilder.prototype.onProjectUpdateGraph = function () { - if (this.hasFileInfos()) { - this.ensureProjectDependencyGraphUpToDate(); - } - }; - ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { - var _this = this; - if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { - var currentScriptInfos = this.project.getScriptInfos(); - for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { - var scriptInfo = currentScriptInfos_1[_i]; - var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); - this.updateFileReferences(fileInfo); - } - this.forEachFileInfo(function (fileInfo) { - if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { - fileInfo.removeFileReferences(); - _this.removeFileInfo(fileInfo.scriptInfo.path); - } - }); - this.projectVersionForDependencyGraph = this.project.getProjectVersion(); - } - }; - ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { - if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { - return; - } - var newReferences = this.getReferencedFileInfos(fileInfo); - var oldReferences = fileInfo.references; - server.enumerateInsertsAndDeletes(newReferences, oldReferences, function (newReference) { return newReference.addReferencedBy(fileInfo); }, function (oldReference) { - oldReference.removeReferencedBy(fileInfo); - }, ModuleBuilderFileInfo.compareFileInfos); - fileInfo.references = newReferences; - fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); - }; - ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - this.ensureProjectDependencyGraphUpToDate(); - var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo || !fileInfo.updateShapeSignature()) { - return singleFileResult; - } - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return this.project.getAllEmittableFiles(); - } - var options = this.project.getCompilerOptions(); - if (options && (options.isolatedModules || options.out || options.outFile)) { - return singleFileResult; - } - var queue = fileInfo.referencedBy.slice(0); - var fileNameSet = ts.createMap(); - fileNameSet.set(scriptInfo.fileName, scriptInfo); - while (queue.length > 0) { - var processingFileInfo = queue.pop(); - if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { - for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { - var potentialFileInfo = _a[_i]; - if (!fileNameSet.has(potentialFileInfo.scriptInfo.fileName)) { - queue.push(potentialFileInfo); - } - } - } - fileNameSet.set(processingFileInfo.scriptInfo.fileName, processingFileInfo.scriptInfo); - } - var result = []; - fileNameSet.forEach(function (scriptInfo, fileName) { - if (shouldEmitFile(scriptInfo)) { - result.push(fileName); - } - }); - return result; - }; - return ModuleBuilder; - }(AbstractBuilder)); - function createBuilder(project) { - var moduleKind = project.getCompilerOptions().module; - switch (moduleKind) { - case ts.ModuleKind.None: - return new NonModuleBuilder(project); - default: - return new ModuleBuilder(project); - } - } - server.createBuilder = createBuilder; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); +/// +/// +/// +/// +/// +/// var ts; (function (ts) { var server; @@ -81401,23 +102857,24 @@ var ts; ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); + /* @internal */ function countEachFileTypes(infos) { var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; switch (info.scriptKind) { - case 1: + case 1 /* JS */: result.js += 1; break; - case 2: + case 2 /* JSX */: result.jsx += 1; break; - case 3: - ts.fileExtensionIs(info.fileName, ".d.ts") + case 3 /* TS */: + ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */) ? result.dts += 1 : result.ts += 1; break; - case 4: + case 4 /* TSX */: result.tsx += 1; break; } @@ -81439,7 +102896,12 @@ var ts; return counts.ts === 0 && counts.tsx === 0; } server.allFilesAreJsOrDts = allFilesAreJsOrDts; - var UnresolvedImportsMap = (function () { + /* @internal */ + function hasNoTypeScriptSource(fileNames) { + return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts" /* Ts */) && !ts.fileExtensionIs(fileName, ".d.ts" /* Dts */)) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */); }); + } + server.hasNoTypeScriptSource = hasNoTypeScriptSource; + var UnresolvedImportsMap = /** @class */ (function () { function UnresolvedImportsMap() { this.perFileMap = ts.createMap(); this.version = 0; @@ -81465,39 +102927,70 @@ var ts; return UnresolvedImportsMap; }()); server.UnresolvedImportsMap = UnresolvedImportsMap; - var Project = (function () { - function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + /* @internal */ + function isScriptInfo(value) { + return value instanceof server.ScriptInfo; + } + server.isScriptInfo = isScriptInfo; + var Project = /** @class */ (function () { + /*@internal*/ + function Project( + /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, + /*@internal*/ directoryStructureHost, currentDirectory) { this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; + this.directoryStructureHost = directoryStructureHost; this.rootFiles = []; this.rootFilesMap = ts.createMap(); - this.missingFilesMap = ts.createMap(); this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); this.languageServiceEnabled = true; + /** + * Last version that was reported. + */ this.lastReportedVersion = 0; + /** + * Current project structure version. + * This property is changed in 'updateGraph' based on the set of files in program + */ this.projectStructureVersion = 0; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ this.projectStateVersion = 0; - this.typesVersion = 0; + /*@internal*/ + this.hasChangedAutomaticTypeDirectiveNames = false; + this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); + this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { this.compilerOptions = ts.getDefaultCompilerOptions(); this.compilerOptions.allowNonTsExtensions = true; this.compilerOptions.allowJs = true; } else if (hasExplicitListOfFiles || this.compilerOptions.allowJs) { + // If files are listed explicitly or allowJs is specified, allow all extensions this.compilerOptions.allowNonTsExtensions = true; } this.setInternalCompilerOptionsForEmittingJsFiles(); - this.lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); - this.lsHost.setCompilationSettings(this.compilerOptions); - this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); + var host = this.projectService.host; + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + if (host.realpath) { + this.realpath = function (path) { return host.realpath(path); }; + } + // Use the current directory as resolution root only if the project created using current directory string + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); + this.languageService = ts.createLanguageService(this, this.documentRegistry); if (!languageServiceEnabled) { this.disableLanguageService(); } - this.builder = server.createBuilder(this); this.markAsDirty(); } Project.prototype.isNonTsProject = function () { @@ -81522,16 +103015,153 @@ var ts; } return result.module; }; + Project.prototype.isKnownTypesPackageName = function (name) { + return this.typingsCache.isKnownTypesPackageName(name); + }; + Project.prototype.installPackage = function (options) { + return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); + }; + Object.defineProperty(Project.prototype, "typingsCache", { + get: function () { + return this.projectService.typingsCache; + }, + enumerable: true, + configurable: true + }); + // Method of LanguageServiceHost + Project.prototype.getCompilationSettings = function () { + return this.compilerOptions; + }; + // Method to support public API + Project.prototype.getCompilerOptions = function () { + return this.getCompilationSettings(); + }; + Project.prototype.getNewLine = function () { + return this.directoryStructureHost.newLine; + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.getScriptFileNames = function () { + var _this = this; + if (!this.rootFiles) { + return ts.emptyArray; + } + var result; + this.rootFilesMap.forEach(function (value) { + if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) { + // if language service is disabled - process only files that are open + (result || (result = [])).push(isScriptInfo(value) ? value.fileName : value); + } + }); + return ts.addRange(result, this.typingFiles) || ts.emptyArray; + }; + Project.prototype.getOrCreateScriptInfoAndAttachToProject = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost); + if (scriptInfo) { + var existingValue = this.rootFilesMap.get(scriptInfo.path); + if (existingValue !== scriptInfo && existingValue !== undefined) { + // This was missing path earlier but now the file exists. Update the root + this.rootFiles.push(scriptInfo); + this.rootFilesMap.set(scriptInfo.path, scriptInfo); + } + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptKind = function (fileName) { + var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); + return info && info.scriptKind; + }; + Project.prototype.getScriptVersion = function (filename) { + var info = this.getOrCreateScriptInfoAndAttachToProject(filename); + return info && info.getLatestVersion(); + }; + Project.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); + if (scriptInfo) { + return scriptInfo.getSnapshot(); + } + }; + Project.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + Project.prototype.getCurrentDirectory = function () { + return this.currentDirectory; + }; + Project.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.projectService.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); + }; + Project.prototype.useCaseSensitiveFileNames = function () { + return this.directoryStructureHost.useCaseSensitiveFileNames; + }; + Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); + }; + Project.prototype.readFile = function (fileName) { + return this.directoryStructureHost.readFile(fileName); + }; + Project.prototype.fileExists = function (file) { + // As an optimization, don't hit the disks for files we already know don't exist + // (because we're watching for their creation). + var path = this.toPath(file); + return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); + }; + Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, /*logChanges*/ true); + }; + Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); + }; + Project.prototype.directoryExists = function (path) { + return this.directoryStructureHost.directoryExists(path); + }; + Project.prototype.getDirectories = function (path) { + return this.directoryStructureHost.getDirectories(path); + }; + /*@internal*/ + Project.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); + }; + /*@internal*/ + Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { + return this.projectService.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution" /* FailedLookupLocation */, this); + }; + /*@internal*/ + Project.prototype.onInvalidatedResolution = function () { + this.projectService.delayUpdateProjectGraphAndInferredProjectsRefresh(this); + }; + /*@internal*/ + Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { + return this.projectService.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory" /* TypeRoots */, this); + }; + /*@internal*/ + Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { + this.hasChangedAutomaticTypeDirectiveNames = true; + this.projectService.delayUpdateProjectGraphAndInferredProjectsRefresh(this); + }; + /*@internal*/ + Project.prototype.getGlobalCache = function () { + return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; + }; + /*@internal*/ + Project.prototype.writeLog = function (s) { + this.projectService.logger.info(s); + }; Project.prototype.setInternalCompilerOptionsForEmittingJsFiles = function () { if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) { this.compilerOptions.noEmitForJsFiles = true; } }; + /** + * Get the errors that dont have any file name associated + */ Project.prototype.getGlobalProjectErrors = function () { - return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }); + return server.emptyArray; }; Project.prototype.getAllProjectErrors = function () { - return this.projectErrors; + return server.emptyArray; }; Project.prototype.getLanguageService = function (ensureSynchronized) { if (ensureSynchronized === void 0) { ensureSynchronized = true; } @@ -81540,22 +103170,50 @@ var ts; } return this.languageService; }; + Project.prototype.ensureBuilder = function () { + var _this = this; + if (!this.builder) { + this.builder = ts.createBuilder({ + getCanonicalFileName: this.projectService.toCanonicalFileName, + computeHash: function (data) { return _this.projectService.host.createHash(data); } + }); + } + }; + Project.prototype.shouldEmitFile = function (scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); + }; Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + var _this = this; if (!this.languageServiceEnabled) { return []; } this.updateGraph(); - return this.builder.getFilesAffectedBy(scriptInfo); - }; - Project.prototype.getProjectVersion = function () { - return this.projectStateVersion.toString(); + this.ensureBuilder(); + return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + }; + /** + * Returns true if emit was conducted + */ + Project.prototype.emitFile = function (scriptInfo, writeFile) { + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return false; + } + var _a = this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; }; Project.prototype.enableLanguageService = function () { if (this.languageServiceEnabled) { return; } this.languageServiceEnabled = true; - this.projectService.onUpdateLanguageServiceStateForProject(this, true); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true); }; Project.prototype.disableLanguageService = function () { if (!this.languageServiceEnabled) { @@ -81563,7 +103221,8 @@ var ts; } this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; - this.projectService.onUpdateLanguageServiceStateForProject(this, false); + this.resolutionCache.closeTypeRootsWatch(); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); }; Project.prototype.getProjectName = function () { return this.projectName; @@ -81577,40 +103236,52 @@ var ts; } return this.program.getSourceFileByPath(path); }; - Project.prototype.updateTypes = function () { - this.typesVersion++; - this.markAsDirty(); - this.updateGraph(); - }; Project.prototype.close = function () { + var _this = this; if (this.program) { + // if we have a program - release all files that are enlisted in program but arent root + // The releasing of the roots happens later + // The project could have pending update remaining and hence the info could be in the files but not in program graph for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; - var info = this.projectService.getScriptInfo(f.fileName); - info.detachFromProject(this); + this.detachScriptInfoIfNotRoot(f.fileName); } } - if (!this.program || !this.languageServiceEnabled) { - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; - root.detachFromProject(this); - } + // Release external files + ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); + // Always remove root files from the project + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); } this.rootFiles = undefined; this.rootFilesMap = undefined; + this.externalFiles = undefined; this.program = undefined; this.builder = undefined; + this.resolutionCache.clear(); + this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; - this.projectErrors = undefined; - this.lsHost.dispose(); - this.lsHost = undefined; - this.missingFilesMap.forEach(function (fileWatcher) { return fileWatcher.close(); }); - this.missingFilesMap = undefined; + this.directoryStructureHost = undefined; + // Clean up file watchers waiting for missing files + if (this.missingFilesMap) { + ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); + this.missingFilesMap = undefined; + } + // signal language service to release source files acquired from document registry this.languageService.dispose(); this.languageService = undefined; }; - Project.prototype.getCompilerOptions = function () { - return this.compilerOptions; + Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { + var info = this.projectService.getScriptInfo(uncheckedFilename); + // We might not find the script info in case its not associated with the project any more + // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk) + if (info && !this.isRoot(info)) { + info.detachFromProject(this); + } + }; + Project.prototype.isClosed = function () { + return this.rootFiles === undefined; }; Project.prototype.hasRoots = function () { return this.rootFiles && this.rootFiles.length > 0; @@ -81618,23 +103289,9 @@ var ts; Project.prototype.getRootFiles = function () { return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); }; - Project.prototype.getRootFilesLSHost = function () { - var result = []; - if (this.rootFiles) { - for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { - var f = _a[_i]; - if (this.languageServiceEnabled || f.isScriptOpen()) { - result.push(f.fileName); - } - } - if (this.typingFiles) { - for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { - var f = _c[_b]; - result.push(f); - } - } - } - return result; + /*@internal*/ + Project.prototype.getRootFilesMap = function () { + return this.rootFilesMap; }; Project.prototype.getRootScriptInfos = function () { return this.rootFiles; @@ -81642,22 +103299,17 @@ var ts; Project.prototype.getScriptInfos = function () { var _this = this; if (!this.languageServiceEnabled) { + // if language service is not enabled - return just root files return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { - ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + ts.Debug.fail("scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' is missing."); } return scriptInfo; }); }; - Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { - if (!this.languageServiceEnabled) { - return undefined; - } - return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); - }; Project.prototype.getExcludedFiles = function () { return server.emptyArray; }; @@ -81666,6 +103318,7 @@ var ts; return []; } if (!this.languageServiceEnabled) { + // if language service is disabled assume that all files in program are root files + default library var rootFiles = this.getRootFiles(); if (this.compilerOptions) { var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); @@ -81716,47 +103369,43 @@ var ts; } return false; }; - Project.prototype.getAllEmittableFiles = function () { - if (!this.languageServiceEnabled) { - return []; - } - var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); - var infos = this.getScriptInfos(); - var result = []; - for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { - var info = infos_2[_i]; - if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { - result.push(info.fileName); - } - } - return result; - }; Project.prototype.containsScriptInfo = function (info) { return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); }; Project.prototype.containsFile = function (filename, requireOpen) { - var info = this.projectService.getScriptInfoForNormalizedPath(filename); + var info = this.projectService.getScriptInfoForPath(this.toPath(filename)); if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } }; Project.prototype.isRoot = function (info) { - return this.rootFilesMap && this.rootFilesMap.has(info.path); + return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; }; + // add a root file to project Project.prototype.addRoot = function (info) { - if (!this.isRoot(info)) { - this.rootFiles.push(info); - this.rootFilesMap.set(info.path, info); - info.attachToProject(this); - this.markAsDirty(); - } + ts.Debug.assert(!this.isRoot(info)); + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); }; - Project.prototype.removeFile = function (info, detachFromProject) { - if (detachFromProject === void 0) { detachFromProject = true; } + // add a root file that doesnt exist on host + Project.prototype.addMissingFileRoot = function (fileName) { + var path = this.projectService.toPath(fileName); + this.rootFilesMap.set(path, fileName); + this.markAsDirty(); + }; + Project.prototype.removeFile = function (info, fileExists, detachFromProject) { if (this.isRoot(info)) { this.removeRoot(info); } - this.lsHost.notifyFileRemoved(info); + if (fileExists) { + // If file is present, just remove the resolutions for the file + this.resolutionCache.removeResolutionsOfFile(info.path); + } + else { + this.resolutionCache.invalidateResolutionOfFile(info.path); + } this.cachedUnresolvedImportsPerFile.remove(info.path); if (detachFromProject) { info.detachFromProject(this); @@ -81772,6 +103421,7 @@ var ts; Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result) { var cached = this.cachedUnresolvedImportsPerFile.get(file.path); if (cached) { + // found cached result - use it and return for (var _i = 0, cached_2 = cached; _i < cached_2.length; _i++) { var f = cached_2[_i]; result.push(f); @@ -81781,10 +103431,13 @@ var ts; var unresolvedImports; if (file.resolvedModules) { file.resolvedModules.forEach(function (resolvedModule, name) { + // pick unresolved non-relative names if (!resolvedModule && !ts.isExternalModuleNameRelative(name)) { + // for non-scoped names extract part up-to the first slash + // for scoped names - extract up to the second slash var trimmed = name.trim(); var i = trimmed.indexOf("/"); - if (i !== -1 && trimmed.charCodeAt(0) === 64) { + if (i !== -1 && trimmed.charCodeAt(0) === 64 /* at */) { i = trimmed.indexOf("/", i + 1); } if (i !== -1) { @@ -81797,15 +103450,28 @@ var ts; } this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); }; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ Project.prototype.updateGraph = function () { - this.lsHost.startRecordingFilesWithChangedResolutions(); + this.resolutionCache.startRecordingFilesWithChangedResolutions(); var hasChanges = this.updateGraphWorker(); - var changedFiles = this.lsHost.finishRecordingFilesWithChangedResolutions() || server.emptyArray; + var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { var file = changedFiles_1[_i]; + // delete cached information for changed files this.cachedUnresolvedImportsPerFile.remove(file); } + // update builder only if language service is enabled + // otherwise tell it to drop its internal state if (this.languageServiceEnabled) { + // 1. no changes in structure, no changes in unresolved imports - do nothing + // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files + // (can reuse cached imports for files that were not changed) + // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files + // (can reuse cached imports for files that were not changed) + // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasChanges || changedFiles.length) { var result = []; for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { @@ -81818,11 +103484,15 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } - this.builder.onProjectUpdateGraph(); + if (this.builder) { + this.builder.updateProgram(this.program); + } } else { this.lastCachedUnresolvedImportsList = undefined; - this.builder.clear(); + if (this.builder) { + this.builder.clear(); + } } if (hasChanges) { this.projectStructureVersion++; @@ -81840,8 +103510,18 @@ var ts; Project.prototype.updateGraphWorker = function () { var _this = this; var oldProgram = this.program; + ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); + this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); + var start = ts.timestamp(); + this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); + this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); - var hasChanges = !oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2)); + this.resolutionCache.finishCachingPerDirectoryResolution(); + // bump up the version if + // - oldProgram is not set - this is a first time updateGraph is called + // - newProgram is different from the old program and structure of the old program was not reused. + var hasChanges = !oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2 /* Completely */)); + this.hasChangedAutomaticTypeDirectiveNames = false; if (hasChanges) { if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -81849,80 +103529,79 @@ var ts; if (this.program.getSourceFileByPath(f.path)) { continue; } - var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(this); - } + // new program does not contain this file - detach it from the project + this.detachScriptInfoFromProject(f.fileName); } } - var missingFilePaths = this.program.getMissingFilePaths(); - var missingFilePathsSet_1 = ts.arrayToSet(missingFilePaths); - this.missingFilesMap.forEach(function (fileWatcher, missingFilePath) { - if (!missingFilePathsSet_1.has(missingFilePath)) { - _this.missingFilesMap.delete(missingFilePath); - fileWatcher.close(); - } - }); - var _loop_9 = function (missingFilePath) { - if (!this_1.missingFilesMap.has(missingFilePath)) { - var fileWatcher_1 = this_1.projectService.host.watchFile(missingFilePath, function (_filename, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { - fileWatcher_1.close(); - _this.missingFilesMap.delete(missingFilePath); - _this.markAsDirty(); - _this.updateGraph(); - } - }); - this_1.missingFilesMap.set(missingFilePath, fileWatcher_1); - } - }; - var this_1 = this; - for (var _b = 0, missingFilePaths_1 = missingFilePaths; _b < missingFilePaths_1.length; _b++) { - var missingFilePath = missingFilePaths_1[_b]; - _loop_9(missingFilePath); + // Update the missing file paths watcher + ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), + // Watch the missing files + function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); + // Watch the type locations that would be added to program as part of automatic type resolutions + if (this.languageServiceEnabled) { + this.resolutionCache.updateTypeRootsWatch(); } } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); - server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, function (inserted) { - var scriptInfo = _this.projectService.getOrCreateScriptInfo(inserted, false); + server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, + // Ensure a ScriptInfo is created for new external files. This is performed indirectly + // by the LSHost for files in the program when the program is retrieved above but + // the program doesn't contain external files so this must be done explicitly. + function (inserted) { + var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost); scriptInfo.attachToProject(_this); - }, function (removed) { - var scriptInfoToDetach = _this.projectService.getScriptInfo(removed); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(_this); - } - }); + }, function (removed) { return _this.detachScriptInfoFromProject(removed); }, ts.compareStringsCaseSensitive); + var elapsed = ts.timestamp() - start; + this.writeLog("Finishing updateGraphWorker: Project: " + this.getProjectName() + " structureChanged: " + hasChanges + " Elapsed: " + elapsed + "ms"); return hasChanges; }; - Project.prototype.isWatchedMissingFile = function (path) { - return this.missingFilesMap.has(path); - }; - Project.prototype.getScriptInfoLSHost = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); - if (scriptInfo) { - scriptInfo.attachToProject(this); + Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName) { + var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); } - return scriptInfo; + }; + Project.prototype.addMissingFileWatcher = function (missingFilePath) { + var _this = this; + var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { + if (_this.projectKind === ProjectKind.Configured) { + _this.directoryStructureHost.addOrDeleteFile(fileName, missingFilePath, eventKind); + } + if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { + _this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + // When a missing file is created, we should update the graph. + _this.projectService.delayUpdateProjectGraphAndInferredProjectsRefresh(_this); + } + }, "Missing file from program" /* MissingFilePath */, this); + return fileWatcher; + }; + Project.prototype.isWatchedMissingFile = function (path) { + return this.missingFilesMap && this.missingFilesMap.has(path); }; Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + var scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); if (scriptInfo && !scriptInfo.isAttached(this)) { return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); } return scriptInfo; }; Project.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + return this.projectService.getScriptInfo(uncheckedFileName); }; - Project.prototype.filesToString = function () { + Project.prototype.filesToString = function (writeProjectFileNames) { if (!this.program) { - return ""; + return "\tFiles (0)\n"; } - var strBuilder = ""; - for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - strBuilder += "\t" + file.fileName + "\n"; + var sourceFiles = this.program.getSourceFiles(); + var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; + if (writeProjectFileNames) { + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var file = sourceFiles_9[_i]; + strBuilder += "\t" + file.fileName + "\n"; + } } return strBuilder; }; @@ -81930,39 +103609,38 @@ var ts; if (compilerOptions) { compilerOptions.allowNonTsExtensions = true; if (ts.changesAffectModuleResolution(this.compilerOptions, compilerOptions)) { + // reset cached unresolved imports if changes in compiler options affected module resolution this.cachedUnresolvedImportsPerFile.clear(); this.lastCachedUnresolvedImportsList = undefined; } + var oldOptions = this.compilerOptions; this.compilerOptions = compilerOptions; this.setInternalCompilerOptionsForEmittingJsFiles(); - this.lsHost.setCompilationSettings(compilerOptions); + if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) { + this.resolutionCache.clear(); + } this.markAsDirty(); } }; - Project.prototype.reloadScript = function (filename, tempFileName) { - var script = this.projectService.getScriptInfoForNormalizedPath(filename); - if (script) { - ts.Debug.assert(script.isAttached(this)); - script.reloadFromFile(tempFileName); - return true; - } - return false; - }; + /* @internal */ Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { this.updateGraph(); var info = { projectName: this.getProjectName(), version: this.projectStructureVersion, isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions(), + options: this.getCompilationSettings(), languageServiceDisabled: !this.languageServiceEnabled }; var updatedFileNames = this.updatedFileNames; this.updatedFileNames = undefined; + // check if requested version is the same that we have reported last time if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + // if current structure version is the same - return info without any changes if (this.projectStructureVersion === this.lastReportedVersion && !updatedFileNames) { return { info: info, projectErrors: this.getGlobalProjectErrors() }; } + // compute and return the difference var lastReportedFileNames_1 = this.lastReportedFileNames; var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles)); @@ -81984,58 +103662,16 @@ var ts; return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() }; } else { + // unknown version - return everything var projectFileNames = this.getFileNames(); var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); - this.lastReportedFileNames = ts.arrayToSet(projectFileNames.concat(externalFiles)); + var allFiles = projectFileNames.concat(externalFiles); + this.lastReportedFileNames = ts.arrayToSet(allFiles); this.lastReportedVersion = this.projectStructureVersion; - return { info: info, files: projectFileNames, projectErrors: this.getGlobalProjectErrors() }; + return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() }; } }; - Project.prototype.getReferencedFiles = function (path) { - var _this = this; - if (!this.languageServiceEnabled) { - return []; - } - var sourceFile = this.getSourceFile(path); - if (!sourceFile) { - return []; - } - var referencedFiles = ts.createMap(); - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = this.program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = symbol.declarations[0].getSourceFile(); - if (declarationSourceFile) { - referencedFiles.set(declarationSourceFile.path, true); - } - } - } - } - var currentDirectory = ts.getDirectoryPath(path); - var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); - referencedFiles.set(referencedPath, true); - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - referencedFiles.set(typeFilePath, true); - }); - } - var allFileNames = ts.arrayFrom(referencedFiles.keys()); - return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); - }; + // remove a root file from project Project.prototype.removeRoot = function (info) { ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); @@ -82043,13 +103679,20 @@ var ts; return Project; }()); server.Project = Project; - var InferredProject = (function (_super) { + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ + var InferredProject = /** @class */ (function (_super) { __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath) { - var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false) || this; + /*@internal*/ + function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, + /*files*/ undefined, + /*languageServiceEnabled*/ true, compilerOptions, + /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; - _this.directoriesWatchedForTsconfig = []; - _this.projectRootPath = projectRootPath; + _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -82059,7 +103702,8 @@ var ts; } }; InferredProject.prototype.setCompilerOptions = function (options) { - var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilerOptions(); + // Avoid manipulating the given options directly + var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilationSettings(); if (!newOptions) { return; } @@ -82073,32 +103717,33 @@ var ts; _super.prototype.setCompilerOptions.call(this, newOptions); }; InferredProject.prototype.addRoot = function (info) { + ts.Debug.assert(info.isScriptOpen()); + this.projectService.startWatchingConfigFilesForInferredProjectRoot(info, this.projectService.openFiles.get(info.path)); if (!this._isJsInferredProject && info.isJavaScript()) { - this.toggleJsInferredProject(true); + this.toggleJsInferredProject(/*isJsInferredProject*/ true); } _super.prototype.addRoot.call(this, info); }; InferredProject.prototype.removeRoot = function (info) { + this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); + _super.prototype.removeRoot.call(this, info); if (this._isJsInferredProject && info.isJavaScript()) { - if (ts.filter(this.getRootScriptInfos(), function (info) { return info.isJavaScript(); }).length === 0) { - this.toggleJsInferredProject(false); + if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) { + this.toggleJsInferredProject(/*isJsInferredProject*/ false); } } - _super.prototype.removeRoot.call(this, info); }; - InferredProject.prototype.getProjectRootPath = function () { - if (this.projectService.useSingleInferredProject) { - return undefined; - } - var rootFiles = this.getRootFiles(); - return ts.getDirectoryPath(rootFiles[0]); + InferredProject.prototype.isProjectWithSingleRoot = function () { + // - when useSingleInferredProject is not set and projectRootPath is not set, + // we can guarantee that this will be the only root + // - other wise it has single root if it has single root script info + return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || + this.getRootScriptInfos().length === 1; }; InferredProject.prototype.close = function () { + var _this = this; + ts.forEach(this.getRootScriptInfos(), function (info) { return _this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); }); _super.prototype.close.call(this); - for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - this.projectService.stopWatchingDirectory(directory); - } }; InferredProject.prototype.getTypeAcquisition = function () { return { @@ -82118,34 +103763,64 @@ var ts; return InferredProject; }(Project)); server.InferredProject = InferredProject; - var ConfiguredProject = (function (_super) { + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successfull create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ + var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; - _this.wildcardDirectories = wildcardDirectories; + /*@internal*/ + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.plugins = []; - _this.openRefCount = 0; + /** Ref count to the project when opened from external project */ + _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); return _this; } + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + ConfiguredProject.prototype.updateGraph = function () { + var reloadLevel = this.pendingReload; + this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return this.projectService.reloadFileNamesOfConfiguredProject(this); + case ts.ConfigFileProgramReloadLevel.Full: + this.projectService.reloadConfiguredProject(this); + return true; + default: + return _super.prototype.updateGraph.call(this); + } + }; + /*@internal*/ + ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { + return this.directoryStructureHost; + }; ConfiguredProject.prototype.getConfigFilePath = function () { - return this.getProjectName(); + return server.asNormalizedPath(this.getProjectName()); }; ConfiguredProject.prototype.enablePlugins = function () { var host = this.projectService.host; - var options = this.getCompilerOptions(); + var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - var searchPaths = [ts.combinePaths(host.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); searchPaths.unshift(local); } + // Enable tsconfig-specified plugins if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -82153,18 +103828,22 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_10 = function (globalPluginName) { + var _loop_12 = function (globalPluginName) { + // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; + // Skip already-locally-loaded plugins if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; + // Provide global: true so plugins can detect why they can't find their config this_2.projectService.logger.info("Loading global plugin " + globalPluginName); this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; var this_2 = this; + // Enable global plugins with synthetic configuration entries for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_10(globalPluginName); + _loop_12(globalPluginName); } } }; @@ -82194,7 +103873,7 @@ var ts; config: configEntry, project: this, languageService: this.languageService, - languageServiceHost: this.lsHost, + languageServiceHost: this, serverHost: this.projectService.host }; var pluginModule = pluginModuleFactory({ typescript: ts }); @@ -82214,8 +103893,17 @@ var ts; this.projectService.logger.info("Plugin activation failed: " + e); } }; - ConfiguredProject.prototype.getProjectRootPath = function () { - return ts.getDirectoryPath(this.getConfigFilePath()); + /** + * Get the errors that dont have any file name associated + */ + ConfiguredProject.prototype.getGlobalProjectErrors = function () { + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; + }; + /** + * Get all the project errors + */ + ConfiguredProject.prototype.getAllProjectErrors = function () { + return this.projectErrors || server.emptyArray; }; ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { this.projectErrors = projectErrors; @@ -82242,129 +103930,102 @@ var ts; } })); }; - ConfiguredProject.prototype.watchConfigFile = function (callback) { + /*@internal*/ + ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { var _this = this; - this.projectFileWatcher = this.projectService.host.watchFile(this.getConfigFilePath(), function (_) { return callback(_this); }); + ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, + // Create new directory watcher + function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); }; - ConfiguredProject.prototype.watchTypeRoots = function (callback) { - var _this = this; - var roots = this.getEffectiveTypeRoots(); - var watchers = []; - for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { - var root = roots_1[_i]; - this.projectService.logger.info("Add type root watcher for: " + root); - watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + /*@internal*/ + ConfiguredProject.prototype.stopWatchingWildCards = function () { + if (this.directoriesWatchedForWildcards) { + ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); + this.directoriesWatchedForWildcards = undefined; } - this.typeRootsWatchers = watchers; }; - ConfiguredProject.prototype.watchConfigDirectory = function (callback) { - var _this = this; - if (this.directoryWatcher) { - return; + ConfiguredProject.prototype.close = function () { + if (this.configFileWatcher) { + this.configFileWatcher.close(); + this.configFileWatcher = undefined; } - var directoryToWatch = ts.getDirectoryPath(this.getConfigFilePath()); - this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); - this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + this.stopWatchingWildCards(); + this.projectErrors = undefined; + this.configFileSpecs = undefined; + _super.prototype.close.call(this); }; - ConfiguredProject.prototype.watchWildcards = function (callback) { - var _this = this; - if (!this.wildcardDirectories) { - return; - } - var configDirectoryPath = ts.getDirectoryPath(this.getConfigFilePath()); - this.directoriesWatchedForWildcards = ts.createMap(); - this.wildcardDirectories.forEach(function (flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - _this.directoriesWatchedForWildcards.set(directory, _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive)); - } - }); + /* @internal */ + ConfiguredProject.prototype.addExternalProjectReference = function () { + this.externalProjectRefCount++; }; - ConfiguredProject.prototype.stopWatchingDirectory = function () { - if (this.directoryWatcher) { - this.directoryWatcher.close(); - this.directoryWatcher = undefined; - } + /* @internal */ + ConfiguredProject.prototype.deleteExternalProjectReference = function () { + this.externalProjectRefCount--; }; - ConfiguredProject.prototype.close = function () { - _super.prototype.close.call(this); - if (this.projectFileWatcher) { - this.projectFileWatcher.close(); - this.projectFileWatcher = undefined; + /** Returns true if the project is needed by any of the open script info/external project */ + /* @internal */ + ConfiguredProject.prototype.hasOpenRef = function () { + var _this = this; + if (!!this.externalProjectRefCount) { + return true; } - if (this.typeRootsWatchers) { - for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { - var watcher = _a[_i]; - watcher.close(); - } - this.typeRootsWatchers = undefined; + // Closed project doesnt have any reference + if (this.isClosed()) { + return false; } - if (this.directoriesWatchedForWildcards) { - this.directoriesWatchedForWildcards.forEach(function (watcher) { - watcher.close(); - }); - this.directoriesWatchedForWildcards = undefined; + var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + if (this.projectService.hasPendingProjectUpdate(this)) { + // If there is pending update for this project, + // we dont know if this project would be needed by any of the open files impacted by this config file + // In that case keep the project alive if there are open files impacted by this project + return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; } - this.stopWatchingDirectory(); - }; - ConfiguredProject.prototype.addOpenRef = function () { - this.openRefCount++; - }; - ConfiguredProject.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; + // If there is no pending update for this project, + // We know exact set of open files that get impacted by this configured project as the files in the project + // The project is referenced only if open files impacted by this project are present in this project + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { - return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; + }; + /*@internal*/ + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { + if (hasFileNames) { + ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); + } + else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { + this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); + } }; return ConfiguredProject; }(Project)); server.ConfiguredProject = ConfiguredProject; - var ExternalProject = (function (_super) { + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ + var ExternalProject = /** @class */ (function (_super) { __extends(ExternalProject, _super); + /*@internal*/ function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { - var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectFilePath = projectFilePath; _this.excludedFiles = []; return _this; } ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; - ExternalProject.prototype.getProjectRootPath = function () { - if (this.projectFilePath) { - return ts.getDirectoryPath(this.projectFilePath); - } - return ts.getDirectoryPath(ts.normalizeSlashes(this.getProjectName())); - }; ExternalProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; - ExternalProject.prototype.setProjectErrors = function (projectErrors) { - this.projectErrors = projectErrors; - }; ExternalProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { - if (!newTypeAcquisition) { - newTypeAcquisition = { - enable: allRootFilesAreJsOrDts(this), - include: [], - exclude: [] - }; - } - else { - if (newTypeAcquisition.enable === undefined) { - newTypeAcquisition.enable = allRootFilesAreJsOrDts(this); - } - if (!newTypeAcquisition.include) { - newTypeAcquisition.include = []; - } - if (!newTypeAcquisition.exclude) { - newTypeAcquisition.exclude = []; - } - } + ts.Debug.assert(!!newTypeAcquisition, "newTypeAcquisition may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); + ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); + ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); this.typeAcquisition = newTypeAcquisition; }; return ExternalProject; @@ -82372,12 +104033,20 @@ var ts; server.ExternalProject = ExternalProject; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// var ts; (function (ts) { var server; (function (server) { server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - server.ContextEvent = "context"; + // tslint:disable variable-name + server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; server.ProjectInfoTelemetryEvent = "projectInfo"; @@ -82387,6 +104056,7 @@ var ts; var option = commandLineOptions_1[_i]; if (typeof option.type === "object") { var optionMap = option.type; + // verify that map contains only numbers optionMap.forEach(function (value) { ts.Debug.assert(typeof value === "number"); }); @@ -82397,37 +104067,59 @@ var ts; } var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); var indentStyle = ts.createMapFromTemplate({ - "none": ts.IndentStyle.None, - "block": ts.IndentStyle.Block, - "smart": ts.IndentStyle.Smart + none: ts.IndentStyle.None, + block: ts.IndentStyle.Block, + smart: ts.IndentStyle.Smart }); + /** + * How to understand this block: + * * The 'match' property is a regexp that matches a filename. + * * If 'match' is successful, then: + * * All files from 'exclude' are removed from the project. See below. + * * All 'types' are included in ATA + * * What the heck is 'exclude' ? + * * An array of an array of strings and numbers + * * Each array is: + * * An array of strings and numbers + * * The strings are literals + * * The numbers refer to capture group indices from the 'match' regexp + * * Remember that '1' is the first group + * * These are concatenated together to form a new regexp + * * Filenames matching these regexps are excluded from the project + * This default value is tested in tsserverProjectSystem.ts; add tests there + * if you are changing this so that you can be sure your regexp works! + */ var defaultTypeSafeList = { "jquery": { - "match": /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, - "types": ["jquery"] + // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") + match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + types: ["jquery"] }, "WinJS": { - "match": /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, - "exclude": [["^", 1, "/.*"]], - "types": ["winjs"] + // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js + match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["winjs"] // And fetch the @types package for WinJS }, "Kendo": { - "match": /^(.*\/kendo)\/kendo\.all\.min\.js$/i, - "exclude": [["^", 1, "/.*"]], - "types": ["kendo-ui"] + // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js + match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["kendo-ui"] }, "Office Nuget": { - "match": /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, - "exclude": [["^", 1, "/.*"]], - "types": ["office"] + // e.g. /scripts/Office/1/excel-15.debug.js + match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, + exclude: [["^", 1, "/.*"]], + types: ["office"] // @types package to fetch instead }, - "Minified files": { - "match": /^(.+\.min\.js)$/i, - "exclude": [["^", 1, "$"]] + "References": { + match: /^(.*\/_references\.js)$/i, + exclude: [["^", 1, "$"]] } }; function convertFormatOptions(protocolOptions) { - if (typeof protocolOptions.indentStyle === "string") { + if (ts.isString(protocolOptions.indentStyle)) { protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase()); ts.Debug.assert(protocolOptions.indentStyle !== undefined); } @@ -82437,7 +104129,7 @@ var ts; function convertCompilerOptions(protocolOptions) { compilerOptionConverters.forEach(function (mappedValues, id) { var propertyValue = protocolOptions[id]; - if (typeof propertyValue === "string") { + if (ts.isString(propertyValue)) { protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase()); } }); @@ -82445,42 +104137,58 @@ var ts; } server.convertCompilerOptions = convertCompilerOptions; function tryConvertScriptKindName(scriptKindName) { - return typeof scriptKindName === "string" - ? convertScriptKindName(scriptKindName) - : scriptKindName; + return ts.isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; } server.tryConvertScriptKindName = tryConvertScriptKindName; function convertScriptKindName(scriptKindName) { switch (scriptKindName) { case "JS": - return 1; + return 1 /* JS */; case "JSX": - return 2; + return 2 /* JSX */; case "TS": - return 3; + return 3 /* TS */; case "TSX": - return 4; + return 4 /* TSX */; default: - return 0; + return 0 /* Unknown */; } } server.convertScriptKindName = convertScriptKindName; + /** + * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. + */ function combineProjectOutput(projects, action, comparer, areEqual) { - var result = ts.flatMap(projects, action).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + var outputs = ts.flatMap(projects, action); + return comparer + ? ts.sortAndDeduplicate(outputs, comparer, areEqual) + : ts.deduplicate(outputs, areEqual); } server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, - getScriptKind: function (_) { return undefined; }, + getScriptKind: function (fileName, extraFileExtensions) { + var result; + if (extraFileExtensions) { + var fileExtension_1 = ts.getAnyExtensionFromPath(fileName); + if (fileExtension_1) { + ts.some(extraFileExtensions, function (info) { + if (info.extension === fileExtension_1) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; + }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, - isDynamicFile: function (x) { return x[0] === "^"; }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, hasMixedContent: function (x) { return x.hasMixedContent; }, - isDynamicFile: function (x) { return x.fileName[0] === "^"; }, }; function findProjectByName(projectName, projects) { for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { @@ -82490,60 +104198,75 @@ var ts; } } } - function createFileNotFoundDiagnostic(fileName) { - return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); - } - function isRootFileInInferredProject(info) { - if (info.containingProjects.length === 0) { - return false; - } - return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); - } - var DirectoryWatchers = (function () { - function DirectoryWatchers(projectService) { - this.projectService = projectService; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - } - DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { - var refCount = this.directoryWatchersRefCount.get(directory) - 1; - this.directoryWatchersRefCount.set(directory, refCount); - if (refCount === 0) { - this.projectService.logger.info("Close directory watcher for: " + directory); - this.directoryWatchersForTsconfig.get(directory).close(); - this.directoryWatchersForTsconfig.delete(directory); - } - }; - DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { - var currentPath = ts.getDirectoryPath(fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath !== parentPath) { - if (!this.directoryWatchersForTsconfig.has(currentPath)) { - this.projectService.logger.info("Add watcher for: " + currentPath); - this.directoryWatchersForTsconfig.set(currentPath, this.projectService.host.watchDirectory(currentPath, callback)); - this.directoryWatchersRefCount.set(currentPath, 1); - } - else { - this.directoryWatchersRefCount.set(currentPath, this.directoryWatchersRefCount.get(currentPath) + 1); - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - }; - return DirectoryWatchers; - }()); - var ProjectService = (function () { + /* @internal */ + var WatchType; + (function (WatchType) { + WatchType["ConfigFilePath"] = "Config file for the program"; + WatchType["MissingFilePath"] = "Missing file from program"; + WatchType["WildcardDirectories"] = "Wild card directory"; + WatchType["ClosedScriptInfo"] = "Closed Script info"; + WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; + WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; + WatchType["TypeRoots"] = "Type root directory"; + })(WatchType = server.WatchType || (server.WatchType = {})); + var ConfigFileWatcherStatus; + (function (ConfigFileWatcherStatus) { + ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; + ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files"; + ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file"; + ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file"; + ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; + ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; + })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + var ProjectService = /** @class */ (function () { function ProjectService(opts) { + var _this = this; + /** + * Container of all known scripts + */ this.filenameToScriptInfo = ts.createMap(); + /** + * maps external project file name to list of config files that were the part of this project + */ this.externalProjectToConfiguredProjectMap = ts.createMap(); + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ this.externalProjects = []; + /** + * projects built from openFileRoots + */ this.inferredProjects = []; - this.configuredProjects = []; - this.openFiles = []; + /** + * projects specified by a tsconfig.json file + */ + this.configuredProjects = ts.createMap(); + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + this.openFiles = ts.createMap(); + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + this.openFilesWithNonRootedDiskPath = ts.createMap(); this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); + /** + * Project size for configured or external projects + */ this.projectToSizeMap = ts.createMap(); + /** + * This is a map of config file paths existance that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + */ + this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; + this.legacySafelist = {}; + this.pendingProjectUpdates = ts.createMap(); + /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; @@ -82556,14 +104279,17 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.host.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.directoryWatchers = new DirectoryWatchers(this); - this.throttledOperations = new server.ThrottledOperations(this.host); - if (opts.typesMapLocation) { + this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); + if (this.typesMapLocation) { this.loadTypesMap(); } + else { + this.logger.info("No types map provided; using the default"); + } this.typingsInstaller.attach(this); this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { @@ -82571,17 +104297,52 @@ var ts; hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.host.getCurrentDirectory()); + this.documentRegistry = ts.createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.watchFile = function (host, file, cb, watchType, project) { return ts.addFileWatcherWithLogging(host, file, cb, _this.createWatcherLog(watchType, project)); }; + this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; + this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; + } + else if (this.logger.loggingEnabled()) { + this.watchFile = function (host, file, cb, watchType, project) { return ts.addFileWatcherWithOnlyTriggerLogging(host, file, cb, _this.createWatcherLog(watchType, project)); }; + this.watchFilePath = function (host, file, cb, path, watchType, project) { return ts.addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, _this.createWatcherLog(watchType, project)); }; + this.watchDirectory = function (host, dir, cb, flags, watchType, project) { return ts.addDirectoryWatcherWithOnlyTriggerLogging(host, dir, cb, flags, _this.createWatcherLog(watchType, project)); }; + } + else { + this.watchFile = ts.addFileWatcher; + this.watchFilePath = ts.addFilePathWatcher; + this.watchDirectory = ts.addDirectoryWatcher; + } } + ProjectService.prototype.createWatcherLog = function (watchType, project) { + var _this = this; + var detailedInfo = " Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + return function (s) { return _this.logger.info(s + detailedInfo); }; + }; + ProjectService.prototype.toPath = function (fileName) { + return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); + }; + /*@internal*/ + ProjectService.prototype.getExecutingFilePath = function () { + return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); + }; + /*@internal*/ + ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { + return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); + }; + /* @internal */ ProjectService.prototype.getChangedFiles_TestOnly = function () { return this.changedFiles; }; + /* @internal */ ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { - this.ensureInferredProjectsUpToDate(); + this.ensureProjectStructuresUptoDate(); }; + /* @internal */ ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { return this.compilerOptionsForInferredProjects; }; + /* @internal */ ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) { if (!this.eventHandler) { return; @@ -82600,15 +104361,23 @@ var ts; return; } var raw = JSON.parse(fileContent); + // Parse the regexps for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) { var k = _a[_i]; raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); } + // raw is now fixed and ready this.safelist = raw.typesMap; + for (var key in raw.simpleMap) { + if (raw.simpleMap.hasOwnProperty(key)) { + this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + } + } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; + this.legacySafelist = {}; } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -82624,66 +104393,163 @@ var ts; this.typingsCache.deleteTypingsForProject(response.projectName); break; } - project.updateGraph(); + this.delayUpdateProjectGraphAndInferredProjectsRefresh(project); + }; + ProjectService.prototype.delayInferredProjectsRefresh = function () { + var _this = this; + this.pendingInferredProjectUpdate = true; + this.throttledOperations.schedule("*refreshInferredProjects*", /*delay*/ 250, function () { + if (_this.pendingProjectUpdates.size !== 0) { + _this.delayInferredProjectsRefresh(); + } + else { + if (_this.pendingInferredProjectUpdate) { + _this.pendingInferredProjectUpdate = false; + _this.refreshInferredProjects(); + } + // Send the event to notify that there were background project updates + // send current list of open files + _this.sendProjectsUpdatedInBackgroundEvent(); + } + }); + }; + ProjectService.prototype.delayUpdateProjectGraph = function (project) { + var _this = this; + var projectName = project.getProjectName(); + this.pendingProjectUpdates.set(projectName, project); + this.throttledOperations.schedule(projectName, /*delay*/ 250, function () { + if (_this.pendingProjectUpdates.delete(projectName)) { + project.updateGraph(); + } + }); + }; + /*@internal*/ + ProjectService.prototype.hasPendingProjectUpdate = function (project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + }; + ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { + var _this = this; + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.ProjectsUpdatedInBackgroundEvent, + data: { + openFiles: ts.arrayFrom(this.openFiles.keys(), function (path) { return _this.getScriptInfoForPath(path).fileName; }) + } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.delayUpdateProjectGraphAndInferredProjectsRefresh = function (project) { + project.markAsDirty(); + this.delayUpdateProjectGraph(project); + this.delayInferredProjectsRefresh(); + }; + ProjectService.prototype.delayUpdateProjectGraphs = function (projects) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + this.delayUpdateProjectGraph(project); + } + this.delayInferredProjectsRefresh(); }; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); var compilerOptions = convertCompilerOptions(projectCompilerOptions); + // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside + // previously we did not expose a way for user to change these settings and this option was enabled by default compilerOptions.allowNonTsExtensions = true; - if (projectRootPath) { - this.compilerOptionsForInferredProjectsPerProjectRoot.set(projectRootPath, compilerOptions); + var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); + if (canonicalProjectRootPath) { + this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); } else { this.compilerOptionsForInferredProjects = compilerOptions; } - var updatedProjects = []; + var projectsToUpdate = []; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (projectRootPath ? - project.projectRootPath === projectRootPath : + // Only update compiler options in the following cases: + // - Inferred projects without a projectRootPath, if the new options do not apply to + // a workspace root + // - Inferred projects with a projectRootPath, if the new options do not apply to a + // workspace root and there is no more specific set of options for that project's + // root path + // - Inferred projects with a projectRootPath, if the new options apply to that + // project root path. + if (canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { project.setCompilerOptions(compilerOptions); project.compileOnSaveEnabled = compilerOptions.compileOnSave; - updatedProjects.push(project); + project.markAsDirty(); + projectsToUpdate.push(project); } } - this.updateProjectGraphs(updatedProjects); - }; - ProjectService.prototype.stopWatchingDirectory = function (directory) { - this.directoryWatchers.stopWatchingDirectory(directory); + this.delayUpdateProjectGraphs(projectsToUpdate); }; ProjectService.prototype.findProject = function (projectName) { if (projectName === undefined) { return undefined; } if (server.isInferredProjectName(projectName)) { - this.ensureInferredProjectsUpToDate(); + this.ensureProjectStructuresUptoDate(); return findProjectByName(projectName, this.inferredProjects); } return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); }; - ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { - if (refreshInferredProjects) { - this.ensureInferredProjectsUpToDate(); - } + ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) { var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo && scriptInfo.getDefaultProject(); - }; - ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (ensureProject && !scriptInfo || scriptInfo.isOrphan()) { + this.ensureProjectStructuresUptoDate(); + scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + if (!scriptInfo) { + return server.Errors.ThrowNoProject(); + } + return scriptInfo.getDefaultProject(); + } + return scriptInfo && !scriptInfo.isOrphan() && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { + this.ensureProjectStructuresUptoDate(); + return this.getScriptInfo(uncheckedFileName); + }; + /** + * Ensures the project structures are upto date + * This means, + * - if there are changedFiles (the files were updated but their containing project graph was not upto date), + * their project graph is updated + * - If there are pendingProjectUpdates (scheduled to be updated with delay so they can batch update the graph if there are several changes in short time span) + * their project graph is updated + * - If there were project graph updates and/or there was pending inferred project update and/or called forced the inferred project structure refresh + * Inferred projects are created/updated/deleted based on open files states + * @param forceInferredProjectsRefresh when true updates the inferred projects even if there is no pending work to update the files/project structures + */ + ProjectService.prototype.ensureProjectStructuresUptoDate = function (forceInferredProjectsRefresh) { if (this.changedFiles) { var projectsToUpdate = void 0; if (this.changedFiles.length === 1) { + // simpliest case - no allocations projectsToUpdate = this.changedFiles[0].containingProjects; } else { projectsToUpdate = []; for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { var f = _a[_i]; - projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + ts.addRange(projectsToUpdate, f.containingProjects); } } - this.updateProjectGraphs(projectsToUpdate); this.changedFiles = undefined; + this.updateProjectGraphs(projectsToUpdate); + } + if (this.pendingProjectUpdates.size !== 0) { + var projectsToUpdate = ts.arrayFrom(this.pendingProjectUpdates.values()); + this.pendingProjectUpdates.clear(); + this.updateProjectGraphs(projectsToUpdate); + } + if (this.pendingInferredProjectUpdate || forceInferredProjectsRefresh) { + this.pendingInferredProjectUpdate = false; + this.refreshInferredProjects(); } }; ProjectService.prototype.findContainingExternalProject = function (fileName) { @@ -82706,181 +104572,186 @@ var ts; return formatCodeSettings || this.hostConfiguration.formatCodeOptions; }; ProjectService.prototype.updateProjectGraphs = function (projects) { - var shouldRefreshInferredProjects = false; - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var p = projects_3[_i]; + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var p = projects_4[_i]; if (!p.updateGraph()) { - shouldRefreshInferredProjects = true; + this.pendingInferredProjectUpdate = true; } } - if (shouldRefreshInferredProjects) { - this.refreshInferredProjects(); - } }; - ProjectService.prototype.onSourceFileChanged = function (fileName) { + ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - this.logger.info("Error: got watch notification for unknown file: " + fileName); - return; + this.logger.msg("Error: got watch notification for unknown file: " + fileName); } - if (!this.host.fileExists(fileName)) { + else if (eventKind === ts.FileWatcherEventKind.Deleted) { + // File was deleted this.handleDeletedFile(info); } - else { - if (info && (!info.isScriptOpen())) { - if (info.containingProjects.length === 0) { - info.stopWatcher(); - this.filenameToScriptInfo.delete(info.path); - } - else { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); - } + else if (!info.isScriptOpen()) { + if (info.containingProjects.length === 0) { + // Orphan script info, remove it as we can always reload it on next open file request + this.stopWatchingScriptInfo(info); + this.filenameToScriptInfo.delete(info.path); + } + else { + // file has been changed which might affect the set of referenced files in projects that include + // this file and set of inferred projects + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); } } }; ProjectService.prototype.handleDeletedFile = function (info) { - this.logger.info(info.fileName + " deleted"); - info.stopWatcher(); + this.stopWatchingScriptInfo(info); + // TODO: handle isOpen = true case if (!info.isScriptOpen()) { this.filenameToScriptInfo.delete(info.path); - this.lastDeletedFile = info; + // capture list of projects since detachAllProjects will wipe out original list var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); - this.updateProjectGraphs(containingProjects); - this.lastDeletedFile = undefined; - if (!this.eventHandler) { - return; - } - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var openFile = _a[_i]; - var event_1 = { - eventName: server.ContextEvent, - data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } - }; - this.eventHandler(event_1); - } + // update projects to make sure that set of referenced files is correct + this.delayUpdateProjectGraphs(containingProjects); } - this.printProjects(); }; - ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + /** + * This is to watch whenever files are added or removed to the wildcard directories + */ + /*@internal*/ + ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { var _this = this; - this.logger.info("Type root file " + fileName + " changed"); - this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", 250, function () { - project.updateTypes(); - _this.updateConfiguredProject(project); - _this.refreshInferredProjects(); - }); - }; - ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { - var _this = this; - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { - return; - } - this.logger.info("Detected source file changes: " + fileName); - this.throttledOperations.schedule(project.getConfigFilePath(), 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project, fileName); }); - }; - ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project, triggerFile) { - var _this = this; - var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { - this.logger.info("Updating configured project"); - this.updateConfiguredProject(project); - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { - var configFileName = project.getConfigFilePath(); - this.logger.info("Config file changed: " + configFileName); - var configFileErrors = this.updateConfiguredProject(project); - this.reportConfigFileDiagnostics(configFileName, configFileErrors, configFileName); - this.refreshInferredProjects(); - }; - ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.logger.info(fileName + " is not tsconfig.json"); - return; + return this.watchDirectory(this.host, directory, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + var configFilename = project.getConfigFilePath(); + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) { + _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + _this.delayUpdateProjectGraphAndInferredProjectsRefresh(project); + } + }, flags, "Wild card directory" /* WildcardDirectories */, project); + }; + /** Gets the config file existence info for the configured project */ + /*@internal*/ + ProjectService.prototype.getConfigFileExistenceInfo = function (project) { + return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (eventKind === ts.FileWatcherEventKind.Deleted) { + // Update the cached status + // We arent updating or removing the cached config file presence info as that will be taken care of by + // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files) + configFileExistenceInfo.exists = false; + this.removeProject(project); + // Reload the configured projects for the open files in the map as they are affectected by this config file + // Since the configured project was deleted, we want to reload projects for all the open files including files + // that are not root of the inferred project + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); } - var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; - this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName); - this.logger.info("Detected newly added tsconfig file: " + fileName); - this.reloadProjects(); - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); + else { + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + this.delayUpdateProjectGraph(project); + // As we scheduled the update on configured project graph, + // we would need to schedule the project reload for only the root of inferred projects + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true); + } + }; + /** + * This is the callback function for the config file add/remove/change at any location + * that matters to open script info but doesnt have configured project open + * for the config file + */ + ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { + // This callback is called only if we dont have config file project for this config file + var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); + configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); + // Because there is no configured project open for the config file, the tracking open files map + // will only have open files that need the re-detection of the project and hence + // reload projects for all the tracking open files in the map + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); }; ProjectService.prototype.removeProject = function (project) { this.logger.info("remove project: " + project.getRootFiles().toString()); project.close(); + if (ts.Debug.shouldAssert(1 /* Normal */)) { + this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); + } + // Remove the project from pending project updates + this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { case server.ProjectKind.External: ts.unorderedRemoveItem(this.externalProjects, project); - this.projectToSizeMap.delete(project.externalProjectName); + this.projectToSizeMap.delete(project.getProjectName()); break; case server.ProjectKind.Configured: - ts.unorderedRemoveItem(this.configuredProjects, project); + this.configuredProjects.delete(project.canonicalConfigFilePath); this.projectToSizeMap.delete(project.canonicalConfigFilePath); + this.setConfigFileExistenceInfoByClosedConfiguredProject(project); break; case server.ProjectKind.Inferred: ts.unorderedRemoveItem(this.inferredProjects, project); break; } }; - ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles, projectRootPath) { - var externalProject = this.findContainingExternalProject(info.fileName); - if (externalProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - var foundConfiguredProject = false; - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - foundConfiguredProject = true; - if (addToListOfOpenFiles) { - (p).addOpenRef(); - } - } - } - if (foundConfiguredProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - if (info.containingProjects.length === 0) { - var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info, projectRootPath); - if (!this.useSingleInferredProject && !inferredProject.projectRootPath) { - for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { - var f = _c[_b]; - if (f.containingProjects.length === 0 || !inferredProject.containsScriptInfo(f)) { - continue; - } - for (var _d = 0, _e = f.containingProjects; _d < _e.length; _d++) { - var containingProject = _e[_d]; - if (containingProject.projectKind === server.ProjectKind.Inferred && - containingProject !== inferredProject && - containingProject.isRoot(f)) { - this.removeProject(containingProject); - f.attachToProject(inferredProject); - } - } + /*@internal*/ + ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) { + ts.Debug.assert(info.isOrphan()); + var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || + this.getOrCreateSingleInferredProjectIfEnabled() || + this.createInferredProject(ts.getDirectoryPath(info.path)); + project.addRoot(info); + project.updateGraph(); + if (!this.useSingleInferredProject && !project.projectRootPath) { + // Note that we need to create a copy of the array since the list of project can change + for (var _i = 0, _a = this.inferredProjects.slice(0, this.inferredProjects.length - 1); _i < _a.length; _i++) { + var inferredProject = _a[_i]; + ts.Debug.assert(inferredProject !== project); + // Remove the inferred project if the root of it is now part of newly created inferred project + // e.g through references + // Which means if any root of inferred project is part of more than 1 project can be removed + // This logic is same as iterating over all open files and calling + // this.removeRootOfInferredProjectIfNowPartOfOtherProject(f); + // Since this is also called from refreshInferredProject and closeOpen file + // to update inferred projects of the open file, this iteration might be faster + // instead of scanning all open files + var roots = inferredProject.getRootScriptInfos(); + ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); + if (roots.length === 1 && roots[0].containingProjects.length > 1) { + this.removeProject(inferredProject); } } } - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } + return project; }; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ ProjectService.prototype.closeOpenFile = function (info) { - info.close(); - ts.unorderedRemoveItem(this.openFiles, info); + var _this = this; + // Closing file should trigger re-reading the file content from disk. This is + // because the user may chose to discard the buffer content before saving + // to the disk, and the server's version of the file can be out of sync. + var fileExists = this.host.fileExists(info.fileName); + info.close(fileExists); + this.stopWatchingConfigFilesForClosedScriptInfo(info); + this.openFiles.delete(info.path); + var canonicalFileName = this.toCanonicalFileName(info.fileName); + if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { + this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); + } + // collect all projects that should be removed var projectsToRemove; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; @@ -82888,14 +104759,24 @@ var ts; if (info.hasMixedContent) { info.registerFileUpdate(); } - if (p.deleteOpenRef() === 0) { - (projectsToRemove || (projectsToRemove = [])).push(p); - } + // Do not remove the project so that we can reuse this project + // if it would need to be re-created with next file open } else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { - (projectsToRemove || (projectsToRemove = [])).push(p); + // If this was the open root file of inferred project + if (p.isProjectWithSingleRoot()) { + // - when useSingleInferredProject is not set, we can guarantee that this will be the only root + // - other wise remove the project if it is the only root + (projectsToRemove || (projectsToRemove = [])).push(p); + } + else { + p.removeFile(info, fileExists, /*detachFromProject*/ true); + } } if (!p.languageServiceEnabled) { + // if project language service is disabled then we create a program only for open files. + // this means that project should be marked as dirty to force rebuilding of the program + // on the next request p.markAsDirty(); } } @@ -82904,21 +104785,20 @@ var ts; var project = projectsToRemove_1[_b]; this.removeProject(project); } - var orphanFiles = void 0; - for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { - var f = _d[_c]; - if (f.containingProjects.length === 0) { - (orphanFiles || (orphanFiles = [])).push(f); + // collect orphaned files and assign them to inferred project just like we treat open of a file + this.openFiles.forEach(function (projectRootPath, path) { + var f = _this.getScriptInfoForPath(path); + if (f.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(f, projectRootPath); } - } - if (orphanFiles) { - for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { - var f = orphanFiles_1[_e]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - } + }); + // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project) + // is postponed to next file open so that if file from same project is opened, + // we wont end up creating same script infos } - if (this.host.fileExists(info.fileName)) { + // If the current info is being just closed - add the watcher file to track changes + // But if file was deleted, handle that part + if (fileExists) { this.watchClosedScriptInfo(info); } else { @@ -82928,45 +104808,220 @@ var ts; ProjectService.prototype.deleteOrphanScriptInfoNotInAnyProject = function () { var _this = this; this.filenameToScriptInfo.forEach(function (info) { - if (!info.isScriptOpen() && info.containingProjects.length === 0) { - info.stopWatcher(); + if (!info.isScriptOpen() && info.isOrphan()) { + // if there are not projects that include this script info - delete it + _this.stopWatchingScriptInfo(info); _this.filenameToScriptInfo.delete(info.path); } }); }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName, projectRootPath) { - var searchPath = ts.getDirectoryPath(fileName); - this.logger.info("Search path: " + searchPath); - var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath), projectRootPath); - if (!configFileName) { - this.logger.info("No config files found."); - return {}; - } - this.logger.info("Config file name: " + configFileName); - var project = this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; - if (!success) { - return { configFileName: configFileName, configFileErrors: errors }; + ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + // By default the info would get impacted by presence of config file since its in the detection path + // Only adding the info as a root to inferred project will need the existence to be watched by file watcher + if (!configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); + } + return configFileExistenceInfo.exists; + } + // Theoretically we should be adding watch for the directory here itself. + // In practice there will be very few scenarios where the config file gets added + // somewhere inside the another config file directory. + // And technically we could handle that case in configFile's directory watcher in some cases + // But given that its a rare scenario it seems like too much overhead. (we werent watching those directories earlier either) + // So what we are now watching is: configFile if the configured project corresponding to it is open + // Or the whole chain of config files for the roots of the inferred projects + // Cache the host value of file exists and add the info to map of open files impacted by this config file + var openFilesImpactedByConfigFile = ts.createMap(); + openFilesImpactedByConfigFile.set(info.path, false); + var exists = this.host.fileExists(configFileName); + configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); + return exists; + }; + ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + if (configFileExistenceInfo) { + ts.Debug.assert(configFileExistenceInfo.exists); + // close existing watcher + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + var configFileName = project.getConfigFilePath(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); } - this.logger.info("Opened configuration file " + configFileName); - if (errors && errors.length > 0) { - return { configFileName: configFileName, configFileErrors: errors }; + } + else { + // We could be in this scenario if project is the configured project tracked by external project + // Since that route doesnt check if the config file is present or not + this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { + exists: true, + openFilesImpactedByConfigFile: ts.createMap() + }); + } + }; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); + }; + ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { + var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); + ts.Debug.assert(!!configFileExistenceInfo); + if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { + var configFileName = closedProject.getConfigFilePath(); + // If there are open files that are impacted by this config file existence + // but none of them are root of inferred project, the config file watcher will be + // created when any of the script infos are added as root of inferred project + if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); } } else { - this.updateConfiguredProject(project); + // There is not a single file open thats tracking the status of this config file. Remove from cache + this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); } - return { configFileName: configFileName }; }; - ProjectService.prototype.findConfigFile = function (searchPath, projectRootPath) { - while (!projectRootPath || searchPath.indexOf(projectRootPath) >= 0) { + ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) { + var _this = this; + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + var inferredRoots = []; + var otherFiles = []; + configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) { + var info = _this.getScriptInfoForPath(key); + (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); + }); + var watches = []; + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { + watches.push("Config file for the inferred project root" /* ConfigFileForInferredRoot */); + } + if (this.configuredProjects.has(canonicalConfigFilePath)) { + watches.push("Config file for the program" /* ConfigFilePath */); + } + this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); + }; + /** + * Create the watcher for the configFileExistenceInfo + */ + ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { + var _this = this; + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, "Config file for the inferred project root" /* ConfigFileForInferredRoot */); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); + }; + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project + */ + ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + // Close the config file watcher if there are no more open files that are root of inferred project + if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + } + }; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { + var _this = this; + ts.Debug.assert(!info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo) { + var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + // Delete the info from map, since this file is no more open + configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */); + // If the script info was not root of inferred project, + // there wont be config file watch open because of this script info + if (infoIsRootOfInferredProject) { + // But if it is a root, it could be the last script info that is root of inferred project + // and hence we would need to close the config file watcher + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + // If there are no open files that are impacted by configFileExistenceInfo after closing this script info + // there is no configured project present, remove the cached existence info + if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } + } + }); + }; + /** + * This is called by inferred project whenever script info is added as a root + */ + /* @internal */ + ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info, projectRootPath) { + var _this = this; + ts.Debug.assert(info.isScriptOpen()); + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + // Create the cache + configFileExistenceInfo = { + exists: _this.host.fileExists(configFileName), + openFilesImpactedByConfigFile: ts.createMap() + }; + _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + } + // Set this file as the root of inferred project + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */); + // If there is no configured project for this config file, add the file watcher + if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { + _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + } + }, projectRootPath); + }; + /** + * This is called by inferred project whenever root script info is removed from it + */ + /* @internal */ + ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { + var _this = this; + this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + ts.Debug.assert(info.isScriptOpen()); + // Info is not root of inferred project any more + configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */); + // Close the config file watcher + _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + } + }); + }; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + ProjectService.prototype.forEachConfigFileLocation = function (info, action, projectRootPath) { + var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); + while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) { + var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); - if (this.host.fileExists(tsconfigFileName)) { + var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); + if (result) { return tsconfigFileName; } var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); - if (this.host.fileExists(jsconfigFileName)) { + result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json")); + if (result) { return jsconfigFileName; } var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); @@ -82977,75 +105032,94 @@ var ts; } return undefined; }; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + ProjectService.prototype.getConfigFileNameForFile = function (info, projectRootPath) { + var _this = this; + ts.Debug.assert(info.isScriptOpen()); + this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); + var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + return _this.configFileExists(configFileName, canonicalConfigFilePath, info); + }, projectRootPath); + if (configFileName) { + this.logger.info("For info: " + info.fileName + " :: Config file name: " + configFileName); + } + else { + this.logger.info("For info: " + info.fileName + " :: No config files found."); + } + return configFileName; + }; ProjectService.prototype.printProjects = function () { var _this = this; - if (!this.logger.hasLevel(server.LogLevel.verbose)) { + if (!this.logger.hasLevel(server.LogLevel.normal)) { return; } + var writeProjectFileNames = this.logger.hasLevel(server.LogLevel.verbose); this.logger.startGroup(); var counter = 0; var printProjects = function (projects, counter) { - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var project = projects_4[_i]; - project.updateGraph(); + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var project = projects_5[_i]; _this.logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - _this.logger.info(project.filesToString()); + _this.logger.info(project.filesToString(writeProjectFileNames)); _this.logger.info("-----------------------------------------------"); counter++; } return counter; }; counter = printProjects(this.externalProjects, counter); - counter = printProjects(this.configuredProjects, counter); + counter = printProjects(ts.arrayFrom(this.configuredProjects.values()), counter); printProjects(this.inferredProjects, counter); this.logger.info("Open files: "); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var rootFile = _a[_i]; - this.logger.info("\t" + rootFile.fileName); - } + this.openFiles.forEach(function (projectRootPath, path) { + _this.logger.info("\tFileName: " + _this.getScriptInfoForPath(path).fileName + " ProjectRootPath: " + projectRootPath); + }); this.logger.endGroup(); }; ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { - configFileName = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); - for (var _i = 0, _a = this.configuredProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.canonicalConfigFilePath === configFileName) { - return proj; - } - } + // make sure that casing of config file name is consistent + var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); + }; + ProjectService.prototype.getConfiguredProjectByCanonicalConfigFilePath = function (canonicalConfigFilePath) { + return this.configuredProjects.get(canonicalConfigFilePath); }; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { configFilename = ts.normalizePath(configFilename); var configFileContent = this.host.readFile(configFilename); var result = ts.parseJsonText(configFilename, configFileContent); if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 }; + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; } var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { errors.push.apply(errors, parsedCommandLine.errors); } ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { success: false, configFileErrors: errors }; - } var projectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw["extends"] !== undefined, - configHasFilesProperty: parsedCommandLine.raw["files"] !== undefined, - configHasIncludeProperty: parsedCommandLine.raw["include"] !== undefined, - configHasExcludeProperty: parsedCommandLine.raw["exclude"] !== undefined, + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave }; - return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; }; ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { @@ -83055,29 +105129,46 @@ var ts; this.projectToSizeMap.set(name, 0); this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); }); var totalNonTsFileSize = 0; - for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { - var f = fileNames_3[_i]; + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); if (ts.hasTypeScriptFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + // Keep the size as zero since it's disabled return true; } } if (totalNonTsFileSize > availableSpace) { + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); return true; } this.projectToSizeMap.set(name, totalNonTsFileSize); return false; + function getExceedLimitMessage(context, totalNonTsFileSize) { + var files = getTop5LargestFiles(context); + return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); + } + function getTop5LargestFiles(_a) { + var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + return fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + } }; - ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typeAcquisition) { + ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); - var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typeAcquisition, undefined); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, + /*languageServiceEnabled*/ !this.exceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + project.excludedFiles = excludedFiles; + this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(project.externalProjectName, project); + this.sendProjectTelemetry(projectFileName, project); return project; }; ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { @@ -83085,12 +105176,13 @@ var ts; return; } this.seenProjects.set(projectKey, true); - if (!this.eventHandler) + if (!this.eventHandler) { return; + } var data = { projectId: this.host.createHash(projectKey), fileStats: server.countEachFileTypes(project.getScriptInfos()), - compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilerOptions()), + compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), extends: projectOptions && projectOptions.configHasExtendsProperty, files: projectOptions && projectOptions.configHasFilesProperty, @@ -83108,8 +105200,7 @@ var ts; return "other"; } var configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); - var base = ts.getBaseFileName(configFilePath); - return base === "tsconfig.json" || base === "jsconfig.json" ? base : "other"; + return server.getBaseConfigFileName(configFilePath) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -83120,186 +105211,173 @@ var ts; }; } }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (!this.eventHandler) { - return; - } - var event = { - eventName: server.ConfigFileDiagEvent, - data: { configFileName: configFileName, diagnostics: diagnostics || server.emptyArray, triggerFile: triggerFile } - }; - this.eventHandler(event); + ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + this.updateNonInferredProjectFiles(project, files, propertyReader); + project.setTypeAcquisition(typeAcquisition); + // This doesnt need scheduling since its either creation or reload of the project + project.updateGraph(); }; - ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host); + var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; + this.logger.info("Opened configuration file " + configFileName); + var languageServiceEnabled = !this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, languageServiceEnabled, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost); + project.configFileSpecs = configFileSpecs; + // TODO: We probably should also watch the configFiles that are extended + project.configFileWatcher = this.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, "Config file for the program" /* ConfigFilePath */, project); + if (languageServiceEnabled) { + project.watchWildcards(projectOptions.wildcardDirectories); + } + project.setProjectErrors(configFileErrors); var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); - project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); - if (!sizeLimitExceeded) { - this.watchConfigDirectoryForProject(project, projectOptions); - } - project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); - this.configuredProjects.push(project); - this.sendProjectTelemetry(project.getConfigFilePath(), project, projectOptions); + this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); + this.configuredProjects.set(project.canonicalConfigFilePath, project); + this.setConfigFileExistenceByNewConfiguredProject(project); + this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; - ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { - var _this = this; - if (!options.configHasFilesProperty) { - project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - } - }; - ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typeAcquisition, configFileErrors) { - var errors; - for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { - var f = files_4[_i]; - var rootFileName = propertyReader.getFileName(f); - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - var isDynamicFile = propertyReader.isDynamicFile(f); - if (isDynamicFile || this.host.fileExists(rootFileName)) { - var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFileName), clientFileName === rootFileName, undefined, scriptKind, hasMixedContent, isDynamicFile); - project.addRoot(info); + ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { + var projectRootFilesMap = project.getRootFilesMap(); + var newRootScriptInfoMap = ts.createMap(); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var f = files_3[_i]; + var newRootFile = propertyReader.getFileName(f); + var normalizedPath = server.toNormalizedPath(newRootFile); + var isDynamic = server.isDynamicFileName(normalizedPath); + var scriptInfo = void 0; + var path = void 0; + // Use the project's fileExists so that it can use caching instead of reaching to disk for the query + if (!isDynamic && !project.fileExists(newRootFile)) { + path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName); + var existingValue = projectRootFilesMap.get(path); + if (server.isScriptInfo(existingValue)) { + project.removeFile(existingValue, /*fileExists*/ false, /*detachFromProject*/ true); + } + projectRootFilesMap.set(path, normalizedPath); + scriptInfo = normalizedPath; } else { - (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFileName)); + var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); + scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); + path = scriptInfo.path; + // If this script info is not already a root add it + if (!project.isRoot(scriptInfo)) { + project.addRoot(scriptInfo); + if (scriptInfo.isScriptOpen()) { + // if file is already root in some inferred project + // - remove the file from that project and delete the project if necessary + this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); + } + } } + newRootScriptInfoMap.set(path, scriptInfo); } - project.setProjectErrors(ts.concatenate(configFileErrors, errors)); - project.setTypeAcquisition(typeAcquisition); - project.updateGraph(); - }; - ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { - var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); - var projectOptions = conversionResult.success - ? conversionResult.projectOptions - : { files: [], compilerOptions: {}, configHasExtendsProperty: false, configHasFilesProperty: false, configHasIncludeProperty: false, configHasExcludeProperty: false, typeAcquisition: { enable: false } }; - var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); - return { - success: conversionResult.success, - project: project, - errors: project.getGlobalProjectErrors() - }; - }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors) { - var oldRootScriptInfos = project.getRootScriptInfos(); - var newRootScriptInfos = []; - var newRootScriptInfoMap = server.createNormalizedPathMap(); - var projectErrors; - var rootFilesChanged = false; - for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { - var f = newUncheckedFiles_1[_i]; - var newRootFile = propertyReader.getFileName(f); - var isDynamic = propertyReader.isDynamicFile(f); - if (!isDynamic && !this.host.fileExists(newRootFile)) { - (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); - continue; - } - var normalizedPath = server.toNormalizedPath(newRootFile); - var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); - if (!scriptInfo || !project.isRoot(scriptInfo)) { - rootFilesChanged = true; - if (!scriptInfo) { - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent, isDynamic); - } - } - newRootScriptInfos.push(scriptInfo); - newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); - } - if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { - var toAdd = void 0; - var toRemove = void 0; - for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { - var oldFile = oldRootScriptInfos_1[_a]; - if (!newRootScriptInfoMap.contains(oldFile.fileName)) { - (toRemove || (toRemove = [])).push(oldFile); - } - } - for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { - var newFile = newRootScriptInfos_1[_b]; - if (!project.isRoot(newFile)) { - (toAdd || (toAdd = [])).push(newFile); - } - } - if (toRemove) { - for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { - var f = toRemove_1[_c]; - project.removeFile(f); - } - } - if (toAdd) { - for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { - var f = toAdd_1[_d]; - if (f.isScriptOpen() && isRootFileInInferredProject(f)) { - var inferredProject = f.containingProjects[0]; - inferredProject.removeFile(f); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); - } + // project's root file map size is always going to be same or larger than new roots map + // as we have already all the new files to the project + if (projectRootFilesMap.size > newRootScriptInfoMap.size) { + projectRootFilesMap.forEach(function (value, path) { + if (!newRootScriptInfoMap.has(path)) { + if (server.isScriptInfo(value)) { + project.removeFile(value, project.fileExists(path), /*detachFromProject*/ true); + } + else { + projectRootFilesMap.delete(path); } - project.addRoot(f); } - } + }); } + // Just to ensure that even if root files dont change, the changes to the non root file are picked up, + // mark the project as dirty unconditionally + project.markAsDirty(); + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); - project.setTypeAcquisition(newTypeAcquisition); + // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently + // therefore if it is undefined, it should not be updated. if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); - project.updateGraph(); + this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; - ProjectService.prototype.updateConfiguredProject = function (project) { - if (!this.host.fileExists(project.getConfigFilePath())) { - this.logger.info("Config file deleted"); - this.removeProject(project); - return; - } - var _a = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath()), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - if (!success) { - this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); - return configFileErrors; - } + /** + * Reload the file names from config file specs and update the project graph + */ + /*@internal*/ + ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { + var configFileSpecs = project.configFileSpecs; + var configFileName = project.getConfigFilePath(); + var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + return project.updateGraph(); + }; + /** + * Read the config file of the project again and update the project + */ + /* @internal */ + ProjectService.prototype.reloadConfiguredProject = function (project) { + // At this point, there is no reason to not have configFile in the host + var host = project.getCachedDirectoryStructureHost(); + // Clear the cache since we are reloading the project from disk + host.clearCache(); + var configFileName = project.getConfigFilePath(); + this.logger.info("Reloading configured project " + configFileName); + // Read updated contents from disk + var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; + // Update the project + project.configFileSpecs = configFileSpecs; + project.setProjectErrors(configFileErrors); if (this.exceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { - project.setCompilerOptions(projectOptions.compilerOptions); - if (!project.languageServiceEnabled) { - return configFileErrors; - } project.disableLanguageService(); - project.stopWatchingDirectory(); + project.stopWatchingWildCards(); } else { project.enableLanguageService(); - this.watchConfigDirectoryForProject(project, projectOptions); - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); + project.watchWildcards(projectOptions.wildcardDirectories); } - return configFileErrors; + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.sendConfigFileDiagEvent(project, configFileName); }; - ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (root, projectRootPath) { + ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: server.ConfigFileDiagEvent, + data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile: triggerFile } + }); + }; + ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { if (!this.useInferredProjectPerProjectRoot) { return undefined; } if (projectRootPath) { + var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); + // if we have an explicit project root path, find (or create) the matching inferred project. for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; - if (project.projectRootPath === projectRootPath) { + if (project.projectRootPath === canonicalProjectRootPath) { return project; } } - return this.createInferredProject(false, projectRootPath); + return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ false, projectRootPath); } + // we don't have an explicit root path, so we should try to find an inferred project + // that more closely contains the file. var bestMatch; for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { var project = _c[_b]; + // ignore single inferred projects (handled elsewhere) if (!project.projectRootPath) continue; - if (!ts.containsPath(project.projectRootPath, root.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) + // ignore inferred projects that don't contain the root's path + if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) continue; + // ignore inferred projects that are higher up in the project root. + // TODO(rbuckton): Should we add the file as a root to these as well? if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) continue; bestMatch = project; @@ -83310,14 +105388,23 @@ var ts; if (!this.useSingleInferredProject) { return undefined; } + // If `useInferredProjectPerProjectRoot` is not enabled, then there will only be one + // inferred project for all files. If `useInferredProjectPerProjectRoot` is enabled + // then we want to put all files that are not opened with a `projectRootPath` into + // the same inferred project. + // + // To avoid the cost of searching through the array and to optimize for the case where + // `useInferredProjectPerProjectRoot` is not enabled, we will always put the inferred + // project for non-rooted files at the front of the array. if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { return this.inferredProjects[0]; } - return this.createInferredProject(true); + // Single inferred project does not have a project root and hence no current directory + return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true); }; - ProjectService.prototype.createInferredProject = function (isSingleInferredProject, projectRootPath) { + ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) { var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath); + var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -83326,61 +105413,82 @@ var ts; } return project; }; - ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root, projectRootPath) { - var _this = this; - var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(root, projectRootPath) || - this.getOrCreateSingleInferredProjectIfEnabled() || - this.createInferredProject(); - project.addRoot(root); - this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); - project.updateGraph(); - return project; - }; - ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { - return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + /*@internal*/ + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined, + /*hasMixedContent*/ undefined, hostToQueryFileExistsOn); }; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; - if (!info.hasMixedContent && !info.isDynamic) { - var fileName_3 = info.fileName; - info.setWatcher(this.host.watchFile(fileName_3, function (_) { return _this.onSourceFileChanged(fileName_3); })); + ts.Debug.assert(!info.fileWatcher); + // do not watch files with mixed content - server doesn't know how to interpret it + if (!info.isDynamicOrHasMixedContent()) { + var fileName_2 = info.fileName; + info.fileWatcher = this.watchFile(this.host, fileName_2, function (_fileName, eventKind) { return _this.onSourceFileChanged(fileName_2, eventKind); }, "Closed Script info" /* ClosedScriptInfo */); } }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, isDynamic) { - var info = this.getScriptInfoForNormalizedPath(fileName); + ProjectService.prototype.stopWatchingScriptInfo = function (info) { + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = undefined; + } + }; + /*@internal*/ + ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + }; + /*@internal*/ + ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + }; + ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); + var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); + var info = this.getScriptInfoForPath(path); if (!info) { - if (openedByClient || isDynamic || this.host.fileExists(fileName)) { - info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, isDynamic); - this.filenameToScriptInfo.set(info.path, info); - if (openedByClient) { - if (fileContent === undefined) { - fileContent = this.host.readFile(fileName) || ""; - } - } - else { - this.watchClosedScriptInfo(info); - } + ts.Debug.assert(ts.isRootedDiskPath(fileName) || openedByClient, "Script info with relative file name can only be open script info"); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); + var isDynamic = server.isDynamicFileName(fileName); + // If the file is not opened by client and the file doesnot exist on the disk, return + if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { + return; } - } - if (info) { - if (openedByClient && !info.isScriptOpen()) { - info.stopWatcher(); - info.open(fileContent); - if (hasMixedContent) { - info.registerFileUpdate(); - } + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, path); + this.filenameToScriptInfo.set(info.path, info); + if (!openedByClient) { + this.watchClosedScriptInfo(info); + } + else if (!ts.isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + // File that is opened by user but isn't rooted disk path + this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } - else if (fileContent !== undefined) { - info.reload(fileContent); + } + if (openedByClient && !info.isScriptOpen()) { + // Opening closed script info + // either it was created just now, or was part of projects but was closed + this.stopWatchingScriptInfo(info); + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); } } + else { + ts.Debug.assert(fileContent === undefined); + } return info; }; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { - return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || + this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); }; ProjectService.prototype.getScriptInfoForPath = function (fileName) { return this.filenameToScriptInfo.get(fileName); @@ -83404,6 +105512,9 @@ var ts; } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + // We need to update the project structures again as it is possible that existing + // project structure could have more or less files depending on extensions permitted + this.reloadProjects(); this.logger.info("Host file extension mappings updated"); } } @@ -83411,67 +105522,195 @@ var ts; ProjectService.prototype.closeLog = function () { this.logger.close(); }; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ ProjectService.prototype.reloadProjects = function () { this.logger.info("reload projects."); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } + // If we want this to also reload open files from disk, we could do that, + // but then we need to make sure we arent calling this function + // (and would separate out below reloading of projects to be called when immediate reload is needed) + // as there is no need to load contents of the files from the disk + // Reload Projects + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue); this.refreshInferredProjects(); }; - ProjectService.prototype.refreshInferredProjects = function () { - this.logger.info("updating project structure from ..."); - this.printProjects(); - var orphantedFiles = []; - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - if (info.containingProjects.length === 0) { - orphantedFiles.push(info); + ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { + // Get open files to reload projects for + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, + /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? + function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project + ts.returnTrue // Reload all the open files impacted by config file + ); + this.delayInferredProjectsRefresh(); + }; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If the there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + var _this = this; + var updatedProjects = ts.createMap(); + // try to reload config file for all open files + openFiles.forEach(function (openFileValue, path) { + // Filter out the files that need to be ignored + if (!shouldReloadProjectFor(openFileValue)) { + return; } - else { - if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { - var inferredProject = info.containingProjects[0]; - ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); - inferredProject.removeFile(info); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); + var info = _this.getScriptInfoForPath(path); + ts.Debug.assert(info.isScriptOpen()); + // This tries to search for a tsconfig.json for the given file. If we found it, + // we first detect if there is already a configured project created for it: if so, + // we re- read the tsconfig file content and update the project only if we havent already done so + // otherwise we create a new one. + var configFileName = _this.getConfigFileNameForFile(info, _this.openFiles.get(path)); + if (configFileName) { + var project = _this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + _this.createConfiguredProject(configFileName); + updatedProjects.set(configFileName, true); + } + else if (!updatedProjects.has(configFileName)) { + if (delayReload) { + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + _this.delayUpdateProjectGraph(project); } + else { + _this.reloadConfiguredProject(project); + } + updatedProjects.set(configFileName, true); } } + }); + }; + /** + * Remove the root of inferred project if script info is part of another project + */ + ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) { + // If the script info is root of inferred project, it could only be first containing project + // since info is added as root to the inferred project only when there are no other projects containing it + // So when it is root of the inferred project and after project structure updates its now part + // of multiple project it needs to be removed from that inferred project because: + // - references in inferred project supercede the root part + // - root / reference in non - inferred project beats root in inferred project + // eg. say this is structure /a/b/a.ts /a/b/c.ts where c.ts references a.ts + // When a.ts is opened, since there is no configured project/external project a.ts can be part of + // a.ts is added as root to inferred project. + // Now at time of opening c.ts, c.ts is also not aprt of any existing project, + // so it will be added to inferred project as a root. (for sake of this example assume single inferred project is false) + // So at this poing a.ts is part of first inferred project and second inferred project (of which c.ts is root) + // And hence it needs to be removed from the first inferred project. + if (info.containingProjects.length > 1 && + info.containingProjects[0].projectKind === server.ProjectKind.Inferred && + info.containingProjects[0].isRoot(info)) { + var inferredProject = info.containingProjects[0]; + if (inferredProject.isProjectWithSingleRoot()) { + this.removeProject(inferredProject); + } + else { + inferredProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true); + } } - for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { - var f = orphantedFiles_1[_b]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { - var p = _d[_c]; + }; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + ProjectService.prototype.refreshInferredProjects = function () { + var _this = this; + this.logger.info("refreshInferredProjects: updating project structure from ..."); + this.printProjects(); + this.openFiles.forEach(function (projectRootPath, path) { + var info = _this.getScriptInfoForPath(path); + // collect all orphaned script infos from open files + if (info.isOrphan()) { + _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + else { + // Or remove the root of inferred project if is referenced in more than one projects + _this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); + } + }); + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var p = _a[_i]; p.updateGraph(); } + this.logger.info("refreshInferredProjects: updated project structure ..."); this.printProjects(); }; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + var _this = this; var configFileName; + var sendConfigFileDiagEvent = false; var configFileErrors; + var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); var project = this.findContainingExternalProject(fileName); if (!project) { - (_a = this.openOrUpdateConfiguredProjectForFile(fileName, projectRootPath), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors); + configFileName = this.getConfigFileNameForFile(info, projectRootPath); if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + project = this.createConfiguredProject(configFileName); + // Send the event only if the project got created as part of this open request + sendConfigFileDiagEvent = true; + } } } if (project && !project.languageServiceEnabled) { + // if project language service is disabled then we create a program only for open files. + // this means that project should be marked as dirty to force rebuilding of the program + // on the next request project.markAsDirty(); } - var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); - this.assignScriptInfoToInferredProjectIfNecessary(info, true, projectRootPath); + // At this point if file is part of any any configured or external project, then it would be present in the containing projects + // So if it still doesnt have any containing projects, it needs to be part of inferred project + if (info.isOrphan()) { + // Since the file isnt part of configured project, do not send config file event + configFileName = undefined; + sendConfigFileDiagEvent = false; + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + ts.Debug.assert(!info.isOrphan()); + this.openFiles.set(info.path, projectRootPath); + if (sendConfigFileDiagEvent) { + configFileErrors = project.getAllProjectErrors(); + this.sendConfigFileDiagEvent(project, fileName); + } + // Remove the configured projects that have zero references from open files. + // This was postponed from closeOpenFile to after opening next file, + // so that we can reuse the project if we need to right away + this.configuredProjects.forEach(function (project) { + if (!project.hasOpenRef()) { + _this.removeProject(project); + } + }); + // Delete the orphan files here because there might be orphan script infos (which are not part of project) + // when some file/s were closed which resulted in project removal. + // It was then postponed to cleanup these script infos so that they can be reused if + // the file from that old project is reopened because of opening file from here. this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; - var _a; }; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ ProjectService.prototype.closeClientFile = function (uncheckedFileName) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); if (info) { @@ -83480,24 +105719,25 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_11 = function (proj) { + var _loop_13 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_11(proj); + _loop_13(proj); } }; + /* @internal */ ProjectService.prototype.synchronizeProjectList = function (knownProjects) { var files = []; this.collectChanges(knownProjects, this.externalProjects, files); - this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, ts.arrayFrom(this.configuredProjects.values()), files); this.collectChanges(knownProjects, this.inferredProjects, files); return files; }; + /* @internal */ ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { - var recordChangedFiles = changedFiles && !openFiles && !closedFiles; if (openFiles) { for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { var file = openFiles_1[_i]; @@ -83512,18 +105752,7 @@ var ts; var file = changedFiles_2[_a]; var scriptInfo = this.getScriptInfo(file.fileName); ts.Debug.assert(!!scriptInfo); - for (var i = file.changes.length - 1; i >= 0; i--) { - var change = file.changes[i]; - scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); - } - if (recordChangedFiles) { - if (!this.changedFiles) { - this.changedFiles = [scriptInfo]; - } - else if (this.changedFiles.indexOf(scriptInfo) < 0) { - this.changedFiles.push(scriptInfo); - } - } + this.applyChangesToFile(scriptInfo, file.changes); } } if (closedFiles) { @@ -83532,15 +105761,34 @@ var ts; this.closeClientFile(file); } } + // if files were open or closed then explicitly refresh list of inferred projects + // otherwise if there were only changes in files - record changed files in `changedFiles` and defer the update if (openFiles || closedFiles) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(/*refreshInferredProjects*/ true); } }; - ProjectService.prototype.closeConfiguredProject = function (configFile) { + /* @internal */ + ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) { + // apply changes in reverse order + for (var i = changes.length - 1; i >= 0; i--) { + var change = changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (!ts.contains(this.changedFiles, scriptInfo)) { + this.changedFiles.push(scriptInfo); + } + }; + ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) { var configuredProject = this.findConfiguredProjectByProjectName(configFile); - if (configuredProject && configuredProject.deleteOpenRef() === 0) { - this.removeProject(configuredProject); - return true; + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return true; + } } return false; }; @@ -83552,40 +105800,44 @@ var ts; var shouldRefreshInferredProjects = false; for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { var configFile = configFiles_1[_i]; - if (this.closeConfiguredProject(configFile)) { + if (this.closeConfiguredProjectReferencedFromExternalProject(configFile)) { shouldRefreshInferredProjects = true; } } this.externalProjectToConfiguredProjectMap.delete(fileName); if (shouldRefreshInferredProjects && !suppressRefresh) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(/*refreshInferredProjects*/ true); } } else { + // close external project var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); if (externalProject) { this.removeProject(externalProject); if (!suppressRefresh) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(/*refreshInferredProjects*/ true); } } } }; ProjectService.prototype.openExternalProjects = function (projects) { var _this = this; + // record project list before the update var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { projectsToClose.set(externalProjectName, true); }); - for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { - var externalProject = projects_5[_i]; - this.openExternalProject(externalProject, true); + for (var _i = 0, projects_6 = projects; _i < projects_6.length; _i++) { + var externalProject = projects_6[_i]; + this.openExternalProject(externalProject, /*suppressRefreshOfInferredProjects*/ true); + // delete project that is present in input list projectsToClose.delete(externalProject.projectFileName); } + // close projects that were missing in the input list ts.forEachKey(projectsToClose, function (externalProjectName) { - _this.closeExternalProject(externalProjectName, true); + _this.closeExternalProject(externalProjectName, /*suppressRefresh*/ true); }); - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(/*refreshInferredProjects*/ true); }; ProjectService.escapeFilenameForRegex = function (filename) { return filename.replace(this.filenameEscapeRegexp, "\\$&"); @@ -83596,35 +105848,47 @@ var ts; ProjectService.prototype.applySafeList = function (proj) { var _this = this; var rootFiles = proj.rootFiles, typeAcquisition = proj.typeAcquisition; - var types = (typeAcquisition && typeAcquisition.include) || []; + ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); + // If type acquisition has been explicitly disabled, do not exclude anything from the project + if (typeAcquisition.enable === false) { + return []; + } + var typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_12 = function (name_70) { - var rule = this_3.safelist[name_70]; + var _loop_14 = function (name) { + var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_3.logger.info("Excluding files based on rule " + name_70); + this_3.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); + // If the file matches, collect its types packages and exclude rules if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { var type = _b[_a]; - if (types.indexOf(type) < 0) { - types.push(type); + // Best-effort de-duping here - doesn't need to be unduplicated but + // we don't want the list to become a 400-element array of just 'kendo' + if (typeAcqInclude.indexOf(type) < 0) { + typeAcqInclude.push(type); } } } if (rule.exclude) { - var _loop_13 = function (exclude) { + var _loop_15 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { groups[_i] = arguments[_i]; } return exclude.map(function (groupNumberOrString) { + // RegExp group numbers are 1-based, but the first element in groups + // is actually the original string, so it all works out in the end. if (typeof groupNumberOrString === "number") { - if (typeof groups[groupNumberOrString] !== "string") { - _this.logger.info("Incorrect RegExp specification in safelist rule " + name_70 + " - not enough groups"); + if (!ts.isString(groups[groupNumberOrString])) { + // Specification was wrong - exclude nothing! + _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); + // * can't appear in a filename; escape it because it's feeding into a RegExp return "\\*"; } return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); @@ -83638,10 +105902,11 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_13(exclude); + _loop_15(exclude); } } else { + // If not rules listed, add the default rule to exclude the matched file var escaped = ProjectService.escapeFilenameForRegex(root); if (excludeRules.indexOf(escaped) < 0) { excludeRules.push(escaped); @@ -83649,45 +105914,78 @@ var ts; } } } - if (types.length > 0) { - proj.typeAcquisition = proj.typeAcquisition || {}; - proj.typeAcquisition.include = types; - } }; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { - var name_70 = _a[_i]; - _loop_12(name_70); + var name = _a[_i]; + _loop_14(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_14 = function (i) { + var _loop_16 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } else { - filesToKeep.push(proj.rootFiles[i]); + var exclude = false; + if (typeAcquisition.enable || typeAcquisition.enableAutoDiscovery) { + var baseName = ts.getBaseFileName(normalizedNames[i].toLowerCase()); + if (ts.fileExtensionIs(baseName, "js")) { + var inferredTypingName = ts.removeFileExtension(baseName); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + if (this_4.legacySafelist[cleanedTypingName]) { + this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); + excludedFiles.push(normalizedNames[i]); + // *exclude* it from the project... + exclude = true; + // ... but *include* it in the list of types to acquire + var typeName = this_4.legacySafelist[cleanedTypingName]; + // Same best-effort dedupe as above + if (typeAcqInclude.indexOf(typeName) < 0) { + typeAcqInclude.push(typeName); + } + } + } + } + if (!exclude) { + // Exclude any minified files that get this far + if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { + excludedFiles.push(normalizedNames[i]); + } + else { + filesToKeep.push(proj.rootFiles[i]); + } + } } }; + var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_14(i); + _loop_16(i); } proj.rootFiles = filesToKeep; return excludedFiles; }; ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } + // typingOptions has been deprecated and is only supported for backward compatibility + // purposes. It should be removed in future releases - use typeAcquisition instead. if (proj.typingOptions && !proj.typeAcquisition) { var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; } + proj.typeAcquisition = proj.typeAcquisition || {}; + proj.typeAcquisition.include = proj.typeAcquisition.include || []; + proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || []; + if (proj.typeAcquisition.enable === undefined) { + proj.typeAcquisition.enable = server.hasNoTypeScriptSource(proj.rootFiles.map(function (f) { return f.fileName; })); + } var excludedFiles = this.applySafeList(proj); var tsConfigFiles; var rootFiles = []; for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { var file = _a[_i]; var normalized = server.toNormalizedPath(file.fileName); - if (ts.getBaseFileName(normalized) === "tsconfig.json") { + if (server.getBaseConfigFileName(normalized)) { if (this.host.fileExists(normalized)) { (tsConfigFiles || (tsConfigFiles = [])).push(normalized); } @@ -83696,6 +105994,7 @@ var ts; rootFiles.push(file); } } + // sort config files to simplify comparison later if (tsConfigFiles) { tsConfigFiles.sort(); } @@ -83711,16 +106010,22 @@ var ts; else { externalProject.enableLanguageService(); } - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, undefined); + // external project already exists and not config files were added - update the project and return; + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); return; } - this.closeExternalProject(proj.projectFileName, true); + // some config files were added to external project (that previously were not there) + // close existing project and later we'll open a set of configured projects for these files + this.closeExternalProject(proj.projectFileName, /*suppressRefresh*/ true); } else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) { + // this project used to include config files if (!tsConfigFiles) { - this.closeExternalProject(proj.projectFileName, true); + // config files were removed from the project - close existing external project which in turn will close configured projects + this.closeExternalProject(proj.projectFileName, /*suppressRefresh*/ true); } else { + // project previously had some config files - compare them with new set of files and close all configured projects that correspond to unused files var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName); var iNew = 0; var iOld = 0; @@ -83728,53 +106033,78 @@ var ts; var newConfig = tsConfigFiles[iNew]; var oldConfig = oldConfigFiles[iOld]; if (oldConfig < newConfig) { - this.closeConfiguredProject(oldConfig); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); iOld++; } else if (oldConfig > newConfig) { iNew++; } else { + // record existing config files so avoid extra add-refs (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); iOld++; iNew++; } } for (var i = iOld; i < oldConfigFiles.length; i++) { - this.closeConfiguredProject(oldConfigFiles[i]); + // projects for all remaining old config files should be closed + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); } } } if (tsConfigFiles) { + // store the list of tsconfig files that belong to the external project this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles); for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - var result = this.openConfigFile(tsconfigFile); - project = result.success && result.project; + // errors are stored in the project + project = this.createConfiguredProject(tsconfigFile); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { - project.addOpenRef(); + // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project + project.addExternalProjectReference(); } } } else { + // no config files - remove the item from the collection this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - var newProj = this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); - newProj.excludedFiles = excludedFiles; + this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); } if (!suppressRefreshOfInferredProjects) { - this.refreshInferredProjects(); + this.ensureProjectStructuresUptoDate(/*refreshInferredProjects*/ true); } }; + /** Makes a filename safe to insert in a RegExp */ ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; }()); server.ProjectService = ProjectService; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/// +/* @internal */ var debugObjectHost = (function () { return this; })(); +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null-keyword */ +/* tslint:disable:no-in-operator */ +/* @internal */ var ts; (function (ts) { function logInternalError(logger, err) { @@ -83782,7 +106112,7 @@ var ts; logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); } } - var ScriptSnapshotShimAdapter = (function () { + var ScriptSnapshotShimAdapter = /** @class */ (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; } @@ -83802,18 +106132,22 @@ var ts; return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { this.scriptSnapshotShim.dispose(); } }; return ScriptSnapshotShimAdapter; }()); - var LanguageServiceShimHostAdapter = (function () { + var LanguageServiceShimHostAdapter = /** @class */ (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; this.loggingEnabled = false; this.tracingEnabled = false; + // if shimHost is a COM object then property check will become method call with no arguments. + // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); @@ -83848,6 +106182,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { if (!this.shimHost.getProjectVersion) { + // shimmed host does not support getProjectVersion return undefined; } return this.shimHost.getProjectVersion(); @@ -83867,6 +106202,7 @@ var ts; throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); } var compilerOptions = JSON.parse(settingsJson); + // permit language service to handle all files (filtering should be performed on the host side) compilerOptions.allowNonTsExtensions = true; return compilerOptions; }; @@ -83883,7 +106219,7 @@ var ts; return this.shimHost.getScriptKind(fileName); } else { - return 0; + return 0 /* Unknown */; } }; LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { @@ -83928,7 +106264,7 @@ var ts; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; - var CoreServicesShimHostAdapter = (function () { + var CoreServicesShimHostAdapter = /** @class */ (function () { function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; @@ -83966,7 +106302,7 @@ var ts; if (logPerformance) { var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof result === "string") { + if (ts.isString(result)) { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -83977,7 +106313,7 @@ var ts; return result; } function forwardJSONCall(logger, actionDescription, action, logPerformance) { - return forwardCall(logger, actionDescription, true, action, logPerformance); + return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance); } function forwardCall(logger, actionDescription, returnJson, action, logPerformance) { try { @@ -83993,7 +106329,7 @@ var ts; return JSON.stringify({ error: err }); } } - var ShimBase = (function () { + var ShimBase = /** @class */ (function () { function ShimBase(factory) { this.factory = factory; factory.registerShim(this); @@ -84012,11 +106348,12 @@ var ts; message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), start: diagnostic.start, length: diagnostic.length, + /// TODO: no need for the tolowerCase call category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), code: diagnostic.code }; } - var LanguageServiceShimObject = (function (_super) { + var LanguageServiceShimObject = /** @class */ (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { var _this = _super.call(this, factory) || this; @@ -84029,10 +106366,16 @@ var ts; LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ LanguageServiceShimObject.prototype.dispose = function (dummy) { this.logger.log("dispose()"); this.languageService.dispose(); this.languageService = null; + // force a GC if (debugObjectHost && debugObjectHost.CollectGarbage) { debugObjectHost.CollectGarbage(); this.logger.log("CollectGarbage()"); @@ -84040,6 +106383,10 @@ var ts; this.logger = null; _super.prototype.dispose.call(this, dummy); }; + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; @@ -84064,11 +106411,17 @@ var ts; }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -84091,30 +106444,68 @@ var ts; return _this.realizeDiagnostics(diagnostics); }); }; + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; + /// SIGNATUREHELP LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; + /// GOTO Implementation + /** + * Computes the implementation location of the symbol + * at the requested position. + */ LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); @@ -84127,6 +106518,7 @@ var ts; var _this = this; return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; + /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); @@ -84139,13 +106531,15 @@ var ts; var _this = this; return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); }; - LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options) { + /// GET SMART INDENT + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { var _this = this; return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { var localOptions = JSON.parse(options); return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); }); }; + /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); @@ -84162,33 +106556,44 @@ var ts; var _this = this; return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + // workaround for VS document highlighting issue - keep only items from the initial file var normalizedName = ts.normalizeSlashes(fileName).toLowerCase(); return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); }); }; - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + /** Get a string based representation of a completion list entry details */ + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/, source) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + }); }; - LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options) { + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; - LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options) { + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; - LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options) { + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); @@ -84199,6 +106604,8 @@ var ts; var _this = this; return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); }; + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { var _this = this; return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); @@ -84219,20 +106626,22 @@ var ts; var _this = this; return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; + /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { var _this = this; - return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); + return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", + /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); }; return LanguageServiceShimObject; }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } - var ClassifierShimObject = (function (_super) { + var ClassifierShimObject = /** @class */ (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { var _this = _super.call(this, factory) || this; @@ -84245,6 +106654,7 @@ var ts; var _this = this; return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; + /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; @@ -84258,7 +106668,7 @@ var ts; }; return ClassifierShimObject; }(ShimBase)); - var CoreServicesShimObject = (function (_super) { + var CoreServicesShimObject = /** @class */ (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { var _this = _super.call(this, factory) || this; @@ -84276,7 +106686,7 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; - if (result.resolvedModule && result.resolvedModule.extension !== ".ts" && result.resolvedModule.extension !== ".tsx" && result.resolvedModule.extension !== ".d.ts") { + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { resolvedFileName = undefined; } return { @@ -84300,7 +106710,8 @@ var ts; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), true, true); + // for now treat files as JavaScript + var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -84338,7 +106749,7 @@ var ts; var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); var result = ts.parseJsonText(fileName, text); var normalizedFileName = ts.normalizeSlashes(fileName); - var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, typeAcquisition: configFile.typeAcquisition, @@ -84353,7 +106764,7 @@ var ts; }; CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) { var _this = this; - var getCanonicalFileName = ts.createGetCanonicalFileName(false); + var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); if (_this.safeList === undefined) { @@ -84364,10 +106775,13 @@ var ts; }; return CoreServicesShimObject; }(ShimBase)); - var TypeScriptServicesFactory = (function () { + var TypeScriptServicesFactory = /** @class */ (function () { function TypeScriptServicesFactory() { this._shims = []; } + /* + * Returns script API version. + */ TypeScriptServicesFactory.prototype.getServicesVersion = function () { return ts.servicesVersion; }; @@ -84405,6 +106819,7 @@ var ts; } }; TypeScriptServicesFactory.prototype.close = function () { + // Forget all the registered shims ts.clear(this._shims); this.documentRegistry = undefined; }; @@ -84427,6 +106842,10 @@ var ts; module.exports = ts; } })(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ +/// TODO: this is used by VS, clean this up on both sides of the interface +/* @internal */ var TypeScript; (function (TypeScript) { var Services; @@ -84434,6 +106853,7 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.6"; - -//# sourceMappingURL=tsserverlibrary.js.map +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. +/* @internal */ +var toolsVersion = ts.versionMajorMinor; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 815cc7bf24ad8..9573a51760fd3 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -200,159 +200,163 @@ declare namespace ts { SymbolKeyword = 137, TypeKeyword = 138, UndefinedKeyword = 139, - FromKeyword = 140, - GlobalKeyword = 141, - OfKeyword = 142, - QualifiedName = 143, - ComputedPropertyName = 144, - TypeParameter = 145, - Parameter = 146, - Decorator = 147, - PropertySignature = 148, - PropertyDeclaration = 149, - MethodSignature = 150, - MethodDeclaration = 151, - Constructor = 152, - GetAccessor = 153, - SetAccessor = 154, - CallSignature = 155, - ConstructSignature = 156, - IndexSignature = 157, - TypePredicate = 158, - TypeReference = 159, - FunctionType = 160, - ConstructorType = 161, - TypeQuery = 162, - TypeLiteral = 163, - ArrayType = 164, - TupleType = 165, - UnionType = 166, - IntersectionType = 167, - ParenthesizedType = 168, - ThisType = 169, - TypeOperator = 170, - IndexedAccessType = 171, - MappedType = 172, - LiteralType = 173, - ObjectBindingPattern = 174, - ArrayBindingPattern = 175, - BindingElement = 176, - ArrayLiteralExpression = 177, - ObjectLiteralExpression = 178, - PropertyAccessExpression = 179, - ElementAccessExpression = 180, - CallExpression = 181, - NewExpression = 182, - TaggedTemplateExpression = 183, - TypeAssertionExpression = 184, - ParenthesizedExpression = 185, - FunctionExpression = 186, - ArrowFunction = 187, - DeleteExpression = 188, - TypeOfExpression = 189, - VoidExpression = 190, - AwaitExpression = 191, - PrefixUnaryExpression = 192, - PostfixUnaryExpression = 193, - BinaryExpression = 194, - ConditionalExpression = 195, - TemplateExpression = 196, - YieldExpression = 197, - SpreadElement = 198, - ClassExpression = 199, - OmittedExpression = 200, - ExpressionWithTypeArguments = 201, - AsExpression = 202, - NonNullExpression = 203, - MetaProperty = 204, - TemplateSpan = 205, - SemicolonClassElement = 206, - Block = 207, - VariableStatement = 208, - EmptyStatement = 209, - ExpressionStatement = 210, - IfStatement = 211, - DoStatement = 212, - WhileStatement = 213, - ForStatement = 214, - ForInStatement = 215, - ForOfStatement = 216, - ContinueStatement = 217, - BreakStatement = 218, - ReturnStatement = 219, - WithStatement = 220, - SwitchStatement = 221, - LabeledStatement = 222, - ThrowStatement = 223, - TryStatement = 224, - DebuggerStatement = 225, - VariableDeclaration = 226, - VariableDeclarationList = 227, - FunctionDeclaration = 228, - ClassDeclaration = 229, - InterfaceDeclaration = 230, - TypeAliasDeclaration = 231, - EnumDeclaration = 232, - ModuleDeclaration = 233, - ModuleBlock = 234, - CaseBlock = 235, - NamespaceExportDeclaration = 236, - ImportEqualsDeclaration = 237, - ImportDeclaration = 238, - ImportClause = 239, - NamespaceImport = 240, - NamedImports = 241, - ImportSpecifier = 242, - ExportAssignment = 243, - ExportDeclaration = 244, - NamedExports = 245, - ExportSpecifier = 246, - MissingDeclaration = 247, - ExternalModuleReference = 248, - JsxElement = 249, - JsxSelfClosingElement = 250, - JsxOpeningElement = 251, - JsxClosingElement = 252, - JsxAttribute = 253, - JsxAttributes = 254, - JsxSpreadAttribute = 255, - JsxExpression = 256, - CaseClause = 257, - DefaultClause = 258, - HeritageClause = 259, - CatchClause = 260, - PropertyAssignment = 261, - ShorthandPropertyAssignment = 262, - SpreadAssignment = 263, - EnumMember = 264, - SourceFile = 265, - Bundle = 266, - JSDocTypeExpression = 267, - JSDocAllType = 268, - JSDocUnknownType = 269, - JSDocNullableType = 270, - JSDocNonNullableType = 271, - JSDocOptionalType = 272, - JSDocFunctionType = 273, - JSDocVariadicType = 274, - JSDocComment = 275, - JSDocTag = 276, - JSDocAugmentsTag = 277, - JSDocClassTag = 278, - JSDocParameterTag = 279, - JSDocReturnTag = 280, - JSDocTypeTag = 281, - JSDocTemplateTag = 282, - JSDocTypedefTag = 283, - JSDocPropertyTag = 284, - JSDocTypeLiteral = 285, - SyntaxList = 286, - NotEmittedStatement = 287, - PartiallyEmittedExpression = 288, - CommaListExpression = 289, - MergeDeclarationMarker = 290, - EndOfDeclarationMarker = 291, - Count = 292, + UniqueKeyword = 140, + FromKeyword = 141, + GlobalKeyword = 142, + OfKeyword = 143, + QualifiedName = 144, + ComputedPropertyName = 145, + TypeParameter = 146, + Parameter = 147, + Decorator = 148, + PropertySignature = 149, + PropertyDeclaration = 150, + MethodSignature = 151, + MethodDeclaration = 152, + Constructor = 153, + GetAccessor = 154, + SetAccessor = 155, + CallSignature = 156, + ConstructSignature = 157, + IndexSignature = 158, + TypePredicate = 159, + TypeReference = 160, + FunctionType = 161, + ConstructorType = 162, + TypeQuery = 163, + TypeLiteral = 164, + ArrayType = 165, + TupleType = 166, + UnionType = 167, + IntersectionType = 168, + ParenthesizedType = 169, + ThisType = 170, + TypeOperator = 171, + IndexedAccessType = 172, + MappedType = 173, + LiteralType = 174, + ObjectBindingPattern = 175, + ArrayBindingPattern = 176, + BindingElement = 177, + ArrayLiteralExpression = 178, + ObjectLiteralExpression = 179, + PropertyAccessExpression = 180, + ElementAccessExpression = 181, + CallExpression = 182, + NewExpression = 183, + TaggedTemplateExpression = 184, + TypeAssertionExpression = 185, + ParenthesizedExpression = 186, + FunctionExpression = 187, + ArrowFunction = 188, + DeleteExpression = 189, + TypeOfExpression = 190, + VoidExpression = 191, + AwaitExpression = 192, + PrefixUnaryExpression = 193, + PostfixUnaryExpression = 194, + BinaryExpression = 195, + ConditionalExpression = 196, + TemplateExpression = 197, + YieldExpression = 198, + SpreadElement = 199, + ClassExpression = 200, + OmittedExpression = 201, + ExpressionWithTypeArguments = 202, + AsExpression = 203, + NonNullExpression = 204, + MetaProperty = 205, + TemplateSpan = 206, + SemicolonClassElement = 207, + Block = 208, + VariableStatement = 209, + EmptyStatement = 210, + ExpressionStatement = 211, + IfStatement = 212, + DoStatement = 213, + WhileStatement = 214, + ForStatement = 215, + ForInStatement = 216, + ForOfStatement = 217, + ContinueStatement = 218, + BreakStatement = 219, + ReturnStatement = 220, + WithStatement = 221, + SwitchStatement = 222, + LabeledStatement = 223, + ThrowStatement = 224, + TryStatement = 225, + DebuggerStatement = 226, + VariableDeclaration = 227, + VariableDeclarationList = 228, + FunctionDeclaration = 229, + ClassDeclaration = 230, + InterfaceDeclaration = 231, + TypeAliasDeclaration = 232, + EnumDeclaration = 233, + ModuleDeclaration = 234, + ModuleBlock = 235, + CaseBlock = 236, + NamespaceExportDeclaration = 237, + ImportEqualsDeclaration = 238, + ImportDeclaration = 239, + ImportClause = 240, + NamespaceImport = 241, + NamedImports = 242, + ImportSpecifier = 243, + ExportAssignment = 244, + ExportDeclaration = 245, + NamedExports = 246, + ExportSpecifier = 247, + MissingDeclaration = 248, + ExternalModuleReference = 249, + JsxElement = 250, + JsxSelfClosingElement = 251, + JsxOpeningElement = 252, + JsxClosingElement = 253, + JsxFragment = 254, + JsxOpeningFragment = 255, + JsxClosingFragment = 256, + JsxAttribute = 257, + JsxAttributes = 258, + JsxSpreadAttribute = 259, + JsxExpression = 260, + CaseClause = 261, + DefaultClause = 262, + HeritageClause = 263, + CatchClause = 264, + PropertyAssignment = 265, + ShorthandPropertyAssignment = 266, + SpreadAssignment = 267, + EnumMember = 268, + SourceFile = 269, + Bundle = 270, + JSDocTypeExpression = 271, + JSDocAllType = 272, + JSDocUnknownType = 273, + JSDocNullableType = 274, + JSDocNonNullableType = 275, + JSDocOptionalType = 276, + JSDocFunctionType = 277, + JSDocVariadicType = 278, + JSDocComment = 279, + JSDocTypeLiteral = 280, + JSDocTag = 281, + JSDocAugmentsTag = 282, + JSDocClassTag = 283, + JSDocParameterTag = 284, + JSDocReturnTag = 285, + JSDocTypeTag = 286, + JSDocTemplateTag = 287, + JSDocTypedefTag = 288, + JSDocPropertyTag = 289, + SyntaxList = 290, + NotEmittedStatement = 291, + PartiallyEmittedExpression = 292, + CommaListExpression = 293, + MergeDeclarationMarker = 294, + EndOfDeclarationMarker = 295, + Count = 296, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -360,15 +364,15 @@ declare namespace ts { FirstReservedWord = 72, LastReservedWord = 107, FirstKeyword = 72, - LastKeyword = 142, + LastKeyword = 143, FirstFutureReservedWord = 108, LastFutureReservedWord = 116, - FirstTypeNode = 158, - LastTypeNode = 173, + FirstTypeNode = 159, + LastTypeNode = 174, FirstPunctuation = 17, LastPunctuation = 70, FirstToken = 0, - LastToken = 142, + LastToken = 143, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -377,11 +381,11 @@ declare namespace ts { LastTemplateToken = 16, FirstBinaryOperator = 27, LastBinaryOperator = 70, - FirstNode = 143, - FirstJSDocNode = 267, - LastJSDocNode = 285, - FirstJSDocTagNode = 276, - LastJSDocTagNode = 285, + FirstNode = 144, + FirstJSDocNode = 271, + LastJSDocNode = 289, + FirstJSDocTagNode = 281, + LastJSDocTagNode = 289, } enum NodeFlags { None = 0, @@ -408,7 +412,7 @@ declare namespace ts { BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, - ContextFlags = 96256, + ContextFlags = 6387712, TypeExcludesFlags = 20480, } enum ModifierFlags { @@ -457,6 +461,7 @@ declare namespace ts { } type DotDotDotToken = Token; type QuestionToken = Token; + type ExclamationToken = Token; type ColonToken = Token; type EqualsToken = Token; type AsteriskToken = Token; @@ -467,7 +472,7 @@ declare namespace ts { type AwaitKeywordToken = Token; type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; type ModifiersArray = NodeArray; - interface Identifier extends PrimaryExpression { + interface Identifier extends PrimaryExpression, Declaration { kind: SyntaxKind.Identifier; /** * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) @@ -533,6 +538,7 @@ declare namespace ts { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -567,8 +573,9 @@ declare namespace ts { } interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; - questionToken?: QuestionToken; name: PropertyName; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -602,6 +609,7 @@ declare namespace ts { dotDotDotToken?: DotDotDotToken; name: DeclarationName; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -664,13 +672,13 @@ declare namespace ts { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; - body: FunctionBody; + body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; - body: FunctionBody; + body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { @@ -736,7 +744,7 @@ declare namespace ts { } interface TypeOperatorNode extends TypeNode { kind: SyntaxKind.TypeOperator; - operator: SyntaxKind.KeyOfKeyword; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; type: TypeNode; } interface IndexedAccessTypeNode extends TypeNode { @@ -1061,6 +1069,20 @@ declare namespace ts { tagName: JsxTagNameExpression; attributes: JsxAttributes; } + interface JsxFragment extends PrimaryExpression { + kind: SyntaxKind.JsxFragment; + openingFragment: JsxOpeningFragment; + children: NodeArray; + closingFragment: JsxClosingFragment; + } + interface JsxOpeningFragment extends Expression { + kind: SyntaxKind.JsxOpeningFragment; + parent?: JsxFragment; + } + interface JsxClosingFragment extends Expression { + kind: SyntaxKind.JsxClosingFragment; + parent?: JsxFragment; + } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; parent?: JsxAttributes; @@ -1088,7 +1110,7 @@ declare namespace ts { containsOnlyWhiteSpaces: boolean; parent?: JsxElement; } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { _statementBrand: any; } @@ -1442,9 +1464,15 @@ declare namespace ts { interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ interface JSDocAugmentsTag extends JSDocTag { kind: SyntaxKind.JSDocAugmentsTag; - typeExpression: JSDocTypeExpression; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; } interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; @@ -1471,7 +1499,7 @@ declare namespace ts { interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ isNameFirst: boolean; isBracketed: boolean; @@ -1586,8 +1614,8 @@ declare namespace ts { } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getSourceFileByPath(path: Path): SourceFile; + getSourceFile(fileName: string): SourceFile | undefined; + getSourceFileByPath(path: Path): SourceFile | undefined; getCurrentDirectory(): string; } interface ParseConfigHost { @@ -1600,9 +1628,7 @@ declare namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray): void; - } + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -1725,16 +1751,20 @@ declare namespace ts { signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + /** + * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead + * This will be removed in a future version. + */ getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; /** - * returns unknownSignature in the case of an error. Don't know when it returns undefined. + * returns unknownSignature in the case of an error. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: FunctionLike): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; @@ -1753,6 +1783,8 @@ declare namespace ts { getApparentType(type: Type): Type; getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; + getBaseConstraintOfType(type: Type): Type | undefined; + getDefaultFromTypeParameter(type: Type): Type | undefined; } enum NodeBuilderFlags { None = 0, @@ -1800,6 +1832,7 @@ declare namespace ts { trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; reportPrivateInBaseOfClassExpression(propertyName: string): void; + reportInaccessibleUniqueSymbolError(): void; } enum TypeFormatFlags { None = 0, @@ -1818,6 +1851,7 @@ declare namespace ts { WriteClassExpressionAsTypeLiteral = 16384, InArrayType = 32768, UseAliasDefinedOutsideCurrentScope = 65536, + AllowUniqueESSymbolType = 131072, } enum SymbolFormatFlags { None = 0, @@ -1869,6 +1903,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, + JSContainer = 67108864, Enum = 384, Variable = 3, Value = 107455, @@ -1971,31 +2006,34 @@ declare namespace ts { BooleanLiteral = 128, EnumLiteral = 256, ESSymbol = 512, - Void = 1024, - Undefined = 2048, - Null = 4096, - Never = 8192, - TypeParameter = 16384, - Object = 32768, - Union = 65536, - Intersection = 131072, - Index = 262144, - IndexedAccess = 524288, - NonPrimitive = 16777216, + UniqueESSymbol = 1024, + Void = 2048, + Undefined = 4096, + Null = 8192, + Never = 16384, + TypeParameter = 32768, + Object = 65536, + Union = 131072, + Intersection = 262144, + Index = 524288, + IndexedAccess = 1048576, + NonPrimitive = 33554432, + MarkerType = 134217728, Literal = 224, - Unit = 6368, + Unit = 13536, StringOrNumberLiteral = 96, - PossiblyFalsy = 7406, - StringLike = 262178, + PossiblyFalsy = 14574, + StringLike = 524322, NumberLike = 84, BooleanLike = 136, EnumLike = 272, - UnionOrIntersection = 196608, - StructuredType = 229376, - StructuredOrTypeVariable = 1032192, - TypeVariable = 540672, - Narrowable = 17810175, - NotUnionOrUnit = 16810497, + ESSymbolLike = 1536, + UnionOrIntersection = 393216, + StructuredType = 458752, + StructuredOrTypeVariable = 2064384, + TypeVariable = 1081344, + Narrowable = 35620607, + NotUnionOrUnit = 33620481, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2010,6 +2048,9 @@ declare namespace ts { freshType?: LiteralType; regularType?: LiteralType; } + interface UniqueESSymbolType extends Type { + symbol: Symbol; + } interface StringLiteralType extends LiteralType { value: string; } @@ -2029,6 +2070,7 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, + ContainsSpread = 1024, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2080,9 +2122,6 @@ declare namespace ts { interface TypeVariable extends Type { } interface TypeParameter extends TypeVariable { - /** Retrieve using getConstraintFromTypeParameter */ - constraint: Type; - default?: Type; } interface IndexedAccessType extends TypeVariable { objectType: Type; @@ -2111,9 +2150,11 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - NakedTypeVariable = 1, - MappedType = 2, - ReturnType = 4, + Contravariant = 1, + NakedTypeVariable = 2, + MappedType = 4, + ReturnType = 8, + NeverType = 16, } interface InferenceInfo { typeParameter: TypeParameter; @@ -2146,6 +2187,7 @@ declare namespace ts { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface DiagnosticMessage { key: string; @@ -2247,7 +2289,9 @@ declare namespace ts { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; + strictFunctionTypes?: boolean; strictNullChecks?: boolean; + strictPropertyInitialization?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; @@ -2293,6 +2337,7 @@ declare namespace ts { LineFeed = 1, } interface LineAndCharacter { + /** 0-based. */ line: number; character: number; } @@ -2311,8 +2356,9 @@ declare namespace ts { ES2015 = 2, ES2016 = 3, ES2017 = 4, - ESNext = 5, - Latest = 5, + ES2018 = 5, + ESNext = 6, + Latest = 6, } enum LanguageVariant { Standard = 0, @@ -2400,22 +2446,23 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", + Json = ".json", } interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModuleFull | undefined; + readonly resolvedModule: ResolvedModuleFull | undefined; } interface ResolvedTypeReferenceDirective { primary: boolean; - resolvedFileName?: string; + resolvedFileName: string | undefined; packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; - failedLookupLocations: string[]; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; - getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -2425,7 +2472,7 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ @@ -2656,7 +2703,7 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.6"; + const versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2678,14 +2725,26 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - interface System { - args: string[]; + /** + * Partial interface of the System thats needed to support the caching of directory structure + */ + interface DirectoryStructureHost { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + exit(exitCode?: number): void; + } + interface System extends DirectoryStructureHost { + args: string[]; + getFileSize?(path: string): number; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2693,13 +2752,7 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; getExecutingFilePath(): string; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2707,7 +2760,6 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; - exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; @@ -2715,17 +2767,11 @@ declare namespace ts { interface FileWatcher { close(): void; } - interface DirectoryWatcher extends FileWatcher { - directoryName: string; - referenceCount: number; - } function getNodeMajorVersion(): number; let sys: System; } declare namespace ts { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } + type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { getStartPos(): number; getToken(): SyntaxKind; @@ -2851,6 +2897,8 @@ declare namespace ts { * @returns The unescaped identifier text. */ function unescapeLeadingUnderscores(identifier: __String): string; + function idText(identifier: Identifier): string; + function symbolName(symbol: Symbol): string; /** * Remove extra underscore from escaped identifier text content. * @deprecated Use `id.text` for the unescaped text. @@ -2912,6 +2960,8 @@ declare namespace ts { function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray | undefined; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3001,6 +3051,7 @@ declare namespace ts { function isForOfStatement(node: Node): node is ForOfStatement; function isContinueStatement(node: Node): node is ContinueStatement; function isBreakStatement(node: Node): node is BreakStatement; + function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; function isReturnStatement(node: Node): node is ReturnStatement; function isWithStatement(node: Node): node is WithStatement; function isSwitchStatement(node: Node): node is SwitchStatement; @@ -3035,6 +3086,9 @@ declare namespace ts { function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; function isJsxOpeningElement(node: Node): node is JsxOpeningElement; function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxFragment(node: Node): node is JsxFragment; + function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; + function isJsxClosingFragment(node: Node): node is JsxClosingFragment; function isJsxAttribute(node: Node): node is JsxAttribute; function isJsxAttributes(node: Node): node is JsxAttributes; function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; @@ -3104,6 +3158,8 @@ declare namespace ts { function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3133,10 +3189,11 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -3177,11 +3234,10 @@ declare namespace ts { } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; - function createLiteral(value: string): StringLiteral; + /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ + function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - /** Create a string literal whose source text is read from a source node during emit. */ - function createLiteral(sourceNode: StringLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; @@ -3256,6 +3312,7 @@ declare namespace ts { function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; @@ -3423,6 +3480,8 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function createJsxAttributes(properties: ReadonlyArray): JsxAttributes; @@ -3650,6 +3709,17 @@ declare namespace ts { declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -3661,6 +3731,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** @@ -3758,7 +3829,7 @@ declare namespace ts { getEscapedName(): __String; getName(): string; getDeclarations(): Declaration[] | undefined; - getDocumentationComment(): SymbolDisplayPart[]; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } interface Type { @@ -3773,13 +3844,15 @@ declare namespace ts { getNumberIndexType(): Type | undefined; getBaseTypes(): BaseType[] | undefined; getNonNullableType(): Type; + getConstraint(): Type | undefined; + getDefault(): Type | undefined; } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { @@ -3829,7 +3902,11 @@ declare namespace ts { interface HostCancellationToken { isCancellationRequested(): boolean; } - interface LanguageServiceHost { + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -3849,14 +3926,15 @@ declare namespace ts { readFile?(path: string, encoding?: string): string | undefined; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. */ getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; } interface LanguageService { cleanupSemanticCache(): void; @@ -3873,9 +3951,9 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; @@ -3883,6 +3961,7 @@ declare namespace ts { getRenameInfo(fileName: string, position: number): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; @@ -3904,12 +3983,27 @@ declare namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + applyCodeActionCommand(action: CodeActionCommand): Promise; + applyCodeActionCommand(action: CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } + interface GetCompletionsAtPositionOptions { + includeExternalModuleExports: boolean; + } + interface ApplyCodeActionCommandResult { + successMessage: string; + } interface Classifications { spans: number[]; endOfLineState: EndOfLineState; @@ -3974,6 +4068,14 @@ declare namespace ts { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + type CodeActionCommand = InstallPackageAction; + interface InstallPackageAction { } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. @@ -4022,6 +4124,7 @@ declare namespace ts { edits: FileTextChanges[]; renameFilename: string | undefined; renameLocation: number | undefined; + commands?: CodeActionCommand[]; } interface TextInsertion { newText: string; @@ -4133,6 +4236,10 @@ declare namespace ts { containerKind: ScriptElementKind; containerName: string; } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { displayParts: SymbolDisplayPart[]; } @@ -4236,11 +4343,14 @@ declare namespace ts { kindModifiers: string; sortText: string; /** - * An optional span that indicates the text to be replaced by this completion item. It will be - * set if the required span differs from the one generated by the default replacement behavior and should - * be used in that case + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; + hasAction?: true; + source?: string; + isRecommended?: true; } interface CompletionEntryDetails { name: string; @@ -4249,6 +4359,8 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; + codeActions?: CodeAction[]; + source?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -4263,20 +4375,11 @@ declare namespace ts { */ autoCollapse: boolean; } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, @@ -4549,7 +4652,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - const servicesVersion = "0.5"; + const servicesVersion = "0.7"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } diff --git a/lib/typescript.js b/lib/typescript.js index 4128b5d17fa8f..1fbae487f8038 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -34,6 +34,13 @@ var __extends = (this && this.__extends) || (function () { })(); var 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 = {})); // token > SyntaxKind.Identifer => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync var SyntaxKind; @@ -189,180 +196,184 @@ var ts; SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 140] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 141] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 142] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 143] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 144] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 145] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 146] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 147] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 148] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 149] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 150] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 151] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 152] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 153] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 154] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 155] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 156] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 157] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 158] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 159] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 160] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 161] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 162] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 163] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 164] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 165] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 166] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 167] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 168] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 169] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 170] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 171] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 172] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 173] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 174] = "LiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 175] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 176] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 177] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 178] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 179] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 180] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 181] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 182] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 183] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 184] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 185] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 186] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 187] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 188] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 189] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 190] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 191] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 192] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 193] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 194] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 195] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 196] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 197] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 198] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 199] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 200] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 201] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 202] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 203] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 204] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 205] = "MetaProperty"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 206] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 207] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 208] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 209] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 210] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 211] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 212] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 213] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 214] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 215] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 216] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 217] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 218] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 219] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 220] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 221] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 222] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 223] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 224] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 225] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 226] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 227] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 228] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 229] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 230] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 231] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 232] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 233] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 234] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 235] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 236] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 237] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 238] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 239] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 240] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 241] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 242] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 243] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 244] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 245] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 246] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 247] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 248] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 249] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 250] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 251] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 252] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 253] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 254] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 255] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 256] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 257] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 258] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 259] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 260] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 261] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 262] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 263] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 264] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 265] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 266] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 267] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 268] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; + SyntaxKind[SyntaxKind["SourceFile"] = 269] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 270] = "Bundle"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 271] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 272] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 270] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 273] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 274] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 275] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 276] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 277] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 278] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 279] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 280] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocTag"] = 281] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 282] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 283] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 284] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 285] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 286] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 287] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 288] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 289] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 290] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 291] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 292] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 293] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 294] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 295] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 296] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -371,15 +382,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 143] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 159] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 174] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 143] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -388,11 +399,13 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 144] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 271] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 289] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 281] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 289] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 143] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -427,11 +440,13 @@ var ts; /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 2097152] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 4194304] = "InWithStatement"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 6387712] = "ContextFlags"; // Exclude these flags when parsing a Type NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); @@ -483,16 +498,21 @@ var ts; GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); /* @internal */ - var NumericLiteralFlags; - (function (NumericLiteralFlags) { - NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; - NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; - NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; - NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; - NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; - })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -576,6 +596,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; // even though `T` can't be accessed in the current scope. + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -658,6 +679,9 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -697,7 +721,9 @@ var ts; /* @internal */ // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. - SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ var EnumKind; @@ -718,6 +744,7 @@ var ts; CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -776,55 +803,60 @@ var ts; TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 32768] = "Object"; - TypeFlags[TypeFlags["Union"] = 65536] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 262144] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 2048] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 8192] = "Null"; + TypeFlags[TypeFlags["Never"] = 16384] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 65536] = "Object"; + TypeFlags[TypeFlags["Union"] = 131072] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 524288] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 2097152] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsWideningType"] = 4194304] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 8388608] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 16777216] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 33554432] = "NonPrimitive"; /* @internal */ - TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; + TypeFlags[TypeFlags["JsxAttributes"] = 67108864] = "JsxAttributes"; + TypeFlags[TypeFlags["MarkerType"] = 134217728] = "MarkerType"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; + TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["Intrinsic"] = 33585807] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 524322] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; - TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; + TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 2064384] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 35620607] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 33620481] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 12582912] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + TypeFlags[TypeFlags["PropagatingFlags"] = 29360128] = "PropagatingFlags"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -838,8 +870,18 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -852,9 +894,11 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -942,8 +986,9 @@ var ts; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; (function (LanguageVariant) { @@ -1097,6 +1142,7 @@ var ts; Extension["Dts"] = ".d.ts"; Extension["Js"] = ".js"; Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ var TransformFlags; @@ -1226,6 +1272,9 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of @@ -1236,8 +1285,6 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1259,9 +1306,8 @@ var ts; (function (ts) { var performance; (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (_markName) { }; + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; var enabled = false; var profilerStart = 0; var counts; @@ -1348,7 +1394,7 @@ 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 = "2.6"; + ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); @@ -1363,18 +1409,14 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(/*locales*/ undefined, { usage: "sort", sensitivity: "accent" }) : undefined; - // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". - ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword // 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["__"]; + map.__ = undefined; + delete map.__; return map; } /** Create a new map. If a template object is provided, the map will copy entries from it. */ @@ -1411,7 +1453,7 @@ var ts; } ts.createMapFromTemplate = createMapFromTemplate; // Internet Explorer's Map doesn't support iteration, so don't use it. - // tslint:disable-next-line:no-in-operator + // tslint:disable-next-line no-in-operator variable-name var 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() { @@ -1487,12 +1529,6 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -1514,6 +1550,17 @@ var ts; return undefined; } ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1529,10 +1576,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1560,7 +1609,6 @@ var ts; return true; } ts.every = every; - /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ function find(array, predicate) { for (var i = 0; i < array.length; i++) { var value = array[i]; @@ -1571,6 +1619,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { @@ -1595,11 +1653,12 @@ var ts; Debug.fail(); } ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (equalityComparer(v, value)) { return true; } } @@ -1662,22 +1721,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1704,6 +1747,14 @@ var ts; return result; } ts.map = map; + function mapIterator(iter, mapFn) { + return { next: next }; + function next() { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + } + ts.mapIterator = mapIterator; function sameMap(array, f) { var result; if (array) { @@ -1733,8 +1784,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1780,8 +1831,14 @@ var ts; if (done) break; var res = mapfn(value); - if (res) - result.push.apply(result, res); + if (res) { + if (isArray(res)) { + result.push.apply(result, res); + } + else { + result.push(res); + } + } } return result; } @@ -1822,6 +1879,20 @@ var ts; return result; } ts.mapDefined = mapDefined; + function mapDefinedIter(iter, mapFn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapFn(value); + if (res !== undefined) { + result.push(res); + } + } + return result; + } + ts.mapDefinedIter = mapDefinedIter; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -1895,8 +1966,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1917,26 +1988,79 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. - function deduplicate(array, areEqual) { - var result; - if (array) { - result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } - } - result.push(item); - } + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } ts.deduplicate = deduplicate; - function arrayIsEqualTo(array1, array2, equaler) { + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (!array1 || !array2) { return array1 === array2; } @@ -1944,8 +2068,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { + if (!equalityComparer(array1[i], array2[i])) { return false; } } @@ -1990,34 +2113,51 @@ var ts; } ts.compact = compact; /** - * Gets the relative complement of `arrayA` with respect to `b`, returning the elements that + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted * based on the provided comparer. */ - function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { - if (comparer === void 0) { comparer = compareValues; } - if (offsetA === void 0) { offsetA = 0; } - if (offsetB === void 0) { offsetB = 0; } + function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; var result = []; - outer: for (; offsetB < arrayB.length; offsetB++) { - inner: for (; offsetA < arrayA.length; offsetA++) { + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1 /* LessThan */: break inner; - case 0 /* EqualTo */: continue outer; - case 1 /* GreaterThan */: continue inner; + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; } } - result.push(arrayB[offsetB]); } return result; } ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2059,15 +2199,14 @@ var ts; * @param end The offset in `from` at which to stop copying values (non-inclusive). */ function addRange(to, from, start, end) { - if (from === undefined) + if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); end = end === undefined ? from.length : toOffset(from, end); for (var i = start; i < end && i < from.length; i++) { - var v = from[i]; - if (v !== undefined) { + if (from[i] !== undefined) { to.push(from[i]); } } @@ -2077,8 +2216,8 @@ var ts; /** * @return Whether the value was added. */ - function pushIfUnique(array, toAdd) { - if (contains(array, toAdd)) { + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { return false; } else { @@ -2090,9 +2229,9 @@ var ts; /** * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. */ - function appendIfUnique(array, toAdd) { + function appendIfUnique(array, toAdd, equalityComparer) { if (array) { - pushIfUnique(array, toAdd); + pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -2100,15 +2239,54 @@ var ts; } } ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function best(iter, isBetter) { + var x = iter.next(); + if (x.done) { + return undefined; + } + var best = x.value; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return best; + } + if (isBetter(value, best)) { + best = value; + } + } + } + ts.best = best; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ function stableSort(array, comparer) { - if (comparer === void 0) { comparer = compareValues; } - return array - .map(function (_, i) { return i; }) // create array of indices - .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) // sort indices by value then position - .map(function (i) { return array[i]; }); // get sorted array + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); } ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { @@ -2142,6 +2320,11 @@ var ts; return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; /** * Returns the last element of an array if non-empty, `undefined` otherwise. */ @@ -2149,6 +2332,11 @@ var ts; return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; /** * Returns the only element of an array if it contains only one element, `undefined` otherwise. */ @@ -2171,32 +2359,35 @@ var ts; } ts.replaceElement = replaceElement; /** - * Performs a binary search, finding the index at which 'value' occurs in 'array'. + * Performs a binary search, finding the index at which `value` occurs in `array`. * If no such index is found, returns the 2's-complement of first index at which - * number[index] exceeds number. + * `array[index]` exceeds `value`. * @param array A sorted array whose first element must be no larger than number - * @param number The value to be searched for in the array. + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. */ - function binarySearch(array, value, comparer, offset) { + function binarySearch(array, value, keySelector, keyComparer, offset) { if (!array || array.length === 0) { return -1; } var low = offset || 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; + var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); - var midValue = array[middle]; - if (comparer(midValue, value) === 0) { - return middle; - } - else if (comparer(midValue, value) > 0) { - high = middle - 1; - } - else { - low = middle + 1; + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; } } return ~low; @@ -2226,30 +2417,6 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial, start, count) { - if (array) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start > size - 1 ? size - 1 : start; - var end = count === undefined || pos - count < 0 ? 0 : pos - count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos--; - } - else { - result = initial; - } - while (pos >= end) { - result = f(result, array[pos], pos); - pos--; - } - return result; - } - } - return initial; - } - ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Indicates whether a map-like contains an own property with the specified key. @@ -2357,6 +2524,7 @@ var ts; * @param right A map-like whose properties should be compared. */ function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (left === right) return true; if (!left || !right) @@ -2365,7 +2533,7 @@ var ts; if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + if (!equalityComparer(left[key], right[key])) return false; } } @@ -2380,13 +2548,22 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2455,6 +2632,17 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -2466,8 +2654,14 @@ var ts; } ts.cast = cast; /** Does nothing. */ - function noop() { } + function noop(_) { } // tslint:disable-line no-empty ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; @@ -2625,49 +2819,206 @@ var ts; return headChain; } ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ function compareValues(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + return compareComparableValues(a, b); } ts.compareValues = compareValues; - function compareStrings(a, b, ignoreCase) { + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { if (a === b) return 0 /* EqualTo */; if (a === undefined) return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; - if (ignoreCase) { - // Checking if "collator exists indicates that Intl is available. - // We still have to check if "collator.compare" is correct. If it is not, use "String.localeComapre" - if (ts.collator) { - var result = ts.localeCompareIsCorrect ? - ts.collator.compare(a, b) : - a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); // accent means a ≠ b, a ≠ á, a = A - return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - a = a.toUpperCase(); - b = b.toUpperCase(); + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { if (a === b) return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } } - return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; } - ts.compareStrings = compareStrings; - function compareStringsCaseInsensitive(a, b) { - return compareStrings(a, b, /*ignoreCase*/ true); + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } function compareDiagnostics(d1, d2) { - return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2678,14 +3029,14 @@ var ts; function compareMessageText(text1, text2) { while (text1 && text2) { // We still have both chains. - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + var string1 = isString(text1) ? text1 : text1.messageText; + var string2 = isString(text2) ? text2 : text2.messageText; + var res = compareStringsCaseSensitive(string1, string2); if (res) { return res; } - text1 = typeof text1 === "string" ? undefined : text1.next; - text2 = typeof text2 === "string" ? undefined : text2.next; + text1 = isString(text1) ? undefined : text1.next; + text2 = isString(text2) ? undefined : text2.next; } if (!text1 && !text2) { // if the chains are done, then these messages are the same. @@ -2695,26 +3046,9 @@ var ts; return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; } function sortAndDeduplicateDiagnostics(diagnostics) { - return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + return sortAndDeduplicate(diagnostics, compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function deduplicateSortedDiagnostics(diagnostics) { - if (diagnostics.length < 2) { - return diagnostics; - } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0 /* EqualTo */; - if (!isDupe) { - newDiagnostics.push(currentDiagnostic); - previousDiagnostic = currentDiagnostic; - } - } - return newDiagnostics; - } - ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; function normalizeSlashes(path) { return path.replace(/\\/g, "/"); } @@ -2737,7 +3071,6 @@ var ts; if (path.charCodeAt(1) === 58 /* colon */) { if (path.charCodeAt(2) === 47 /* slash */) return 3; - return 2; } // Per RFC 1738 'file' URI schema has the shape file:/// // if is omitted then it is assumed that host value is 'localhost', @@ -2809,7 +3142,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -2839,6 +3172,17 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2990,10 +3334,6 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; - /** - * Removes a trailing directory separator from a path. - * @param path The path. - */ function removeTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) === ts.directorySeparator) { return path.substr(0, path.length - 1); @@ -3024,8 +3364,9 @@ var ts; var aComponents = getNormalizedPathComponents(a, currentDirectory); var bComponents = getNormalizedPathComponents(b, currentDirectory); var sharedLength = Math.min(aComponents.length, bComponents.length); + var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; for (var i = 0; i < sharedLength; i++) { - var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + var result = comparer(aComponents[i], bComponents[i]); if (result !== 0 /* EqualTo */) { return result; } @@ -3047,9 +3388,9 @@ var ts; if (childComponents.length < parentComponents.length) { return false; } + var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { - var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); - if (result !== 0 /* EqualTo */) { + if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } } @@ -3069,8 +3410,16 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -3245,6 +3594,7 @@ var ts; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); + var comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive; var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var regexFlag = useCaseSensitiveFileNames ? "" : "i"; var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); @@ -3253,7 +3603,6 @@ var ts; // Associate an array of results with each include regex. This keeps results in order of the "include" order. // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -3261,7 +3610,6 @@ var ts; return flatten(results); function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - files = files.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -3279,8 +3627,8 @@ var ts; } } }; - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; + for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + var current = _b[_i]; _loop_1(current); } if (depth !== undefined) { @@ -3289,9 +3637,8 @@ var ts; return; } } - directories = directories.slice().sort(comparer); - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var current = directories_1[_b]; + for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && @@ -3320,7 +3667,7 @@ var ts; includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); @@ -3366,7 +3713,7 @@ var ts; return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; - case ".json": + case ".json" /* Json */: return 6 /* JSON */; default: return 0 /* Unknown */; @@ -3386,7 +3733,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3484,6 +3831,16 @@ var ts; return (removeFileExtension(path) + newExtension); } ts.changeExtension = changeExtension; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; function Symbol(flags, name) { this.flags = flags; this.escapedName = name; @@ -3495,8 +3852,7 @@ var ts; this.checker = checker; } } - function Signature() { - } + function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { this.id = 0; this.kind = kind; @@ -3744,6 +4100,16 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3752,8 +4118,182 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; - function assertTypeIsNever(_) { } + function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; + function createCachedDirectoryStructureHost(host) { + var cachedReadDirectoryResult = createMap(); + var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); + var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, + newLine: host.newLine, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + write: function (s) { return host.write(s); }, + writeFile: writeFile, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: createDirectory, + getCurrentDirectory: getCurrentDirectory, + getDirectories: getDirectories, + readDirectory: readDirectory, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache, + exit: function (code) { return host.exit(code); } + }; + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + } + else { + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (parentResult) { + var baseName = getBaseNameOfFileName(fileOrDirectory); + if (parentResult) { + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + } + } + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; })(ts || (ts = {})); /// var ts; @@ -3792,12 +4332,13 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { + var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); // One file can have multiple watchers @@ -3820,7 +4361,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3842,7 +4383,7 @@ var ts; } function fileEventHandler(eventName, relativeFileName, baseDirPath) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = typeof relativeFileName !== "string" + var fileName = !ts.isString(relativeFileName) ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations @@ -3877,6 +4418,82 @@ var ts; } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { + return; + } + callback(fileName, eventKind); + } + } + function fsWatchDirectory(directoryName, callback, recursive) { + var options; + /** Watcher for the directory depending on whether it is missing or present */ + var watcher = !directoryExists(directoryName) ? + watchMissingDirectory() : + watchPresentDirectory(); + return { + close: function () { + // Close the watcher (either existing directory watcher or missing directory watcher) + watcher.close(); + } + }; + /** + * Watch the directory that is currently present + * and when the watched directory is deleted, switch to missing directory watcher + */ + function watchPresentDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + var dirWatcher = _fs.watch(directoryName, options, callback); + dirWatcher.on("error", function () { + if (!directoryExists(directoryName)) { + // Deleting directory + watcher = watchMissingDirectory(); + // Call the callback for current directory + callback("rename", ""); + } + }); + return dirWatcher; + } + /** + * Watch the directory that is missing + * and switch to existing directory when the directory is created + */ + function watchMissingDirectory() { + return fsWatchFile(directoryName, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { + watcher.close(); + watcher = watchPresentDirectory(); + // Call the callback for current directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + callback("rename", ""); + } + }); + } + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -3908,7 +4525,7 @@ var ts; function writeFile(fileName, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } var fd; try { @@ -3983,7 +4600,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -4001,42 +4617,13 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); - return { - close: function () { return _fs.unwatchFile(fileName, fileChanged); } - }; - } - function fileChanged(curr, prev) { - var isCurrZero = +curr.mtime === 0; - var isPrevZero = +prev.mtime === 0; - var created = !isCurrZero && isPrevZero; - var deleted = isCurrZero && !isPrevZero; - var eventKind = created - ? FileWatcherEventKind.Created - : deleted - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { - return; - } - callback(fileName, eventKind); + return fsWatchFile(fileName, callback, pollingInterval); } }, watchDirectory: function (directoryName, callback, recursive) { // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - var options; - if (!directoryExists(directoryName)) { - // do nothing if target folder does not exist - return noOpFileWatcher; - } - if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - return _fs.watch(directoryName, options, function (eventName, relativeFileName) { + return fsWatchDirectory(directoryName, function (eventName, relativeFileName) { // In watchDirectory we only care about adding and removing files (when event name is // "rename"); changes made within files are handled by corresponding fileWatchers (when // event name is "change") @@ -4044,7 +4631,7 @@ var ts; // When deleting a file, the passed baseFileName is null callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); } - }); + }, recursive); }, resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, @@ -4091,7 +4678,7 @@ var ts; return stat.size; } } - catch (e) { } + catch (_a) { } return 0; }, exit: function (exitCode) { @@ -4105,7 +4692,7 @@ var ts; try { require("source-map-support").install(); } - catch (e) { + catch (_a) { // Could not enable source maps. } }, @@ -4128,7 +4715,7 @@ var ts; writeFile: function (path, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } ChakraHost.writeFile(path, data); }, @@ -4150,7 +4737,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -4190,6 +4777,7 @@ var ts; } })(ts || (ts = {})); // +// generated from './diagnosticInformationMap.generated.ts' by '../../scripts/processDiagnosticMessages.js' /// /* @internal */ var ts; @@ -4197,6 +4785,7 @@ var ts; function diag(code, category, key, message) { return { code: code, category: category, key: key, message: message }; } + // tslint:disable-next-line variable-name ts.Diagnostics = { Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), @@ -4321,11 +4910,11 @@ var ts; An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), @@ -4406,6 +4995,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "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."), @@ -4425,6 +5015,13 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4626,7 +5223,7 @@ var ts; No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), - Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), @@ -4642,7 +5239,7 @@ var ts; await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), @@ -4671,14 +5268,16 @@ var ts; Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), - Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4752,6 +5351,11 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "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."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4775,16 +5379,16 @@ var ts; Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), @@ -4827,6 +5431,14 @@ var ts; Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4855,6 +5467,7 @@ var ts; File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -4868,7 +5481,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -4970,7 +5583,6 @@ var ts; Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), - The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), @@ -5026,6 +5638,8 @@ var ts; Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), 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."), @@ -5075,6 +5689,13 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5092,37 +5713,50 @@ var ts; super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), - Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), - Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), - Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), - Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), - Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), - Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), - Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), - Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), - Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), - Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), - Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), - Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), - Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), - Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), - Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), + Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), }; })(ts || (ts = {})); /// @@ -5134,6 +5768,11 @@ var ts; return token >= 71 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; var textToToken = ts.createMapFromTemplate({ "abstract": 117 /* AbstractKeyword */, "any": 119 /* AnyKeyword */, @@ -5158,7 +5797,7 @@ var ts; "false": 86 /* FalseKeyword */, "finally": 87 /* FinallyKeyword */, "for": 88 /* ForKeyword */, - "from": 140 /* FromKeyword */, + "from": 141 /* FromKeyword */, "function": 89 /* FunctionKeyword */, "get": 125 /* GetKeyword */, "if": 90 /* IfKeyword */, @@ -5183,7 +5822,7 @@ var ts; "public": 114 /* PublicKeyword */, "readonly": 131 /* ReadonlyKeyword */, "require": 132 /* RequireKeyword */, - "global": 141 /* GlobalKeyword */, + "global": 142 /* GlobalKeyword */, "return": 96 /* ReturnKeyword */, "set": 135 /* SetKeyword */, "static": 115 /* StaticKeyword */, @@ -5198,6 +5837,7 @@ var ts; "type": 138 /* TypeKeyword */, "typeof": 103 /* TypeOfKeyword */, "undefined": 139 /* UndefinedKeyword */, + "unique": 140 /* UniqueKeyword */, "var": 104 /* VarKeyword */, "void": 105 /* VoidKeyword */, "while": 106 /* WhileKeyword */, @@ -5205,7 +5845,7 @@ var ts; "yield": 116 /* YieldKeyword */, "async": 120 /* AsyncKeyword */, "await": 121 /* AwaitKeyword */, - "of": 142 /* OfKeyword */, + "of": 143 /* OfKeyword */, "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, @@ -5417,7 +6057,7 @@ var ts; * We assume the first line starts at position 0 and 'position' is non-negative. */ function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position); + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); if (lineNumber < 0) { // If the actual position was not found, // the binary search returns the 2's-complement of the next line start @@ -5835,10 +6475,7 @@ var ts; var tokenPos; var token; var tokenValue; - var precedingLineBreak; - var hasExtendedUnicodeEscape; - var tokenIsUnterminated; - var numericLiteralFlags; + var tokenFlags; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -5847,12 +6484,12 @@ var ts; getTokenPos: function () { return tokenPos; }, getTokenText: function () { return text.substring(tokenPos, pos); }, getTokenValue: function () { return tokenValue; }, - hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, - hasPrecedingLineBreak: function () { return precedingLineBreak; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, - isUnterminated: function () { return tokenIsUnterminated; }, - getNumericLiteralFlags: function () { return numericLiteralFlags; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, @@ -5889,7 +6526,7 @@ var ts; var end = pos; if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { pos++; - numericLiteralFlags = 2 /* Scientific */; + tokenFlags |= 16 /* Scientific */; if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; if (isDigit(text.charCodeAt(pos))) { @@ -5950,8 +6587,8 @@ var ts; } return value; } - function scanString(allowEscapes) { - if (allowEscapes === void 0) { allowEscapes = true; } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -5959,7 +6596,7 @@ var ts; while (true) { if (pos >= end) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -5969,15 +6606,15 @@ var ts; pos++; break; } - if (ch === 92 /* backslash */ && allowEscapes) { + if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; continue; } - if (isLineBreak(ch)) { + if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -5998,7 +6635,7 @@ var ts; while (true) { if (pos >= end) { contents += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; break; @@ -6073,7 +6710,7 @@ var ts; case 117 /* u */: // '\u{DDDDDDDD}' if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { - hasExtendedUnicodeEscape = true; + tokenFlags |= 8 /* ExtendedUnicodeEscape */; pos++; return scanExtendedUnicodeEscape(); } @@ -6222,10 +6859,7 @@ var ts; } function scan() { startPos = pos; - hasExtendedUnicodeEscape = false; - precedingLineBreak = false; - tokenIsUnterminated = false; - numericLiteralFlags = 0; + tokenFlags = 0; while (true) { tokenPos = pos; if (pos >= end) { @@ -6245,7 +6879,7 @@ var ts; switch (ch) { case 10 /* lineFeed */: case 13 /* carriageReturn */: - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; if (skipTrivia) { pos++; continue; @@ -6373,6 +7007,9 @@ var ts; // Multi-line comment if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } var commentClosed = false; while (pos < end) { var ch_1 = text.charCodeAt(pos); @@ -6382,7 +7019,7 @@ var ts; break; } if (isLineBreak(ch_1)) { - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; } pos++; } @@ -6393,7 +7030,9 @@ var ts; continue; } else { - tokenIsUnterminated = !commentClosed; + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } return token = 3 /* MultiLineCommentTrivia */; } } @@ -6411,7 +7050,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 8 /* HexSpecifier */; + tokenFlags |= 64 /* HexSpecifier */; return token = 8 /* NumericLiteral */; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { @@ -6422,7 +7061,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 16 /* BinarySpecifier */; + tokenFlags |= 128 /* BinarySpecifier */; return token = 8 /* NumericLiteral */; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { @@ -6433,13 +7072,13 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 32 /* OctalSpecifier */; + tokenFlags |= 256 /* OctalSpecifier */; return token = 8 /* NumericLiteral */; } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); - numericLiteralFlags = 4 /* Octal */; + tokenFlags |= 32 /* Octal */; return token = 8 /* NumericLiteral */; } // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero @@ -6593,7 +7232,7 @@ var ts; continue; } else if (isLineBreak(ch)) { - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; pos++; continue; } @@ -6634,13 +7273,13 @@ var ts; // If we reach the end of a file, or hit a newline, then this is an unterminated // regex. Report error and return what we have so far. if (p >= end) { - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } var ch = text.charCodeAt(p); if (isLineBreak(ch)) { - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } @@ -6760,7 +7399,7 @@ var ts; switch (text.charCodeAt(pos)) { case 34 /* doubleQuote */: case 39 /* singleQuote */: - tokenValue = scanString(/*allowEscapes*/ false); + tokenValue = scanString(/*jsxAttributeString*/ true); return token = 9 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. @@ -6805,6 +7444,12 @@ var ts; case 93 /* closeBracket */: pos++; return token = 22 /* CloseBracketToken */; + case 60 /* lessThan */: + pos++; + return token = 27 /* LessThanToken */; + case 62 /* greaterThan */: + pos++; + return token = 29 /* GreaterThanToken */; case 61 /* equals */: pos++; return token = 58 /* EqualsToken */; @@ -6813,13 +7458,24 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: pos++; + if (text.substr(tokenPos, pos + 2) === "...") { + pos += 2; + return token = 24 /* DotDotDotToken */; + } return token = 23 /* DotToken */; + case 33 /* exclamation */: + pos++; + return token = 51 /* ExclamationToken */; + case 63 /* question */: + pos++; + return token = 55 /* QuestionToken */; } - if (isIdentifierStart(ch, 5 /* Latest */)) { + if (isIdentifierStart(ch, 6 /* Latest */)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 5 /* Latest */) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } + tokenValue = text.substring(tokenPos, pos); return token = 71 /* Identifier */; } else { @@ -6832,7 +7488,7 @@ var ts; var saveTokenPos = tokenPos; var saveToken = token; var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; + var saveTokenFlags = tokenFlags; var result = callback(); // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. @@ -6842,7 +7498,7 @@ var ts; tokenPos = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; - precedingLineBreak = savePrecedingLineBreak; + tokenFlags = saveTokenFlags; } return result; } @@ -6852,10 +7508,8 @@ var ts; var saveStartPos = startPos; var saveTokenPos = tokenPos; var saveToken = token; - var savePrecedingLineBreak = precedingLineBreak; var saveTokenValue = tokenValue; - var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - var saveTokenIsUnterminated = tokenIsUnterminated; + var saveTokenFlags = tokenFlags; setText(text, start, length); var result = callback(); end = saveEnd; @@ -6863,10 +7517,8 @@ var ts; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; - precedingLineBreak = savePrecedingLineBreak; tokenValue = saveTokenValue; - hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; - tokenIsUnterminated = saveTokenIsUnterminated; + tokenFlags = saveTokenFlags; return result; } function lookAhead(callback) { @@ -6898,10 +7550,8 @@ var ts; startPos = textPos; tokenPos = textPos; token = 0 /* Unknown */; - precedingLineBreak = false; tokenValue = undefined; - hasExtendedUnicodeEscape = false; - tokenIsUnterminated = false; + tokenFlags = 0; } } ts.createScanner = createScanner; @@ -6948,6 +7598,7 @@ var ts; clear: function () { return str = ""; }, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; } @@ -7038,7 +7689,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 265 /* SourceFile */) { + while (node && node.kind !== 269 /* SourceFile */) { node = node.parent; } return node; @@ -7046,11 +7697,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 207 /* Block */: - case 235 /* CaseBlock */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 208 /* Block */: + case 236 /* CaseBlock */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return true; } return false; @@ -7159,7 +7810,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 290 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -7193,19 +7844,17 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } /** * Note: it is expected that the `nodeArray` and the `node` are within the same file. * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. */ function indexOfNode(nodeArray, node) { - return ts.binarySearch(nodeArray, node, compareNodePos); + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } ts.indexOfNode = indexOfNode; - function compareNodePos(_a, _b) { - var aPos = _a.pos; - var bPos = _b.pos; - return aPos < bPos ? -1 /* LessThan */ : bPos < aPos ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } /** * Gets flags that control emit behavior of a node. */ @@ -7234,8 +7883,10 @@ var ts; case 13 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; case 14 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; case 15 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; case 16 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; @@ -7247,7 +7898,7 @@ var ts; } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { - return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' @@ -7276,15 +7927,18 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 226 /* VariableDeclaration */ && node.parent.kind === 260 /* CatchClause */; + return node.kind === 227 /* VariableDeclaration */ && node.parent.kind === 264 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 233 /* ModuleDeclaration */ && + return node && node.kind === 234 /* ModuleDeclaration */ && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - /* @internal */ + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } @@ -7296,11 +7950,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 233 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 234 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 /* SourceFile */ || - node.kind === 233 /* ModuleDeclaration */ || + return node.kind === 269 /* SourceFile */ || + node.kind === 234 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -7316,37 +7970,36 @@ var ts; return false; } switch (node.parent.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: return ts.isExternalModule(node.parent); - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; - /* @internal */ function isBlockScope(node, parentNode) { switch (node.kind) { - case 265 /* SourceFile */: - case 235 /* CaseBlock */: - case 260 /* CatchClause */: - case 233 /* ModuleDeclaration */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 269 /* SourceFile */: + case 236 /* CaseBlock */: + case 264 /* CatchClause */: + case 234 /* ModuleDeclaration */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; - case 207 /* Block */: + case 208 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return parentNode && !ts.isFunctionLike(parentNode); @@ -7356,25 +8009,25 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 273 /* JSDocFunctionType */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 282 /* JSDocTemplateTag */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 287 /* JSDocTemplateTag */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; default: ts.assertTypeIsNever(node); @@ -7382,6 +8035,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -7412,7 +8075,7 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: if (isStringOrNumericLiteral(name.expression)) { return escapeLeadingUnderscores(name.expression.text); } @@ -7423,22 +8086,22 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71 /* Identifier */: - return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); - case 143 /* QualifiedName */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 144 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); } } ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { @@ -7463,7 +8126,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207 /* Block */) { + if (node.body && node.body.kind === 208 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -7477,7 +8140,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -7486,23 +8149,23 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 231 /* TypeAliasDeclaration */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 232 /* TypeAliasDeclaration */: errorNode = node.name; break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -7521,7 +8184,7 @@ var ts; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isConstEnumDeclaration(node) { - return node.kind === 232 /* EnumDeclaration */ && isConst(node); + return node.kind === 233 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -7534,15 +8197,15 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 181 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 182 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 181 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 182 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isPrologueDirective(node) { - return node.kind === 210 /* ExpressionStatement */ + return node.kind === 211 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -7551,11 +8214,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 /* Parameter */ || - node.kind === 145 /* TypeParameter */ || - node.kind === 186 /* FunctionExpression */ || - node.kind === 187 /* ArrowFunction */ || - node.kind === 185 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 147 /* Parameter */ || + node.kind === 146 /* TypeParameter */ || + node.kind === 187 /* FunctionExpression */ || + node.kind === 188 /* ArrowFunction */ || + node.kind === 186 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -7571,7 +8234,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (158 /* FirstTypeNode */ <= node.kind && node.kind <= 173 /* LastTypeNode */) { + if (159 /* FirstTypeNode */ <= node.kind && node.kind <= 174 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -7584,27 +8247,27 @@ var ts; case 130 /* NeverKeyword */: return true; case 105 /* VoidKeyword */: - return node.parent.kind !== 190 /* VoidExpression */; - case 201 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 191 /* VoidExpression */; + case 202 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 71 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 143 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */ || node.kind === 179 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */ || node.kind === 180 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 143 /* QualifiedName */: - case 179 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: case 99 /* ThisKeyword */: var parent = node.parent; - if (parent.kind === 162 /* TypeQuery */) { + if (parent.kind === 163 /* TypeQuery */) { return false; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -7613,38 +8276,38 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (158 /* FirstTypeNode */ <= parent.kind && parent.kind <= 173 /* LastTypeNode */) { + if (159 /* FirstTypeNode */ <= parent.kind && parent.kind <= 174 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return node === parent.constraint; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 146 /* Parameter */: - case 226 /* VariableDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 147 /* Parameter */: + case 227 /* VariableDeclaration */: return node === parent.type; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return node === parent.type; - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return node === parent.type; - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return node === parent.type; - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -7668,23 +8331,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitor(node); - case 235 /* CaseBlock */: - case 207 /* Block */: - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 220 /* WithStatement */: - case 221 /* SwitchStatement */: - case 257 /* CaseClause */: - case 258 /* DefaultClause */: - case 222 /* LabeledStatement */: - case 224 /* TryStatement */: - case 260 /* CatchClause */: + case 236 /* CaseBlock */: + case 208 /* Block */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 221 /* WithStatement */: + case 222 /* SwitchStatement */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -7694,19 +8357,19 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 232 /* EnumDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -7714,7 +8377,7 @@ var ts; default: if (ts.isFunctionLike(node)) { var name = node.name; - if (name && name.kind === 144 /* ComputedPropertyName */) { + if (name && name.kind === 145 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(name.expression); @@ -7737,10 +8400,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 164 /* ArrayType */) { + if (node && node.kind === 165 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 159 /* TypeReference */) { + else if (node && node.kind === 160 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -7748,32 +8411,55 @@ var ts; } } ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 231 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 164 /* TypeLiteral */: + return node.members; + case 179 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; function isVariableLike(node) { if (node) { switch (node.kind) { - case 176 /* BindingElement */: - case 264 /* EnumMember */: - case 146 /* Parameter */: - case 261 /* PropertyAssignment */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 262 /* ShorthandPropertyAssignment */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 268 /* EnumMember */: + case 147 /* Parameter */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 266 /* ShorthandPropertyAssignment */: + case 227 /* VariableDeclaration */: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 228 /* VariableDeclarationList */ + && node.parent.parent.kind === 209 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return true; } return false; @@ -7784,7 +8470,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 222 /* LabeledStatement */) { + if (node.statement.kind !== 223 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -7792,17 +8478,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 208 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 151 /* MethodDeclaration */ && node.parent.kind === 178 /* ObjectLiteralExpression */; + return node && node.kind === 152 /* MethodDeclaration */ && node.parent.kind === 179 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 /* MethodDeclaration */ && - (node.parent.kind === 178 /* ObjectLiteralExpression */ || - node.parent.kind === 199 /* ClassExpression */); + return node.kind === 152 /* MethodDeclaration */ && + (node.parent.kind === 179 /* ObjectLiteralExpression */ || + node.parent.kind === 200 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -7815,7 +8501,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 261 /* PropertyAssignment */) { + if (property.kind === 265 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); } @@ -7837,7 +8523,7 @@ var ts; return undefined; } switch (node.kind) { - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -7852,9 +8538,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 147 /* Decorator */: + case 148 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 147 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -7865,26 +8551,26 @@ var ts; node = node.parent; } break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 233 /* ModuleDeclaration */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 232 /* EnumDeclaration */: - case 265 /* SourceFile */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 234 /* ModuleDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 233 /* EnumDeclaration */: + case 269 /* SourceFile */: return node; } } @@ -7894,9 +8580,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return container; } } @@ -7918,27 +8604,27 @@ var ts; return node; } switch (node.kind) { - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: node = node.parent; break; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return node; - case 147 /* Decorator */: + case 148 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 147 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -7954,45 +8640,54 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */) { + if (func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 185 /* ParenthesizedExpression */) { + while (parent.kind === 186 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 181 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 182 /* CallExpression */ && parent.expression === prev) { return parent; } } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; /** - * Determines whether a node is a property or element access expression for super. + * Determines whether a node is a property or element access expression for `super`. */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 179 /* PropertyAccessExpression */ || kind === 180 /* ElementAccessExpression */) + return (kind === 180 /* PropertyAccessExpression */ || kind === 181 /* ElementAccessExpression */) && node.expression.kind === 97 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 180 /* PropertyAccessExpression */ || kind === 181 /* ElementAccessExpression */) + && node.expression.kind === 99 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return node.typeName; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71 /* Identifier */: - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { return node.tag; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -8002,105 +8697,106 @@ var ts; return node.expression; } ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { + function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: // classes are valid targets return true; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 229 /* ClassDeclaration */; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: + return parent.kind === 230 /* ClassDeclaration */; + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && node.parent.kind === 229 /* ClassDeclaration */; - case 146 /* Parameter */: + && parent.kind === 230 /* ClassDeclaration */; + case 147 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; - return node.parent.body !== undefined - && (node.parent.kind === 152 /* Constructor */ - || node.parent.kind === 151 /* MethodDeclaration */ - || node.parent.kind === 154 /* SetAccessor */) - && node.parent.parent.kind === 229 /* ClassDeclaration */; + return parent.body !== undefined + && (parent.kind === 153 /* Constructor */ + || parent.kind === 152 /* MethodDeclaration */ + || parent.kind === 155 /* SetAccessor */) + && grandparent.kind === 230 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { + function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node); + && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { + function childIsDecorated(node, parent) { switch (node.kind) { - case 229 /* ClassDeclaration */: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151 /* MethodDeclaration */: - case 154 /* SetAccessor */: - return ts.forEach(node.parameters, nodeIsDecorated); + case 230 /* ClassDeclaration */: + return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 152 /* MethodDeclaration */: + case 155 /* SetAccessor */: + return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 251 /* JsxOpeningElement */ || - parent.kind === 250 /* JsxSelfClosingElement */ || - parent.kind === 252 /* JsxClosingElement */) { + if (parent.kind === 252 /* JsxOpeningElement */ || + parent.kind === 251 /* JsxSelfClosingElement */ || + parent.kind === 253 /* JsxClosingElement */) { return parent.tagName === node; } return false; } ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { + function isExpressionNode(node) { switch (node.kind) { case 97 /* SuperKeyword */: case 95 /* NullKeyword */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 12 /* RegularExpressionLiteral */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 183 /* TaggedTemplateExpression */: - case 202 /* AsExpression */: - case 184 /* TypeAssertionExpression */: - case 203 /* NonNullExpression */: - case 185 /* ParenthesizedExpression */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: - case 187 /* ArrowFunction */: - case 190 /* VoidExpression */: - case 188 /* DeleteExpression */: - case 189 /* TypeOfExpression */: - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: - case 194 /* BinaryExpression */: - case 195 /* ConditionalExpression */: - case 198 /* SpreadElement */: - case 196 /* TemplateExpression */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 184 /* TaggedTemplateExpression */: + case 203 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 204 /* NonNullExpression */: + case 186 /* ParenthesizedExpression */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 195 /* BinaryExpression */: + case 196 /* ConditionalExpression */: + case 199 /* SpreadElement */: + case 197 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: - case 200 /* OmittedExpression */: - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 197 /* YieldExpression */: - case 191 /* AwaitExpression */: - case 204 /* MetaProperty */: + case 201 /* OmittedExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 198 /* YieldExpression */: + case 192 /* AwaitExpression */: + case 205 /* MetaProperty */: return true; - case 143 /* QualifiedName */: - while (node.parent.kind === 143 /* QualifiedName */) { + case 144 /* QualifiedName */: + while (node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 163 /* TypeQuery */ || isJSXTagName(node); case 71 /* Identifier */: - if (node.parent.kind === 162 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 163 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -8112,59 +8808,59 @@ var ts; return false; } } - ts.isPartOfExpression = isPartOfExpression; + ts.isExpressionNode = isExpressionNode; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 264 /* EnumMember */: - case 261 /* PropertyAssignment */: - case 176 /* BindingElement */: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 268 /* EnumMember */: + case 265 /* PropertyAssignment */: + case 177 /* BindingElement */: return parent.initializer === node; - case 210 /* ExpressionStatement */: - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 219 /* ReturnStatement */: - case 220 /* WithStatement */: - case 221 /* SwitchStatement */: - case 257 /* CaseClause */: - case 223 /* ThrowStatement */: + case 211 /* ExpressionStatement */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 220 /* ReturnStatement */: + case 221 /* WithStatement */: + case 222 /* SwitchStatement */: + case 261 /* CaseClause */: + case 224 /* ThrowStatement */: return parent.expression === node; - case 214 /* ForStatement */: + case 215 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 228 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 228 /* VariableDeclarationList */) || forInStatement.expression === node; - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return node === parent.expression; - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return node === parent.expression; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return node === parent.expression; - case 147 /* Decorator */: - case 256 /* JsxExpression */: - case 255 /* JsxSpreadAttribute */: - case 263 /* SpreadAssignment */: + case 148 /* Decorator */: + case 260 /* JsxExpression */: + case 259 /* JsxSpreadAttribute */: + case 267 /* SpreadAssignment */: return true; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: - return isPartOfExpression(parent); + return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */; + return node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 249 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -8173,7 +8869,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 248 /* ExternalModuleReference */; + return node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 249 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -8188,13 +8884,21 @@ var ts; return node && !!(node.flags & 1048576 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). * This function does not test if the node is in a JavaScript file or not. */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181 /* CallExpression */) { + if (callExpression.kind !== 182 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -8212,14 +8916,18 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; /** - * Returns true if the node is a variable declaration whose initializer is a function expression. + * Returns true if the node is a variable declaration whose initializer is a function or class expression. * This function does not test if the node is in a JavaScript file or not. */ function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226 /* VariableDeclaration */) { + if (s.valueDeclaration && s.valueDeclaration.kind === 227 /* VariableDeclaration */) { var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 /* FunctionExpression */ || declaration.initializer.kind === 199 /* ClassExpression */); + return declaration.initializer && (declaration.initializer.kind === 187 /* FunctionExpression */ || declaration.initializer.kind === 200 /* ClassExpression */); } return false; } @@ -8241,12 +8949,11 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { + function getSpecialPropertyAssignmentKind(expr) { + if (!isInJavaScriptFile(expr)) { return 0 /* None */; } - var expr = expression; - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 179 /* PropertyAccessExpression */) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 180 /* PropertyAccessExpression */) { return 0 /* None */; } var lhs = expr.left; @@ -8268,7 +8975,7 @@ var ts; else if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 179 /* PropertyAccessExpression */) { + else if (lhs.expression.kind === 180 /* PropertyAccessExpression */) { // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71 /* Identifier */) { @@ -8285,36 +8992,42 @@ var ts; return 0 /* None */; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isSpecialPropertyDeclaration(expr) { + return isInJavaScriptFile(expr) && + expr.parent && expr.parent.kind === 211 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function getExternalModuleName(node) { - if (node.kind === 238 /* ImportDeclaration */) { + if (node.kind === 239 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { + if (node.kind === 238 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 248 /* ExternalModuleReference */) { + if (reference.kind === 249 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 244 /* ExportDeclaration */) { + if (node.kind === 245 /* ExportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 233 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + if (isModuleWithStringLiteralName(node)) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 237 /* ImportEqualsDeclaration */) { + if (node.kind === 238 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 241 /* NamespaceImport */) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 238 /* ImportDeclaration */ + return node.kind === 239 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } @@ -8322,13 +9035,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 146 /* Parameter */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 262 /* ShorthandPropertyAssignment */: - case 261 /* PropertyAssignment */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 147 /* Parameter */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 266 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -8336,7 +9049,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 273 /* JSDocFunctionType */ && + return node.kind === 277 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; @@ -8349,45 +9062,62 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 58 /* EqualsToken */ && + node.expression.right; + } + ts.getSourceOfAssignment = getSourceOfAssignment; + function getSingleInitializerOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0].initializer === child) && + node.declarationList.declarations[0].initializer; + } + ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; + function getSingleVariableOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0] === child) && + node.declarationList.declarations[0]; + } + ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; + function getNestedModuleDeclaration(node) { + return node.kind === 234 /* ModuleDeclaration */ && + node.body && + node.body.kind === 234 /* ModuleDeclaration */ && + node.body; + } + ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; + if (parent && (parent.kind === 265 /* PropertyAssignment */ || getNestedModuleDeclaration(parent))) { + getJSDocCommentsAndTagsWorker(parent); + } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** // * @param {number} name // * @returns {number} // */ // var x = function(name) { return name.length; } - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208 /* VariableStatement */; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208 /* VariableStatement */; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocCommentsAndTagsWorker(variableStatementNode); - } - // Also recognize when the node is the RHS of an assignment expression - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 /* BinaryExpression */ && - parent.operatorToken.kind === 58 /* EqualsToken */ && - parent.parent.kind === 210 /* ExpressionStatement */; - if (isSourceOfAssignmentExpressionStatement) { + if (parent && parent.parent && + (getSingleVariableOfVariableStatement(parent.parent, node) || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - var isModuleDeclaration = node.kind === 233 /* ModuleDeclaration */ && - parent && parent.kind === 233 /* ModuleDeclaration */; - var isPropertyAssignmentExpression = parent && parent.kind === 261 /* PropertyAssignment */; - if (isModuleDeclaration || isPropertyAssignmentExpression) { + if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatement(parent.parent.parent, node)) { + getJSDocCommentsAndTagsWorker(parent.parent.parent); + } + if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || + node.kind === 180 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 211 /* ExpressionStatement */) { getJSDocCommentsAndTagsWorker(parent); } // Pull parameter comments from declaring function as well - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { @@ -8408,17 +9138,29 @@ var ts; return undefined; } var name = node.name.escapedText; - ts.Debug.assert(node.parent.kind === 275 /* JSDocComment */); - var func = node.parent.parent; - if (!ts.isFunctionLike(func)) { + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { return undefined; } - var parameter = ts.find(func.parameters, function (p) { - return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; - }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + var host = getJSDocHost(node); + var decl = getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatement(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getJSDocHost(node) { + ts.Debug.assert(node.parent.kind === 279 /* JSDocComment */); + return node.parent.parent; + } + ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { var name = node.name.escapedText; var typeParameters = node.parent.parent.parent.typeParameters; @@ -8426,27 +9168,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -8457,30 +9186,30 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 185 /* ParenthesizedExpression */: - case 177 /* ArrayLiteralExpression */: - case 198 /* SpreadElement */: + case 186 /* ParenthesizedExpression */: + case 178 /* ArrayLiteralExpression */: + case 199 /* SpreadElement */: node = parent; break; - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -8501,16 +9230,27 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 169 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 186 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { + if (node.kind !== 180 /* PropertyAccessExpression */ && node.kind !== 181 /* ElementAccessExpression */) { return false; } - node = node.parent; - while (node && node.kind === 185 /* ParenthesizedExpression */) { - node = node.parent; - } - return node && node.kind === 188 /* DeleteExpression */; + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 189 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -8522,16 +9262,6 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2 /* Ambient */) || (node.kind === 265 /* SourceFile */ && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { switch (name.kind) { @@ -8544,7 +9274,6 @@ var ts; } } ts.isDeclarationName = isDeclarationName; - /* @internal */ // See GH#16030 function isAnyDeclarationName(name) { switch (name.kind) { @@ -8563,7 +9292,7 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 144 /* ComputedPropertyName */ && + node.parent.kind === 145 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -8571,32 +9300,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 264 /* EnumMember */: - case 261 /* PropertyAssignment */: - case 179 /* PropertyAccessExpression */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 268 /* EnumMember */: + case 265 /* PropertyAssignment */: + case 180 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 143 /* QualifiedName */) { + while (parent.kind === 144 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 162 /* TypeQuery */; + return parent.kind === 163 /* TypeQuery */; } return false; - case 176 /* BindingElement */: - case 242 /* ImportSpecifier */: + case 177 /* BindingElement */: + case 243 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 246 /* ExportSpecifier */: - case 253 /* JsxAttribute */: + case 247 /* ExportSpecifier */: + case 257 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -8612,13 +9341,13 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */ || - node.kind === 236 /* NamespaceExportDeclaration */ || - node.kind === 239 /* ImportClause */ && !!node.name || - node.kind === 240 /* NamespaceImport */ || - node.kind === 242 /* ImportSpecifier */ || - node.kind === 246 /* ExportSpecifier */ || - node.kind === 243 /* ExportAssignment */ && exportAssignmentIsAlias(node); + return node.kind === 238 /* ImportEqualsDeclaration */ || + node.kind === 237 /* NamespaceExportDeclaration */ || + node.kind === 240 /* ImportClause */ && !!node.name || + node.kind === 241 /* NamespaceImport */ || + node.kind === 243 /* ImportSpecifier */ || + node.kind === 247 /* ExportSpecifier */ || + node.kind === 244 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -8702,9 +9431,22 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 142 /* LastKeyword */; + return 72 /* FirstKeyword */ <= token && token <= 143 /* LastKeyword */; } ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 117 /* FirstContextualKeyword */ <= token && token <= 143 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -8723,14 +9465,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -8744,10 +9486,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -8774,7 +9516,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 144 /* ComputedPropertyName */ && + return name.kind === 145 /* ComputedPropertyName */ && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -8795,11 +9537,10 @@ var ts; if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.escapedText; - return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(nameExpression.text); @@ -8811,7 +9552,7 @@ var ts; function getTextOfIdentifierOrLiteral(node) { if (node) { if (node.kind === 71 /* Identifier */) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { @@ -8851,11 +9592,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 146 /* Parameter */; + return root.kind === 147 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 176 /* BindingElement */) { + while (node.kind === 177 /* BindingElement */) { node = node.parent.parent; } return node; @@ -8863,15 +9604,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 152 /* Constructor */ - || kind === 186 /* FunctionExpression */ - || kind === 228 /* FunctionDeclaration */ - || kind === 187 /* ArrowFunction */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 233 /* ModuleDeclaration */ - || kind === 265 /* SourceFile */; + return kind === 153 /* Constructor */ + || kind === 187 /* FunctionExpression */ + || kind === 229 /* FunctionDeclaration */ + || kind === 188 /* ArrowFunction */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 234 /* ModuleDeclaration */ + || kind === 269 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -8890,23 +9631,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 182 /* NewExpression */: + case 183 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 192 /* PrefixUnaryExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 188 /* DeleteExpression */: - case 191 /* AwaitExpression */: - case 195 /* ConditionalExpression */: - case 197 /* YieldExpression */: + case 193 /* PrefixUnaryExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 192 /* AwaitExpression */: + case 196 /* ConditionalExpression */: + case 198 /* YieldExpression */: return 1 /* Right */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (operator) { case 40 /* AsteriskAsteriskToken */: case 58 /* EqualsToken */: @@ -8930,15 +9671,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 194 /* BinaryExpression */) { + if (expression.kind === 195 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 192 /* PrefixUnaryExpression */ || expression.kind === 193 /* PostfixUnaryExpression */) { + else if (expression.kind === 193 /* PrefixUnaryExpression */ || expression.kind === 194 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -8956,36 +9697,37 @@ var ts; case 86 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 199 /* ClassExpression */: - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 200 /* ClassExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: case 12 /* RegularExpressionLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 196 /* TemplateExpression */: - case 185 /* ParenthesizedExpression */: - case 200 /* OmittedExpression */: + case 197 /* TemplateExpression */: + case 186 /* ParenthesizedExpression */: + case 201 /* OmittedExpression */: return 19; - case 183 /* TaggedTemplateExpression */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 184 /* TaggedTemplateExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: return 18; - case 182 /* NewExpression */: + case 183 /* NewExpression */: return hasArguments ? 18 : 17; - case 181 /* CallExpression */: + case 182 /* CallExpression */: return 17; - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return 16; - case 192 /* PrefixUnaryExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 188 /* DeleteExpression */: - case 191 /* AwaitExpression */: + case 193 /* PrefixUnaryExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 192 /* AwaitExpression */: return 15; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (operatorKind) { case 51 /* ExclamationToken */: case 52 /* TildeToken */: @@ -9043,13 +9785,13 @@ var ts; default: return -1; } - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return 4; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return 2; - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return 1; - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return 0; default: return -1; @@ -9059,6 +9801,7 @@ var ts; function createDiagnosticCollection() { var nonFileDiagnostics = []; var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; var diagnosticsModified = false; var modificationCount = 0; return { @@ -9084,6 +9827,11 @@ var ts; } } else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); @@ -9092,6 +9840,7 @@ var ts; } function getGlobalDiagnostics() { sortAndDeduplicate(); + hasReadNonFileDiagnostics = true; return nonFileDiagnostics; } function getDiagnostics(fileName) { @@ -9165,10 +9914,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { - // An escaped identifier had a leading underscore prior to being escaped, which would return true - // The escape adds an extra underscore which does not change the result - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -9367,7 +10114,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 152 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 153 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -9413,10 +10160,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 153 /* GetAccessor */) { + if (accessor.kind === 154 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 154 /* SetAccessor */) { + else if (accessor.kind === 155 /* SetAccessor */) { setAccessor = accessor; } else { @@ -9425,7 +10172,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 153 /* GetAccessor */ || member.kind === 154 /* SetAccessor */) + if ((member.kind === 154 /* GetAccessor */ || member.kind === 155 /* SetAccessor */) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -9436,10 +10183,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 153 /* GetAccessor */ && !getAccessor) { + if (member.kind === 154 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 154 /* SetAccessor */ && !setAccessor) { + if (member.kind === 155 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -9458,11 +10205,11 @@ var ts; * Gets the effective type annotation of a variable, parameter, or property. If the node was * parsed in a JavaScript file, gets the type annotation from JSDoc. */ - function getEffectiveTypeAnnotationNode(node) { + function getEffectiveTypeAnnotationNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocType(node); } } @@ -9471,11 +10218,11 @@ var ts; * Gets the effective return type annotation of a signature. If the node was parsed in a * JavaScript file, gets the return type annotation from JSDoc. */ - function getEffectiveReturnTypeNode(node) { + function getEffectiveReturnTypeNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocReturnType(node); } } @@ -9484,11 +10231,11 @@ var ts; * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ - function getEffectiveTypeParameterDeclarations(node) { + function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } @@ -9498,9 +10245,9 @@ var ts; * Gets the effective type annotation of the value parameter of a set accessor. If the node * was parsed in a JavaScript file, gets the type annotation from JSDoc. */ - function getEffectiveSetAccessorTypeAnnotationNode(node) { + function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter); + return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -9703,6 +10450,14 @@ var ts; return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; function getSelectedModifierFlags(node, flags) { return getModifierFlags(node) & flags; } @@ -9716,7 +10471,6 @@ var ts; return flags; } ts.getModifierFlags = getModifierFlags; - /* @internal */ function getModifierFlagsNoCache(node) { var flags = 0 /* None */; if (node.modifiers) { @@ -9760,7 +10514,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 /* ExpressionWithTypeArguments */ && + if (node.kind === 202 /* ExpressionWithTypeArguments */ && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -9778,8 +10532,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 178 /* ObjectLiteralExpression */ - || kind === 177 /* ArrayLiteralExpression */; + return kind === 179 /* ObjectLiteralExpression */ + || kind === 178 /* ArrayLiteralExpression */; } return false; } @@ -9789,7 +10543,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 /* ExpressionWithTypeArguments */ + return node.kind === 202 /* ExpressionWithTypeArguments */ && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 /* ImplementsKeyword */ @@ -9799,21 +10553,21 @@ var ts; ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || - node.kind === 179 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + node.kind === 180 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 178 /* ObjectLiteralExpression */ && + return expression.kind === 179 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 177 /* ArrayLiteralExpression */ && + return expression.kind === 178 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -9897,17 +10651,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options) { + function getNewLineCharacter(options, system) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; + return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -10085,8 +10836,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -10128,26 +10879,6 @@ var ts; return 0; } ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; - function levenshtein(s1, s2) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - for (var i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (var i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (var j = 1; j < s2.length + 1; j++) { - current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - // shift current back to previous, and then reuse previous' array - var tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; function skipAlias(symbol, checker) { return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; } @@ -10179,28 +10910,122 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 193 /* PostfixUnaryExpression */: - case 192 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 210 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && parent.parent.kind === 211 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } } + return true; } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + 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); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 65536 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 5 /* ESNext */: + case 6 /* ESNext */: return "lib.esnext.full.d.ts"; case 4 /* ES2017 */: return "lib.es2017.full.d.ts"; @@ -10419,9 +11244,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 145 /* TypeParameter */) { + if (d && d.kind === 146 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 231 /* InterfaceDeclaration */) { return current; } } @@ -10429,7 +11254,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 152 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 153 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -10447,7 +11272,7 @@ var ts; } ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 /* BindingElement */ || ts.isBindingPattern(node))) { + while (node && (node.kind === 177 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -10455,14 +11280,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 226 /* VariableDeclaration */) { + if (node.kind === 227 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 227 /* VariableDeclarationList */) { + if (node && node.kind === 228 /* VariableDeclarationList */) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 208 /* VariableStatement */) { + if (node && node.kind === 209 /* VariableStatement */) { flags |= ts.getModifierFlags(node); } return flags; @@ -10478,14 +11303,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 226 /* VariableDeclaration */) { + if (node.kind === 227 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 227 /* VariableDeclarationList */) { + if (node && node.kind === 228 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 208 /* VariableStatement */) { + if (node && node.kind === 209 /* VariableStatement */) { flags |= node.flags; } return flags; @@ -10510,6 +11335,8 @@ var ts; if (!trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } + // Set the UI locale for string collation + ts.setUILocale(locale); function trySetLanguageAndTerritory(language, territory, errors) { var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); @@ -10585,6 +11412,14 @@ var ts; return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; } ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; /** * Remove extra underscore from escaped identifier text content. * @deprecated Use `id.text` for the unescaped text. @@ -10611,18 +11446,18 @@ var ts; } // Covers remaining cases switch (hostNode.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return expr.name; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -10631,10 +11466,10 @@ var ts; return undefined; case 1 /* EndOfFileToken */: return undefined; - case 185 /* ParenthesizedExpression */: { + case 186 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 222 /* LabeledStatement */: { + case 223 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -10656,27 +11491,37 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { - return declaration.name.right; - } - if (declaration.kind === 194 /* BinaryExpression */) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - case 3 /* PrototypeProperty */: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 71 /* Identifier */: + return declaration; + case 289 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 144 /* QualifiedName */) { + return name.right; + } + break; + } + case 195 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + case 288 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 244 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283 /* JSDocTypedefTag */) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; /** @@ -10708,33 +11553,33 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, 284 /* JSDocParameterTag */); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, 282 /* JSDocAugmentsTag */); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278 /* JSDocClassTag */); + return getFirstJSDocTag(node, 283 /* JSDocClassTag */); } ts.getJSDocClassTag = getJSDocClassTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); + return getFirstJSDocTag(node, 285 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, 287 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; /** Gets the JSDoc type tag for the node if present and valid */ function getJSDocTypeTag(node) { // We should have already issued an error if there were multiple type jsdocs, so just use the first one. - var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -10753,8 +11598,8 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); - if (!tag && node.kind === 146 /* Parameter */) { + var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */); + if (!tag && node.kind === 147 /* Parameter */) { var paramTags = getJSDocParameterTags(node); if (paramTags) { tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); @@ -10789,6 +11634,12 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -10832,592 +11683,608 @@ var ts; ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 143 /* QualifiedName */; + return node.kind === 144 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 144 /* ComputedPropertyName */; + return node.kind === 145 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 145 /* TypeParameter */; + return node.kind === 146 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 146 /* Parameter */; + return node.kind === 147 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 147 /* Decorator */; + return node.kind === 148 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 148 /* PropertySignature */; + return node.kind === 149 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 149 /* PropertyDeclaration */; + return node.kind === 150 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 150 /* MethodSignature */; + return node.kind === 151 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 151 /* MethodDeclaration */; + return node.kind === 152 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 152 /* Constructor */; + return node.kind === 153 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 153 /* GetAccessor */; + return node.kind === 154 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 154 /* SetAccessor */; + return node.kind === 155 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 155 /* CallSignature */; + return node.kind === 156 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 156 /* ConstructSignature */; + return node.kind === 157 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 157 /* IndexSignature */; + return node.kind === 158 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 158 /* TypePredicate */; + return node.kind === 159 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 159 /* TypeReference */; + return node.kind === 160 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 160 /* FunctionType */; + return node.kind === 161 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 161 /* ConstructorType */; + return node.kind === 162 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 162 /* TypeQuery */; + return node.kind === 163 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 163 /* TypeLiteral */; + return node.kind === 164 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 164 /* ArrayType */; + return node.kind === 165 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 165 /* TupleType */; + return node.kind === 166 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 166 /* UnionType */; + return node.kind === 167 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 167 /* IntersectionType */; + return node.kind === 168 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 168 /* ParenthesizedType */; + return node.kind === 169 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 169 /* ThisType */; + return node.kind === 170 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 170 /* TypeOperator */; + return node.kind === 171 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 171 /* IndexedAccessType */; + return node.kind === 172 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 172 /* MappedType */; + return node.kind === 173 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 173 /* LiteralType */; + return node.kind === 174 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 174 /* ObjectBindingPattern */; + return node.kind === 175 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 175 /* ArrayBindingPattern */; + return node.kind === 176 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 176 /* BindingElement */; + return node.kind === 177 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 177 /* ArrayLiteralExpression */; + return node.kind === 178 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 178 /* ObjectLiteralExpression */; + return node.kind === 179 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 179 /* PropertyAccessExpression */; + return node.kind === 180 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 180 /* ElementAccessExpression */; + return node.kind === 181 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 181 /* CallExpression */; + return node.kind === 182 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 182 /* NewExpression */; + return node.kind === 183 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 183 /* TaggedTemplateExpression */; + return node.kind === 184 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 184 /* TypeAssertionExpression */; + return node.kind === 185 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 185 /* ParenthesizedExpression */; + return node.kind === 186 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288 /* PartiallyEmittedExpression */) { + while (node.kind === 292 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 186 /* FunctionExpression */; + return node.kind === 187 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 187 /* ArrowFunction */; + return node.kind === 188 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 188 /* DeleteExpression */; + return node.kind === 189 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 191 /* AwaitExpression */; + return node.kind === 192 /* AwaitExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; + return node.kind === 191 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 191 /* AwaitExpression */; + return node.kind === 192 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 192 /* PrefixUnaryExpression */; + return node.kind === 193 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 193 /* PostfixUnaryExpression */; + return node.kind === 194 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 194 /* BinaryExpression */; + return node.kind === 195 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 195 /* ConditionalExpression */; + return node.kind === 196 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 196 /* TemplateExpression */; + return node.kind === 197 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 197 /* YieldExpression */; + return node.kind === 198 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 198 /* SpreadElement */; + return node.kind === 199 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 199 /* ClassExpression */; + return node.kind === 200 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 200 /* OmittedExpression */; + return node.kind === 201 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 201 /* ExpressionWithTypeArguments */; + return node.kind === 202 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 202 /* AsExpression */; + return node.kind === 203 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 203 /* NonNullExpression */; + return node.kind === 204 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 204 /* MetaProperty */; + return node.kind === 205 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 205 /* TemplateSpan */; + return node.kind === 206 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 206 /* SemicolonClassElement */; + return node.kind === 207 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 207 /* Block */; + return node.kind === 208 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 208 /* VariableStatement */; + return node.kind === 209 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 209 /* EmptyStatement */; + return node.kind === 210 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 210 /* ExpressionStatement */; + return node.kind === 211 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 211 /* IfStatement */; + return node.kind === 212 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 212 /* DoStatement */; + return node.kind === 213 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 213 /* WhileStatement */; + return node.kind === 214 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 214 /* ForStatement */; + return node.kind === 215 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 215 /* ForInStatement */; + return node.kind === 216 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 216 /* ForOfStatement */; + return node.kind === 217 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 217 /* ContinueStatement */; + return node.kind === 218 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 218 /* BreakStatement */; + return node.kind === 219 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 219 /* BreakStatement */ || node.kind === 218 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 219 /* ReturnStatement */; + return node.kind === 220 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 220 /* WithStatement */; + return node.kind === 221 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 221 /* SwitchStatement */; + return node.kind === 222 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 222 /* LabeledStatement */; + return node.kind === 223 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 223 /* ThrowStatement */; + return node.kind === 224 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 224 /* TryStatement */; + return node.kind === 225 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 225 /* DebuggerStatement */; + return node.kind === 226 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 226 /* VariableDeclaration */; + return node.kind === 227 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 227 /* VariableDeclarationList */; + return node.kind === 228 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 228 /* FunctionDeclaration */; + return node.kind === 229 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 229 /* ClassDeclaration */; + return node.kind === 230 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 230 /* InterfaceDeclaration */; + return node.kind === 231 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 231 /* TypeAliasDeclaration */; + return node.kind === 232 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 232 /* EnumDeclaration */; + return node.kind === 233 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 233 /* ModuleDeclaration */; + return node.kind === 234 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 234 /* ModuleBlock */; + return node.kind === 235 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 235 /* CaseBlock */; + return node.kind === 236 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 236 /* NamespaceExportDeclaration */; + return node.kind === 237 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */; + return node.kind === 238 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 238 /* ImportDeclaration */; + return node.kind === 239 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 239 /* ImportClause */; + return node.kind === 240 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 240 /* NamespaceImport */; + return node.kind === 241 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 241 /* NamedImports */; + return node.kind === 242 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 242 /* ImportSpecifier */; + return node.kind === 243 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 243 /* ExportAssignment */; + return node.kind === 244 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 244 /* ExportDeclaration */; + return node.kind === 245 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 245 /* NamedExports */; + return node.kind === 246 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 246 /* ExportSpecifier */; + return node.kind === 247 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 247 /* MissingDeclaration */; + return node.kind === 248 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 248 /* ExternalModuleReference */; + return node.kind === 249 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 249 /* JsxElement */; + return node.kind === 250 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 250 /* JsxSelfClosingElement */; + return node.kind === 251 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 251 /* JsxOpeningElement */; + return node.kind === 252 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 252 /* JsxClosingElement */; + return node.kind === 253 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 254 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 255 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 256 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 253 /* JsxAttribute */; + return node.kind === 257 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 254 /* JsxAttributes */; + return node.kind === 258 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 255 /* JsxSpreadAttribute */; + return node.kind === 259 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 256 /* JsxExpression */; + return node.kind === 260 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 257 /* CaseClause */; + return node.kind === 261 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 258 /* DefaultClause */; + return node.kind === 262 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 259 /* HeritageClause */; + return node.kind === 263 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 260 /* CatchClause */; + return node.kind === 264 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 261 /* PropertyAssignment */; + return node.kind === 265 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 262 /* ShorthandPropertyAssignment */; + return node.kind === 266 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 263 /* SpreadAssignment */; + return node.kind === 267 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 264 /* EnumMember */; + return node.kind === 268 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 265 /* SourceFile */; + return node.kind === 269 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 266 /* Bundle */; + return node.kind === 270 /* Bundle */; } ts.isBundle = isBundle; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 267 /* JSDocTypeExpression */; + return node.kind === 271 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 268 /* JSDocAllType */; + return node.kind === 272 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 269 /* JSDocUnknownType */; + return node.kind === 273 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 270 /* JSDocNullableType */; + return node.kind === 274 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 271 /* JSDocNonNullableType */; + return node.kind === 275 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 272 /* JSDocOptionalType */; + return node.kind === 276 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 273 /* JSDocFunctionType */; + return node.kind === 277 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 274 /* JSDocVariadicType */; + return node.kind === 278 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 275 /* JSDocComment */; + return node.kind === 279 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 277 /* JSDocAugmentsTag */; + return node.kind === 282 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocParameterTag(node) { - return node.kind === 279 /* JSDocParameterTag */; + return node.kind === 284 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 280 /* JSDocReturnTag */; + return node.kind === 285 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 281 /* JSDocTypeTag */; + return node.kind === 286 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 282 /* JSDocTemplateTag */; + return node.kind === 287 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 283 /* JSDocTypedefTag */; + return node.kind === 288 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 284 /* JSDocPropertyTag */; + return node.kind === 289 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 284 /* JSDocPropertyTag */ || node.kind === 279 /* JSDocParameterTag */; + return node.kind === 289 /* JSDocPropertyTag */ || node.kind === 284 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 285 /* JSDocTypeLiteral */; + return node.kind === 280 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; })(ts || (ts = {})); @@ -11428,7 +12295,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 286 /* SyntaxList */; + return n.kind === 290 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -11438,7 +12305,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 143 /* FirstNode */; + return kind >= 144 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -11446,7 +12313,7 @@ var ts; * For example, this is true for an IfKeyword but not for an IfStatement. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 142 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 143 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -11478,16 +12345,7 @@ var ts; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isStringTextContainingNode(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 13 /* NoSubstitutionTemplateLiteral */: - return true; - default: - return false; - } + return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -11523,7 +12381,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 143 /* QualifiedName */ + return kind === 144 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isEntityName = isEntityName; @@ -11532,14 +12390,14 @@ var ts; return kind === 71 /* Identifier */ || kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 144 /* ComputedPropertyName */; + || kind === 145 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 174 /* ObjectBindingPattern */ - || kind === 175 /* ArrayBindingPattern */; + || kind === 175 /* ObjectBindingPattern */ + || kind === 176 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -11554,13 +12412,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; default: return false; @@ -11569,13 +12427,13 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 273 /* JSDocFunctionType */: - case 161 /* ConstructorType */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 161 /* FunctionType */: + case 277 /* JSDocFunctionType */: + case 162 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -11590,49 +12448,49 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 152 /* Constructor */ - || kind === 149 /* PropertyDeclaration */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */ - || kind === 247 /* MissingDeclaration */; + return kind === 153 /* Constructor */ + || kind === 150 /* PropertyDeclaration */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 158 /* IndexSignature */ + || kind === 207 /* SemicolonClassElement */ + || kind === 248 /* MissingDeclaration */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */); + return node && (node.kind === 230 /* ClassDeclaration */ || node.kind === 200 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */); + return node && (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */); } ts.isAccessor = isAccessor; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 156 /* ConstructSignature */ - || kind === 155 /* CallSignature */ - || kind === 148 /* PropertySignature */ - || kind === 150 /* MethodSignature */ - || kind === 157 /* IndexSignature */ - || kind === 247 /* MissingDeclaration */; + return kind === 157 /* ConstructSignature */ + || kind === 156 /* CallSignature */ + || kind === 149 /* PropertySignature */ + || kind === 151 /* MethodSignature */ + || kind === 158 /* IndexSignature */ + || kind === 248 /* MissingDeclaration */; } ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 261 /* PropertyAssignment */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 263 /* SpreadAssignment */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 247 /* MissingDeclaration */; + return kind === 265 /* PropertyAssignment */ + || kind === 266 /* ShorthandPropertyAssignment */ + || kind === 267 /* SpreadAssignment */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 248 /* MissingDeclaration */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) + return (kind >= 159 /* FirstTypeNode */ && kind <= 174 /* LastTypeNode */) || kind === 119 /* AnyKeyword */ || kind === 133 /* NumberKeyword */ || kind === 134 /* ObjectKeyword */ @@ -11644,7 +12502,14 @@ var ts; || kind === 139 /* UndefinedKeyword */ || kind === 95 /* NullKeyword */ || kind === 130 /* NeverKeyword */ - || kind === 201 /* ExpressionWithTypeArguments */; + || kind === 202 /* ExpressionWithTypeArguments */ + || kind === 272 /* JSDocAllType */ + || kind === 273 /* JSDocUnknownType */ + || kind === 274 /* JSDocNullableType */ + || kind === 275 /* JSDocNonNullableType */ + || kind === 276 /* JSDocOptionalType */ + || kind === 277 /* JSDocFunctionType */ + || kind === 278 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -11657,8 +12522,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return true; } return false; @@ -11669,8 +12534,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 175 /* ArrayBindingPattern */ - || kind === 174 /* ObjectBindingPattern */; + return kind === 176 /* ArrayBindingPattern */ + || kind === 175 /* ObjectBindingPattern */; } return false; } @@ -11678,15 +12543,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 177 /* ArrayLiteralExpression */ - || kind === 178 /* ObjectLiteralExpression */; + return kind === 178 /* ArrayLiteralExpression */ + || kind === 179 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 176 /* BindingElement */ - || kind === 200 /* OmittedExpression */; + return kind === 177 /* BindingElement */ + || kind === 201 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -11695,9 +12560,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 176 /* BindingElement */: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 177 /* BindingElement */: return true; } return false; @@ -11718,8 +12583,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 174 /* ObjectBindingPattern */: - case 178 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 179 /* ObjectLiteralExpression */: return true; } return false; @@ -11731,8 +12596,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: return true; } return false; @@ -11741,18 +12606,18 @@ var ts; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 179 /* PropertyAccessExpression */ - || kind === 143 /* QualifiedName */; + return kind === 180 /* PropertyAccessExpression */ + || kind === 144 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 183 /* TaggedTemplateExpression */: - case 147 /* Decorator */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 184 /* TaggedTemplateExpression */: + case 148 /* Decorator */: return true; default: return false; @@ -11760,12 +12625,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + return node.kind === 182 /* CallExpression */ || node.kind === 183 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 196 /* TemplateExpression */ + return kind === 197 /* TemplateExpression */ || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -11776,31 +12641,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - case 182 /* NewExpression */: - case 181 /* CallExpression */: - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 183 /* TaggedTemplateExpression */: - case 177 /* ArrayLiteralExpression */: - case 185 /* ParenthesizedExpression */: - case 178 /* ObjectLiteralExpression */: - case 199 /* ClassExpression */: - case 186 /* FunctionExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 183 /* NewExpression */: + case 182 /* CallExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 184 /* TaggedTemplateExpression */: + case 178 /* ArrayLiteralExpression */: + case 186 /* ParenthesizedExpression */: + case 179 /* ObjectLiteralExpression */: + case 200 /* ClassExpression */: + case 187 /* FunctionExpression */: case 71 /* Identifier */: case 12 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 99 /* ThisKeyword */: case 101 /* TrueKeyword */: case 97 /* SuperKeyword */: - case 203 /* NonNullExpression */: - case 204 /* MetaProperty */: + case 204 /* NonNullExpression */: + case 205 /* MetaProperty */: case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression return true; default: @@ -11814,13 +12680,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: - case 188 /* DeleteExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 191 /* AwaitExpression */: - case 184 /* TypeAssertionExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 192 /* AwaitExpression */: + case 185 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -11829,9 +12695,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return true; - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; default: @@ -11842,7 +12708,7 @@ var ts; /* @internal */ /** * Determines whether a node is an expression based only on its kind. - * Use `isPartOfExpression` if not in transforms. + * Use `isExpressionNode` if not in transforms. */ function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); @@ -11850,15 +12716,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 195 /* ConditionalExpression */: - case 197 /* YieldExpression */: - case 187 /* ArrowFunction */: - case 194 /* BinaryExpression */: - case 198 /* SpreadElement */: - case 202 /* AsExpression */: - case 200 /* OmittedExpression */: - case 289 /* CommaListExpression */: - case 288 /* PartiallyEmittedExpression */: + case 196 /* ConditionalExpression */: + case 198 /* YieldExpression */: + case 188 /* ArrowFunction */: + case 195 /* BinaryExpression */: + case 199 /* SpreadElement */: + case 203 /* AsExpression */: + case 201 /* OmittedExpression */: + case 293 /* CommaListExpression */: + case 292 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -11866,18 +12732,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 184 /* TypeAssertionExpression */ - || kind === 202 /* AsExpression */; + return kind === 185 /* TypeAssertionExpression */ + || kind === 203 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 288 /* PartiallyEmittedExpression */; + return node.kind === 292 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 287 /* NotEmittedStatement */; + return node.kind === 291 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -11889,13 +12755,13 @@ var ts; // Statement function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return true; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -11903,7 +12769,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 215 /* ForInStatement */ || node.kind === 216 /* ForOfStatement */; + return node.kind === 216 /* ForInStatement */ || node.kind === 217 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -11927,111 +12793,111 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */ + return kind === 235 /* ModuleBlock */ + || kind === 234 /* ModuleDeclaration */ || kind === 71 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */; + return kind === 235 /* ModuleBlock */ + || kind === 234 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 233 /* ModuleDeclaration */; + || kind === 234 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 241 /* NamedImports */ - || kind === 240 /* NamespaceImport */; + return kind === 242 /* NamedImports */ + || kind === 241 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; + return node.kind === 234 /* ModuleDeclaration */ || node.kind === 233 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 187 /* ArrowFunction */ - || kind === 176 /* BindingElement */ - || kind === 229 /* ClassDeclaration */ - || kind === 199 /* ClassExpression */ - || kind === 152 /* Constructor */ - || kind === 232 /* EnumDeclaration */ - || kind === 264 /* EnumMember */ - || kind === 246 /* ExportSpecifier */ - || kind === 228 /* FunctionDeclaration */ - || kind === 186 /* FunctionExpression */ - || kind === 153 /* GetAccessor */ - || kind === 239 /* ImportClause */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 242 /* ImportSpecifier */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 253 /* JsxAttribute */ - || kind === 151 /* MethodDeclaration */ - || kind === 150 /* MethodSignature */ - || kind === 233 /* ModuleDeclaration */ - || kind === 236 /* NamespaceExportDeclaration */ - || kind === 240 /* NamespaceImport */ - || kind === 146 /* Parameter */ - || kind === 261 /* PropertyAssignment */ - || kind === 149 /* PropertyDeclaration */ - || kind === 148 /* PropertySignature */ - || kind === 154 /* SetAccessor */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 145 /* TypeParameter */ - || kind === 226 /* VariableDeclaration */ - || kind === 283 /* JSDocTypedefTag */; + return kind === 188 /* ArrowFunction */ + || kind === 177 /* BindingElement */ + || kind === 230 /* ClassDeclaration */ + || kind === 200 /* ClassExpression */ + || kind === 153 /* Constructor */ + || kind === 233 /* EnumDeclaration */ + || kind === 268 /* EnumMember */ + || kind === 247 /* ExportSpecifier */ + || kind === 229 /* FunctionDeclaration */ + || kind === 187 /* FunctionExpression */ + || kind === 154 /* GetAccessor */ + || kind === 240 /* ImportClause */ + || kind === 238 /* ImportEqualsDeclaration */ + || kind === 243 /* ImportSpecifier */ + || kind === 231 /* InterfaceDeclaration */ + || kind === 257 /* JsxAttribute */ + || kind === 152 /* MethodDeclaration */ + || kind === 151 /* MethodSignature */ + || kind === 234 /* ModuleDeclaration */ + || kind === 237 /* NamespaceExportDeclaration */ + || kind === 241 /* NamespaceImport */ + || kind === 147 /* Parameter */ + || kind === 265 /* PropertyAssignment */ + || kind === 150 /* PropertyDeclaration */ + || kind === 149 /* PropertySignature */ + || kind === 155 /* SetAccessor */ + || kind === 266 /* ShorthandPropertyAssignment */ + || kind === 232 /* TypeAliasDeclaration */ + || kind === 146 /* TypeParameter */ + || kind === 227 /* VariableDeclaration */ + || kind === 288 /* JSDocTypedefTag */; } function isDeclarationStatementKind(kind) { - return kind === 228 /* FunctionDeclaration */ - || kind === 247 /* MissingDeclaration */ - || kind === 229 /* ClassDeclaration */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 232 /* EnumDeclaration */ - || kind === 233 /* ModuleDeclaration */ - || kind === 238 /* ImportDeclaration */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 244 /* ExportDeclaration */ - || kind === 243 /* ExportAssignment */ - || kind === 236 /* NamespaceExportDeclaration */; + return kind === 229 /* FunctionDeclaration */ + || kind === 248 /* MissingDeclaration */ + || kind === 230 /* ClassDeclaration */ + || kind === 231 /* InterfaceDeclaration */ + || kind === 232 /* TypeAliasDeclaration */ + || kind === 233 /* EnumDeclaration */ + || kind === 234 /* ModuleDeclaration */ + || kind === 239 /* ImportDeclaration */ + || kind === 238 /* ImportEqualsDeclaration */ + || kind === 245 /* ExportDeclaration */ + || kind === 244 /* ExportAssignment */ + || kind === 237 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 /* BreakStatement */ - || kind === 217 /* ContinueStatement */ - || kind === 225 /* DebuggerStatement */ - || kind === 212 /* DoStatement */ - || kind === 210 /* ExpressionStatement */ - || kind === 209 /* EmptyStatement */ - || kind === 215 /* ForInStatement */ - || kind === 216 /* ForOfStatement */ - || kind === 214 /* ForStatement */ - || kind === 211 /* IfStatement */ - || kind === 222 /* LabeledStatement */ - || kind === 219 /* ReturnStatement */ - || kind === 221 /* SwitchStatement */ - || kind === 223 /* ThrowStatement */ - || kind === 224 /* TryStatement */ - || kind === 208 /* VariableStatement */ - || kind === 213 /* WhileStatement */ - || kind === 220 /* WithStatement */ - || kind === 287 /* NotEmittedStatement */ - || kind === 291 /* EndOfDeclarationMarker */ - || kind === 290 /* MergeDeclarationMarker */; + return kind === 219 /* BreakStatement */ + || kind === 218 /* ContinueStatement */ + || kind === 226 /* DebuggerStatement */ + || kind === 213 /* DoStatement */ + || kind === 211 /* ExpressionStatement */ + || kind === 210 /* EmptyStatement */ + || kind === 216 /* ForInStatement */ + || kind === 217 /* ForOfStatement */ + || kind === 215 /* ForStatement */ + || kind === 212 /* IfStatement */ + || kind === 223 /* LabeledStatement */ + || kind === 220 /* ReturnStatement */ + || kind === 222 /* SwitchStatement */ + || kind === 224 /* ThrowStatement */ + || kind === 225 /* TryStatement */ + || kind === 209 /* VariableStatement */ + || kind === 214 /* WhileStatement */ + || kind === 221 /* WithStatement */ + || kind === 291 /* NotEmittedStatement */ + || kind === 295 /* EndOfDeclarationMarker */ + || kind === 294 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 145 /* TypeParameter */) { - return node.parent.kind !== 282 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 146 /* TypeParameter */) { + return node.parent.kind !== 287 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -12058,10 +12924,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 207 /* Block */) + if (node.kind !== 208 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 224 /* TryStatement */ || node.parent.kind === 260 /* CatchClause */) { + if (node.parent.kind === 225 /* TryStatement */ || node.parent.kind === 264 /* CatchClause */) { return false; } } @@ -12071,8 +12937,8 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 248 /* ExternalModuleReference */ - || kind === 143 /* QualifiedName */ + return kind === 249 /* ExternalModuleReference */ + || kind === 144 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -12082,63 +12948,72 @@ var ts; var kind = node.kind; return kind === 99 /* ThisKeyword */ || kind === 71 /* Identifier */ - || kind === 179 /* PropertyAccessExpression */; + || kind === 180 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 249 /* JsxElement */ - || kind === 256 /* JsxExpression */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */; + return kind === 250 /* JsxElement */ + || kind === 260 /* JsxExpression */ + || kind === 251 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */ + || kind === 254 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 253 /* JsxAttribute */ - || kind === 255 /* JsxSpreadAttribute */; + return kind === 257 /* JsxAttribute */ + || kind === 259 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 256 /* JsxExpression */; + || kind === 260 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 251 /* JsxOpeningElement */ - || kind === 250 /* JsxSelfClosingElement */; + return kind === 252 /* JsxOpeningElement */ + || kind === 251 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 257 /* CaseClause */ - || kind === 258 /* DefaultClause */; + return kind === 261 /* CaseClause */ + || kind === 262 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 267 /* FirstJSDocNode */ && node.kind <= 285 /* LastJSDocNode */; + return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 275 /* JSDocComment */ || isJSDocTag(node); + return node.kind === 279 /* JSDocComment */ || isJSDocTag(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + return node.kind >= 281 /* FirstJSDocTagNode */ && node.kind <= 289 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 155 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 154 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ function hasJSDocNodes(node) { @@ -12160,12 +13035,14 @@ var ts; SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; + // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 265 /* SourceFile */) { + if (kind === 269 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71 /* Identifier */) { @@ -12210,59 +13087,60 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 142 /* LastToken */) { + if (!node || node.kind <= 143 /* LastToken */) { return; } switch (node.kind) { - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -12273,287 +13151,291 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 165 /* TupleType */: + case 166 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 166 /* UnionType */: - case 167 /* IntersectionType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: + case 169 /* ParenthesizedType */: + case 171 /* TypeOperator */: return visitNode(cbNode, node.type); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 172 /* MappedType */: + case 173 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return visitNode(cbNode, node.literal); - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 202 /* AsExpression */: + case 203 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return visitNode(cbNode, node.name); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 207 /* Block */: - case 234 /* ModuleBlock */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 265 /* SourceFile */: + case 269 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: return visitNode(cbNode, node.label); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 257 /* CaseClause */: + case 261 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 147 /* Decorator */: + case 148 /* Decorator */: return visitNode(cbNode, node.expression); - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 264 /* EnumMember */: + case 268 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 247 /* MissingDeclaration */: + case 248 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 249 /* JsxElement */: + case 250 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: + case 254 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.attributes); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 267 /* JSDocTypeExpression */: + case 271 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 271 /* JSDocNonNullableType */: + case 275 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 270 /* JSDocNullableType */: + case 274 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 272 /* JSDocOptionalType */: + case 276 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 273 /* JSDocFunctionType */: + case 277 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 274 /* JSDocVariadicType */: + case 278 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 275 /* JSDocComment */: + case 279 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 279 /* JSDocParameterTag */: - case 284 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: + case 289 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -12562,17 +13444,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 280 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 281 /* JSDocTypeTag */: + case 285 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 277 /* JSDocAugmentsTag */: + case 286 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 282 /* JSDocTemplateTag */: + case 282 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.class); + case 287 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 267 /* JSDocTypeExpression */) { + node.typeExpression.kind === 271 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -12580,7 +13462,7 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 285 /* JSDocTypeLiteral */: + case 280 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -12588,7 +13470,7 @@ var ts; } } return; - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -12661,13 +13543,15 @@ var ts; (function (Parser) { // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; + // tslint:enable variable-name var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -12761,6 +13645,7 @@ var ts; } Parser.parseSourceFile = parseSourceFile; function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); // Prime the scanner. nextToken(); @@ -12773,7 +13658,7 @@ var ts; function parseJsonText(fileName, sourceText) { initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); // Set source file so that errors will be reported with this file name - sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */); + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); var result = sourceFile; // Prime the scanner. nextToken(); @@ -12809,7 +13694,16 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ || scriptKind === 6 /* JSON */ ? 65536 /* JavaScriptFile */ : 0 /* None */; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); @@ -12829,7 +13723,11 @@ var ts; sourceText = undefined; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 2097152 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); @@ -12853,13 +13751,14 @@ var ts; for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; + if (jsDoc) { + if (!node.jsDoc) { + node.jsDoc = [jsDoc]; + } + else { + node.jsDoc.push(jsDoc); + } } - node.jsDoc.push(jsDoc); } } return node; @@ -12894,17 +13793,17 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(265 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(269 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + sourceFile.isDeclarationFile = isDeclarationFile; sourceFile.scriptKind = scriptKind; return sourceFile; } @@ -13172,15 +14071,19 @@ var ts; return parseExpected(25 /* SemicolonToken */); } } - // note: this function creates only node function createNode(kind, pos) { nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind) { + var node = createNode(kind); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); } - return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return node; } function createNodeArray(elements, pos, end) { // Since the element list of a node array is typically created by starting with an empty array and @@ -13213,7 +14116,7 @@ var ts; else { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); + var result = createNode(kind); if (kind === 71 /* Identifier */) { result.escapedText = ""; } @@ -13251,8 +14154,8 @@ var ts; function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || @@ -13277,7 +14180,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(144 /* ComputedPropertyName */); + var node = createNode(145 /* ComputedPropertyName */); parseExpected(21 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -13434,6 +14337,10 @@ var ts; nextToken(); return ts.tokenIsIdentifierOrKeyword(token()); } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } function isHeritageClauseExtendsOrImplementsKeyword() { if (token() === 108 /* ImplementsKeyword */ || token() === 85 /* ExtendsKeyword */) { @@ -13590,7 +14497,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 96256 /* ContextFlags */; + var nodeContextFlags = node.flags & 6387712 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -13672,14 +14579,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 152 /* Constructor */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 149 /* PropertyDeclaration */: - case 206 /* SemicolonClassElement */: + case 153 /* Constructor */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 207 /* SemicolonClassElement */: return true; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -13694,8 +14601,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 257 /* CaseClause */: - case 258 /* DefaultClause */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: return true; } } @@ -13704,58 +14611,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 208 /* VariableStatement */: - case 207 /* Block */: - case 211 /* IfStatement */: - case 210 /* ExpressionStatement */: - case 223 /* ThrowStatement */: - case 219 /* ReturnStatement */: - case 221 /* SwitchStatement */: - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 214 /* ForStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 209 /* EmptyStatement */: - case 224 /* TryStatement */: - case 222 /* LabeledStatement */: - case 212 /* DoStatement */: - case 225 /* DebuggerStatement */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 209 /* VariableStatement */: + case 208 /* Block */: + case 212 /* IfStatement */: + case 211 /* ExpressionStatement */: + case 224 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 222 /* SwitchStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 210 /* EmptyStatement */: + case 225 /* TryStatement */: + case 223 /* LabeledStatement */: + case 213 /* DoStatement */: + case 226 /* DebuggerStatement */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 232 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 264 /* EnumMember */; + return node.kind === 268 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 148 /* PropertySignature */: - case 155 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 149 /* PropertySignature */: + case 156 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 226 /* VariableDeclaration */) { + if (node.kind !== 227 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -13776,7 +14683,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 146 /* Parameter */) { + if (node.kind !== 147 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -13891,7 +14798,7 @@ var ts; return createMissingList(); } function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); while (parseOptional(23 /* DotToken */)) { if (token() === 27 /* LessThanToken */) { @@ -13905,7 +14812,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(143 /* QualifiedName */, entity.pos); + var node = createNode(144 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -13942,7 +14849,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(196 /* TemplateExpression */); + var template = createNode(197 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); var list = []; @@ -13954,7 +14861,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(205 /* TemplateSpan */); + var span = createNode(206 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18 /* CloseBraceToken */) { @@ -13997,7 +14904,7 @@ var ts; // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + node.numericLiteralFlags = scanner.getTokenFlags() & 496 /* NumericLiteralFlags */; } nextToken(); finishNode(node); @@ -14005,8 +14912,8 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(159 /* TypeReference */); - node.typeName = parseEntityName(/*allowReservedWords*/ !!(contextFlags & 1048576 /* JSDoc */), ts.Diagnostics.Type_expected); + var node = createNode(160 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } @@ -14014,18 +14921,18 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(158 /* TypePredicate */, lhs.pos); + var node = createNode(159 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(169 /* ThisType */); + var node = createNode(170 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType() { - var result = createNode(268 /* JSDocAllType */); + var result = createNode(272 /* JSDocAllType */); nextToken(); return finishNode(result); } @@ -14048,28 +14955,28 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(269 /* JSDocUnknownType */, pos); + var result = createNode(273 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(270 /* JSDocNullableType */, pos); + var result = createNode(274 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNode(273 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(277 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); - return addJSDocComment(finishNode(result)); + return finishNode(result); } - var node = createNode(159 /* TypeReference */); + var node = createNode(160 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(146 /* Parameter */); + var parameter = createNode(147 /* Parameter */); if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); @@ -14080,17 +14987,17 @@ var ts; function parseJSDocNodeWithType(kind) { var result = createNode(kind); nextToken(); - result.type = parseType(); + result.type = parseNonArrayType(); return finishNode(result); } function parseTypeQuery() { - var node = createNode(162 /* TypeQuery */); + var node = createNode(163 /* TypeQuery */); parseExpected(103 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(145 /* TypeParameter */); + var node = createNode(146 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(85 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -14134,8 +15041,8 @@ var ts; token() === 57 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ true); } - function parseParameter(requireEqualsToken) { - var node = createNode(146 /* Parameter */); + function parseParameter() { + var node = createNodeWithJSDoc(147 /* Parameter */); if (token() === 99 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); @@ -14160,8 +15067,8 @@ var ts; } node.questionToken = parseOptionalToken(55 /* QuestionToken */); node.type = parseParameterType(); - node.initializer = parseInitializer(/*inParameter*/ true, requireEqualsToken); - return addJSDocComment(finishNode(node)); + node.initializer = parseInitializer(); + return finishNode(node); } function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { @@ -14208,7 +15115,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8 /* RequireCompleteParameterList */)); }); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { @@ -14233,19 +15140,16 @@ var ts; parseSemicolon(); } function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156 /* ConstructSignature */) { + var node = createNodeWithJSDoc(kind); + if (kind === 157 /* ConstructSignature */) { parseExpected(94 /* NewKeyword */); } fillSignature(56 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isIndexSignature() { - if (token() !== 21 /* OpenBracketToken */) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); + return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -14297,44 +15201,34 @@ var ts; nextToken(); return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157 /* IndexSignature */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseIndexSignatureDeclaration(node) { + node.kind = 158 /* IndexSignature */; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55 /* QuestionToken */); + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - var method = createNode(150 /* MethodSignature */, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; + node.kind = 151 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); + fillSignature(56 /* ColonToken */, 4 /* Type */, node); } else { - var property = createNode(148 /* PropertySignature */, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + node.kind = 149 /* PropertySignature */; + node.type = parseTypeAnnotation(); if (token() === 58 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. - property.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); } + parseTypeMemberSemicolon(); + return finishNode(node); } function isTypeMemberStart() { // Return true if we have the start of a signature member @@ -14370,24 +15264,24 @@ var ts; } function parseTypeMember() { if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(155 /* CallSignature */); + return parseSignatureMember(156 /* CallSignature */); } if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(156 /* ConstructSignature */); + return parseSignatureMember(157 /* ConstructSignature */); } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); + return parseIndexSignatureDeclaration(node); } - return parsePropertyOrMethodSignature(fullStart, modifiers); + return parsePropertyOrMethodSignature(node); } function nextTokenIsOpenParenOrLessThan() { nextToken(); return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(163 /* TypeLiteral */); + var node = createNode(164 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -14410,14 +15304,14 @@ var ts; return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(145 /* TypeParameter */); + var node = createNode(146 /* TypeParameter */); node.name = parseIdentifier(); parseExpected(92 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(172 /* MappedType */); + var node = createNode(173 /* MappedType */); parseExpected(17 /* OpenBraceToken */); node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); parseExpected(21 /* OpenBracketToken */); @@ -14430,34 +15324,34 @@ var ts; return finishNode(node); } function parseTupleType() { - var node = createNode(165 /* TupleType */); + var node = createNode(166 /* TupleType */); node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(168 /* ParenthesizedType */); + var node = createNode(169 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161 /* ConstructorType */) { + var node = createNodeWithJSDoc(kind); + if (kind === 162 /* ConstructorType */) { parseExpected(94 /* NewKeyword */); } fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); return token() === 23 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(173 /* LiteralType */); + var node = createNode(174 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(192 /* PrefixUnaryExpression */); + unaryMinusExpression = createNode(193 /* PrefixUnaryExpression */); unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } @@ -14480,8 +15374,8 @@ var ts; case 119 /* AnyKeyword */: case 136 /* StringKeyword */: case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: + case 122 /* BooleanKeyword */: case 139 /* UndefinedKeyword */: case 130 /* NeverKeyword */: case 134 /* ObjectKeyword */: @@ -14493,10 +15387,8 @@ var ts; return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 24 /* DotDotDotToken */: - return parseJSDocNodeWithType(274 /* JSDocVariadicType */); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(271 /* JSDocNonNullableType */); + return parseJSDocNodeWithType(275 /* JSDocNonNullableType */); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -14536,6 +15428,7 @@ var ts; case 133 /* NumberKeyword */: case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: + case 140 /* UniqueKeyword */: case 105 /* VoidKeyword */: case 139 /* UndefinedKeyword */: case 95 /* NullKeyword */: @@ -14572,59 +15465,72 @@ var ts; nextToken(); return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } - function parseJSDocPostfixTypeOrHigher() { + function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); - var kind = getKind(token()); - if (!kind) - return type; - nextToken(); - var postfix = createNode(kind, type.pos); - postfix.type = type; - return finishNode(postfix); - function getKind(tokenKind) { - switch (tokenKind) { + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { case 58 /* EqualsToken */: // only parse postfix = inside jsdoc, because it's ambiguous elsewhere - return contextFlags & 1048576 /* JSDoc */ ? 272 /* JSDocOptionalType */ : undefined; + if (!(contextFlags & 1048576 /* JSDoc */)) { + return type; + } + type = createJSDocPostfixType(276 /* JSDocOptionalType */, type); + break; case 51 /* ExclamationToken */: - return 271 /* JSDocNonNullableType */; + type = createJSDocPostfixType(275 /* JSDocNonNullableType */, type); + break; case 55 /* QuestionToken */: - return 270 /* JSDocNullableType */; - } - } - } - function parseArrayTypeOrHigher() { - var type = parseJSDocPostfixTypeOrHigher(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21 /* OpenBracketToken */)) { - if (isStartOfType()) { - var node = createNode(171 /* IndexedAccessType */, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); - } - else { - var node = createNode(164 /* ArrayType */, type.pos); - node.elementType = type; - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); + type = createJSDocPostfixType(274 /* JSDocNullableType */, type); + break; + case 21 /* OpenBracketToken */: + parseExpected(21 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(172 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(165 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; } } return type; } + function createJSDocPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } function parseTypeOperator(operator) { - var node = createNode(170 /* TypeOperator */); + var node = createNode(171 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseTypeOperatorOrHigher() { - switch (token()) { + var operator = token(); + switch (operator) { case 127 /* KeyOfKeyword */: - return parseTypeOperator(127 /* KeyOfKeyword */); + case 140 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 24 /* DotDotDotToken */: { + var result = createNode(278 /* JSDocVariadicType */); + nextToken(); + result.type = parsePostfixTypeOrHigher(); + return finishNode(result); + } } - return parseArrayTypeOrHigher(); + return parsePostfixTypeOrHigher(); } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { parseOptional(operator); @@ -14641,10 +15547,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(168 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(167 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); } function isStartOfFunctionType() { if (token() === 27 /* LessThanToken */) { @@ -14701,7 +15607,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(158 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(159 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -14724,10 +15630,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160 /* FunctionType */); + return parseFunctionOrConstructorType(161 /* FunctionType */); } if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(161 /* ConstructorType */); + return parseFunctionOrConstructorType(162 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -14821,33 +15727,8 @@ var ts; } return expr; } - function parseInitializer(inParameter, requireEqualsToken) { - if (token() !== 58 /* EqualsToken */) { - // It's not uncommon during typing for the user to miss writing the '=' token. Check if - // there is no newline after the last token and if we're on an expression. If so, parse - // this as an equals-value clause with a missing equals. - // NOTE: There are two places where we allow equals-value clauses. The first is in a - // variable declarator. The second is with a parameter. For variable declarators - // it's more likely that a { would be a allowed (as an object literal). While this - // is also allowed for parameters, the risk is that we consume the { as an object - // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17 /* OpenBraceToken */) || !isStartOfExpression()) { - // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - - // do not try to parse initializer - return undefined; - } - if (inParameter && requireEqualsToken) { - // = is required when speculatively parsing arrow function parameters, - // so return a fake initializer as a signal that the equals token was missing - var result = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics._0_expected, "="); - result.escapedText = "= not found"; - return result; - } - } - // Initializer[In, Yield] : - // = AssignmentExpression[?In, ?Yield] - parseExpected(58 /* EqualsToken */); - return parseAssignmentExpressionOrHigher(); + function parseInitializer() { + return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -14937,7 +15818,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(197 /* YieldExpression */); + var node = createNode(198 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -14959,13 +15840,13 @@ var ts; ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(187 /* ArrowFunction */, asyncModifier.pos); + node = createNode(188 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(187 /* ArrowFunction */, identifier.pos); + node = createNode(188 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(146 /* Parameter */, identifier.pos); + var parameter = createNode(147 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -14998,7 +15879,7 @@ var ts; arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); + return finishNode(arrowFunction); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -15059,22 +15940,38 @@ var ts; if (second === 24 /* DotDotDotToken */) { return 1 /* True */; } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. - // Note: we could be a little more lenient and allow - // "(public" or "(private". These would not ever actually be allowed, - // but we could provide a good error message instead of bailing out. if (!isIdentifier()) { return 0 /* False */; } - // If we have something like "(a:", then we must have a - // type-annotated parameter in an arrow function expression. - if (nextToken() === 56 /* ColonToken */) { - return 1 /* True */; + switch (nextToken()) { + case 56 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 55 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 26 /* CommaToken */: + case 58 /* EqualsToken */: + case 20 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; } - // This *could* be a parenthesized arrow function. - // Return Unknown to let the caller know. - return 2 /* Unknown */; + // It is definitely not an arrow function + return 0 /* False */; } else { ts.Debug.assert(first === 27 /* LessThanToken */); @@ -15145,7 +16042,7 @@ var ts; return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187 /* ArrowFunction */); + var node = createNodeWithJSDoc(188 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -15168,8 +16065,7 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && ((token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) || - ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { + if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } @@ -15212,7 +16108,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(195 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(196 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -15225,7 +16121,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 142 /* OfKeyword */; + return t === 92 /* InKeyword */ || t === 143 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -15333,39 +16229,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194 /* BinaryExpression */, left.pos); + var node = createNode(195 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(202 /* AsExpression */, left.pos); + var node = createNode(203 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(192 /* PrefixUnaryExpression */); + var node = createNode(193 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(188 /* DeleteExpression */); + var node = createNode(189 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(189 /* TypeOfExpression */); + var node = createNode(190 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(190 /* VoidExpression */); + var node = createNode(191 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -15381,7 +16277,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(191 /* AwaitExpression */); + var node = createNode(192 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -15424,7 +16320,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 185 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -15521,20 +16417,20 @@ var ts; */ function parseUpdateExpression() { if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(192 /* PrefixUnaryExpression */); + var node = createNode(193 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(194 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -15648,7 +16544,7 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(179 /* PropertyAccessExpression */, expression.pos); + var node = createNode(180 /* PropertyAccessExpression */, expression.pos); node.expression = expression; parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -15670,21 +16566,28 @@ var ts; return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 251 /* JsxOpeningElement */) { - var node = createNode(249 /* JsxElement */, opening.pos); + if (opening.kind === 252 /* JsxOpeningElement */) { + var node = createNode(250 /* JsxElement */, opening.pos); node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); + node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } + else if (opening.kind === 255 /* JsxOpeningFragment */) { + var node = createNode(254 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } else { - ts.Debug.assert(opening.kind === 250 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 251 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -15696,10 +16599,10 @@ var ts; // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. if (inExpressionContext && token() === 27 /* LessThanToken */) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194 /* BinaryExpression */, result.pos); + var badNode = createNode(195 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -15711,7 +16614,7 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */, scanner.getStartPos()); + var node = createNode(10 /* JsxText */); node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); @@ -15724,11 +16627,11 @@ var ts; case 17 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); } ts.Debug.fail("Unknown JSX child kind " + token()); } - function parseJsxChildren(openingTagName) { + function parseJsxChildren(openingTag) { var list = []; var listPos = getNodePos(); var saveParsingContext = parsingContext; @@ -15742,7 +16645,13 @@ var ts; else if (token() === 1 /* EndOfFileToken */) { // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + var openingTagName = openingTag.tagName; + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + } break; } else if (token() === 7 /* ConflictMarkerTrivia */) { @@ -15757,13 +16666,18 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(254 /* JsxAttributes */); + var jsxAttributes = createNode(258 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); parseExpected(27 /* LessThanToken */); + if (token() === 29 /* GreaterThanToken */) { + parseExpected(29 /* GreaterThanToken */); + var node_1 = createNode(255 /* JsxOpeningFragment */, fullStart); + return finishNode(node_1); + } var tagName = parseJsxElementName(); var attributes = parseJsxAttributes(); var node; @@ -15771,7 +16685,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(251 /* JsxOpeningElement */, fullStart); + node = createNode(252 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -15783,7 +16697,7 @@ var ts; parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(250 /* JsxSelfClosingElement */, fullStart); + node = createNode(251 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -15799,7 +16713,7 @@ var ts; var expression = token() === 99 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(180 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -15807,7 +16721,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(256 /* JsxExpression */); + var node = createNode(260 /* JsxExpression */); parseExpected(17 /* OpenBraceToken */); if (token() !== 18 /* CloseBraceToken */) { node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); @@ -15827,7 +16741,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(253 /* JsxAttribute */); + var node = createNode(257 /* JsxAttribute */); node.name = parseIdentifierName(); if (token() === 58 /* EqualsToken */) { switch (scanJsxAttributeValue()) { @@ -15842,7 +16756,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(255 /* JsxSpreadAttribute */); + var node = createNode(259 /* JsxSpreadAttribute */); parseExpected(17 /* OpenBraceToken */); parseExpected(24 /* DotDotDotToken */); node.expression = parseExpression(); @@ -15850,7 +16764,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252 /* JsxClosingElement */); + var node = createNode(253 /* JsxClosingElement */); parseExpected(28 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -15862,8 +16776,24 @@ var ts; } return finishNode(node); } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(256 /* JsxClosingFragment */); + parseExpected(28 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + var unexpectedTagName = parseJsxElementName(); + parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } function parseTypeAssertion() { - var node = createNode(184 /* TypeAssertionExpression */); + var node = createNode(185 /* TypeAssertionExpression */); parseExpected(27 /* LessThanToken */); node.type = parseType(); parseExpected(29 /* GreaterThanToken */); @@ -15874,7 +16804,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(180 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -15882,14 +16812,14 @@ var ts; } if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(203 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(204 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(180 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(181 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. @@ -15905,7 +16835,7 @@ var ts; continue; } if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { - var tagExpression = createNode(183 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(184 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -15928,7 +16858,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(181 /* CallExpression */, expression.pos); + var callExpr = createNode(182 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -15936,7 +16866,7 @@ var ts; continue; } else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(181 /* CallExpression */, expression.pos); + var callExpr = createNode(182 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -16046,28 +16976,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(185 /* ParenthesizedExpression */); + var node = createNodeWithJSDoc(186 /* ParenthesizedExpression */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseSpreadElement() { - var node = createNode(198 /* SpreadElement */); + var node = createNode(199 /* SpreadElement */); parseExpected(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(200 /* OmittedExpression */) : + token() === 26 /* CommaToken */ ? createNode(201 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(177 /* ArrayLiteralExpression */); + var node = createNode(178 /* ArrayLiteralExpression */); parseExpected(21 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -16076,36 +17006,28 @@ var ts; parseExpected(22 /* CloseBracketToken */); return finishNode(node); } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(153 /* GetAccessor */, fullStart, decorators, modifiers); + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(24 /* DotDotDotToken */)) { + node.kind = 267 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } - else if (parseContextualModifier(135 /* SetKeyword */)) { - return parseAccessorDeclaration(154 /* SetAccessor */, fullStart, decorators, modifiers); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 154 /* GetAccessor */); } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - if (dotDotDotToken) { - var spreadElement = createNode(263 /* SpreadAssignment */, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 155 /* SetAccessor */); } var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); + node.name = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production @@ -16114,28 +17036,22 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262 /* ShorthandPropertyAssignment */, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; + node.kind = 266 /* ShorthandPropertyAssignment */; var equalsToken = parseOptionalToken(58 /* EqualsToken */); if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(261 /* PropertyAssignment */, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; + node.kind = 265 /* PropertyAssignment */; parseExpected(56 /* ColonToken */); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } + return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(178 /* ObjectLiteralExpression */); + var node = createNode(179 /* ObjectLiteralExpression */); parseExpected(17 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -16154,7 +17070,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNode(186 /* FunctionExpression */); + var node = createNodeWithJSDoc(187 /* FunctionExpression */); node.modifiers = parseModifiers(); parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); @@ -16170,7 +17086,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; @@ -16179,12 +17095,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(94 /* NewKeyword */); if (parseOptional(23 /* DotToken */)) { - var node_1 = createNode(204 /* MetaProperty */, fullStart); - node_1.keywordToken = 94 /* NewKeyword */; - node_1.name = parseIdentifierName(); - return finishNode(node_1); + var node_2 = createNode(205 /* MetaProperty */, fullStart); + node_2.keywordToken = 94 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); } - var node = createNode(182 /* NewExpression */, fullStart); + var node = createNode(183 /* NewExpression */, fullStart); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); if (node.typeArguments || token() === 19 /* OpenParenToken */) { @@ -16194,7 +17110,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207 /* Block */); + var node = createNode(208 /* Block */); if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -16227,12 +17143,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(209 /* EmptyStatement */); + var node = createNode(210 /* EmptyStatement */); parseExpected(25 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(211 /* IfStatement */); + var node = createNode(212 /* IfStatement */); parseExpected(90 /* IfKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -16242,7 +17158,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(212 /* DoStatement */); + var node = createNode(213 /* DoStatement */); parseExpected(81 /* DoKeyword */); node.statement = parseStatement(); parseExpected(106 /* WhileKeyword */); @@ -16257,7 +17173,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(213 /* WhileStatement */); + var node = createNode(214 /* WhileStatement */); parseExpected(106 /* WhileKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -16280,8 +17196,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142 /* OfKeyword */) : parseOptional(142 /* OfKeyword */)) { - var forOfStatement = createNode(216 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(143 /* OfKeyword */) : parseOptional(143 /* OfKeyword */)) { + var forOfStatement = createNode(217 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -16289,14 +17205,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(215 /* ForInStatement */, pos); + var forInStatement = createNode(216 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(214 /* ForStatement */, pos); + var forStatement = createNode(215 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(25 /* SemicolonToken */); if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { @@ -16314,7 +17230,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 218 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 219 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -16322,7 +17238,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(219 /* ReturnStatement */); + var node = createNode(220 /* ReturnStatement */); parseExpected(96 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -16331,16 +17247,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(220 /* WithStatement */); + var node = createNode(221 /* WithStatement */); parseExpected(107 /* WithKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - node.statement = parseStatement(); + node.statement = doInsideOfContext(4194304 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(257 /* CaseClause */); + var node = createNode(261 /* CaseClause */); parseExpected(73 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(56 /* ColonToken */); @@ -16348,7 +17264,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(258 /* DefaultClause */); + var node = createNode(262 /* DefaultClause */); parseExpected(79 /* DefaultKeyword */); parseExpected(56 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -16358,12 +17274,12 @@ var ts; return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(221 /* SwitchStatement */); + var node = createNode(222 /* SwitchStatement */); parseExpected(98 /* SwitchKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(235 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(236 /* CaseBlock */); parseExpected(17 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(18 /* CloseBraceToken */); @@ -16378,7 +17294,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(223 /* ThrowStatement */); + var node = createNode(224 /* ThrowStatement */); parseExpected(100 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -16386,7 +17302,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(224 /* TryStatement */); + var node = createNode(225 /* TryStatement */); parseExpected(102 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -16399,7 +17315,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(260 /* CatchClause */); + var result = createNode(264 /* CatchClause */); parseExpected(74 /* CatchKeyword */); if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -16413,7 +17329,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(225 /* DebuggerStatement */); + var node = createNode(226 /* DebuggerStatement */); parseExpected(78 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -16422,20 +17338,19 @@ var ts; // Avoiding having to do the lookahead for a labeled statement by just trying to parse // out an expression, seeing if it is identifier and then seeing if it is followed by // a colon. - var fullStart = scanner.getStartPos(); + var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - var labeledStatement = createNode(222 /* LabeledStatement */, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); + node.kind = 223 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); } else { - var expressionStatement = createNode(210 /* ExpressionStatement */, fullStart); - expressionStatement.expression = expression; + node.kind = 211 /* ExpressionStatement */; + node.expression = expression; parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); } + return finishNode(node); } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); @@ -16503,7 +17418,7 @@ var ts; return false; } continue; - case 141 /* GlobalKeyword */: + case 142 /* GlobalKeyword */: nextToken(); return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; case 91 /* ImportKeyword */: @@ -16567,7 +17482,7 @@ var ts; case 128 /* ModuleKeyword */: case 129 /* NamespaceKeyword */: case 138 /* TypeKeyword */: - case 141 /* GlobalKeyword */: + case 142 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 114 /* PublicKeyword */: @@ -16598,16 +17513,16 @@ var ts; case 17 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); case 104 /* VarKeyword */: - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseVariableStatement(createNodeWithJSDoc(227 /* VariableDeclaration */)); case 110 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseVariableStatement(createNodeWithJSDoc(227 /* VariableDeclaration */)); } break; case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseFunctionDeclaration(createNodeWithJSDoc(229 /* FunctionDeclaration */)); case 75 /* ClassKeyword */: - return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseClassDeclaration(createNodeWithJSDoc(230 /* ClassDeclaration */)); case 90 /* IfKeyword */: return parseIfStatement(); case 81 /* DoKeyword */: @@ -16617,9 +17532,9 @@ var ts; case 88 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(217 /* ContinueStatement */); + return parseBreakOrContinueStatement(218 /* ContinueStatement */); case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(218 /* BreakStatement */); + return parseBreakOrContinueStatement(219 /* BreakStatement */); case 96 /* ReturnKeyword */: return parseReturnStatement(); case 107 /* WithKeyword */: @@ -16653,7 +17568,7 @@ var ts; case 117 /* AbstractKeyword */: case 115 /* StaticKeyword */: case 131 /* ReadonlyKeyword */: - case 141 /* GlobalKeyword */: + case 142 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -16661,51 +17576,66 @@ var ts; } return parseExpressionOrLabeledStatement(); } + function isDeclareModifier(modifier) { + return modifier.kind === 124 /* DeclareKeyword */; + } function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 2097152 /* Ambient */; + } + return doInsideOfContext(2097152 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { switch (token()) { case 104 /* VarKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: - return parseVariableStatement(fullStart, decorators, modifiers); + return parseVariableStatement(node); case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(fullStart, decorators, modifiers); + return parseFunctionDeclaration(node); case 75 /* ClassKeyword */: - return parseClassDeclaration(fullStart, decorators, modifiers); + return parseClassDeclaration(node); case 109 /* InterfaceKeyword */: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); + return parseInterfaceDeclaration(node); case 138 /* TypeKeyword */: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + return parseTypeAliasDeclaration(node); case 83 /* EnumKeyword */: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141 /* GlobalKeyword */: + return parseEnumDeclaration(node); + case 142 /* GlobalKeyword */: case 128 /* ModuleKeyword */: case 129 /* NamespaceKeyword */: - return parseModuleDeclaration(fullStart, decorators, modifiers); + return parseModuleDeclaration(node); case 91 /* ImportKeyword */: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + return parseImportDeclarationOrImportEqualsDeclaration(node); case 84 /* ExportKeyword */: nextToken(); switch (token()) { case 79 /* DefaultKeyword */: case 58 /* EqualsToken */: - return parseExportAssignment(fullStart, decorators, modifiers); + return parseExportAssignment(node); case 118 /* AsKeyword */: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + return parseNamespaceExportDeclaration(node); default: - return parseExportDeclaration(fullStart, decorators, modifiers); + return parseExportDeclaration(node); } default: - if (decorators || modifiers) { + if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(247 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); + var missing = createMissingNode(248 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); } } } @@ -16723,16 +17653,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token() === 26 /* CommaToken */) { - return createNode(200 /* OmittedExpression */); + return createNode(201 /* OmittedExpression */); } - var node = createNode(176 /* BindingElement */); + var node = createNode(177 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); - node.initializer = parseInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(176 /* BindingElement */); + var node = createNode(177 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -16744,18 +17674,18 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(174 /* ObjectBindingPattern */); + var node = createNode(175 /* ObjectBindingPattern */); parseExpected(17 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(175 /* ArrayBindingPattern */); + var node = createNode(176 /* ArrayBindingPattern */); parseExpected(21 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(22 /* CloseBracketToken */); @@ -16773,17 +17703,24 @@ var ts; } return parseIdentifier(); } - function parseVariableDeclaration() { - var node = createNode(226 /* VariableDeclaration */); + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(227 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 71 /* Identifier */ && + token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227 /* VariableDeclarationList */); + var node = createNode(228 /* VariableDeclarationList */); switch (token()) { case 104 /* VarKeyword */: break; @@ -16806,13 +17743,13 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 142 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 143 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -16820,18 +17757,14 @@ var ts; function canFollowContextualOfKeyword() { return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208 /* VariableStatement */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseVariableStatement(node) { + node.kind = 209 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228 /* FunctionDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseFunctionDeclaration(node) { + node.kind = 229 /* FunctionDeclaration */; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); @@ -16839,37 +17772,30 @@ var ts; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152 /* Constructor */, pos); - node.decorators = decorators; - node.modifiers = modifiers; + function parseConstructorDeclaration(node) { + node.kind = 153 /* Constructor */; parseExpected(123 /* ConstructorKeyword */); fillSignature(56 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151 /* MethodDeclaration */, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 152 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; - var isAsync = ts.hasModifier(method, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149 /* PropertyDeclaration */, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 150 /* PropertyDeclaration */; + if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); // For instance properties specifically, since they are evaluated inside the constructor, // we do *not * want to parse yield expressions, so we specifically turn the yield context // off. The grammar would look something like this: @@ -16879,36 +17805,29 @@ var ts; // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = ts.hasModifier(property, 32 /* Static */) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); parseSemicolon(); - return addJSDocComment(finishNode(property)); + return finishNode(node); } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + function parsePropertyOrMethodDeclaration(node) { var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var name = parsePropertyName(); + node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } + return parsePropertyDeclaration(node); } - function parseNonParameterInitializer() { - return parseInitializer(/*inParameter*/ false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseAccessorDeclaration(node, kind) { + node.kind = kind; node.name = parsePropertyName(); fillSignature(56 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -16988,7 +17907,7 @@ var ts; if (!parseOptional(57 /* AtToken */)) { break; } - var decorator = createNode(147 /* Decorator */, decoratorStart); + var decorator = createNode(148 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -17038,22 +17957,24 @@ var ts; } function parseClassElement() { if (token() === 25 /* SemicolonToken */) { - var result = createNode(206 /* SemicolonClassElement */); + var result = createNode(207 /* SemicolonClassElement */); nextToken(); return finishNode(result); } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 154 /* GetAccessor */); + } + if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 155 /* SetAccessor */); } if (token() === 123 /* ConstructorKeyword */) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); + return parseConstructorDeclaration(node); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + return parseIndexSignatureDeclaration(node); } // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name @@ -17062,29 +17983,24 @@ var ts; token() === 8 /* NumericLiteral */ || token() === 39 /* AsteriskToken */ || token() === 21 /* OpenBracketToken */) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + return parsePropertyOrMethodDeclaration(node); } - if (decorators || modifiers) { + if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - var name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); + node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression( - /*fullStart*/ scanner.getStartPos(), - /*decorators*/ undefined, - /*modifiers*/ undefined, 199 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 200 /* ClassExpression */); } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229 /* ClassDeclaration */); + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 230 /* ClassDeclaration */); } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; parseExpected(75 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -17098,7 +18014,7 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseNameOfClassDeclarationOrExpression() { // implements is a future reserved word so @@ -17124,7 +18040,7 @@ var ts; function parseHeritageClause() { var tok = token(); if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(259 /* HeritageClause */); + var node = createNode(263 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -17133,56 +18049,53 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(201 /* ExpressionWithTypeArguments */); + var node = createNode(202 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } + node.typeArguments = tryParseTypeArguments(); return finishNode(node); } + function tryParseTypeArguments() { + return token() === 27 /* LessThanToken */ + ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + : undefined; + } function isHeritageClause() { return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230 /* InterfaceDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseInterfaceDeclaration(node) { + node.kind = 231 /* InterfaceDeclaration */; parseExpected(109 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231 /* TypeAliasDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseTypeAliasDeclaration(node) { + node.kind = 232 /* TypeAliasDeclaration */; parseExpected(138 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(58 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(264 /* EnumMember */, scanner.getStartPos()); + var node = createNodeWithJSDoc(268 /* EnumMember */); node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232 /* EnumDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseEnumDeclaration(node) { + node.kind = 233 /* EnumDeclaration */; parseExpected(83 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(17 /* OpenBraceToken */)) { @@ -17192,10 +18105,10 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseModuleBlock() { - var node = createNode(234 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(235 /* ModuleBlock */); if (parseExpected(17 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(18 /* CloseBraceToken */); @@ -17205,25 +18118,21 @@ var ts; } return finishNode(node); } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 234 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; - node.decorators = decorators; - node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(23 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141 /* GlobalKeyword */) { + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 234 /* ModuleDeclaration */; + if (token() === 142 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -17240,11 +18149,11 @@ var ts; } return finishNode(node); } - function parseModuleDeclaration(fullStart, decorators, modifiers) { + function parseModuleDeclaration(node) { var flags = 0; - if (token() === 141 /* GlobalKeyword */) { + if (token() === 142 /* GlobalKeyword */) { // global augmentation - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } else if (parseOptional(129 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; @@ -17252,10 +18161,10 @@ var ts; else { parseExpected(128 /* ModuleKeyword */); if (token() === 9 /* StringLiteral */) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { return token() === 132 /* RequireKeyword */ && @@ -17267,52 +18176,46 @@ var ts; function nextTokenIsSlash() { return nextToken() === 41 /* SlashToken */; } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236 /* NamespaceExportDeclaration */, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; + function parseNamespaceExportDeclaration(node) { + node.kind = 237 /* NamespaceExportDeclaration */; parseExpected(118 /* AsKeyword */); parseExpected(129 /* NamespaceKeyword */); - exportDeclaration.name = parseIdentifier(); + node.name = parseIdentifier(); parseSemicolon(); - return finishNode(exportDeclaration); + return finishNode(node); } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + function parseImportDeclarationOrImportEqualsDeclaration(node) { parseExpected(91 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 140 /* FromKeyword */) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + if (token() !== 26 /* CommaToken */ && token() !== 141 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); } } // Import statement - var importDeclaration = createNode(238 /* ImportDeclaration */, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; + node.kind = 239 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id token() === 39 /* AsteriskToken */ || // import * token() === 17 /* OpenBraceToken */) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140 /* FromKeyword */); + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(141 /* FromKeyword */); } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); + node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); - return finishNode(importDeclaration); + return finishNode(node); } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237 /* ImportEqualsDeclaration */, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 238 /* ImportEqualsDeclaration */; + node.name = identifier; parseExpected(58 /* EqualsToken */); - importEqualsDeclaration.moduleReference = parseModuleReference(); + node.moduleReference = parseModuleReference(); parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); + return finishNode(node); } function parseImportClause(identifier, fullStart) { // ImportClause: @@ -17321,7 +18224,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(239 /* ImportClause */, fullStart); + var importClause = createNode(240 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -17331,7 +18234,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(241 /* NamedImports */); + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(242 /* NamedImports */); } return finishNode(importClause); } @@ -17341,7 +18244,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(248 /* ExternalModuleReference */); + var node = createNode(249 /* ExternalModuleReference */); parseExpected(132 /* RequireKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -17364,7 +18267,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(240 /* NamespaceImport */); + var namespaceImport = createNode(241 /* NamespaceImport */); parseExpected(39 /* AsteriskToken */); parseExpected(118 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -17379,14 +18282,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 241 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 242 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(246 /* ExportSpecifier */); + return parseImportOrExportSpecifier(247 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(242 /* ImportSpecifier */); + return parseImportOrExportSpecifier(243 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -17411,37 +18314,33 @@ var ts; else { node.name = identifierName; } - if (kind === 242 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 243 /* ImportSpecifier */ && checkIdentifierIsKeyword) { // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244 /* ExportDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportDeclaration(node) { + node.kind = 245 /* ExportDeclaration */; if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(140 /* FromKeyword */); + parseExpected(141 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(245 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(246 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 140 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(140 /* FromKeyword */); + if (token() === 141 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(141 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } parseSemicolon(); return finishNode(node); } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243 /* ExportAssignment */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportAssignment(node) { + node.kind = 244 /* ExportAssignment */; if (parseOptional(58 /* EqualsToken */)) { node.isExportEquals = true; } @@ -17520,7 +18419,7 @@ var ts; var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment); if (checkJsDirectiveMatchResult) { checkJsDirective = { - enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", /*ignoreCase*/ true) === 0 /* EqualTo */, + enabled: ts.equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"), end: range.end, pos: range.pos }; @@ -17536,10 +18435,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */ - || node.kind === 238 /* ImportDeclaration */ - || node.kind === 243 /* ExportAssignment */ - || node.kind === 244 /* ExportDeclaration */ + || node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 249 /* ExternalModuleReference */ + || node.kind === 239 /* ImportDeclaration */ + || node.kind === 244 /* ExportAssignment */ + || node.kind === 245 /* ExportDeclaration */ ? node : undefined; }); @@ -17580,8 +18479,8 @@ var ts; var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = createSourceFile("file.js", 5 /* Latest */, 1 /* JS */); + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -17590,19 +18489,20 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression(requireBraces) { - var result = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); - if (!parseExpected(17 /* OpenBraceToken */) && requireBraces) { - return undefined; - } + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(271 /* JSDocTypeExpression */, scanner.getTokenPos()); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); - parseExpected(18 /* CloseBraceToken */); + if (!mayOmitBraces || hasBrace) { + parseExpected(18 /* CloseBraceToken */); + } fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -17618,7 +18518,7 @@ var ts; if (comment) { comment.parent = parent; } - if (ts.isInJavaScriptFile(parent)) { + if (contextFlags & 65536 /* JavaScriptFile */) { if (!sourceFile.jsDocDiagnostics) { sourceFile.jsDocDiagnostics = []; } @@ -17775,7 +18675,7 @@ var ts; content.charCodeAt(start + 3) !== 42 /* asterisk */; } function createJSDocComment() { - var result = createNode(275 /* JSDocComment */, start); + var result = createNode(279 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -17799,6 +18699,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -17898,7 +18799,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(276 /* JSDocTag */, atToken.pos); + var result = createNode(281 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -17936,7 +18837,7 @@ var ts; switch (node.kind) { case 134 /* ObjectKeyword */: return true; - case 164 /* ArrayType */: + case 165 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; @@ -17952,8 +18853,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Parameter */ ? - createNode(279 /* JSDocParameterTag */, atToken.pos) : - createNode(284 /* JSDocPropertyTag */, atToken.pos); + createNode(284 /* JSDocParameterTag */, atToken.pos) : + createNode(289 /* JSDocPropertyTag */, atToken.pos); var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -17969,7 +18870,7 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(271 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); @@ -17981,9 +18882,9 @@ var ts; children.push(child); } if (children) { - jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 164 /* ArrayType */) { + if (typeExpression.type.kind === 165 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -17992,35 +18893,55 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 280 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 285 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(280 /* JSDocReturnTag */, atToken.pos); + var result = createNode(285 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 281 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 286 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(281 /* JSDocTypeTag */, atToken.pos); + var result = createNode(286 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); - var result = createNode(277 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(282 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = typeExpression; + result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(17 /* OpenBraceToken */); + var node = createNode(202 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(/*createIfMissing*/ true); + while (parseOptional(23 /* DotToken */)) { + var prop = createNode(180 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } function parseClassTag(atToken, tagName) { - var tag = createNode(278 /* JSDocClassTag */, atToken.pos); + var tag = createNode(283 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); @@ -18028,7 +18949,7 @@ var ts; function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(283 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(288 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); @@ -18053,9 +18974,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 281 /* JSDocTypeTag */) { + if (child.kind === 286 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -18071,10 +18992,10 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 165 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -18084,7 +19005,7 @@ var ts; var pos = scanner.getTokenPos(); var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(233 /* ModuleDeclaration */, pos); + var jsDocNamespaceNode = createNode(234 /* ModuleDeclaration */, pos); jsDocNamespaceNode.flags |= flags; jsDocNamespaceNode.name = typeNameOrNamespaceName; jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); @@ -18117,7 +19038,7 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 279 /* JSDocParameterTag */ && + if (child && child.kind === 284 /* JSDocParameterTag */ && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -18145,7 +19066,7 @@ var ts; } function tryParseChildTag(target) { ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getStartPos()); + var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -18167,7 +19088,7 @@ var ts; return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocTemplateTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' @@ -18180,7 +19101,7 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145 /* TypeParameter */, name.pos); + var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -18192,7 +19113,7 @@ var ts; break; } } - var result = createNode(282 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(287 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -18716,6 +19637,9 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } })(ts || (ts = {})); /// /// @@ -18729,48 +19653,63 @@ var ts; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 231 /* TypeAliasDeclaration */) { - return 0 /* NonInstantiated */; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2 /* ConstEnumOnly */; - } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { - return 0 /* NonInstantiated */; - } - else if (node.kind === 234 /* ModuleBlock */) { - var state_1 = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return false; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state_1 = 2 /* ConstEnumOnly */; - return false; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state_1 = 1 /* Instantiated */; - return true; + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 233 /* EnumDeclaration */: + if (ts.isConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 235 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 234 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 71 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; } - }); - return state_1; - } - else if (node.kind === 233 /* ModuleDeclaration */) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1 /* Instantiated */; - } - else if (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace) { - return 0 /* NonInstantiated */; - } - else { - return 1 /* Instantiated */; } + return 1 /* Instantiated */; } - ts.getModuleInstanceState = getModuleInstanceState; var ContainerFlags; (function (ContainerFlags) { // The current node is not a container, and no container manipulation should happen before @@ -18830,13 +19769,21 @@ var ts; // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; - var Symbol; + var Symbol; // tslint:disable-line variable-name var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; // state used to aggregate transform flags during bind. var subtreeTransformFlags = 0 /* None */; var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -18872,7 +19819,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -18902,7 +19849,7 @@ var ts; if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233 /* ModuleDeclaration */)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 234 /* ModuleDeclaration */)) { // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } @@ -18911,58 +19858,59 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { + if (node.kind === 244 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } return ts.getEscapedTextOfIdentifierOrLiteral(name); } switch (node.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: return "__constructor" /* Constructor */; - case 160 /* FunctionType */: - case 155 /* CallSignature */: + case 161 /* FunctionType */: + case 156 /* CallSignature */: return "__call" /* Call */; - case 161 /* ConstructorType */: - case 156 /* ConstructSignature */: + case 162 /* ConstructorType */: + case 157 /* ConstructSignature */: return "__new" /* New */; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return "__index" /* Index */; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); - case 273 /* JSDocFunctionType */: + case 277 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 146 /* Parameter */: + case 147 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 273 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } @@ -19012,7 +19960,7 @@ var ts; // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. symbol = symbolTable.get(name); - if (includes & 788448 /* Classifiable */) { + if (includes & 2885600 /* Classifiable */) { classifiableNames.set(name, true); } if (!symbol) { @@ -19052,15 +20000,15 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 /* ExportAssignment */ && !node.isExportEquals))) { + (isDefaultExport || (node.kind === 244 /* ExportAssignment */ && !node.isExportEquals))) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -19072,7 +20020,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 246 /* ExportSpecifier */ || (node.kind === 237 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 247 /* ExportSpecifier */ || (node.kind === 238 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -19094,9 +20042,9 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 283 /* JSDocTypedefTag */) + if (node.kind === 288 /* JSDocTypedefTag */) ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - var isJSDocTypedefInJSDocNamespace = node.kind === 283 /* JSDocTypedefTag */ && + var isJSDocTypedefInJSDocNamespace = node.kind === 288 /* JSDocTypedefTag */ && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; @@ -19159,16 +20107,15 @@ var ts; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); // A non-async 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) { - currentReturnTarget = createBranchLabel(); - } - else { + if (!isIIFE) { currentFlow = { flags: 2 /* Start */ }; if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } - currentReturnTarget = undefined; } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 153 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -19181,14 +20128,17 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { node.flags |= emitFlags; } - if (isIIFE) { + if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 153 /* Constructor */) { + node.returnFlowNode = currentFlow; + } } - else { + if (!isIIFE) { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; @@ -19271,70 +20221,70 @@ var ts; return; } switch (node.kind) { - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: bindWhileStatement(node); break; - case 212 /* DoStatement */: + case 213 /* DoStatement */: bindDoStatement(node); break; - case 214 /* ForStatement */: + case 215 /* ForStatement */: bindForStatement(node); break; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 211 /* IfStatement */: + case 212 /* IfStatement */: bindIfStatement(node); break; - case 219 /* ReturnStatement */: - case 223 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 224 /* TryStatement */: + case 225 /* TryStatement */: bindTryStatement(node); break; - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: bindSwitchStatement(node); break; - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: bindCaseBlock(node); break; - case 257 /* CaseClause */: + case 261 /* CaseClause */: bindCaseClause(node); break; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: bindLabeledStatement(node); break; - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 181 /* CallExpression */: + case 182 /* CallExpression */: bindCallExpressionFlow(node); break; - case 275 /* JSDocComment */: + case 279 /* JSDocComment */: bindJSDocComment(node); break; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: bindJSDocTypedefTag(node); break; default: @@ -19346,15 +20296,15 @@ var ts; switch (expr.kind) { case 71 /* Identifier */: case 99 /* ThisKeyword */: - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return isNarrowableReference(expr); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return hasNarrowableArgument(expr); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); } return false; @@ -19363,7 +20313,7 @@ var ts; return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || - expr.kind === 179 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + expr.kind === 180 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -19374,14 +20324,14 @@ var ts; } } } - if (expr.expression.kind === 179 /* PropertyAccessExpression */ && + if (expr.expression.kind === 180 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -19402,9 +20352,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 58 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -19482,33 +20432,33 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 211 /* IfStatement */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: + case 212 /* IfStatement */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: return parent.expression === node; - case 214 /* ForStatement */: - case 195 /* ConditionalExpression */: + case 215 /* ForStatement */: + case 196 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 185 /* ParenthesizedExpression */) { + if (node.kind === 186 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 192 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 193 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 194 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + return node.kind === 195 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 54 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 /* ParenthesizedExpression */ || - node.parent.kind === 192 /* PrefixUnaryExpression */ && + while (node.parent.kind === 186 /* ParenthesizedExpression */ || + node.parent.kind === 193 /* PrefixUnaryExpression */ && node.parent.operator === 51 /* ExclamationToken */) { node = node.parent; } @@ -19550,7 +20500,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 223 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -19584,13 +20534,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 216 /* ForOfStatement */) { + if (node.kind === 217 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 227 /* VariableDeclarationList */) { + if (node.initializer.kind !== 228 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -19612,7 +20562,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 219 /* ReturnStatement */) { + if (node.kind === 220 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -19632,7 +20582,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 219 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -19728,7 +20678,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 262 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -19793,16 +20743,16 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 213 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -19813,10 +20763,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 177 /* ArrayLiteralExpression */) { + else if (node.kind === 178 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 198 /* SpreadElement */) { + if (e.kind === 199 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -19824,16 +20774,16 @@ var ts; } } } - else if (node.kind === 178 /* ObjectLiteralExpression */) { + else if (node.kind === 179 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 261 /* PropertyAssignment */) { + if (p.kind === 265 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 262 /* ShorthandPropertyAssignment */) { + else if (p.kind === 266 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 263 /* SpreadAssignment */) { + else if (p.kind === 267 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -19889,7 +20839,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 180 /* ElementAccessExpression */) { + if (operator === 58 /* EqualsToken */ && node.left.kind === 181 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -19900,7 +20850,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 179 /* PropertyAccessExpression */) { + if (node.expression.kind === 180 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -19939,7 +20889,7 @@ var ts; } function bindJSDocComment(node) { ts.forEachChild(node, function (n) { - if (n.kind !== 283 /* JSDocTypedefTag */) { + if (n.kind !== 288 /* JSDocTypedefTag */) { bind(n); } }); @@ -19960,10 +20910,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 185 /* ParenthesizedExpression */) { + while (expr.kind === 186 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 186 /* FunctionExpression */ || expr.kind === 187 /* ArrowFunction */) { + if (expr.kind === 187 /* FunctionExpression */ || expr.kind === 188 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -19971,7 +20921,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 179 /* PropertyAccessExpression */) { + if (node.expression.kind === 180 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -19980,53 +20930,53 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 254 /* JsxAttributes */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 179 /* ObjectLiteralExpression */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 258 /* JsxAttributes */: return 1 /* IsContainer */; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 173 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 265 /* SourceFile */: + case 269 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 273 /* JSDocFunctionType */: - case 160 /* FunctionType */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 161 /* ConstructorType */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 156 /* CallSignature */: + case 277 /* JSDocFunctionType */: + case 161 /* FunctionType */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 162 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 260 /* CatchClause */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 235 /* CaseBlock */: + case 264 /* CatchClause */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 236 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 207 /* Block */: + case 208 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -20059,42 +21009,42 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265 /* SourceFile */: + case 269 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 178 /* ObjectLiteralExpression */: - case 230 /* InterfaceDeclaration */: - case 254 /* JsxAttributes */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 179 /* ObjectLiteralExpression */: + case 231 /* InterfaceDeclaration */: + case 258 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 273 /* JSDocFunctionType */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 277 /* JSDocFunctionType */: + case 232 /* TypeAliasDeclaration */: + case 173 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -20115,11 +21065,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 265 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 265 /* SourceFile */ || body.kind === 234 /* ModuleBlock */)) { + var body = node.kind === 269 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 269 /* SourceFile */ || body.kind === 235 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 244 /* ExportDeclaration */ || stat.kind === 243 /* ExportAssignment */) { + if (stat.kind === 245 /* ExportDeclaration */ || stat.kind === 244 /* ExportAssignment */) { return true; } } @@ -20129,7 +21079,7 @@ var ts; function setExportContextFlag(node) { // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + if (node.flags & 2097152 /* Ambient */ && !hasExportDeclarations(node)) { node.flags |= 32 /* ExportContext */; } else { @@ -20165,22 +21115,13 @@ var ts; else { var state = declareModuleSymbol(node); if (state !== 0 /* NonInstantiated */) { - if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; } } } @@ -20214,7 +21155,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 267 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { continue; } var identifier = prop.name; @@ -20226,7 +21167,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */ || prop.kind === 151 /* MethodDeclaration */ + var currentKind = prop.kind === 265 /* PropertyAssignment */ || prop.kind === 266 /* ShorthandPropertyAssignment */ || prop.kind === 152 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -20250,17 +21191,17 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & 8 /* EnumMember */) { + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { symbol.parent = container.symbol; } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -20284,10 +21225,10 @@ var ts; node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { + !(node.flags & 2097152 /* Ambient */)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -20335,7 +21276,7 @@ var ts; // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -20370,8 +21311,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 265 /* SourceFile */ && - blockScopeContainer.kind !== 233 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 269 /* SourceFile */ && + blockScopeContainer.kind !== 234 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -20381,8 +21322,8 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -20445,7 +21386,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 142 /* LastToken */) { + if (node.kind > 143 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -20473,7 +21414,7 @@ var ts; } for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; - if (tag.kind === 283 /* JSDocTypedefTag */) { + if (tag.kind === 288 /* JSDocTypedefTag */) { var savedParent = parent; parent = jsDoc; bind(tag); @@ -20512,7 +21453,7 @@ var ts; // current "blockScopeContainer" needs to be set to its immediate namespace parent. if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 283 /* JSDocTypedefTag */) { + while (parentNode && parentNode.kind !== 288 /* JSDocTypedefTag */) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); @@ -20520,16 +21461,19 @@ var ts; } // falls through case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 266 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -20554,132 +21498,132 @@ var ts; ts.Debug.fail("Unknown special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return checkStrictModeCatchClause(node); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return checkStrictModeWithStatement(node); - case 169 /* ThisType */: + case 170 /* ThisType */: seenThisKeyword = true; return; - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return checkTypePredicate(node); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); - case 146 /* Parameter */: + case 147 /* Parameter */: return bindParameter(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return bindPropertyWorker(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 264 /* EnumMember */: + case 268 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 160 /* FunctionType */: - case 273 /* JSDocFunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 277 /* JSDocFunctionType */: + case 162 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 172 /* MappedType */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 173 /* MappedType */: return bindAnonymousTypeWorker(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return bindFunctionExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return bindJsxAttributes(node); - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return bindImportClause(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return bindExportDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return bindExportAssignment(node); - case 265 /* SourceFile */: + case 269 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 207 /* Block */: + case 208 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 279 /* JSDocParameterTag */: - if (node.parent.kind !== 285 /* JSDocTypeLiteral */) { + case 284 /* JSDocParameterTag */: + if (node.parent.kind !== 280 /* JSDocTypeLiteral */) { break; } // falls through - case 284 /* JSDocPropertyTag */: + case 289 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 276 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 283 /* JSDocTypedefTag */: { + case 288 /* JSDocTypedefTag */: { var fullName = node.fullName; if (!fullName || fullName.kind === 71 /* Identifier */) { return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); @@ -20699,7 +21643,7 @@ var ts; if (parameterName && parameterName.kind === 71 /* Identifier */) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 169 /* ThisType */) { + if (parameterName && parameterName.kind === 170 /* ThisType */) { seenThisKeyword = true; } bind(type); @@ -20719,31 +21663,32 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - // An export default clause with an expression exports a value - // We want to exclude both class and function here, this is necessary to issue an error when there are both - // default export-assignment and default export function and class declaration. - var flags = node.kind === 243 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 244 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression exports all meanings of that identifier ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 2097152 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + if (node.parent.kind !== 269 /* SourceFile */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -20782,15 +21727,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -20815,18 +21757,18 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (container.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: // Declare a 'member' if the container is an ES5 class or ES6 constructor container.symbol.members = container.symbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); break; - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 153 /* Constructor */: + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = container.parent; @@ -20835,8 +21777,18 @@ var ts; break; } } + function bindSpecialPropertyDeclaration(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (node.expression.kind === 99 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if ((node.expression.kind === 71 /* Identifier */ || node.expression.kind === 180 /* PropertyAccessExpression */) && + node.parent.parent.kind === 269 /* SourceFile */) { + bindStaticPropertyAssignment(node); + } + } function bindPrototypePropertyAssignment(node) { - // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x is a function or class, or not declared. // Look up the function in the local scope, since prototype assignments should // follow the function declaration var leftSideOfAssignment = node.left; @@ -20848,34 +21800,67 @@ var ts; classPrototype.parent = leftSideOfAssignment; bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ true); } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function or class, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ function bindStaticPropertyAssignment(node) { - // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function. - // Look up the function in the local scope, since prototype assignments should + // Look up the function in the local scope, since static assignments should // follow the function declaration - var leftSideOfAssignment = node.left; + var leftSideOfAssignment = node.kind === 180 /* PropertyAccessExpression */ ? node : node.left; var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + if (ts.isIdentifier(target)) { + // Fix up parent pointers since we're going to use these nodes before we bind into them + target.parent = leftSideOfAssignment; + if (node.kind === 195 /* BinaryExpression */) { + leftSideOfAssignment.parent = node; + } + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } } } function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { + var symbol = lookupSymbolForName(functionName); + var targetSymbol = symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol) ? + symbol.valueDeclaration.initializer.symbol : + symbol; + ts.Debug.assert(propertyAccess.parent.kind === 195 /* BinaryExpression */ || propertyAccess.parent.kind === 211 /* ExpressionStatement */); + var isLegalPosition; + if (propertyAccess.parent.kind === 195 /* BinaryExpression */) { + var initializerKind = propertyAccess.parent.right.kind; + isLegalPosition = (initializerKind === 200 /* ClassExpression */ || initializerKind === 187 /* FunctionExpression */) && + propertyAccess.parent.parent.parent.kind === 269 /* SourceFile */; + } + else { + isLegalPosition = propertyAccess.parent.parent.kind === 269 /* SourceFile */; + } + if (!isPrototypeProperty && (!targetSymbol || !(targetSymbol.flags & 1920 /* Namespace */)) && isLegalPosition) { + ts.Debug.assert(ts.isIdentifier(propertyAccess.expression)); + var identifier = propertyAccess.expression; + var flags = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags = 106639 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + if (targetSymbol) { + addDeclarationToSymbol(symbol, identifier, flags); + } + else { + targetSymbol = declareSymbol(container.locals, /*parent*/ undefined, identifier, flags, excludeFlags); + } } - if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) { + if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */))) { return; } // Set up the members collection if it doesn't exist already @@ -20883,7 +21868,7 @@ var ts; (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */); + declareSymbol(symbolTable, targetSymbol, propertyAccess, 4 /* Property */, 0 /* PropertyExcludes */); } function bindCallExpression(node) { // We're only inspecting call expressions to detect CommonJS modules, so we can skip @@ -20893,7 +21878,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { @@ -20920,7 +21905,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -20956,7 +21941,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { + if (inStrictMode && !(node.flags & 2097152 /* Ambient */)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -20975,7 +21960,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -20990,7 +21975,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -21003,7 +21988,7 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */) && ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { @@ -21025,13 +22010,13 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 209 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 210 /* EmptyStatement */) || // report error on class declarations - node.kind === 229 /* ClassDeclaration */ || + node.kind === 230 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 233 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 234 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 232 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (node.kind === 233 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; // unreachable code is reported if @@ -21044,8 +22029,8 @@ var ts; // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 /* VariableStatement */ || + !(node.flags & 2097152 /* Ambient */) && + (node.kind !== 209 /* VariableStatement */ || ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -21065,56 +22050,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 181 /* CallExpression */: + case 182 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 146 /* Parameter */: + case 147 /* Parameter */: return computeParameter(node, subtreeFlags); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152 /* Constructor */: + case 153 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -21136,6 +22121,11 @@ var ts; } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; @@ -21144,8 +22134,8 @@ var ts; switch (kind) { case 97 /* SuperKeyword */: return true; - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: var expression = node.expression; var expressionKind = expression.kind; return expressionKind === 97 /* SuperKeyword */; @@ -21169,12 +22159,12 @@ var ts; var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 179 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 177 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } @@ -21223,8 +22213,8 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (expressionKind === 202 /* AsExpression */ - || expressionKind === 184 /* TypeAssertionExpression */) { + if (expressionKind === 203 /* AsExpression */ + || expressionKind === 185 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -21342,6 +22332,7 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } @@ -21366,6 +22357,7 @@ var ts; if (node.decorators || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } @@ -21587,7 +22579,7 @@ var ts; var excludeFlags = 536872257 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; @@ -21597,24 +22589,27 @@ var ts; case 117 /* AbstractKeyword */: case 124 /* DeclareKeyword */: case 76 /* ConstKeyword */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - case 203 /* NonNullExpression */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: case 10 /* JsxText */: - case 252 /* JsxClosingElement */: - case 253 /* JsxAttribute */: - case 254 /* JsxAttributes */: - case 255 /* JsxSpreadAttribute */: - case 256 /* JsxExpression */: + case 253 /* JsxClosingElement */: + case 254 /* JsxFragment */: + case 255 /* JsxOpeningFragment */: + case 256 /* JsxClosingFragment */: + case 257 /* JsxAttribute */: + case 258 /* JsxAttributes */: + case 259 /* JsxSpreadAttribute */: + case 260 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; @@ -21622,11 +22617,11 @@ var ts; case 14 /* TemplateHead */: case 15 /* TemplateMiddle */: case 16 /* TemplateTail */: - case 196 /* TemplateExpression */: - case 183 /* TaggedTemplateExpression */: - case 262 /* ShorthandPropertyAssignment */: + case 197 /* TemplateExpression */: + case 184 /* TaggedTemplateExpression */: + case 266 /* ShorthandPropertyAssignment */: case 115 /* StaticKeyword */: - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; @@ -21636,18 +22631,18 @@ var ts; } break; case 8 /* NumericLiteral */: - if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; @@ -21660,36 +22655,36 @@ var ts; case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 158 /* TypePredicate */: - case 159 /* TypeReference */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 162 /* TypeQuery */: - case 163 /* TypeLiteral */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 169 /* ThisType */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 173 /* LiteralType */: - case 236 /* NamespaceExportDeclaration */: + case 146 /* TypeParameter */: + case 149 /* PropertySignature */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 159 /* TypePredicate */: + case 160 /* TypeReference */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 163 /* TypeQuery */: + case 164 /* TypeLiteral */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 170 /* ThisType */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 174 /* LiteralType */: + case 237 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. @@ -21706,10 +22701,10 @@ var ts; transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; break; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; break; case 97 /* SuperKeyword */: @@ -21720,28 +22715,28 @@ var ts; // Mark this node and its ancestors as containing a lexical `this` keyword. transformFlags |= 16384 /* ContainsLexicalThis */; break; - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 176 /* BindingElement */: + case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { transformFlags |= 524288 /* ContainsRest */; } break; - case 147 /* Decorator */: + case 148 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: excludeFlags = 540087617 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it @@ -21759,8 +22754,8 @@ var ts; transformFlags |= 8 /* AssertESNext */; } break; - case 177 /* ArrayLiteralExpression */: - case 182 /* NewExpression */: + case 178 /* ArrayLiteralExpression */: + case 183 /* NewExpression */: excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 @@ -21768,23 +22763,23 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 219 /* ReturnStatement */: - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: + case 220 /* ReturnStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; break; } @@ -21800,33 +22795,33 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) { + if (kind >= 159 /* FirstTypeNode */ && kind <= 174 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 177 /* ArrayLiteralExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 178 /* ArrayLiteralExpression */: return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return 574674241 /* ModuleExcludes */; - case 146 /* Parameter */: + case 147 /* Parameter */: return 536872257 /* ParameterExcludes */; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return 601249089 /* ArrowFunctionExcludes */; - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: return 601281857 /* FunctionExcludes */; - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return 546309441 /* VariableDeclarationListExcludes */; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return 539358529 /* ClassExcludes */; - case 152 /* Constructor */: + case 153 /* Constructor */: return 601015617 /* ConstructorExcludes */; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return 601015617 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: @@ -21836,21 +22831,21 @@ var ts; case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 146 /* TypeParameter */: + case 149 /* PropertySignature */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return 540087617 /* ObjectLiteralExcludes */; - case 260 /* CatchClause */: + case 264 /* CatchClause */: return 537920833 /* CatchClauseExcludes */; - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return 537396545 /* BindingPatternExcludes */; default: return 536872257 /* NodeExcludes */; @@ -21911,7 +22906,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -21927,16 +22922,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 32768 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 196608 /* UnionOrIntersection */) { + if (type.flags & 393216 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 262144 /* Index */) { + if (type.flags & 524288 /* Index */) { visitIndexType(type); } - if (type.flags & 524288 /* IndexedAccess */) { + if (type.flags & 1048576 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -22024,7 +23019,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 162 /* TypeQuery */) { + if (d.type && d.type.kind === 163 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -22089,7 +23084,7 @@ var ts; return; } var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { + if (!ts.isString(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); } @@ -22138,7 +23133,7 @@ var ts; // And if it doesn't exist, tough. } var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -22574,8 +23569,8 @@ var ts; matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -22797,7 +23792,7 @@ var ts; var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; - return { packageJsonContent: packageJsonContent, packageId: packageId }; + return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { if (directoryExists && traceEnabled) { @@ -22805,7 +23800,7 @@ var ts; } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocations.push(packageJsonPath); - return { packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined }; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { @@ -22854,14 +23849,27 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); + if (packageInfo.found) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); + } + else { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. + packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + } + } var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); } + /* @internal */ function getPackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { @@ -22869,6 +23877,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } @@ -22878,7 +23887,7 @@ var ts; } function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); if (resolutionFromCache) { @@ -22915,24 +23924,32 @@ var ts; /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" } } - return moduleName; + return packageName; } /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -22963,7 +23980,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { // Climb up parent directories looking for a module. - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -23009,20 +24026,6 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } - /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ - 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 || (ts = {})); /// /// @@ -23070,9 +24073,11 @@ var ts; var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; + // tslint:disable variable-name var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name var typeCount = 0; var symbolCount = 0; var enumCount = 0; @@ -23083,10 +24088,12 @@ var ts; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -23239,15 +24246,34 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, - getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -23255,25 +24281,27 @@ var ts; var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(4096 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 /* Undefined */ | 4194304 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(8192 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 /* Null */ | 4194304 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); var booleanType = createBooleanType([trueType, falseType]); var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(1024 /* Void */, "void"); - var neverType = createIntrinsicType(8192 /* Never */, "never"); - var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var voidType = createIntrinsicType(2048 /* Void */, "void"); + var neverType = createIntrinsicType(16384 /* Never */, "never"); + var silentNeverType = createIntrinsicType(16384 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(16384 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(33554432 /* NonPrimitive */, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); @@ -23283,9 +24311,14 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 16777216 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(32768 /* TypeParameter */); + var markerSubType = createType(32768 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(32768 /* TypeParameter */); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -23293,6 +24326,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -23420,29 +24454,29 @@ var ts; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ - "string": 1 /* TypeofEQString */, - "number": 2 /* TypeofEQNumber */, - "boolean": 4 /* TypeofEQBoolean */, - "symbol": 8 /* TypeofEQSymbol */, - "undefined": 16384 /* EQUndefined */, - "object": 16 /* TypeofEQObject */, - "function": 32 /* TypeofEQFunction */ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + boolean: 4 /* TypeofEQBoolean */, + symbol: 8 /* TypeofEQSymbol */, + undefined: 16384 /* EQUndefined */, + object: 16 /* TypeofEQObject */, + function: 32 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128 /* TypeofNEString */, - "number": 256 /* TypeofNENumber */, - "boolean": 512 /* TypeofNEBoolean */, - "symbol": 1024 /* TypeofNESymbol */, - "undefined": 131072 /* NEUndefined */, - "object": 2048 /* TypeofNEObject */, - "function": 4096 /* TypeofNEFunction */ + string: 128 /* TypeofNEString */, + number: 256 /* TypeofNENumber */, + boolean: 512 /* TypeofNEBoolean */, + symbol: 1024 /* TypeofNESymbol */, + undefined: 131072 /* NEUndefined */, + object: 2048 /* TypeofNEObject */, + function: 4096 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType + string: stringType, + number: numberType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType }); var typeofType = createTypeofType(); var _jsxNamespace; @@ -23453,16 +24487,6 @@ var ts; var _hasComputedJsxElementChildrenPropertyName = false; /** Things we lazy load from the JSX namespace */ var jsxTypes = ts.createUnderscoreEscapedMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); @@ -23483,6 +24507,29 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["Readonly"] = 1] = "Readonly"; + MappedTypeModifiers[MappedTypeModifiers["Optional"] = 2] = "Optional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -23509,16 +24556,16 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } - function error(location, message, arg0, arg1, arg2) { + function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); } - function createSymbol(flags, name) { + function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); - symbol.checkFlags = 0; + symbol.checkFlags = checkFlags || 0; return symbol; } function isTransientSymbol(symbol) { @@ -23583,7 +24630,9 @@ var ts; return result; } function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + source.flags & 67108864 /* JSContainer */ || target.flags & 67108864 /* JSContainer */) { + // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums target.constEnumOnlyModule = false; @@ -23591,7 +24640,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 233 /* ModuleDeclaration */))) { + (target.valueDeclaration.kind === 234 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 234 /* ModuleDeclaration */))) { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } @@ -23622,6 +24671,16 @@ var ts; }); } } + function combineSymbolTables(first, second) { + if (!first || first.size === 0) + return second; + if (!second || second.size === 0) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); @@ -23652,7 +24711,7 @@ var ts; else { // find a module that about to be augmented // do not validate names of augmentations that are defined in ambient context - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152 /* Ambient */) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); @@ -23698,11 +24757,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } - function getObjectFlags(type) { - return type.flags & 32768 /* Object */ ? type.objectFlags : 0; - } function isGlobalSourceFile(node) { - return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 269 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -23733,7 +24789,7 @@ var ts; var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -23746,7 +24802,7 @@ var ts; if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - ts.isInAmbientContext(declaration)) { + declaration.flags & 2097152 /* Ambient */) { // nodes are in different files and order cannot be determined return true; } @@ -23760,17 +24816,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 176 /* BindingElement */) { + if (declaration.kind === 177 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 176 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 177 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 227 /* VariableDeclaration */), usage); } - else if (declaration.kind === 226 /* VariableDeclaration */) { + else if (declaration.kind === 227 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -23784,12 +24840,12 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 246 /* ExportSpecifier */ || (usage.parent.kind === 243 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 247 /* ExportSpecifier */ || (usage.parent.kind === 244 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 243 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 244 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -23797,9 +24853,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 208 /* VariableStatement */: - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: + case 209 /* VariableStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -23819,16 +24875,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 149 /* PropertyDeclaration */ && + current.parent.kind === 150 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 151 /* MethodDeclaration */) { + if (declaration.kind === 152 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -23851,6 +24907,7 @@ var ts; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -23867,11 +24924,13 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 275 /* JSDocComment */) { + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 279 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 146 /* Parameter */ || - lastLocation.kind === 145 /* TypeParameter */ + lastLocation.kind === 147 /* Parameter */ || + lastLocation.kind === 146 /* TypeParameter */ + // local types not visible outside the function body : false; } if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { @@ -23880,9 +24939,9 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 146 /* Parameter */ || + lastLocation.kind === 147 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 146 /* Parameter */); + result.valueDeclaration.kind === 147 /* Parameter */); } } if (useResult) { @@ -23894,14 +24953,14 @@ var ts; } } switch (location.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default")) { @@ -23925,7 +24984,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 246 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 247 /* ExportSpecifier */)) { break; } } @@ -23933,13 +24992,13 @@ var ts; break loop; } break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -23956,10 +25015,10 @@ var ts; } } break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -23974,7 +25033,7 @@ var ts; } break loop; } - if (location.kind === 199 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 200 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -23982,7 +25041,7 @@ var ts; } } break; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -24002,9 +25061,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 231 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -24012,19 +25071,19 @@ var ts; } } break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -24037,7 +25096,7 @@ var ts; } } break; - case 147 /* Decorator */: + case 148 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -24046,7 +25105,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 146 /* Parameter */) { + if (location.parent && location.parent.kind === 147 /* Parameter */) { location = location.parent; } // @@ -24060,18 +25119,21 @@ var ts; } break; } + if (location.kind !== 208 /* Block */) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 265 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 269 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -24090,7 +25152,7 @@ var ts; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); } } if (!suggestion) { @@ -24132,7 +25194,7 @@ var ts; // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236 /* NamespaceExportDeclaration */) { + if (decls && decls.length === 1 && decls[0].kind === 237 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -24140,12 +25202,12 @@ var ts; return result; } function diagnosticName(nameArg) { - return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 145 /* TypeParameter */ && decl.parent === container) { + if (decl.kind === 146 /* TypeParameter */ && decl.parent === container) { return true; } } @@ -24198,18 +25260,20 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201 /* ExpressionWithTypeArguments */: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; + case 202 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through default: return undefined; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~1920 /* Namespace */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -24250,7 +25314,7 @@ var ts; } } else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -24261,9 +25325,9 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 233 /* EnumDeclaration */) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + if (!(declaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } @@ -24284,13 +25348,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return node; - case 239 /* ImportClause */: + case 240 /* ImportClause */: return node.parent; - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return node.parent.parent; - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -24300,7 +25364,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -24430,19 +25494,19 @@ var ts; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246 /* ExportSpecifier */: + case 247 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); } } @@ -24497,11 +25561,11 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 243 /* ExportAssignment */) { + if (node.kind === 244 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 246 /* ExportSpecifier */) { + else if (node.kind === 247 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -24523,13 +25587,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 143 /* QualifiedName */) { + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 144 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 237 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 238 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -24551,13 +25615,13 @@ var ts; return undefined; } } - else if (name.kind === 143 /* QualifiedName */ || name.kind === 179 /* PropertyAccessExpression */) { + else if (name.kind === 144 /* QualifiedName */ || name.kind === 180 /* PropertyAccessExpression */) { var left = void 0; - if (name.kind === 143 /* QualifiedName */) { + if (name.kind === 144 /* QualifiedName */) { left = name.left; } - else if (name.kind === 179 /* PropertyAccessExpression */ && - (name.expression.kind === 185 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { + else if (name.kind === 180 /* PropertyAccessExpression */ && + (name.expression.kind === 186 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { left = name.expression; } else { @@ -24567,7 +25631,7 @@ var ts; // i.e class C extends foo()./*do language service operation here*/B {} return undefined; } - var right = name.kind === 143 /* QualifiedName */ ? name.right : name.name; + var right = name.kind === 144 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -24575,6 +25639,9 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } + if (ts.isInJavaScriptFile(name) && ts.isDeclarationOfFunctionOrClassExpression(namespace)) { + namespace = getSymbolOfNode(namespace.valueDeclaration.initializer); + } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { @@ -24583,7 +25650,7 @@ var ts; return undefined; } } - else if (name.kind === 185 /* ParenthesizedExpression */) { + else if (name.kind === 186 /* ParenthesizedExpression */) { // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. // This is the case when we are trying to do any language service operation in heritage clauses. // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. @@ -24712,16 +25779,20 @@ var ts; } function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); - if (!symbol) { - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); - } + if (symbol) { + return symbol; } - return symbol; + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 16382 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; } function getExportsOfModule(moduleSymbol) { var links = getSymbolLinks(moduleSymbol); @@ -24732,7 +25803,9 @@ var ts; * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables */ function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { if (id === "default") return; var targetSymbol = target.get(id); @@ -24799,10 +25872,10 @@ var ts; return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; } function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); } function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 @@ -24816,7 +25889,7 @@ var ts; var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 152 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 153 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -24839,7 +25912,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(32768 /* Object */); + var type = createType(65536 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; return type; @@ -24894,12 +25967,12 @@ var ts; } } switch (location.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -24952,7 +26025,6 @@ var ts; return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */) && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { @@ -24985,7 +26057,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 247 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -25000,10 +26072,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: continue; default: return false; @@ -25085,7 +26157,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -25119,12 +26191,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 162 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 163 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 145 /* ComputedPropertyName */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 143 /* QualifiedName */ || entityName.kind === 179 /* PropertyAccessExpression */ || - entityName.parent.kind === 237 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 144 /* QualifiedName */ || entityName.kind === 180 /* PropertyAccessExpression */ || + entityName.parent.kind === 238 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -25201,18 +26275,21 @@ var ts; function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; @@ -25246,10 +26323,10 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 272 /* EnumLike */) { @@ -25265,25 +26342,28 @@ var ts; if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 1024 /* Void */) { + if (type.flags & 1024 /* UniqueESSymbol */) { + return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); + } + if (type.flags & 2048 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } - if (type.flags & 2048 /* Undefined */) { + if (type.flags & 4096 /* Undefined */) { return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); } - if (type.flags & 4096 /* Null */) { + if (type.flags & 8192 /* Null */) { return ts.createKeywordTypeNode(95 /* NullKeyword */); } - if (type.flags & 8192 /* Never */) { + if (type.flags & 16384 /* Never */) { return ts.createKeywordTypeNode(130 /* NeverKeyword */); } if (type.flags & 512 /* ESSymbol */) { return ts.createKeywordTypeNode(137 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 33554432 /* NonPrimitive */) { return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; @@ -25291,13 +26371,13 @@ var ts; } return ts.createThis(); } - var objectFlags = getObjectFlags(type); + var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = type.symbol ? symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -25306,11 +26386,11 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { - var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { + var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; var typeNodes = mapToTypeNodes(types, context); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 /* Union */ ? 167 /* UnionType */ : 168 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -25321,23 +26401,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 262144 /* Index */) { + if (type.flags & 524288 /* Index */) { var indexedType = type.type; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 524288 /* IndexedAccess */) { + if (type.flags & 1048576 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); @@ -25388,7 +26468,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -25407,12 +26487,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 162 /* ConstructorType */, context); return signatureNode; } } @@ -25526,11 +26606,11 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); @@ -25554,7 +26634,7 @@ var ts; var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 151 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); @@ -25574,8 +26654,8 @@ var ts; function mapToTypeNodes(types, context) { if (ts.some(types)) { var result = []; - for (var i = 0; i < types.length; ++i) { - var type = types[i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -25636,28 +26716,23 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); - if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { - // special-case synthetic rest parameters in JS files - return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, parameterSymbol.isRestParameter ? ts.createToken(24 /* DotDotDotToken */) : undefined, "args", - /*questionToken*/ undefined, typeToTypeNodeHelper(anyArrayType, context), - /*initializer*/ undefined); - } - var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; - var name = parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : - ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); - var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 147 /* Parameter */); + ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); var parameterType = getTypeOfSymbol(parameterSymbol); - if (isRequiredInitializedParameter(parameterDeclaration)) { - parameterType = getNullableType(parameterType, 2048 /* Undefined */); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -25667,7 +26742,7 @@ var ts; function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 176 /* BindingElement */) { + if (clone.kind === 177 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); @@ -25709,8 +26784,7 @@ var ts; } typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol, context); - var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -25755,10 +26829,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 6144 /* Nullable */)) { + if (!(t.flags & 12288 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 65536 /* Union */) { + if (baseType.flags & 131072 /* Union */) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -25770,9 +26844,9 @@ var ts; result.push(t); } } - if (flags & 4096 /* Null */) + if (flags & 8192 /* Null */) result.push(nullType); - if (flags & 2048 /* Undefined */) + if (flags & 4096 /* Undefined */) result.push(undefinedType); return result || types; } @@ -25787,8 +26861,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168 /* ParenthesizedType */; }); - if (node.kind === 231 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 169 /* ParenthesizedType */; }); + if (node.kind === 232 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -25796,30 +26870,37 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 234 /* ModuleBlock */ && + node.parent.kind === 235 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol, context) { + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { context.encounteredError = true; } switch (declaration.kind) { - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -25829,7 +26910,7 @@ var ts; return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; } } - return ts.unescapeLeadingUnderscores(symbol.escapedName); + return ts.symbolName(symbol); } function getSymbolDisplayBuilder() { /** @@ -25837,7 +26918,7 @@ var ts; * for the name of the symbol if it is available to match how the user wrote the name. */ function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); + writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); } /** * Writes a property access or element access with the name of the symbol out to the writer. @@ -25845,18 +26926,22 @@ var ts; * ensuring that any names written with literals use element accesses. */ function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); + var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 21 /* OpenBracketToken */); + if (firstChar !== 91 /* openBracket */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + } if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 22 /* CloseBracketToken */); + if (firstChar !== 91 /* openBracket */) { + writePunctuation(writer, 22 /* CloseBracketToken */); + } } else { writePunctuation(writer, 23 /* DotToken */); @@ -25942,22 +27027,22 @@ var ts; function writeType(type, flags) { var nextFlags = flags & ~1024 /* InTypeAlias */; // Write undefined/null type as any - if (type.flags & 16793231 /* Intrinsic */) { + if (type.flags & 33585807 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (getObjectFlags(type) & 4 /* Reference */) { + else if (ts.getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parent = getParentOfSymbol(type.symbol); buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); // In a literal enum type with a single member E { A }, E and E.A denote the @@ -25967,7 +27052,7 @@ var ts; appendSymbolNameOnly(type.symbol, writer); } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { + else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -25976,16 +27061,26 @@ var ts; var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } - else if (type.flags & 196608 /* UnionOrIntersection */) { + else if (type.flags & 393216 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); } - else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { + else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { writeAnonymousType(type, nextFlags); } + else if (type.flags & 1024 /* UniqueESSymbol */) { + if (flags & 131072 /* AllowUniqueESSymbolType */) { + writeKeyword(writer, 140 /* UniqueKeyword */); + writeSpace(writer); + } + else { + writer.reportInaccessibleUniqueSymbolError(); + } + writeKeyword(writer, 137 /* SymbolKeyword */); + } else if (type.flags & 96 /* StringOrNumberLiteral */) { writer.writeStringLiteral(literalTypeToString(type)); } - else if (type.flags & 262144 /* Index */) { + else if (type.flags & 524288 /* Index */) { if (flags & 128 /* InElementType */) { writePunctuation(writer, 19 /* OpenParenToken */); } @@ -25996,7 +27091,7 @@ var ts; writePunctuation(writer, 20 /* CloseParenToken */); } } - else if (type.flags & 524288 /* IndexedAccess */) { + else if (type.flags & 1048576 /* IndexedAccess */) { writeType(type.objectType, 128 /* InElementType */); writePunctuation(writer, 21 /* OpenBracketToken */); writeType(type.indexType, 0 /* None */); @@ -26056,8 +27151,8 @@ var ts; } else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 199 /* ClassExpression */) { - writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + writeAnonymousType(type, flags); } else { // Write the type reference in the format f.g.C where A and B are type arguments @@ -26090,7 +27185,7 @@ var ts; if (flags & 128 /* InElementType */) { writePunctuation(writer, 19 /* OpenParenToken */); } - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); } else { @@ -26106,12 +27201,12 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 199 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || + !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (ts.contains(symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name @@ -26155,7 +27250,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -26164,13 +27259,13 @@ var ts; } } } - function writeTypeOfSymbol(type, typeFormatFlags) { + function writeTypeOfSymbol(symbol, typeFormatFlags) { if (typeFormatFlags & 32768 /* InArrayType */) { writePunctuation(writer, 19 /* OpenParenToken */); } writeKeyword(writer, 103 /* TypeOfKeyword */); writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); if (typeFormatFlags & 32768 /* InArrayType */) { writePunctuation(writer, 20 /* CloseParenToken */); } @@ -26180,6 +27275,13 @@ var ts; writeKeyword(writer, 131 /* ReadonlyKeyword */); writeSpace(writer); } + if (ts.getCheckFlags(prop) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(prop.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name) { + writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); + } + } buildSymbolDisplay(prop, writer); if (prop.flags & 16777216 /* Optional */) { writePunctuation(writer, 55 /* QuestionToken */); @@ -26265,7 +27367,7 @@ var ts; continue; } if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); } } var t = getTypeOfSymbol(p); @@ -26357,18 +27459,18 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048 /* Undefined */); + type = getOptionalType(type); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { writePunctuation(writer, 17 /* OpenBraceToken */); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); writePunctuation(writer, 18 /* CloseBraceToken */); } - else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { writePunctuation(writer, 21 /* OpenBracketToken */); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); @@ -26382,7 +27484,7 @@ var ts; if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 176 /* BindingElement */); + ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); if (bindingElement.propertyName) { writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 56 /* ColonToken */); @@ -26542,22 +27644,22 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 176 /* BindingElement */: + case 177 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 228 /* FunctionDeclaration */: - case 232 /* EnumDeclaration */: - case 237 /* ImportEqualsDeclaration */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 233 /* EnumDeclaration */: + case 238 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -26565,77 +27667,82 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 237 /* ImportEqualsDeclaration */ && parent.kind !== 265 /* SourceFile */ && ts.isInAmbientContext(parent))) { + !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 152 /* Constructor */: - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 157 /* IndexSignature */: - case 146 /* Parameter */: - case 234 /* ModuleBlock */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 159 /* TypeReference */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: + case 153 /* Constructor */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: + case 147 /* Parameter */: + case 235 /* ModuleBlock */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 160 /* TypeReference */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: return false; // Type parameters are always visible - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: // Source file and namespace export are always visible - case 265 /* SourceFile */: - case 236 /* NamespaceExportDeclaration */: + case 269 /* SourceFile */: + case 237 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return false; default: return false; } } } - function collectLinkedAliases(node) { + function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 246 /* ExportSpecifier */) { + else if (node.parent.kind === 247 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } - var result = []; + var result; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } return result; function buildVisibleNodeList(declarations) { ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - ts.pushIfUnique(result, resultNode); + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; @@ -26710,12 +27817,12 @@ var ts; function getDeclarationContainer(node) { node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 226 /* VariableDeclaration */: - case 227 /* VariableDeclarationList */: - case 242 /* ImportSpecifier */: - case 241 /* NamedImports */: - case 240 /* NamespaceImport */: - case 239 /* ImportClause */: + case 227 /* VariableDeclaration */: + case 228 /* VariableDeclarationList */: + case 243 /* ImportSpecifier */: + case 242 /* NamedImports */: + case 241 /* NamespaceImport */: + case 240 /* ImportClause */: return false; default: return true; @@ -26746,14 +27853,14 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 144 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 145 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (source.flags & 8192 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 12288 /* Nullable */); }); + if (source.flags & 16384 /* Never */) { return emptyObjectType; } - if (source.flags & 65536 /* Union */) { + if (source.flags & 131072 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); @@ -26783,17 +27890,17 @@ var ts; if (parentType === unknownType) { return unknownType; } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; - if (pattern.kind === 174 /* ObjectBindingPattern */) { + if (pattern.kind === 175 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (!isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -26815,12 +27922,13 @@ var ts; // computed properties with non-literal names are treated as 'any' return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. var text = ts.getTextOfPropertyName(name); + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || @@ -26859,7 +27967,7 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer ? @@ -26879,20 +27987,21 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 178 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 215 /* ForInStatement */) { + if (declaration.parent.parent.kind === 216 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; + return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 216 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 217 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -26907,11 +28016,11 @@ var ts; var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); + return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 226 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { + declaration.kind === 227 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 2097152 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no // initializer or a 'null' or 'undefined' initializer. @@ -26924,11 +28033,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 146 /* Parameter */) { + if (declaration.kind === 147 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 154 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153 /* GetAccessor */); + if (func.kind === 155 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 154 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -26949,13 +28058,13 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. @@ -26963,7 +28072,7 @@ var ts; return trueType; } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 262 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 266 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -26980,14 +28089,14 @@ var ts; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : - declaration.kind === 179 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 194 /* BinaryExpression */) : + var expression = declaration.kind === 195 /* BinaryExpression */ ? declaration : + declaration.kind === 180 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 195 /* BinaryExpression */) : undefined; if (!expression) { return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 152 /* Constructor */) { + if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 153 /* Constructor */) { definedInConstructor = true; } else { @@ -27001,9 +28110,10 @@ var ts; if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { - var name = ts.getNameOfDeclaration(declaration); - error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); + else if (jsDocType !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(jsDocType, declarationType) && + !(symbol.flags & 67108864 /* JSContainer */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } else if (!jsDocType) { @@ -27085,7 +28195,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 /* ObjectBindingPattern */ + return pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -27104,10 +28214,14 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 1024 /* UniqueESSymbol */ && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. - if (declaration.kind === 261 /* PropertyAssignment */) { + if (declaration.kind === 265 /* PropertyAssignment */) { return type; } return getWidenedType(type); @@ -27124,7 +28238,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 147 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -27140,7 +28254,7 @@ var ts; return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 243 /* ExportAssignment */) { + if (declaration.kind === 244 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { @@ -27156,8 +28270,8 @@ var ts; // * exports.p = expr // * this.p = expr // * className.prototype.method = expr - if (declaration.kind === 194 /* BinaryExpression */ || - declaration.kind === 179 /* PropertyAccessExpression */ && declaration.parent.kind === 194 /* BinaryExpression */) { + if (declaration.kind === 195 /* BinaryExpression */ || + declaration.kind === 180 /* PropertyAccessExpression */ && declaration.parent.kind === 195 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } else { @@ -27172,7 +28286,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 153 /* GetAccessor */) { + if (accessor.kind === 154 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -27193,8 +28307,8 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 154 /* SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 154 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 155 /* SetAccessor */); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { @@ -27238,7 +28352,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 154 /* GetAccessor */); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -27248,7 +28362,7 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 1081344 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -27263,7 +28377,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; } } } @@ -27349,20 +28463,20 @@ var ts; function isReferenceToType(type, target) { return type !== undefined && target !== undefined - && (getObjectFlags(type) & 4 /* Reference */) !== 0 + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target; } function getTargetType(type) { - return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); function check(type) { - if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); return target === checkBase || ts.forEach(getBaseTypes(target), check); } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { return ts.forEach(type.types, check); } } @@ -27386,29 +28500,29 @@ var ts; return undefined; } switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 273 /* JSDocFunctionType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 231 /* TypeAliasDeclaration */: - case 282 /* JSDocTemplateTag */: - case 172 /* MappedType */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 232 /* TypeAliasDeclaration */: + case 287 /* JSDocTemplateTag */: + case 173 /* MappedType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 172 /* MappedType */) { + if (node.kind === 173 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); var thisType = includeThisTypes && - (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || node.kind === 230 /* InterfaceDeclaration */) && + (node.kind === 230 /* ClassDeclaration */ || node.kind === 200 /* ClassExpression */ || node.kind === 231 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -27416,7 +28530,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, 230 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 231 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -27425,8 +28539,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 229 /* ClassDeclaration */ || - node.kind === 199 /* ClassExpression */ || node.kind === 231 /* TypeAliasDeclaration */) { + if (node.kind === 231 /* InterfaceDeclaration */ || node.kind === 230 /* ClassDeclaration */ || + node.kind === 200 /* ClassExpression */ || node.kind === 232 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -27454,14 +28568,22 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 540672 /* TypeVariable */) { + if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + var decl = type.symbol.valueDeclaration; + if (ts.isInJavaScriptFile(decl)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(decl); + if (tag) { + return tag.class; + } + } + return ts.getClassExtendsHeritageClauseElement(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -27483,6 +28605,8 @@ var ts; */ function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getClassExtendsHeritageClauseElement(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -27491,7 +28615,11 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) { + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -27530,7 +28658,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -27558,14 +28686,6 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag && augTag.typeExpression && augTag.typeExpression.type) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } if (baseType === unknownType) { return; } @@ -27574,7 +28694,7 @@ var ts; return; } if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } type.resolvedBaseTypes = [baseType]; @@ -27584,23 +28704,23 @@ var ts; // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. var outerTypeParameters = type.outerTypeParameters; if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; + var last_1 = outerTypeParameters.length - 1; var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; } return true; } // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return type.flags & (65536 /* Object */ | 33554432 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 231 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -27626,13 +28746,17 @@ var ts; } } } - // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is - // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, - // and if none of the base interfaces have a "this" type. - function isIndependentInterface(symbol) { + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */) { + if (declaration.kind === 231 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -27664,7 +28788,7 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { type.objectFlags |= 4 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; @@ -27673,7 +28797,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); + type.thisType = createType(32768 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -27690,9 +28814,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; + return d.kind === 288 /* JSDocTypedefTag */ || d.kind === 232 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = declaration.kind === 288 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { @@ -27716,13 +28840,13 @@ var ts; function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !ts.isInAmbientContext(member); + return !(member.flags & 2097152 /* Ambient */); } switch (expr.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 71 /* Identifier */: @@ -27739,7 +28863,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { + if (declaration.kind === 233 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { @@ -27754,7 +28878,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -27766,7 +28890,7 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { + if (declaration.kind === 233 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); @@ -27777,7 +28901,7 @@ var ts; } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 65536 /* Union */) { + if (enumType_1.flags & 131072 /* Union */) { enumType_1.flags |= 256 /* EnumLiteral */; enumType_1.symbol = symbol; } @@ -27801,7 +28925,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384 /* TypeParameter */); + var type = createType(32768 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -27815,6 +28939,9 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { return getDeclaredTypeOfClassOrInterface(symbol); } @@ -27833,24 +28960,14 @@ var ts; if (symbol.flags & 2097152 /* Alias */) { return getDeclaredTypeOfAlias(symbol); } - return unknownType; - } - // A type reference is considered independent if each type argument is considered independent. - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; + return undefined; } - // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string - // literal type, an array with an element type that is considered independent, or a type reference that is - // considered independent. - function isIndependentType(node) { + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { switch (node.kind) { case 119 /* AnyKeyword */: case 136 /* StringKeyword */: @@ -27862,55 +28979,57 @@ var ts; case 139 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 130 /* NeverKeyword */: - case 173 /* LiteralType */: + case 174 /* LiteralType */: return true; - case 164 /* ArrayType */: - return isIndependentType(node.elementType); - case 159 /* TypeReference */: - return isIndependentTypeReference(node); + case 165 /* ArrayType */: + return isThislessType(node.elementType); + case 160 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; } - // A variable-like declaration is considered independent (free of this references) if it has a type annotation - // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). - function isIndependentVariableLikeDeclaration(node) { + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + return !node.constraint || isThislessType(node.constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isIndependentType(typeNode) : !node.initializer; - } - // A function-like declaration is considered independent (free of this references) if it has a return type - // annotation that is considered independent and if each parameter is considered independent. - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 /* Constructor */) { - var typeNode = ts.getEffectiveReturnTypeNode(node); - if (!typeNode || !isIndependentType(typeNode)) { - return false; - } - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; + return typeNode ? isThislessType(typeNode) : !node.initializer; } - // Returns true if the class or interface member given by the symbol is free of "this" references. The - // function may return false for symbols that are actually free of "this" references because it is not - // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are conservatively - // assumed not to be free of "this" references. - function isIndependentMember(symbol) { + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + return (node.kind === 153 /* Constructor */ || (returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return isIndependentVariableLikeDeclaration(declaration); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - return isIndependentFunctionLikeDeclaration(declaration); + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); } } } @@ -27922,7 +29041,7 @@ var ts; var result = ts.createSymbolTable(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; - result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; } @@ -27937,23 +29056,219 @@ var ts; function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call" /* Call */)); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new" /* New */)); + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); } return type; } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 1120 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 1024 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & 96 /* StringOrNumberLiteral */) { + return ts.escapeLeadingUnderscores("" + type.value); + } + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + lateSymbol.parent = parent; + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { + var member = members_3[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4 /* Reference */) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); } } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); } return type; @@ -27967,7 +29282,7 @@ var ts; var numberIndexInfo; if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = identityMapper; - members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); callSignatures = source.declaredCallSignatures; constructSignatures = source.declaredConstructSignatures; stringIndexInfo = source.declaredStringIndexInfo; @@ -27983,7 +29298,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -28044,7 +29359,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -28122,8 +29437,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type = types_1[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -28213,7 +29528,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { - var members = symbol.members; + var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -28230,7 +29545,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { + if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1081344 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -28272,13 +29587,15 @@ var ts; var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170 /* TypeOperator */) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 171 /* TypeOperator */ && + constraintDeclaration.operator === 127 /* KeyOfKeyword */) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var propertySymbol = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); } - if (getIndexInfoOfType(modifiersType, 0 /* String */)) { + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); } } @@ -28286,8 +29603,8 @@ var ts; // First, if the constraint type is a type parameter, obtain the base constraint. Then, // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + var keyType = constraintType.flags & 1081344 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 524288 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -28311,8 +29628,8 @@ var ts; var propName = ts.escapeLeadingUnderscores(t.value); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216 /* Optional */); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + var checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, checkFlags); prop.type = propType; if (propertySymbol) { prop.syntheticOrigin = propertySymbol; @@ -28321,7 +29638,7 @@ var ts; prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } - else if (t.flags & 2 /* String */) { + else if (t.flags & (1 /* Any */ | 2 /* String */)) { stringIndexInfo = createIndexInfo(propType, templateReadonly); } } @@ -28343,7 +29660,8 @@ var ts; function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170 /* TypeOperator */) { + if (constraintDeclaration.kind === 171 /* TypeOperator */ && + constraintDeclaration.operator === 127 /* KeyOfKeyword */) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. @@ -28355,21 +29673,30 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } + function getMappedTypeModifiers(type) { + return (type.declaration.readonlyToken ? 1 /* Readonly */ : 0) | + (type.declaration.questionToken ? 2 /* Optional */ : 0); + } + function getCombinedMappedTypeModifiers(type) { + var modifiersType = getModifiersTypeFromMappedType(type); + return getMappedTypeModifiers(type) | + (isGenericMappedType(modifiersType) ? getMappedTypeModifiers(modifiersType) : 0); + } function isPartialMappedType(type) { - return getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; + return ts.getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -28383,10 +29710,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 65536 /* Union */) { + else if (type.flags & 131072 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -28394,7 +29721,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -28403,7 +29730,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -28427,7 +29754,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { break; } } @@ -28437,19 +29764,19 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 196608 /* UnionOrIntersection */ ? + return type.flags & 393216 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 65536 /* Union */)) { - return getPropertiesOfType(unionType); + if (!(unionType.flags & 131072 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var memberType = types_2[_i]; - for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); @@ -28459,8 +29786,8 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + return type.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 1048576 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { @@ -28476,13 +29803,13 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) { + if (type.flags & (1081344 /* TypeVariable */ | 393216 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 262144 /* Index */) { + else if (type.flags & 524288 /* Index */) { return stringType; } return undefined; @@ -28515,29 +29842,29 @@ var ts; return result; } function computeBaseConstraint(t) { - if (t.flags & 16384 /* TypeParameter */) { + if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType ? constraint : constraint ? getBaseConstraint(constraint) : undefined; } - if (t.flags & 196608 /* UnionOrIntersection */) { + if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_2 = types_4[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 131072 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 262144 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 262144 /* Index */) { + if (t.flags & 524288 /* Index */) { return stringType; } - if (t.flags & 524288 /* IndexedAccess */) { + if (t.flags & 1048576 /* IndexedAccess */) { var transformed = getTransformedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); @@ -28556,27 +29883,48 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - /** - * Gets the default type for a type parameter. - * - * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. - */ - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -28584,26 +29932,26 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 /* StringLike */ ? globalStringType : + var t = type.flags & 1081344 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 262144 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 524322 /* StringLike */ ? globalStringType : t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : - t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1536 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 33554432 /* NonPrimitive */ ? emptyObjectType : t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var types = containingType.types; - var isUnion = containingType.flags & 65536 /* Union */; + var isUnion = containingType.flags & 131072 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var current = types_5[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -28648,8 +29996,7 @@ var ts; } propTypes.push(type); } - var result = createSymbol(4 /* Property */ | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; result.declarations = declarations; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -28686,7 +30033,7 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -28700,13 +30047,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 196608 /* UnionOrIntersection */) { + if (type.flags & 393216 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { + if (type.flags & 458752 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -28720,7 +30067,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { + if (type.flags & 458752 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -28740,7 +30087,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -28775,7 +30122,7 @@ var ts; } function isJSDocOptionalParameter(node) { if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 272 /* JSDocOptionalType */) { + if (node.type && node.type.kind === 276 /* JSDocOptionalType */) { return true; } var paramTags = ts.getJSDocParameterTags(node); @@ -28786,7 +30133,7 @@ var ts; return true; } if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 272 /* JSDocOptionalType */; + return paramTag.typeExpression.type.kind === 276 /* JSDocOptionalType */; } } } @@ -28844,7 +30191,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -28859,11 +30206,11 @@ var ts; * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { if (!typeArguments) { typeArguments = []; } @@ -28871,13 +30218,17 @@ var ts; // If a type parameter does not have a default type, or if the default type // is a forward reference, the empty object type is used. for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); } for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + defaultType = anyType; + } + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); } + typeArguments.length = typeParameters.length; } } return typeArguments; @@ -28911,7 +30262,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 173 /* LiteralType */) { + if (param.type && param.type.kind === 174 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -28924,36 +30275,50 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 153 /* GetAccessor */ || declaration.kind === 154 /* SetAccessor */) && - !ts.hasDynamicName(declaration) && + if ((declaration.kind === 154 /* GetAccessor */ || declaration.kind === 155 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + var otherKind = declaration.kind === 154 /* GetAccessor */ ? 155 /* SetAccessor */ : 154 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 152 /* Constructor */ ? + var classType = declaration.kind === 153 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 /* TypePredicate */ ? + var typePredicate = declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - // JS functions get a free rest parameter if they reference `arguments` - var hasRestLikeParameter = ts.hasRestParameter(declaration); - if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { - hasRestLikeParameter = true; - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - parameters.push(syntheticArgsSymbol); - } + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + // JS functions get a free rest parameter if: + // a) The last parameter has `...` preceding its type + // b) It references `arguments` somewhere + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { + return false; + } + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); @@ -28967,8 +30332,8 @@ var ts; } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 153 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154 /* SetAccessor */); + if (declaration.kind === 154 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 155 /* SetAccessor */); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -28991,12 +30356,12 @@ var ts; return false; switch (node.kind) { case 71 /* Identifier */: - return node.escapedText === "arguments" && ts.isPartOfExpression(node); - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return node.name.kind === 144 /* ComputedPropertyName */ + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return node.name.kind === 145 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); @@ -29010,20 +30375,20 @@ var ts; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 273 /* JSDocFunctionType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 277 /* JSDocFunctionType */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -29091,7 +30456,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { + if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -29133,13 +30498,22 @@ var ts; // that uses the original type identities for all unconstrained type parameters. return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } function getOrCreateTypeFromSignature(signature) { // There are two ways to declare a construct signature, one is by declaring a class constructor // using the constructor keyword, and the other is declaring a bare construct signature in an // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 /* Constructor */ || signature.declaration.kind === 156 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 153 /* Constructor */ || signature.declaration.kind === 157 /* ConstructSignature */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -29180,7 +30554,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145 /* TypeParameter */).constraint; + return type.symbol && ts.getDeclarationOfKind(type.symbol, 146 /* TypeParameter */).constraint; } function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { @@ -29196,7 +30570,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 146 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -29227,13 +30601,13 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } } - return result & 14680064 /* PropagatingFlags */; + return result & 29360128 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -29267,17 +30641,28 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJavascript = ts.isInJavaScriptFile(node); - if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); - return unknownType; + var isJs = ts.isInJavaScriptFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && node.parent.kind !== 282 /* JSDocAugmentsTag */; + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return unknownType; + } } // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -29322,21 +30707,11 @@ var ts; } return type; } - /** - * Get type from reference to named type that cannot be generic (enum or type parameter) - */ - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } function getTypeReferenceName(node) { switch (node.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return node.typeName; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -29361,22 +30736,31 @@ var ts; if (type) { return type; } - if (symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node)) { - // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If - // the symbol is a constructor function, return the inferred class type; otherwise, - // the type of this reference is just the type of the value we resolved to. - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res !== undefined) { + if (typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return res; + } + if (!(symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node))) { + return unknownType; + } + // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + // the symbol is a constructor function, return the inferred class type; otherwise, + // the type of this reference is just the type of the value we resolved to. + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; } - // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); - return valueType; } - return getTypeFromNonGenericTypeReference(node, symbol); + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -29392,18 +30776,16 @@ var ts; } } function isJSDocTypeReference(node) { - return node.flags & 1048576 /* JSDoc */ && node.kind === 159 /* TypeReference */; + return node.flags & 1048576 /* JSDoc */ && node.kind === 160 /* TypeReference */; } function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -29434,7 +30816,7 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; + return strictNullChecks ? getNullableType(type, 8192 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); @@ -29477,9 +30859,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: return declaration; } } @@ -29488,12 +30870,12 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768 /* Object */)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + if (!(type.flags & 65536 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } return type; @@ -29607,12 +30989,15 @@ var ts; var typeParameters = []; var properties = []; for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384 /* TypeParameter */); + var typeParameter = createType(32768 /* TypeParameter */); typeParameters.push(typeParameter); var property = createSymbol(4 /* Property */, "" + i); property.type = typeParameter; properties.push(property); } + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = getLiteralType(arity); + properties.push(lengthSymbol); var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; @@ -29621,7 +31006,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); + type.thisType = createType(32768 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -29644,27 +31029,11 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; + function getTypeId(type) { + return type.id; } function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } // Return true if the given intersection type contains (a) more than one unit type or (b) an object // type and a nullable type (null or undefined). @@ -29672,11 +31041,11 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6368 /* Unit */ && combined & 6368 /* Unit */) { + if (t.flags & 13536 /* Unit */ && combined & 13536 /* Unit */) { return true; } combined |= t.flags; - if (combined & 6144 /* Nullable */ && combined & (32768 /* Object */ | 16777216 /* NonPrimitive */)) { + if (combined & 12288 /* Nullable */ && combined & (65536 /* Object */ | 33554432 /* NonPrimitive */)) { return true; } } @@ -29684,21 +31053,21 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 65536 /* Union */) { + if (flags & 131072 /* Union */) { addTypesToUnion(typeSet, type.types); } else if (flags & 1 /* Any */) { typeSet.containsAny = true; } - else if (!strictNullChecks && flags & 6144 /* Nullable */) { - if (flags & 2048 /* Undefined */) + else if (!strictNullChecks && flags & 12288 /* Nullable */) { + if (flags & 4096 /* Undefined */) typeSet.containsUndefined = true; - if (flags & 4096 /* Null */) + if (flags & 8192 /* Null */) typeSet.containsNull = true; - if (!(flags & 2097152 /* ContainsWideningType */)) + if (!(flags & 4194304 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 /* Never */ || flags & 131072 /* Intersection */ && isEmptyIntersectionType(type))) { + else if (!(flags & 16384 /* Never */ || flags & 262144 /* Intersection */ && isEmptyIntersectionType(type))) { // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it @@ -29707,12 +31076,14 @@ var ts; typeSet.containsString = true; if (flags & 4 /* Number */) typeSet.containsNumber = true; - if (flags & 96 /* StringOrNumberLiteral */) - typeSet.containsStringOrNumberLiteral = true; + if (flags & 512 /* ESSymbol */) + typeSet.containsESSymbol = true; + if (flags & 1120 /* StringOrNumberLiteralOrUnique */) + typeSet.containsLiteralOrUniqueESSymbol = true; var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } @@ -29722,24 +31093,26 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; if (isTypeIdenticalTo(t, type)) { return true; } } return false; } - function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - if (candidate !== type && isTypeSubtypeOf(candidate, type)) { + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { return true; } } @@ -29778,7 +31151,8 @@ var ts; var t = types[i]; var remove = t.flags & 32 /* StringLiteral */ && types.containsString || t.flags & 64 /* NumberLiteral */ && types.containsNumber || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 1024 /* UniqueESSymbol */ && types.containsESSymbol || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 2097152 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -29806,7 +31180,7 @@ var ts; if (subtypeReduction) { removeSubtypes(typeSet); } - else if (typeSet.containsStringOrNumberLiteral) { + else if (typeSet.containsLiteralOrUniqueESSymbol) { removeRedundantLiteralTypes(typeSet); } if (typeSet.length === 0) { @@ -29827,8 +31201,8 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(65536 /* Union */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); + type = createType(131072 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; /* @@ -29850,37 +31224,37 @@ var ts; return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072 /* Intersection */) { + if (type.flags & 262144 /* Intersection */) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1 /* Any */) { typeSet.containsAny = true; } - else if (type.flags & 8192 /* Never */) { + else if (type.flags & 16384 /* Never */) { typeSet.containsNever = true; } - else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { + else if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { typeSet.containsEmptyObject = true; } - else if ((strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768 /* Object */) { + else if ((strictNullChecks || !(type.flags & 12288 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 /* Object */) { typeSet.containsObjectType = true; } - if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { + if (type.flags & 131072 /* Union */ && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.push(type); } } } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { var type = types_9[_i]; - addTypeToIntersection(typeSet, type); + addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -29922,8 +31296,8 @@ var ts; var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(131072 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 12288 /* Nullable */); + type = createType(262144 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -29940,7 +31314,7 @@ var ts; } function getIndexTypeForGenericType(type) { if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144 /* Index */); + type.resolvedIndexType = createType(524288 /* Index */); type.resolvedIndexType.type = type; } return type.resolvedIndexType; @@ -29948,40 +31322,48 @@ var ts; function getLiteralTypeFromPropertyName(prop) { return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? neverType : - getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + getLiteralType(ts.symbolName(prop)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + return maybeTypeOfKind(type, 1081344 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; + return indexType.flags & 16384 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + switch (node.operator) { + case 127 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 140 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 137 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : unknownType; + break; + } } return links.resolvedType; } function createIndexedAccessType(objectType, indexType) { - var type = createType(524288 /* IndexedAccess */); + var type = createType(1048576 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? - ts.escapeLeadingUnderscores("" + indexType.value) : + var accessExpression = accessNode && accessNode.kind === 181 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); @@ -29998,7 +31380,7 @@ var ts; return getTypeOfSymbol(prop); } } - if (!(indexType.flags & 6144 /* Nullable */) && isTypeAssignableToKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!(indexType.flags & 12288 /* Nullable */) && isTypeAssignableToKind(indexType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */)) { if (isTypeAny(objectType)) { return anyType; } @@ -30024,7 +31406,7 @@ var ts; } } if (accessNode) { - var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = accessNode.kind === 181 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } @@ -30039,20 +31421,20 @@ var ts; return anyType; } function isGenericObjectType(type) { - return type.flags & 540672 /* TypeVariable */ ? true : - getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : - type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : + return type.flags & 1081344 /* TypeVariable */ ? true : + ts.getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 393216 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : false; } function isGenericIndexType(type) { - return type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) ? true : - type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : + return type.flags & (1081344 /* TypeVariable */ | 524288 /* Index */) ? true : + type.flags & 393216 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : false; } // Return true if the given type is a non-generic object type with a string index signature and no // other members. function isStringIndexOnlyType(type) { - if (type.flags & 32768 /* Object */ && !isGenericMappedType(type)) { + if (type.flags & 65536 /* Object */ && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && @@ -30068,7 +31450,7 @@ var ts; // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed // access types with default property values as expressed by D. - if (objectType.flags & 131072 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { @@ -30102,7 +31484,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 1 /* Any */) { return objectType; } @@ -30118,7 +31500,7 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { + if (indexType.flags & 131072 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -30158,7 +31540,7 @@ var ts; if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { links.resolvedType = emptyTypeLiteralType; } else { @@ -30174,7 +31556,7 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return node.parent.kind === 232 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; } function getAliasTypeArgumentsForTypeNode(node) { var symbol = getAliasSymbolForTypeNode(node); @@ -30185,26 +31567,26 @@ var ts; * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } - if (left.flags & 8192 /* Never */) { + if (left.flags & 16384 /* Never */) { return right; } - if (right.flags & 8192 /* Never */) { + if (right.flags & 16384 /* Never */) { return left; } - if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + if (left.flags & 131072 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } - if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + if (right.flags & 131072 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 16777216 /* NonPrimitive */) { + if (right.flags & 33554432 /* NonPrimitive */) { return nonPrimitiveType; } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 262178 /* StringLike */ | 272 /* EnumLike */)) { + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */)) { return left; } var members = ts.createSymbolTable(); @@ -30256,7 +31638,11 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= propagatedFlags; + spread.flags |= 2097152 /* FreshLiteral */ | 8388608 /* ContainsObjectLiteral */; + spread.objectFlags |= (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -30269,6 +31655,12 @@ var ts; result.syntheticOrigin = prop; return result; } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } @@ -30279,9 +31671,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 2097152 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 2097152 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -30290,7 +31682,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? type.regularType : type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -30313,20 +31705,25 @@ var ts; } return links.resolvedType; } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; + function createUniqueESSymbolType(symbol) { + var type = createType(1024 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.type || (links.type = createUniqueESSymbolType(symbol)); } - return links.resolvedType; + return esSymbolType; } function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 231 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 153 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -30343,8 +31740,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 268 /* JSDocAllType */: - case 269 /* JSDocUnknownType */: + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: return anyType; case 136 /* StringKeyword */: return stringType; @@ -30364,54 +31761,54 @@ var ts; return neverType; case 134 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 169 /* ThisType */: + case 170 /* ThisType */: case 99 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return getTypeFromTypeReference(node); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return booleanType; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 165 /* TupleType */: + case 166 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 166 /* UnionType */: + case 167 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 270 /* JSDocNullableType */: + case 274 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 168 /* ParenthesizedType */: - case 271 /* JSDocNonNullableType */: - case 272 /* JSDocOptionalType */: - case 267 /* JSDocTypeExpression */: + case 169 /* ParenthesizedType */: + case 275 /* JSDocNonNullableType */: + case 276 /* JSDocOptionalType */: + case 271 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 273 /* JSDocFunctionType */: + case 278 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 277 /* JSDocFunctionType */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 172 /* MappedType */: + case 173 /* MappedType */: return getTypeFromMappedTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 71 /* Identifier */: - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 274 /* JSDocVariadicType */: - return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -30480,7 +31877,7 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { - var result = createType(16384 /* TypeParameter */); + var result = createType(32768 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -30535,8 +31932,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName); - result.checkFlags = 1 /* Instantiated */; + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -30558,11 +31954,11 @@ var ts; // The first time an anonymous type is instantiated we compute and store a list of the type // parameters that are in scope (and therefore potentially referenced). For type literals that // aren't the right hand side of a generic type alias declaration we optimize by reducing the - // set of type parameters to those that are actually referenced somewhere in the literal. + // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -30587,13 +31983,27 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 208 /* Block */ ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 170 /* ThisType */: + return tp.isThisType; + case 71 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 163 /* TypeQuery */: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -30603,9 +32013,9 @@ var ts; // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a // union type A | undefined, we produce { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144 /* Index */) { + if (constraintType.flags & 524288 /* Index */) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384 /* TypeParameter */) { + if (typeVariable_1.flags & 32768 /* TypeParameter */) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -30620,7 +32030,7 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); + return type.flags & (1 /* Any */ | 32768 /* TypeParameter */ | 65536 /* Object */ | 262144 /* Intersection */ | 1048576 /* IndexedAccess */); } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); @@ -30635,10 +32045,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 32768 /* TypeParameter */) { return mapper(type); } - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { if (type.objectFlags & 16 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need @@ -30653,16 +32063,16 @@ var ts; return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } - if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 131072 /* Intersection */) { + if (type.flags & 262144 /* Intersection */) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 262144 /* Index */) { + if (type.flags & 524288 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 524288 /* IndexedAccess */) { + if (type.flags & 1048576 /* IndexedAccess */) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } @@ -30674,32 +32084,32 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return node.operatorToken.kind === 54 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return ts.forEach(node.properties, isContextSensitive); - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. return node.initializer && isContextSensitive(node.initializer); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: // It is possible to that node.expression is undefined (e.g
) return node.expression && isContextSensitive(node.expression); } @@ -30714,7 +32124,7 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 187 /* ArrowFunction */) { + if (node.kind !== 188 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -30723,13 +32133,13 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 207 /* Block */ ? false : isContextSensitive(node.body); + return node.body.kind === 208 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -30740,7 +32150,7 @@ var ts; return result; } } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -30761,11 +32171,20 @@ var ts; function isTypeAssignableTo(source, target) { return isTypeRelatedTo(source, target, assignableRelation); } - // A type S is considered to be an instance of a type T if S and T are the same type or if S is a - // subtype of T but not structurally identical to T. This specifically means that two distinct but - // structurally identical types (such as two classes) are not considered instances of each other. - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 131072 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 131072 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 1081344 /* TypeVariable */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -30794,13 +32213,13 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -30812,13 +32231,16 @@ var ts; target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 152 /* MethodDeclaration */ && + kind !== 151 /* MethodSignature */ && kind !== 153 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { var targetThisType = getThisTypeOfSignature(target); if (targetThisType) { // void sources are assignable to anything. - var related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) || compareTypes(targetThisType, sourceThisType, reportErrors); if (!related) { if (reportErrors) { @@ -30837,24 +32259,24 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have - // function types with a single call signature, we known we are relating two callback parameters. In + // function types with a single call signature, we know we are relating two callback parameters. In // that case it is sufficient to only relate the parameters of the signatures co-variantly because, // similar to return values, callback parameters are output positions. This means that a Promise, // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); + (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); } return 0 /* False */; } @@ -30882,7 +32304,7 @@ var ts; // When relating callback signatures, we still need to relate return types bi-variantly as otherwise // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -30960,10 +32382,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 33554432 /* NonPrimitive */ ? true : + type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -30986,7 +32408,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -30999,11 +32421,11 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 8192 /* Never */) - return false; - if (t & 1 /* Any */ || s & 8192 /* Never */) + if (t & 1 /* Any */ || s & 16384 /* Never */) return true; - if (s & 262178 /* StringLike */ && t & 2 /* String */) + if (t & 16384 /* Never */) + return false; + if (s & 524322 /* StringLike */ && t & 2 /* String */) return true; if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && @@ -31017,22 +32439,26 @@ var ts; return true; if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; + if (s & 1536 /* ESSymbolLike */ && t & 512 /* ESSymbol */) + return true; if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { - if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 131072 /* Union */ && t & 131072 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 224 /* Literal */ && t & 224 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 4096 /* Undefined */ && (!strictNullChecks || t & (4096 /* Undefined */ | 2048 /* Void */))) return true; - if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + if (s & 8192 /* Null */ && (!strictNullChecks || t & 8192 /* Null */)) return true; - if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 65536 /* Object */ && t & 33554432 /* NonPrimitive */) return true; + if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) + return false; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; @@ -31045,22 +32471,24 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 2097152 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 2097152 /* FreshLiteral */) { target = target.regularType; } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + if (source === target || + relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { + if (source.flags & 2064384 /* StructuredOrTypeVariable */ || target.flags & 2064384 /* StructuredOrTypeVariable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -31082,13 +32510,6 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var ExpandingFlags; - (function (ExpandingFlags) { - ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; - ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; - ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; - ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; - })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0 /* None */; var overflow = false; var isIntersectionConstituent = false; @@ -31139,7 +32560,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608 /* UnionOrIntersection */)) { + if (!(type.flags & 393216 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -31147,7 +32568,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6144 /* Nullable */) { + if (t.flags & 12288 /* Nullable */) { continue; } if (seenNonNullable) { @@ -31164,10 +32585,10 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 2097152 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 2097152 /* FreshLiteral */) { target = target.regularType; } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases @@ -31176,9 +32597,10 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + if (relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (isObjectLiteralType(source) && source.flags & 2097152 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -31194,13 +32616,11 @@ var ts; } } if (relation !== comparableRelation && - !(source.flags & 196608 /* UnionOrIntersection */) && - !(target.flags & 65536 /* Union */) && + !(source.flags & 393216 /* UnionOrIntersection */) && + !(target.flags & 131072 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && - (getPropertiesOfType(source).length > 0 || - getSignaturesOfType(source, 0 /* Call */).length > 0 || - getSignaturesOfType(source, 1 /* Construct */).length > 0) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { @@ -31223,20 +32643,20 @@ var ts; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 65536 /* Union */) { + if (source.flags & 131072 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)); } else { - if (target.flags & 65536 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */)); + if (target.flags & 131072 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */) && !(target.flags & 16382 /* Primitive */)); } - else if (target.flags & 131072 /* Intersection */) { + else if (target.flags & 262144 /* Intersection */) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 131072 /* Intersection */) { + else if (source.flags & 262144 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -31252,7 +32672,7 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */)) { + if (!result && (source.flags & 2064384 /* StructuredOrTypeVariable */ || target.flags & 2064384 /* StructuredOrTypeVariable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } @@ -31260,10 +32680,10 @@ var ts; } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { + if (source.flags & 65536 /* Object */ && target.flags & 16382 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 65536 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -31272,11 +32692,11 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || - source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ || + source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; @@ -31286,12 +32706,19 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { - var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + if (maybeTypeOfKind(target, 65536 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(source.flags & 67108864 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 131072 /* Union */) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -31317,7 +32744,7 @@ var ts; } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); } else { reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); @@ -31351,7 +32778,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 131072 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -31367,23 +32794,32 @@ var ts; } return 0 /* False */; } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { + var sourceProperty = sourcePropertiesFiltered_1[_i]; var sourceType = getTypeOfSymbol(sourceProperty); for (var _a = 0, _b = target.types; _a < _b.length; _a++) { var type = _b[_a]; var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); if (targetType && isRelatedTo(sourceType, targetType)) { - return type; + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + if (match) { + return undefined; + } + match = type; } } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -31400,7 +32836,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 131072 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -31425,7 +32861,7 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, reportErrors) { + function typeArgumentsRelatedTo(source, target, variances, reportErrors) { var sources = source.typeArguments || ts.emptyArray; var targets = target.typeArguments || ts.emptyArray; if (sources.length !== targets.length && relation === identityRelation) { @@ -31434,11 +32870,45 @@ var ts; var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0 /* False */; + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; } - result &= related; } return result; } @@ -31513,10 +32983,11 @@ var ts; } function structuredTypeRelatedTo(source, target, reportErrors) { var result; + var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 16384 /* TypeParameter */) { + if (target.flags & 32768 /* TypeParameter */) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -31526,9 +32997,9 @@ var ts; } } } - else if (target.flags & 262144 /* Index */) { + else if (target.flags & 524288 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 262144 /* Index */) { + if (source.flags & 524288 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -31542,7 +33013,7 @@ var ts; } } } - else if (target.flags & 524288 /* IndexedAccess */) { + else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and // A is the apparent type of S. var constraint = getConstraintOfIndexedAccess(target); @@ -31553,35 +33024,31 @@ var ts; } } } - if (source.flags & 16384 /* TypeParameter */) { + else if (isGenericMappedType(target) && !isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + if (source.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(source); + // A type parameter with no constraint is not related to the non-primitive object type. + if (constraint || !(target.flags & 33554432 /* NonPrimitive */)) { + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; } } - else { - var constraint = getConstraintOfTypeParameter(source); - // A type parameter with no constraint is not related to the non-primitive object type. - if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) { - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; - } - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } } - else if (source.flags & 524288 /* IndexedAccess */) { + else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and // A is the apparent type of S. var constraint = getConstraintOfIndexedAccess(source); @@ -31591,31 +33058,59 @@ var ts; return result; } } - else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { + else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { // if we have indexed access types with identical index types, see if relationship holds for // the two object types. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } else { - if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { - // We have type references to same target type, see if relationship holds for all type arguments - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(source.flags & 134217728 /* MarkerType */ || target.flags & 134217728 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { return result; } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */); + var sourceIsPrimitive = !!(source.flags & 16382 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { + if (source.flags & (65536 /* Object */ | 262144 /* Intersection */) && target.flags & 65536 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; // An empty object type is related to any mapped type that includes a '?' modifier. @@ -31641,8 +33136,11 @@ var ts; } } if (result) { - errorInfo = saveErrorInfo; - return result; + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; } } } @@ -31652,18 +33150,14 @@ var ts; // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. function mappedTypeRelatedTo(source, target, reportErrors) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + !(getCombinedMappedTypeModifiers(source) & 2 /* Optional */) || + getCombinedMappedTypeModifiers(target) & 2 /* Optional */); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_1; + if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -31672,7 +33166,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -31680,10 +33174,24 @@ var ts; } return 0 /* False */; } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { + var targetProp = properties_3[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -31754,20 +33262,20 @@ var ts; * and no required properties, call/construct signatures or index signatures */ function isWeakType(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); } - if (type.flags & 131072 /* Intersection */) { + if (type.flags & 262144 /* Intersection */) { return ts.every(type.types, isWeakType); } return false; } function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + var isComparingJsxAttributes = !!(source.flags & 67108864 /* JsxAttributes */); for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { @@ -31777,7 +33285,7 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { + if (!(source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -31786,8 +33294,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0 /* False */; @@ -31810,7 +33318,7 @@ var ts; var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type // as it would otherwise be possible to new an abstract class. Note that the assignability // check we perform for an extends clause excludes construct signatures from the target, @@ -31826,7 +33334,7 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { // We have instantiations of the same anonymous type (which typically will be the type of a // method). Simply do a pairwise comparison of the signatures in the two signature lists instead // of the much more expensive N * M comparison matrix we explore below. We erase type parameters @@ -31875,8 +33383,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, - /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -31937,7 +33444,7 @@ var ts; // if T is related to U. return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); @@ -31990,11 +33497,72 @@ var ts; return false; } } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.flags |= 134217728 /* MarkerType */; + return result; + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + var typeParameters = type.typeParameters || ts.emptyArray; + var variances = type.variances; + if (!variances) { + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this + variances = [1 /* Covariant */]; + } + else { + // The emptyArray singleton is used to signal a recursive invocation. + type.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); + var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + } + type.variances = variances; + } + return variances; + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 2048 /* Void */) { + return true; + } + } + return false; + } function isUnconstrainedTypeParameter(type) { - return type.flags & 16384 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -32077,19 +33645,6 @@ var ts; return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } - // Return true if the given type is the constructor type for an abstract class - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16 /* Anonymous */) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32 /* Class */) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.hasModifier(declaration, 128 /* Abstract */)) { - return true; - } - } - } - return false; - } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely @@ -32097,13 +33652,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 32768 /* Object */) { + if (depth >= 5 && type.flags & 65536 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 32768 /* Object */ && t.symbol === symbol) { + if (t.flags & 65536 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -32243,29 +33798,37 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : getUnionType(types, /*subtypeReduction*/ true); } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } function isArrayType(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 12288 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return !!(type.flags & 6368 /* Unit */); + return !!(type.flags & 13536 /* Unit */); } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 131072 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -32273,23 +33836,34 @@ var ts; type.flags & 32 /* StringLiteral */ ? stringType : type.flags & 64 /* NumberLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 32 /* StringLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 1024 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -32303,15 +33877,15 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 131072 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : - type.flags & 7406 /* PossiblyFalsy */; + type.flags & 14574 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 14560 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -32321,7 +33895,7 @@ var ts; return type.flags & 2 /* String */ ? emptyStringType : type.flags & 4 /* Number */ ? zeroType : type.flags & 8 /* Boolean */ || type === falseType ? falseType : - type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & (2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */) || type.flags & 32 /* StringLiteral */ && type.value === "" || type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : neverType; @@ -32332,23 +33906,26 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + var missing = (flags & ~type.flags) & (4096 /* Undefined */ | 8192 /* Null */); return missing === 0 ? type : - missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + missing === 4096 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 8192 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } /** - * Return true if type was inferred from an object literal or written as an object type literal + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module * with no call or construct signatures. */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && - getSignaturesOfType(type, 0 /* Call */).length === 0 && - getSignaturesOfType(type, 1 /* Construct */).length === 0; + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName); @@ -32377,7 +33954,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && type.flags & 2097152 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -32387,41 +33964,102 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; + regularNew.flags = resolved.flags & ~2097152 /* FreshLiteral */; regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } - function getWidenedProperty(prop) { + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertyNamesOfContext(context) { + if (!context.resolvedPropertyNames) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, true); + } + } + } + context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + } + return context.resolvedPropertyNames; + } + function getWidenedProperty(prop, context) { var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getWidenedTypeOfObjectLiteral(type) { + function getUndefinedProperty(name) { + var cached = undefinedProperties.get(name); + if (cached) { + return cached; + } + var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); + result.type = undefinedType; + undefinedProperties.set(name, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; // Since get accessors already widen their return value there is no need to // widen accessor based properties here. - members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop); + members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop, context) : prop); + } + if (context) { + for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { + var name = _c[_b]; + if (!members.has(name)) { + members.set(name, getUndefinedProperty(name)); + } + } } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } - function getWidenedConstituentType(type) { - return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); - } function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { - if (type.flags & 6144 /* Nullable */) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 12582912 /* RequiresWidening */) { + if (type.flags & 12288 /* Nullable */) { return anyType; } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - return getWidenedTypeOfObjectLiteral(type); + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 65536 /* Union */) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + if (type.flags & 131072 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -32442,31 +34080,38 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 65536 /* Union */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { + if (type.flags & 4194304 /* ContainsWideningType */) { + if (type.flags & 131072 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } } } - } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152 /* ContainsWideningType */) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 4194304 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.symbolName(p), typeToString(getWidenedType(t))); + } + errorReported = true; } - errorReported = true; } } } @@ -32476,25 +34121,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 146 /* Parameter */: + case 147 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 176 /* BindingElement */: + case 177 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -32507,7 +34152,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && type.flags & 4194304 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -32576,12 +34221,12 @@ var ts; // we perform type inference (i.e. a type parameter of a generic function). We cache // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) || + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & (1081344 /* TypeVariable */ | 524288 /* Index */) || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 393216 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -32590,13 +34235,34 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `{}` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 32 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = emptyObjectType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 2 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } - // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct - // an object type with the same set of properties as the source type, where the type of each - // property is computed by inferring from the source property type to X for the type - // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). - function inferTypeForHomomorphicMappedType(source, target) { + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { var properties = getPropertiesOfType(source); var indexInfo = getIndexInfoOfType(source, 0 /* String */); if (properties.length === 0 && !indexInfo) { @@ -32611,32 +34277,30 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); - if (!inferredPropType) { + var propType = getTypeOfSymbol(prop); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + if (propType.flags & 16777216 /* ContainsAnyFunctionType */) { return undefined; } - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; + inferredProp.type = inferTargetType(propType); members.set(prop.escapedName, inferredProp); } if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); } return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); function inferTargetType(sourceType) { inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType); - return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); + inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); + return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; } } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = getPropertiesOfObjectType(target); + var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { @@ -32648,7 +34312,7 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; @@ -32667,8 +34331,8 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || - source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || + source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -32706,51 +34370,69 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 540672 /* TypeVariable */) { + if (target.flags & 1081344 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType which is used as a wildcard - // when constructing types from type parameters that had no inference candidates. - if (source.flags & 8388608 /* ContainsAnyFunctionType */ || source === silentNeverType) { + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 16777216 /* ContainsAnyFunctionType */ || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - if (!inference.candidates || priority < inference.priority) { + // We give lowest priority to inferences of implicitNeverType (which is used as the + // element type for empty array literals). Thus, inferences from empty array literals + // only matter when no other inferences are made. + var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); + if (!inference.candidates || p < inference.priority) { inference.candidates = [source]; - inference.priority = priority; + inference.priority = p; } - else if (priority === inference.priority) { + else if (p === inference.priority) { inference.candidates.push(source); } - if (!(priority & 4 /* ReturnType */) && target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + else if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } } } - else if (source.flags & 262144 /* Index */ && target.flags & 262144 /* Index */) { + else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { + priority ^= 1 /* Contravariant */; inferFromTypes(source.type, target.type); + priority ^= 1 /* Contravariant */; } - else if (source.flags & 524288 /* IndexedAccess */ && target.flags & 524288 /* IndexedAccess */) { + else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + priority ^= 1 /* Contravariant */; + inferFromTypes(empty, target.type); + priority ^= 1 /* Contravariant */; + } + else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (target.flags & 196608 /* UnionOrIntersection */) { + else if (target.flags & 393216 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -32770,12 +34452,12 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; + priority |= 2 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } } - else if (source.flags & 65536 /* Union */) { + else if (source.flags & 131072 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -32785,7 +34467,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & (32768 /* Object */ | 131072 /* Intersection */)) { + if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -32795,8 +34477,8 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 32768 /* Object */ && - !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var isNonConstructorObject = target.flags & 65536 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (ts.contains(symbolStack, symbol)) { @@ -32812,8 +34494,18 @@ var ts; } } } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes) { + priority ^= 1 /* Contravariant */; + inferFromTypes(source, target); + priority ^= 1 /* Contravariant */; + } + else { + inferFromTypes(source, target); + } + } function getInferenceInfoForType(type) { - if (type.flags & 540672 /* TypeVariable */) { + if (type.flags & 1081344 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -32830,26 +34522,32 @@ var ts; inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); } - if (getObjectFlags(target) & 32 /* Mapped */) { + if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144 /* Index */) { + if (constraintType.flags & 524288 /* Index */) { // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference // such that direct inferences to T get priority over inferences to Partial, for example. var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); + var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); + if (ts.contains(mappedTypeStack, key)) { + return; + } + (mappedTypeStack || (mappedTypeStack = [])).push(key); + var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); + mappedTypeStack.pop(); if (inferredType) { var savePriority = priority; - priority |= 2 /* MappedType */; + priority |= 4 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } } return; } - if (constraintType.flags & 16384 /* TypeParameter */) { + if (constraintType.flags & 32768 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. inferFromTypes(getIndexType(source), constraintType); @@ -32883,11 +34581,11 @@ var ts; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); } } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromContravariantTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -32936,17 +34634,32 @@ var ts; reducedTypes.push(t); } } - return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 131072 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); + return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; } function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; if (!inferredType) { if (inference.candidates) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if // all inferences were made to top-level ocurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and @@ -32955,12 +34668,14 @@ var ts; var widenLiteralTypes = inference.topLevel && !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; - // Infer widened union or supertype, or the unknown type for no common supertype. We infer union types - // for inferences coming from return types in order to avoid common supertype failures. - var unionOrSuperType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? - getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unionOrSuperType); + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if + // union types were requested or if all inferences were made from the return type position, infer a + // union type. Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : + context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : + getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unwidenedType); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -32982,12 +34697,13 @@ var ts; inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); } } + inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); } } } @@ -33016,7 +34732,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 162 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 143 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 163 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 144 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -33032,13 +34748,13 @@ var ts; if (node.kind === 99 /* ThisKeyword */) { return "0"; } - if (node.kind === 179 /* PropertyAccessExpression */) { + if (node.kind === 180 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + return key && key + "." + ts.idText(node.name); } - if (node.kind === 176 /* BindingElement */) { + if (node.kind === 177 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 176 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 177 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -33046,12 +34762,12 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 174 /* ObjectBindingPattern */) { + if (element.parent.kind === 175 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: - return ts.unescapeLeadingUnderscores(name.escapedText); - case 144 /* ComputedPropertyName */: + return ts.idText(name); + case 145 /* ComputedPropertyName */: return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -33069,26 +34785,26 @@ var ts; switch (source.kind) { case 71 /* Identifier */: return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 /* VariableDeclaration */ || target.kind === 176 /* BindingElement */) && + (target.kind === 227 /* VariableDeclaration */ || target.kind === 177 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99 /* ThisKeyword */: return target.kind === 99 /* ThisKeyword */; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; - case 179 /* PropertyAccessExpression */: - return target.kind === 179 /* PropertyAccessExpression */ && + case 180 /* PropertyAccessExpression */: + return target.kind === 180 /* PropertyAccessExpression */ && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 176 /* BindingElement */: - if (target.kind !== 179 /* PropertyAccessExpression */) + case 177 /* BindingElement */: + if (target.kind !== 180 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 176 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 177 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 226 /* VariableDeclaration */) { + if (source.parent.parent.kind === 227 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return maybeId && isMatchingReference(maybeId, t.expression); } @@ -33096,7 +34812,7 @@ var ts; return false; } function containsMatchingReference(source, target) { - while (source.kind === 179 /* PropertyAccessExpression */) { + while (source.kind === 180 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -33109,7 +34825,7 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 /* PropertyAccessExpression */ && + return target.kind === 180 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -33117,14 +34833,14 @@ var ts; if (expr.kind === 71 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 179 /* PropertyAccessExpression */) { + if (expr.kind === 180 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536 /* Union */) { + if (type && type.flags & 131072 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { @@ -33135,6 +34851,20 @@ var ts; } return false; } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -33147,7 +34877,7 @@ var ts; } } } - if (callExpression.expression.kind === 179 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 180 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -33161,7 +34891,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536 /* Union */)) { + if (!(source.flags & 131072 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -33177,11 +34907,11 @@ var ts; // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 8192 /* Never */) { + if (assignedType.flags & 16384 /* Never */) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192 /* Never */)) { + if (!(reducedType.flags & 16384 /* Never */)) { return reducedType; } } @@ -33230,32 +34960,42 @@ var ts; type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 32768 /* Object */) { + if (flags & 65536 /* Object */) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; } - if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { + if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 4096 /* Null */) { + if (flags & 8192 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 512 /* ESSymbol */) { + if (flags & 1536 /* ESSymbolLike */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { + if (flags & 33554432 /* NonPrimitive */) { return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; } - if (flags & 540672 /* TypeVariable */) { + if (flags & 1081344 /* TypeVariable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 196608 /* UnionOrIntersection */) { + if (flags & 393216 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } return 8388607 /* All */; } function getTypeWithFacts(type, include) { + if (type.flags & 1048576 /* IndexedAccess */) { + // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to + // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -33281,15 +35021,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 178 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 265 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 216 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 195 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); @@ -33306,21 +35046,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return stringType; - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return undefinedType; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -33328,7 +35068,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 /* ObjectBindingPattern */ ? + var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : @@ -33346,35 +35086,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 215 /* ForInStatement */) { + if (node.parent.parent.kind === 216 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 216 /* ForOfStatement */) { + if (node.parent.parent.kind === 217 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 226 /* VariableDeclaration */ ? + return node.kind === 227 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */ ? + return node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 226 /* VariableDeclaration */ && node.initializer && + return node.kind === 227 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 /* BindingElement */ && node.parent.kind === 194 /* BinaryExpression */ && + node.kind !== 177 /* BindingElement */ && node.parent.kind === 195 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: return getReferenceCandidate(node.left); @@ -33386,13 +35126,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 185 /* ParenthesizedExpression */ || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 186 /* ParenthesizedExpression */ || + parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 257 /* CaseClause */) { + if (clause.kind === 261 /* CaseClause */) { var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } @@ -33416,13 +35156,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 131072 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 131072 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536 /* Union */) { + if (source.flags & 131072 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -33437,10 +35177,10 @@ var ts; return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 131072 /* Union */ ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); @@ -33451,7 +35191,7 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union // of the resulting types is returned. function mapType(type, mapper) { - if (!(type.flags & 65536 /* Union */)) { + if (!(type.flags & 131072 /* Union */)) { return mapper(type); } var types = type.types; @@ -33520,9 +35260,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 8192 /* Never */ ? + return elementType.flags & 16384 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 65536 /* Union */ ? + createArrayType(elementType.flags & 131072 /* Union */ ? getUnionType(elementType.types, /*subtypeReduction*/ true) : elementType); } @@ -33531,17 +35271,17 @@ var ts; return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); } function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; } function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var t = types_15[_i]; - if (!(t.flags & 8192 /* Never */)) { - if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + if (!(t.flags & 16384 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } hasEvolvingArrayType = true; @@ -33562,11 +35302,11 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 181 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 180 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 182 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 181 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 194 /* BinaryExpression */ && + parent.parent.kind === 195 /* BinaryExpression */ && parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -33606,7 +35346,7 @@ var ts; if (flowAnalysisDisabled) { return unknownType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 35620607 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -33616,8 +35356,8 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 204 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 16384 /* Never */) { return declaredType; } return resultType; @@ -33688,7 +35428,7 @@ var ts; else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && reference.kind !== 180 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -33726,7 +35466,7 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 65536 /* Union */) { + if (declaredType.flags & 131072 /* Union */) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; @@ -33744,15 +35484,15 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 181 /* CallExpression */ ? + var expr = node.kind === 182 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256 /* EvolvingArray */) { + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 181 /* CallExpression */) { + if (node.kind === 182 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -33774,7 +35514,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 8192 /* Never */) { + if (type.flags & 16384 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -33791,7 +35531,7 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 16384 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -33917,8 +35657,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 179 /* PropertyAccessExpression */ && - computedType.flags & 65536 /* Union */ && + return expr.kind === 180 /* PropertyAccessExpression */ && + computedType.flags & 131072 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -33951,10 +35691,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 189 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -33988,7 +35728,7 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144 /* Nullable */) { + if (valueType.flags & 12288 /* Nullable */) { if (!strictNullChecks) { return type; } @@ -34000,12 +35740,12 @@ var ts; assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16810497 /* NotUnionOrUnit */) { + if (type.flags & 33620481 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 16384 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -34027,7 +35767,7 @@ var ts; if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 65536 /* Union */)) { + if (assumeTrue && !(type.flags & 131072 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. @@ -34036,7 +35776,7 @@ var ts; if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 540672 /* TypeVariable */) { + if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -34058,13 +35798,13 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 16384 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); @@ -34097,10 +35837,10 @@ var ts; if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2 /* Interface */) { + if (ts.getObjectFlags(rightType) & 2 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (getObjectFlags(rightType) & 16 /* Anonymous */) { + else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -34108,7 +35848,7 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } return type; } @@ -34118,9 +35858,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192 /* Never */)) { + if (!(assignableType.flags & 16384 /* Never */)) { return assignableType; } } @@ -34160,7 +35900,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 /* ElementAccessExpression */ || invokedExpression.kind === 179 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 181 /* ElementAccessExpression */ || invokedExpression.kind === 180 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -34180,15 +35920,15 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: if (expr.operator === 51 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -34207,7 +35947,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -34224,9 +35964,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 /* ModuleBlock */ || - node.kind === 265 /* SourceFile */ || - node.kind === 149 /* PropertyDeclaration */; + node.kind === 235 /* ModuleBlock */ || + node.kind === 269 /* SourceFile */ || + node.kind === 150 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. @@ -34248,7 +35988,7 @@ var ts; if (node.kind === 71 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 147 /* Parameter */) { symbol.isAssigned = true; } } @@ -34263,20 +36003,20 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 /* Parameter */ && + declaration.kind === 147 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 2048 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); + getFalsyFlags(declaredType) & 4096 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } function isApparentTypePosition(node) { var parent = node.parent; - return parent.kind === 179 /* PropertyAccessExpression */ || - parent.kind === 181 /* CallExpression */ && parent.expression === node || - parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + return parent.kind === 180 /* PropertyAccessExpression */ || + parent.kind === 182 /* CallExpression */ && parent.expression === node || + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; } function typeHasNullableConstraint(type) { - return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } function getDeclaredOrApparentType(symbol, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -34303,7 +36043,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 187 /* ArrowFunction */) { + if (container.kind === 188 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -34324,7 +36064,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 229 /* ClassDeclaration */ + if (declaration.kind === 230 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -34336,14 +36076,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 199 /* ClassExpression */) { + else if (declaration.kind === 200 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); while (container !== undefined) { if (container.parent === declaration) { - if (container.kind === 149 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + if (container.kind === 150 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } @@ -34389,15 +36129,15 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 146 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 147 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 /* FunctionExpression */ || - flowContainer.kind === 187 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 187 /* FunctionExpression */ || + flowContainer.kind === 188 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -34405,12 +36145,14 @@ var ts; // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 246 /* ExportSpecifier */) || - node.parent.kind === 203 /* NonNullExpression */ || - ts.isInAmbientContext(declaration); + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || + node.parent.kind === 204 /* NonNullExpression */ || + declaration.kind === 227 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 2097152 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048 /* Undefined */); + getOptionalType(type); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -34424,7 +36166,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -34437,7 +36179,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 260 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 264 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -34462,8 +36204,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 214 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 227 /* VariableDeclarationList */).parent === container && + if (container.kind === 215 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 228 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -34477,7 +36219,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 185 /* ParenthesizedExpression */) { + while (current.parent.kind === 186 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -34485,7 +36227,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 192 /* PrefixUnaryExpression */ || current.parent.kind === 193 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 193 /* PrefixUnaryExpression */ || current.parent.kind === 194 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; } @@ -34498,7 +36240,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 149 /* PropertyDeclaration */ || container.kind === 152 /* Constructor */) { + if (container.kind === 150 /* PropertyDeclaration */ || container.kind === 153 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -34566,38 +36308,38 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 152 /* Constructor */) { + if (container.kind === 153 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 187 /* ArrowFunction */) { + if (container.kind === 188 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 152 /* Constructor */: + case 153 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -34609,8 +36351,8 @@ var ts; // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } - if (container.kind === 186 /* FunctionExpression */ && - container.parent.kind === 194 /* BinaryExpression */ && + if (container.kind === 187 /* FunctionExpression */ && + container.parent.kind === 195 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') var className = container.parent // x.prototype.y = f @@ -34646,7 +36388,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 273 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 277 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -34656,15 +36398,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 147 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 182 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 187 /* ArrowFunction */) { + while (container && container.kind === 188 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -34677,14 +36419,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144 /* ComputedPropertyName */; }); - if (current && current.kind === 144 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 145 /* ComputedPropertyName */; }); + if (current && current.kind === 145 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 179 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -34692,7 +36434,7 @@ var ts; } return unknownType; } - if (!isCallExpression && container.kind === 152 /* Constructor */) { + if (!isCallExpression && container.kind === 153 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -34758,7 +36500,7 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 151 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (container.kind === 152 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -34772,7 +36514,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (container.parent.kind === 179 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -34784,15 +36526,16 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return unknownType; + } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } return unknownType; } - if (container.kind === 152 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 153 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -34807,7 +36550,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 152 /* Constructor */; + return container.kind === 153 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -34815,21 +36558,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 179 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */; + return container.kind === 152 /* MethodDeclaration */ || + container.kind === 151 /* MethodSignature */ || + container.kind === 154 /* GetAccessor */ || + container.kind === 155 /* SetAccessor */; } else { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */ || - container.kind === 149 /* PropertyDeclaration */ || - container.kind === 148 /* PropertySignature */ || - container.kind === 152 /* Constructor */; + return container.kind === 152 /* MethodDeclaration */ || + container.kind === 151 /* MethodSignature */ || + container.kind === 154 /* GetAccessor */ || + container.kind === 155 /* SetAccessor */ || + container.kind === 150 /* PropertyDeclaration */ || + container.kind === 149 /* PropertySignature */ || + container.kind === 153 /* Constructor */; } } } @@ -34837,22 +36580,22 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 151 /* MethodDeclaration */ || - func.kind === 153 /* GetAccessor */ || - func.kind === 154 /* SetAccessor */) && func.parent.kind === 178 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 186 /* FunctionExpression */ && func.parent.kind === 261 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 152 /* MethodDeclaration */ || + func.kind === 154 /* GetAccessor */ || + func.kind === 155 /* SetAccessor */) && func.parent.kind === 179 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 187 /* FunctionExpression */ && func.parent.kind === 265 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 262144 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 187 /* ArrowFunction */) { + if (func.kind === 188 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -34879,7 +36622,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 261 /* PropertyAssignment */) { + if (literal.parent.kind !== 265 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -34893,9 +36636,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { var target = parent.left; - if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { + if (target.kind === 180 /* PropertyAccessExpression */ || target.kind === 181 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -34938,6 +36681,10 @@ var ts; var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. + indexOfParameter -= 1; + } if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -34961,12 +36708,12 @@ var ts; // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer) { + if (node === declaration.initializer || node.kind === 58 /* EqualsToken */) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 146 /* Parameter */) { + if (declaration.kind === 147 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -34978,7 +36725,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 /* BindingElement */) { + if (parentDeclaration.kind !== 177 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -35019,10 +36766,14 @@ var ts; return undefined; } function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 /* Parameter */ && node.parent.initializer === node) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { return true; } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } node = node.parent; } return false; @@ -35030,7 +36781,7 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 152 /* Constructor */ || + if (functionDecl.kind === 153 /* Constructor */ || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); @@ -35056,43 +36807,58 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183 /* TaggedTemplateExpression */) { + if (template.parent.kind === 184 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (ts.isAssignmentOperator(operator)) { - // Don't do this for special property assignments to avoid circularity - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 58 /* EqualsToken */: + return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + case 54 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand. + var type = getContextualType(binaryExpression); + return !type && node === right ? getTypeOfExpression(left, /*cache*/ true) : type; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + // For completions after `x === ` + return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; + default: return undefined; - } - // In an assignment expression, the right operand is contextually typed by the type of the left operand. - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } } - else if (operator === 54 /* BarBarToken */) { - // When an || expression has a contextual type, the operands are contextually typed by that type. When an || - // expression has no contextual type, the right operand is contextually typed by the type of the left operand. - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left, /*cache*/ true); - } - return type; - } - else if (operator === 53 /* AmpersandAmpersandToken */ || operator === 26 /* CommaToken */) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for special property assignments to avoid circularity. + function isContextSensitiveAssignment(binaryExpression) { + var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + return !binaryExpression.left.symbol; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + return false; + default: + ts.Debug.assertNever(kind); } - return undefined; } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -35101,14 +36867,14 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 131072 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -35118,12 +36884,12 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { - if (!ts.hasDynamicName(element)) { + if (!hasNonBindableDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + var symbolName_1 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); if (propertyType) { return propertyType; } @@ -35151,7 +36917,12 @@ var ts; // JSX expression can appear in two position : JSX Element's children or JSX attribute var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? node.parent.parent : - node.parent.openingElement.attributes; // node.parent is JsxElement + ts.isJsxElement(node.parent) ? + node.parent.openingElement.attributes : + undefined; // node.parent is JsxFragment with no attributes + if (!jsxAttributes) { + return undefined; // don't check children of a fragment + } // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName @@ -35163,7 +36934,7 @@ var ts; // JSX expression is in JSX attribute return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } - else if (node.parent.kind === 249 /* JsxElement */) { + else if (node.parent.kind === 250 /* JsxElement */) { // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; @@ -35191,8 +36962,37 @@ var ts; // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (!(contextualType && contextualType.flags & 131072 /* Union */ && ts.isObjectLiteralExpression(node))) { + return contextualType; + } + // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` + var match; + propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (!prop.symbol) + continue; + if (prop.kind !== 265 /* PropertyAssignment */) + continue; + if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = getTypeOfNode(prop.initializer); + for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); + if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + match = undefined; + break propLoop; + } + match = type; + } + } + } + } + return match || contextualType; } /** * Woah! Do you really want to use this function? @@ -35212,7 +37012,7 @@ var ts; * @returns the contextual type of an expression. */ function getContextualType(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -35221,53 +37021,63 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 176 /* BindingElement */: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 177 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 187 /* ArrowFunction */: - case 219 /* ReturnStatement */: + case 188 /* ArrowFunction */: + case 220 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 183 /* NewExpression */: + if (node.kind === 94 /* NewKeyword */) { + return getContextualType(parent); + } + // falls through + case 182 /* CallExpression */: return getContextualTypeForArgument(parent, node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 177 /* ArrayLiteralExpression */: { + case 178 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 205 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); + case 206 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 197 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185 /* ParenthesizedExpression */: { + case 186 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: return getAttributesTypeFromJsxOpeningLikeElement(parent); + case 261 /* CaseClause */: { + if (node.kind === 73 /* CaseKeyword */) { + var switchStatement = parent.parent.parent; + return getTypeOfExpression(switchStatement.expression); + } + } } return undefined; } @@ -35302,7 +37112,7 @@ var ts; return sourceLength < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */; + return node.kind === 187 /* FunctionExpression */ || node.kind === 188 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -35321,12 +37131,12 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 65536 /* Union */)) { + if (!(type.flags & 131072 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; @@ -35367,8 +37177,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 176 /* BindingElement */ && !!node.initializer) || - (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 177 /* BindingElement */ && !!node.initializer) || + (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; @@ -35378,7 +37188,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elements.length; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 199 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -35403,7 +37213,7 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; + hasSpreadElement = hasSpreadElement || e.kind === 199 /* SpreadElement */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -35413,20 +37223,19 @@ var ts; type.pattern = node; return type; } - var contextualType_1 = getApparentTypeOfContextualType(node); - if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { - var pattern = contextualType_1.pattern; + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 176 /* ArrayBindingPattern */ || pattern.kind === 178 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType_1.typeArguments[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 200 /* OmittedExpression */) { + if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -35440,11 +37249,11 @@ var ts; } return createArrayType(elementTypes.length ? getUnionType(elementTypes, /*subtypeReduction*/ true) : - strictNullChecks ? neverType : undefinedWideningType); + strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return isNumericComputedName(name); case 71 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -35493,8 +37302,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 6144 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */) && + if (links.resolvedType.flags & 12288 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -35524,7 +37333,7 @@ var ts; var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 /* ObjectBindingPattern */ || contextualType.pattern.kind === 178 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 175 /* ObjectBindingPattern */ || contextualType.pattern.kind === 179 /* ObjectLiteralExpression */); var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); var typeFlags = 0; var patternWithComputedProperties = false; @@ -35534,18 +37343,18 @@ var ts; var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; - var member = memberDecl.symbol; + var member = getSymbolOfNode(memberDecl); var literalName = void 0; - if (memberDecl.kind === 261 /* PropertyAssignment */ || - memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 265 /* PropertyAssignment */ || + memberDecl.kind === 266 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var jsdocType = void 0; if (isInJSFile) { jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); } var type = void 0; - if (memberDecl.kind === 261 /* PropertyAssignment */) { - if (memberDecl.name.kind === 144 /* ComputedPropertyName */) { + if (memberDecl.kind === 265 /* PropertyAssignment */) { + if (memberDecl.name.kind === 145 /* ComputedPropertyName */) { var t = checkComputedPropertyName(memberDecl.name); if (t.flags & 224 /* Literal */) { literalName = ts.escapeLeadingUnderscores("" + t.value); @@ -35553,11 +37362,11 @@ var ts; } type = checkPropertyAssignment(memberDecl, checkMode); } - else if (memberDecl.kind === 151 /* MethodDeclaration */) { + else if (memberDecl.kind === 152 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, checkMode); } else { - ts.Debug.assert(memberDecl.kind === 262 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 266 /* ShorthandPropertyAssignment */); type = checkExpressionForMutableLocation(memberDecl.name, checkMode); } if (jsdocType) { @@ -35565,12 +37374,15 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); + var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; + var prop = nameType && isTypeUsableAsLateBoundName(nameType) + ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) + : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 261 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 265 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 266 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -35578,7 +37390,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.escapedName); @@ -35598,12 +37410,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 263 /* SpreadAssignment */) { + else if (memberDecl.kind === 267 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -35615,7 +37427,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -35625,10 +37437,10 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 154 /* GetAccessor */ || memberDecl.kind === 155 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (!literalName && ts.hasDynamicName(memberDecl)) { + if (!literalName && hasNonBindableDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -35646,7 +37458,7 @@ var ts; if (contextualTypeHasPattern) { for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; - if (!propertiesTable.get(prop.escapedName)) { + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { if (!(prop.flags & 16777216 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -35657,14 +37469,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -35673,8 +37478,8 @@ var ts; var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 2097152 /* FreshLiteral */; + result.flags |= 8388608 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 29360128 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -35682,25 +37487,25 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 6144 /* Nullable */)) { - propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); + if (!(result.flags & 12288 /* Nullable */)) { + propagatedFlags |= (result.flags & 29360128 /* PropagatingFlags */); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 32768 /* Object */ && !isGenericMappedType(type) || - type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (1 /* Any */ | 33554432 /* NonPrimitive */) || + getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 65536 /* Object */ && !isGenericMappedType(type) || + type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); + checkJsxOpeningLikeElementOrOpeningFragment(node); return getJsxGlobalElementType() || anyType; } function checkJsxElement(node) { // Check attributes - checkJsxOpeningLikeElement(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -35710,12 +37515,19 @@ var ts; } return getJsxGlobalElementType() || anyType; } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { + error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + } + return getJsxGlobalElementType() || anyType; + } /** * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers */ function isUnhyphenatedJsxName(name) { // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } /** * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name @@ -35723,7 +37535,7 @@ var ts; function isJsxIntrinsicIdentifier(tagName) { // TODO (yuisu): comment switch (tagName.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: case 99 /* ThisKeyword */: return false; case 71 /* Identifier */: @@ -35772,9 +37584,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 259 /* JsxSpreadAttribute */); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -35783,7 +37595,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -35793,7 +37605,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); } attributesArray = getPropertiesOfType(spread); } @@ -35806,23 +37618,10 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 250 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { - var childrenTypes = []; - for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that - // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } + var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { // Error if there is a attribute named "children" explicitly specified and children element. // This is because children element will overwrite the value from attributes. @@ -35851,11 +37650,28 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; + result.flags |= 67108864 /* JsxAttributes */ | 8388608 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 10 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + return childrenTypes; + } /** * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) @@ -35897,7 +37713,7 @@ var ts; return links.resolvedSymbol = intrinsicElementsType.symbol; } // Wasn't found - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { @@ -35915,7 +37731,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); + ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -35999,7 +37815,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 131072 /* Intersection */) { + if (propsType.flags & 262144 /* Intersection */) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -36020,7 +37836,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { @@ -36054,7 +37870,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type var jsxStatelessElementType = getJsxGlobalStatelessElementType(); @@ -36119,7 +37935,7 @@ var ts; */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } - if (elementType.flags & 65536 /* Union */) { + if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); @@ -36136,8 +37952,8 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + var stringLiteralTypeName = elementType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); } @@ -36145,7 +37961,7 @@ var ts; if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); } // If we need to report an error, we already done so here. So just return any to prevent any more error downstream return anyType; @@ -36323,14 +38139,18 @@ var ts; } } } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } checkJsxPreconditions(node); // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -36340,7 +38160,12 @@ var ts; markAliasSymbolAsReferenced(reactSym); } } - checkJsxAttributesAssignableToTagNameAttributes(node); + if (isNodeOpeningLikeElement) { + checkJsxAttributesAssignableToTagNameAttributes(node); + } + else { + checkJsxChildren(node.parent); + } } /** * Check if a property with the given name is known anywhere in the given type. In an object type, a property @@ -36356,7 +38181,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 32768 /* Object */) { + if (targetType.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -36366,7 +38191,7 @@ var ts; return true; } } - else if (targetType.flags & 196608 /* UnionOrIntersection */) { + else if (targetType.flags & 393216 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -36412,7 +38237,7 @@ var ts; for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -36424,7 +38249,7 @@ var ts; if (node.expression) { var type = checkExpression(node.expression, checkMode); if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); } return type; } @@ -36435,7 +38260,7 @@ var ts; // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 150 /* PropertyDeclaration */; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; @@ -36453,7 +38278,7 @@ var ts; */ function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? + var errorNode = node.kind === 180 /* PropertyAccessExpression */ || node.kind === 227 /* VariableDeclaration */ ? node.name : node.right; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { @@ -36470,11 +38295,7 @@ var ts; // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 /* MethodDeclaration */ && propKind !== 150 /* MethodSignature */; - }); - if (hasNonMethodDeclaration) { + if (symbolHasNonMethodDeclaration(prop)) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -36488,6 +38309,14 @@ var ts; return false; } } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + return false; + } + } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { return true; @@ -36495,7 +38324,7 @@ var ts; // Property is known to be private or protected at this point // Private property is accessible if the property is within the declaring class if (flags & 8 /* Private */) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; @@ -36522,29 +38351,34 @@ var ts; if (flags & 32 /* Static */) { return true; } - // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (type.flags & 32768 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = getConstraintOfTypeParameter(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } - if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { + if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; } + function symbolHasNonMethodDeclaration(symbol) { + return forEachProperty(symbol, function (prop) { + var propKind = getDeclarationKindFromSymbol(prop); + return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; + }); + } function checkNonNullExpression(node) { return checkNonNullType(checkExpression(node), node); } function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? + error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); var t = getNonNullableType(type); - return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t; + return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } return type; } @@ -36555,50 +38389,76 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { - // handle cases when type is Type parameter with invalid or any constraint + var propType; + var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; + var leftType = checkNonNullExpression(left); + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { return apparentType; } + var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); - if (indexInfo && indexInfo.type) { - if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { - error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + if (!(indexInfo && indexInfo.type)) { + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 32768 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } - return indexInfo.type; + return unknownType; } - if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); } - return unknownType; + propType = indexInfo.type; } - checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); - return unknownType; + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module + leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && + !(isNonLocalAlias(leftSymbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { + getSymbolLinks(leftSymbol).referenced = undefined; + } + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + return unknownType; + } } + propType = getDeclaredOrApparentType(prop, node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { + if (node.kind !== 180 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 131072 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 153 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + // Return the declared type to reduce follow-on errors return propType; } - var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { @@ -36609,25 +38469,25 @@ var ts; if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); } - else if (valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(valueDeclaration) && + else if (valueDeclaration.kind === 230 /* ClassDeclaration */ && + node.parent.kind !== 160 /* TypeReference */ && + !(valueDeclaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return true; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: - return ts.isPartOfExpression(node) ? false : "quit"; + return ts.isExpressionNode(node) ? false : "quit"; } }); } @@ -36658,7 +38518,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + if (containingType.flags & 131072 /* Union */ && !(containingType.flags & 16382 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -36669,7 +38529,7 @@ var ts; } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -36677,23 +38537,20 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455 /* Value */); - return suggestion && suggestion.escapedName; + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455 /* Value */); + return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ false, function (symbols, name, meaning) { + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); - if (symbol) { - // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function - // So the table *contains* `x` but `x` isn't actually in scope. - // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol; - } - return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - if (result) { - return result.escapedName; - } + return result && ts.symbolName(result); } /** * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. @@ -36705,67 +38562,103 @@ var ts; * except for candidates: * * With no name * * Whose meaning doesn't match the `meaning` parameter. - * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose length differs from the target name by more than 0.34 of the length of the name. * * Whose levenshtein distance is more than 0.4 of the length of the name * (0.4 allows 1 substitution/transposition for every 5 characters, * and 1 insertion/deletion at 3 characters) - * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. */ function getSpellingSuggestionForName(name, symbols, meaning) { - var worstDistance = name.length * 0.4; - var maximumLengthDifference = Math.min(3, name.length * 0.34); - var bestDistance = Number.MAX_VALUE; - var bestCandidate = undefined; + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; var justCheckExactMatches = false; - if (name.length > 30) { - return undefined; - } - name = name.toLowerCase(); + var nameLowerCase = name.toLowerCase(); for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; - var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); - if (candidate.flags & meaning && - candidateName && - Math.abs(candidateName.length - name.length) < maximumLengthDifference) { - candidateName = candidateName.toLowerCase(); - if (candidateName === name) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3 || - name.length < 3 || - candidateName === "eval" || - candidateName === "intl" || - candidateName === "undefined" || - candidateName === "map" || - candidateName === "nan" || - candidateName === "set") { - continue; - } - var distance = ts.levenshtein(name, candidateName); - if (distance > worstDistance) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else if (distance < bestDistance) { - bestDistance = distance; - bestCandidate = candidate; - } + var candidateName = ts.symbolName(candidate); + if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + continue; + } + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; } } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -36775,7 +38668,7 @@ var ts; } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 179 /* PropertyAccessExpression */ + var left = node.kind === 180 /* PropertyAccessExpression */ ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); @@ -36787,7 +38680,7 @@ var ts; return checkPropertyAccessibility(node, left, type, prop); } // In js files properties of unions are allowed in completion - if (ts.isInJavaScriptFile(left) && (type.flags & 65536 /* Union */)) { + if (ts.isInJavaScriptFile(left) && (type.flags & 131072 /* Union */)) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var elementType = _a[_i]; if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { @@ -36804,7 +38697,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 227 /* VariableDeclarationList */) { + if (initializer.kind === 228 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -36833,7 +38726,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 215 /* ForInStatement */ && + if (node.kind === 216 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -36851,7 +38744,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 183 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -36882,7 +38775,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 512 /* ESSymbol */) === 0) { + if ((expressionType.flags & 1536 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -36918,10 +38811,10 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 147 /* Decorator */) { + else if (node.kind !== 148 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -36987,7 +38880,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 198 /* SpreadElement */) { + if (arg && arg.kind === 199 /* SpreadElement */) { return i; } } @@ -37003,13 +38896,13 @@ var ts; // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 196 /* TemplateExpression */) { + if (tagExpression.template.kind === 197 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; @@ -37026,7 +38919,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 147 /* Decorator */) { + else if (node.kind === 148 /* Decorator */) { typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } @@ -37034,7 +38927,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 182 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 183 /* NewExpression */); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -37052,10 +38945,10 @@ var ts; if (!hasRightNumberOfTypeArgs) { return false; } - // If spread arguments are present, check that they correspond to a rest parameter. If so, no - // further checking is necessary. + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + return isRestParameterIndex(signature, spreadArgIndex) || + signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -37067,7 +38960,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -37084,7 +38977,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -37104,7 +38997,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 147 /* Decorator */) { + if (node.kind !== 148 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -37124,7 +39017,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -37139,7 +39032,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 201 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type @@ -37170,29 +39063,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (!constraint) + continue; + var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return false; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. @@ -37231,7 +39122,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 183 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // 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. @@ -37248,7 +39139,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 201 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); // If the effective argument type is undefined, there is no synthetic type for the argument. @@ -37272,12 +39163,12 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 181 /* CallExpression */) { + if (node.kind === 182 /* CallExpression */) { var callee = node.expression; - if (callee.kind === 179 /* PropertyAccessExpression */) { + if (callee.kind === 180 /* PropertyAccessExpression */) { return callee.expression; } - else if (callee.kind === 180 /* ElementAccessExpression */) { + else if (callee.kind === 181 /* ElementAccessExpression */) { return callee.expression; } } @@ -37292,17 +39183,17 @@ var ts; * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { var template = node.template; var args_4 = [undefined]; - if (template.kind === 196 /* TemplateExpression */) { + if (template.kind === 197 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 147 /* Decorator */) { + else if (node.kind === 148 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -37329,19 +39220,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147 /* Decorator */) { + if (node.kind === 148 /* Decorator */) { switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -37351,7 +39242,7 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 146 /* Parameter */: + case 147 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -37375,25 +39266,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 152 /* Constructor */) { + if (node.kind === 153 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -37420,23 +39311,23 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { node = node.parent; - if (node.kind === 152 /* Constructor */) { + if (node.kind === 153 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } // For a non-constructor parameter decorator, the `propertyKey` will be either // a string or a symbol, based on the name of the parameter's containing method. } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will @@ -37444,13 +39335,13 @@ var ts; var element = node; switch (element.name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + return getLiteralType(ts.idText(element.name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return getLiteralType(element.name.text); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 512 /* ESSymbol */)) { + if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { return nameType; } else { @@ -37474,21 +39365,21 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 149 /* PropertyDeclaration */) { + if (node.kind === 150 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -37520,10 +39411,10 @@ var ts; // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 147 /* Decorator */) { + if (node.kind === 148 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -37535,8 +39426,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 147 /* Decorator */ || - (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */)) { + if (node.kind === 148 /* Decorator */ || + (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -37545,11 +39436,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147 /* Decorator */) { + if (node.kind === 148 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -37558,8 +39449,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 147 /* Decorator */; + var isTaggedTemplate = node.kind === 184 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 148 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { @@ -37633,7 +39524,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 182 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -37670,8 +39561,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -37697,10 +39587,13 @@ var ts; var paramCount = hasRestParameter_1 ? min : min < max ? min + "-" + max : min; - var argCount = args.length - (hasSpreadArgument ? 1 : 0); - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + var argCount = args.length; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1; diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); } @@ -37721,14 +39614,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -37763,10 +39656,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -37774,6 +39669,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -37871,21 +39767,9 @@ var ts; * but is a subtype of the Function interface, the call is an untyped function call. */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (funcType.flags & 65536 /* Union */) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 /* Union */ | 16384 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -37930,9 +39814,9 @@ var ts; // Note, only class declarations can be declared abstract. // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } return resolveCall(node, constructSignatures, candidatesOutArray); @@ -37965,7 +39849,7 @@ var ts; if (!modifiers) { return true; } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { @@ -38015,16 +39899,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146 /* Parameter */: + case 147 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -38042,6 +39926,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -38052,6 +39941,18 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + }); + } /** * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName @@ -38063,9 +39964,8 @@ var ts; * the function will fill it up with appropriate candidate signatures */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); } /** * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. @@ -38078,7 +39978,7 @@ var ts; */ function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 65536 /* Union */) { + if (elementType.flags & 131072 /* Union */) { var types = elementType.types; var result = void 0; for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { @@ -38095,18 +39995,18 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 181 /* CallExpression */: + case 182 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147 /* Decorator */: + case 148 /* Decorator */: return resolveDecorator(node, candidatesOutArray); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -38169,13 +40069,13 @@ var ts; function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } function isInferredClassType(type) { return type.symbol - && getObjectFlags(type) & 16 /* Anonymous */ + && ts.getObjectFlags(type) & 16 /* Anonymous */ && getSymbolLinks(type.symbol).inferredClassType === type; } /** @@ -38184,27 +40084,28 @@ var ts; * @returns On success, the expression's signature's return type. On failure, anyType. */ function checkCallExpression(node) { - // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; } - if (node.kind === 182 /* NewExpression */) { + if (node.kind === 183 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 152 /* Constructor */ && - declaration.kind !== 156 /* ConstructSignature */ && - declaration.kind !== 161 /* ConstructorType */ && + declaration.kind !== 153 /* Constructor */ && + declaration.kind !== 157 /* ConstructSignature */ && + declaration.kind !== 162 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations // in a JS file // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. - var funcSymbol = node.expression.kind === 71 /* Identifier */ ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { return type; @@ -38219,11 +40120,35 @@ var ts; if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } - return getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 1536 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + return returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import - checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -38233,7 +40158,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 2048 /* Undefined */ || specifierType.flags & 4096 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 4096 /* Undefined */ || specifierType.flags & 8192 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -38285,18 +40210,21 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 228 /* FunctionDeclaration */ + ? 229 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 226 /* VariableDeclaration */ + ? 227 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); // function/variable declaration should be ambient - return ts.isInAmbientContext(decl); + return !!decl && !!(decl.flags & 2097152 /* Ambient */); } return false; } function checkTaggedTemplateExpression(node) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { @@ -38324,7 +40252,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return unknownType; } - else if (container.kind === 152 /* Constructor */) { + else if (container.kind === 153 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -38338,7 +40266,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return getNullableType(type, 2048 /* Undefined */); + return getOptionalType(type); } } return type; @@ -38452,7 +40380,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 207 /* Block */) { + if (func.body.kind !== 208 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -38493,27 +40421,43 @@ var ts; } // Return a union of the return expression types. type = getUnionType(types, /*subtypeReduction*/ true); - if (functionFlags & 1 /* Generator */) { - type = functionFlags & 2 /* Async */ - ? createAsyncIterableIteratorType(type) // AsyncGenerator function - : createIterableIteratorType(type); // Generator function - } } if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); } var widenedType = getWidenedType(type); - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ - ? createPromiseReturnType(func, widenedType) // Async function - : widenedType; // Generator function, AsyncGenerator function, or normal function + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; @@ -38554,8 +40498,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 222 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -38576,7 +40519,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 8192 /* Never */) { + if (type.flags & 16384 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -38586,7 +40529,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */)) { + func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -38608,16 +40551,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 2048 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 /* Block */ || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 208 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 8192 /* Never */) { + if (returnType && returnType.flags & 16384 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -38646,7 +40589,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { checkNodeDeferred(node); @@ -38654,7 +40597,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 187 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -38689,7 +40632,7 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 151 /* MethodDeclaration */) { + if (produceDiagnostics && node.kind !== 152 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -38697,12 +40640,12 @@ var ts; return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnOrPromisedType = returnTypeNode && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : + checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { // return is not necessary in the body of generators @@ -38717,7 +40660,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 207 /* Block */) { + if (node.body.kind === 208 /* Block */) { checkSourceElement(node.body); } else { @@ -38764,11 +40707,11 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) && + (expr.kind === 180 /* PropertyAccessExpression */ || expr.kind === 181 /* ElementAccessExpression */) && expr.expression.kind === 99 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152 /* Constructor */)) { + if (!(func && func.kind === 153 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -38781,13 +40724,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) { + if (expr.kind === 180 /* PropertyAccessExpression */ || expr.kind === 181 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240 /* NamespaceImport */; + return declaration && declaration.kind === 241 /* NamespaceImport */; } } } @@ -38796,7 +40739,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { + if (node.kind !== 71 /* Identifier */ && node.kind !== 180 /* PropertyAccessExpression */ && node.kind !== 181 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -38805,7 +40748,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 /* PropertyAccessExpression */ && expr.kind !== 180 /* ElementAccessExpression */) { + if (expr.kind !== 180 /* PropertyAccessExpression */ && expr.kind !== 181 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -38855,7 +40798,7 @@ var ts; case 38 /* MinusToken */: case 52 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 1536 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -38893,7 +40836,7 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 196608 /* UnionOrIntersection */) { + if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { var t = types_18[_i]; @@ -38908,21 +40851,26 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 /* Any */ | 1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */)) { + if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { return false; } return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 262178 /* StringLike */ && isTypeAssignableTo(source, stringType)) || + (kind & 524322 /* StringLike */ && isTypeAssignableTo(source, stringType)) || (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 1024 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 8192 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 4096 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 2048 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || + (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || + (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || + (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || + (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 16777216 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + (kind & 33554432 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 131072 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -38936,14 +40884,12 @@ var ts; // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190 /* Primitive */)) { + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 16382 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0 /* Call */).length || - getSignaturesOfType(rightType, 1 /* Construct */).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); } return booleanType; @@ -38958,10 +40904,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { + if (!isTypeAssignableToKind(rightType, 33554432 /* NonPrimitive */ | 1081344 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -38976,9 +40922,9 @@ var ts; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 /* PropertyAssignment */ || property.kind === 262 /* ShorthandPropertyAssignment */) { + if (property.kind === 265 /* PropertyAssignment */ || property.kind === 266 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -38991,7 +40937,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 262 /* ShorthandPropertyAssignment */) { + if (property.kind === 266 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { @@ -39003,8 +40949,8 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 263 /* SpreadAssignment */) { - if (languageVersion < 5 /* ESNext */) { + else if (property.kind === 267 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } var nonRestNames = []; @@ -39037,8 +40983,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 200 /* OmittedExpression */) { - if (element.kind !== 198 /* SpreadElement */) { + if (element.kind !== 201 /* OmittedExpression */) { + if (element.kind !== 199 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -39066,7 +41012,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 194 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 195 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -39079,13 +41025,13 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 262 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 266 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -39095,21 +41041,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 194 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 195 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 178 /* ObjectLiteralExpression */) { + if (target.kind === 179 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 177 /* ArrayLiteralExpression */) { + if (target.kind === 178 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 /* SpreadAssignment */ ? + var error = target.parent.kind === 267 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -39131,35 +41077,35 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 12 /* RegularExpressionLiteral */: - case 183 /* TaggedTemplateExpression */: - case 196 /* TemplateExpression */: + case 184 /* TaggedTemplateExpression */: + case 197 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 139 /* UndefinedKeyword */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: - case 187 /* ArrowFunction */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 189 /* TypeOfExpression */: - case 203 /* NonNullExpression */: - case 250 /* JsxSelfClosingElement */: - case 249 /* JsxElement */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 190 /* TypeOfExpression */: + case 204 /* NonNullExpression */: + case 251 /* JsxSelfClosingElement */: + case 250 /* JsxElement */: return true; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -39171,29 +41117,22 @@ var ts; } return false; // Some forms listed here for clarity - case 190 /* VoidExpression */: // Explicit opt-out - case 184 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 202 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 191 /* VoidExpression */: // Explicit opt-out + case 185 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 203 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], /*subtypeReduction*/ true); + return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 178 /* ObjectLiteralExpression */ || left.kind === 177 /* ArrayLiteralExpression */)) { + if (operator === 58 /* EqualsToken */ && (left.kind === 179 /* ObjectLiteralExpression */ || left.kind === 178 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); @@ -39248,7 +41187,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 262178 /* StringLike */) && !isTypeAssignableToKind(rightType, 262178 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 524322 /* StringLike */) && !isTypeAssignableToKind(rightType, 524322 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } @@ -39258,7 +41197,7 @@ var ts; // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } - else if (isTypeAssignableToKind(leftType, 262178 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 262178 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 524322 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 524322 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -39315,7 +41254,7 @@ var ts; leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : leftType; case 58 /* EqualsToken */: checkAssignmentOperator(rightType); @@ -39331,8 +41270,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 1536 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -39407,7 +41346,7 @@ var ts; // Async generator functions prior to ESNext require the __await, __asyncDelegator, // and __asyncValues helpers if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && - languageVersion < 5 /* ESNext */) { + languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } // Generator functions prior to ES2015 require the __values helper @@ -39451,7 +41390,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2], /*subtypeReduction*/ true); } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -39491,27 +41430,42 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 184 /* TypeAssertionExpression */ || node.kind === 202 /* AsExpression */; + return node.kind === 185 /* TypeAssertionExpression */ || node.kind === 203 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || + (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } - function isLiteralContextualType(contextualType) { + function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { - return true; - } - contextualType = constraint; + if (contextualType.flags & 131072 /* Union */ && !(contextualType.flags & 8 /* Boolean */)) { + // If the contextual type is a union containing both of the 'true' and 'false' types we + // don't consider it a literal context for boolean literals. + var types_19 = contextualType.types; + return ts.some(types_19, function (t) { + return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_19, trueType) && containsType(types_19, falseType)) && + isLiteralOfContextualType(candidateType, t); + }); } - return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); + if (contextualType.flags & 1081344 /* TypeVariable */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || + constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || + contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); } return false; } @@ -39520,14 +41474,14 @@ var ts; contextualType = getContextualType(node); } var type = checkExpression(node, checkMode); - var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); - return shouldWiden ? type : getWidenedLiteralType(type); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -39538,7 +41492,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -39568,7 +41522,7 @@ var ts; function getTypeOfExpression(node, cache) { // 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 (node.kind === 181 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (node.kind === 182 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -39603,7 +41557,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, checkMode) { var type; - if (node.kind === 143 /* QualifiedName */) { + if (node.kind === 144 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -39615,9 +41569,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -39651,72 +41605,74 @@ var ts; return trueType; case 86 /* FalseKeyword */: return falseType; - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: return globalRegExpType; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: if (node.expression.kind === 91 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 182 /* NewExpression */: + case 183 /* NewExpression */: return checkCallExpression(node); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return checkClassExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return checkAssertion(node); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return checkNonNullAssertion(node); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return checkMetaProperty(node); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return checkDeleteExpression(node); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return checkVoidExpression(node); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return checkAwaitExpression(node); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 200 /* OmittedExpression */: + case 201 /* OmittedExpression */: return undefinedWideningType; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return checkYieldExpression(node); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 249 /* JsxElement */: + case 250 /* JsxElement */: return checkJsxElement(node); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 254 /* JsxAttributes */: + case 254 /* JsxFragment */: + return checkJsxFragment(node); + case 258 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 251 /* JsxOpeningElement */: + case 252 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -39733,6 +41689,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -39747,13 +41706,11 @@ var ts; // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code // or if its FunctionBody is strict code(11.1.5). - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 153 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -39764,7 +41721,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 152 /* Constructor */ || func.kind === 156 /* ConstructSignature */ || func.kind === 161 /* ConstructorType */) { + if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -39830,13 +41787,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 187 /* ArrowFunction */: - case 155 /* CallSignature */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 160 /* FunctionType */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 188 /* ArrowFunction */: + case 156 /* CallSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 161 /* FunctionType */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -39854,7 +41811,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 175 /* ArrayBindingPattern */ || name.kind === 174 /* ObjectBindingPattern */) { + else if (name.kind === 176 /* ArrayBindingPattern */ || name.kind === 175 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -39863,18 +41820,18 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 160 /* FunctionType */ || node.kind === 228 /* FunctionDeclaration */ || node.kind === 161 /* ConstructorType */ || - node.kind === 155 /* CallSignature */ || node.kind === 152 /* Constructor */ || - node.kind === 156 /* ConstructSignature */) { + else if (node.kind === 161 /* FunctionType */ || node.kind === 229 /* FunctionDeclaration */ || node.kind === 162 /* ConstructorType */ || + node.kind === 156 /* CallSignature */ || node.kind === 153 /* Constructor */ || + node.kind === 157 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); if (!(functionFlags & 4 /* Invalid */)) { // Async generators prior to ESNext require the __await and __asyncGenerator helpers - if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } // Async functions prior to ES2017 require the __awaiter helper @@ -39898,10 +41855,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 155 /* CallSignature */: + case 156 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -39948,7 +41905,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152 /* Constructor */) { + if (member.kind === 153 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -39962,16 +41919,16 @@ var ts; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: addName(names, member.name, memberName, 1 /* Getter */); break; - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: addName(names, member.name, memberName, 2 /* Setter */); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: addName(names, member.name, memberName, 3 /* Property */); break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: addName(names, member.name, memberName, 4 /* Method */); break; } @@ -40023,7 +41980,7 @@ var ts; case "arguments": case "prototype": var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); error(memberNameNode, message, memberName, className); break; } @@ -40034,7 +41991,7 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148 /* PropertySignature */) { + if (member.kind === 149 /* PropertySignature */) { var memberName = void 0; switch (member.name.kind) { case 9 /* StringLiteral */: @@ -40042,7 +41999,7 @@ var ts; memberName = member.name.text; break; case 71 /* Identifier */: - memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + memberName = ts.idText(member.name); break; default: continue; @@ -40058,7 +42015,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230 /* InterfaceDeclaration */) { + if (node.kind === 231 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -40101,12 +42058,14 @@ var ts; } function checkPropertyDeclaration(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); } function checkMethodDeclaration(node) { // Grammar checking - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. @@ -40119,7 +42078,8 @@ var ts; // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); // Grammar check for checking only related to constructorDeclaration - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); @@ -40152,7 +42112,7 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function isInstancePropertyWithInitializer(n) { - return n.kind === 149 /* PropertyDeclaration */ && + return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -40182,7 +42142,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -40203,11 +42163,12 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { // Grammar checking accessors - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 153 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (node.kind === 154 /* GetAccessor */) { + if (!(node.flags & 2097152 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } @@ -40216,14 +42177,14 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + var otherKind = node.kind === 154 /* GetAccessor */ ? 155 /* SetAccessor */ : 154 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); var otherFlags = ts.getModifierFlags(otherAccessor); @@ -40240,7 +42201,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153 /* GetAccessor */) { + if (node.kind === 154 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -40270,14 +42231,14 @@ var ts; mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, instantiateType(constraint, mapper), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 159 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 160 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -40291,11 +42252,14 @@ var ts; // There is no resolved symbol cached if the type resolved to a builtin // via JSDoc type reference resolution (eg, Boolean became boolean), none // of which are generic when they have no associated symbol - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + // (additionally, JSDoc's index signature syntax, Object actually uses generic syntax without being generic) + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; - if (!typeParameters && getObjectFlags(type) & 4 /* Reference */) { + if (!typeParameters && ts.getObjectFlags(type) & 4 /* Reference */) { typeParameters = type.target.localTypeParameters; } checkTypeArgumentConstraints(typeParameters, node.typeArguments); @@ -40333,15 +42297,15 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288 /* IndexedAccess */)) { + if (!(type.flags & 1048576 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { + if (accessNode.kind === 181 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; @@ -40366,17 +42330,21 @@ var ts; var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8 /* Private */) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 2097152 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 230 /* InterfaceDeclaration */ && - n.parent.kind !== 229 /* ClassDeclaration */ && - n.parent.kind !== 199 /* ClassExpression */ && - ts.isInAmbientContext(n)) { + if (n.parent.kind !== 231 /* InterfaceDeclaration */ && + n.parent.kind !== 230 /* ClassDeclaration */ && + n.parent.kind !== 200 /* ClassExpression */ && + n.flags & 2097152 /* Ambient */) { if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; @@ -40466,7 +42434,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && + var reportError = (node.kind === 152 /* MethodDeclaration */ || node.kind === 151 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -40504,8 +42472,8 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; + var inAmbientContext = node.flags & 2097152 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 231 /* InterfaceDeclaration */ || node.parent.kind === 164 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -40516,7 +42484,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 228 /* FunctionDeclaration */ || node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */ || node.kind === 152 /* Constructor */) { + if (node.kind === 229 /* FunctionDeclaration */ || node.kind === 152 /* MethodDeclaration */ || node.kind === 151 /* MethodSignature */ || node.kind === 153 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -40644,30 +42612,30 @@ var ts; })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(d) { switch (d.kind) { - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: // A jsdoc typedef is, by definition, a type alias - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return 2 /* ExportType */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 239 /* ImportClause */: - var result_3 = 0 /* None */; + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 240 /* ImportClause */: + var result_2 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - case 228 /* FunctionDeclaration */: - case 242 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 229 /* FunctionDeclaration */: + case 243 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: ts.Debug.fail(ts.SyntaxKind[d.kind]); @@ -40745,7 +42713,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -40754,7 +42722,7 @@ var ts; if (!types) { return undefined; } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true); + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { @@ -40919,7 +42887,7 @@ var ts; var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455 /* Value */); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; } } @@ -40937,22 +42905,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 146 /* Parameter */: + case 147 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -40996,11 +42964,20 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 167 /* IntersectionType */: - case 166 /* UnionType */: + case 168 /* IntersectionType */: + case 167 /* UnionType */: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) { // Individual is something like string number @@ -41024,9 +43001,9 @@ var ts; } } return commonEntityName; - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return node.typeName; } } @@ -41042,7 +43019,7 @@ var ts; } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { @@ -41050,14 +43027,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -41066,20 +43043,25 @@ var ts; } } break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 146 /* Parameter */: + case 147 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } break; } } @@ -41102,6 +43084,42 @@ var ts; error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 144 /* QualifiedName */ ? node.name.right : node.name)); + } + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 282 /* JSDocAugmentsTag */); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 71 /* Identifier */: + return node; + case 180 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); @@ -41109,12 +43127,12 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 145 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -41171,68 +43189,67 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 265 /* SourceFile */: - case 233 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 234 /* ModuleDeclaration */: checkUnusedModuleMembers(node); break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: checkUnusedTypeParameters(node); break; - case 207 /* Block */: - case 235 /* CaseBlock */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 208 /* Block */: + case 236 /* CaseBlock */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: checkUnusedLocalsAndParameters(node); break; - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - checkUnusedTypeParameters(node); - break; - case 231 /* TypeAliasDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 232 /* TypeAliasDeclaration */: checkUnusedTypeParameters(node); break; + default: + ts.Debug.fail("Node should not have been registered for unused identifiers check"); } } } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + if (noUnusedIdentifiers && !(node.flags & 2097152 /* Ambient */)) { node.locals.forEach(function (local) { if (!local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 147 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); } } }); @@ -41249,8 +43266,8 @@ var ts; var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 145 /* TypeParameter */) { + if ((declaration_2.kind === 227 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 146 /* TypeParameter */) { return; } } @@ -41262,23 +43279,23 @@ var ts; return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95 /* _ */; + return node.kind === 71 /* Identifier */ && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { + if (member.kind === 152 /* MethodDeclaration */ || member.kind === 150 /* PropertyDeclaration */) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); } } - else if (member.kind === 152 /* Constructor */) { + else if (member.kind === 153 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } } @@ -41287,7 +43304,7 @@ var ts; } } function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { if (node.typeParameters) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. @@ -41299,20 +43316,20 @@ var ts; for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); } } } } } function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { node.locals.forEach(function (local) { if (!local.isReferenced && !local.exportSymbol) { for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.symbolName(local)); } } } @@ -41321,7 +43338,7 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 207 /* Block */) { + if (node.kind === 208 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -41338,7 +43355,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -41351,21 +43368,21 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 148 /* PropertySignature */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 150 /* MethodSignature */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 149 /* PropertySignature */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 151 /* MethodSignature */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152 /* Ambient */) { // ambient context - no codegen impact return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 146 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 147 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -41417,7 +43434,7 @@ var ts; // bubble up and find containing type var enclosingClass = ts.getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + if (!enclosingClass || enclosingClass.flags & 2097152 /* Ambient */) { return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { @@ -41439,12 +43456,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -41454,12 +43471,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -41494,7 +43511,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 226 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 227 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -41506,17 +43523,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 208 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 228 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 209 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 207 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 234 /* ModuleBlock */ || - container.kind === 233 /* ModuleDeclaration */ || - container.kind === 265 /* SourceFile */); + (container.kind === 208 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 235 /* ModuleBlock */ || + container.kind === 234 /* ModuleDeclaration */ || + container.kind === 269 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -41531,7 +43548,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 147 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -41542,7 +43559,7 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 179 /* PropertyAccessExpression */) { + if (n.kind === 180 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } @@ -41561,8 +43578,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 /* Parameter */ || - symbol.valueDeclaration.kind === 176 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 147 /* Parameter */ || + symbol.valueDeclaration.kind === 177 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -41576,7 +43593,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 149 /* PropertyDeclaration */ && + (current.parent.kind === 150 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -41607,18 +43624,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 176 /* BindingElement */) { - if (node.parent.kind === 174 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { + if (node.kind === 177 /* BindingElement */) { + if (node.parent.kind === 175 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 144 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -41626,27 +43643,27 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 176 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 146 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 147 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -41657,7 +43674,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -41666,8 +43683,10 @@ var ts; // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); + if (type !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* JSContainer */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); @@ -41677,10 +43696,10 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */) { + if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */) { + if (node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -41690,9 +43709,16 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 150 /* PropertyDeclaration */ || nextDeclaration.kind === 149 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 /* Parameter */ && right.kind === 226 /* VariableDeclaration */) || - (left.kind === 226 /* VariableDeclaration */ && right.kind === 146 /* Parameter */)) { + if ((left.kind === 147 /* Parameter */ && right.kind === 227 /* VariableDeclaration */) || + (left.kind === 227 /* VariableDeclaration */ && right.kind === 147 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -41717,12 +43743,13 @@ var ts; } function checkVariableStatement(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 179 /* ObjectLiteralExpression */) { if (ts.getFunctionFlags(node) & 2 /* Async */) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -41743,7 +43770,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209 /* EmptyStatement */) { + if (node.thenStatement.kind === 210 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -41763,12 +43790,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 228 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -41786,10 +43813,10 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 216 /* ForOfStatement */) { + if (node.kind === 217 /* ForOfStatement */) { if (node.awaitModifier) { var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } @@ -41804,14 +43831,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + if (varExpr.kind === 178 /* ArrayLiteralExpression */ || varExpr.kind === 179 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -41843,7 +43870,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -41857,7 +43884,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + if (varExpr.kind === 178 /* ArrayLiteralExpression */ || varExpr.kind === 179 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -41870,7 +43897,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { + if (!isTypeAssignableToKind(rightType, 33554432 /* NonPrimitive */ | 1081344 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -41921,16 +43948,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 65536 /* Union */) { + if (arrayType.flags & 131072 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); } } - else if (arrayType.flags & 262178 /* StringLike */) { + else if (arrayType.flags & 524322 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -41943,7 +43970,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 8192 /* Never */) { + if (arrayType.flags & 16384 /* Never */) { return stringType; } } @@ -41969,7 +43996,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 262178 /* StringLike */) { + if (arrayElementType.flags & 524322 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); @@ -42166,18 +44193,19 @@ var ts; } function checkBreakOrContinueStatement(node) { // Grammar checking - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 153 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */)) !== undefined; + return node.kind === 154 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 155 /* SetAccessor */)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -42191,22 +44219,22 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return expressions of generators when return type tracking is added + // for generators. + return; + } + if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { - // A generator does not need its return expressions checked against its return type. - // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added - // for generators. - return; - } - if (func.kind === 154 /* SetAccessor */) { + if (func.kind === 155 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 152 /* Constructor */) { + else if (func.kind === 153 /* Constructor */) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -42227,7 +44255,7 @@ var ts; } } } - else if (func.kind !== 152 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -42257,7 +44285,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 258 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 262 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -42269,7 +44297,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 257 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 261 /* CaseClause */) { var caseClause = clause; // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable @@ -42299,7 +44327,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 222 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 223 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); return true; @@ -42363,17 +44391,18 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasModifier(member, 32 /* Static */) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); } } } @@ -42382,7 +44411,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -42403,15 +44432,15 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && - (propDeclaration.kind === 194 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + (propDeclaration.kind === 195 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 145 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (getObjectFlags(containingType) & 2 /* Interface */) { + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -42561,7 +44590,7 @@ var ts; checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!ts.isInAmbientContext(node)) { + if (!(node.flags & 2097152 /* Ambient */)) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); @@ -42587,10 +44616,10 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 1081344 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked @@ -42627,6 +44656,7 @@ var ts; if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); } } function checkBaseTypeAccessibility(type, node) { @@ -42634,7 +44664,7 @@ var ts; if (signatures.length) { var declaration = signatures[0].declaration; if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } @@ -42646,12 +44676,9 @@ var ts; // so we'll need to get back original 'target' symbol to work with correct set of flags return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); - } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 /* ClassDeclaration */ || d.kind === 230 /* InterfaceDeclaration */; + return d.kind === 230 /* ClassDeclaration */ || d.kind === 231 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -42685,12 +44712,12 @@ var ts; // type declaration, derived and base resolve to the same symbol even in the case of generic classes. if (derived === base) { // derived class inherits base without override/redeclaration - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 199 /* ClassExpression */) { + if (derivedClassDecl.kind === 200 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -42761,9 +44788,42 @@ var ts; } return ok; } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 1 /* Any */ || getFalsyFlags(type) & 4096 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 150 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 4096 /* Undefined */); + } function checkInterfaceDeclaration(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); @@ -42771,7 +44831,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 231 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -42800,7 +44860,7 @@ var ts; } function checkTypeAliasDeclaration(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); checkTypeParameters(node.typeParameters); checkSourceElement(node.type); @@ -42834,7 +44894,7 @@ var ts; } // In ambient enum declarations that specify no const modifier, enum member declarations that omit // a value are considered computed members (as opposed to having auto-incremented values). - if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + if (member.parent.flags & 2097152 /* Ambient */ && !ts.isConst(member.parent)) { return undefined; } // If the member declaration specifies no value, the member is considered a constant enum member. @@ -42866,7 +44926,7 @@ var ts; else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (ts.isInAmbientContext(member.parent)) { + else if (member.parent.flags & 2097152 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { @@ -42876,7 +44936,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: var value_1 = evaluate(expr.operand); if (typeof value_1 === "number") { switch (expr.operator) { @@ -42886,7 +44946,7 @@ var ts; } } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -42910,18 +44970,18 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 179 /* PropertyAccessExpression */) { + if (ex.kind === 180 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -42942,7 +45002,7 @@ var ts; var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { - return getNodeLinks(declaration).enumMemberValue; + return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; @@ -42953,8 +45013,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 /* Identifier */ || - node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 180 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 181 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9 /* StringLiteral */; } function checkEnumDeclaration(node) { @@ -42962,7 +45022,7 @@ var ts; return; } // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -42971,7 +45031,7 @@ var ts; checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152 /* Ambient */) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } // Spec 2014 - Section 9.3: @@ -42994,7 +45054,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 232 /* EnumDeclaration */) { + if (declaration.kind !== 233 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -43017,9 +45077,9 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { var declaration = declarations_7[_i]; - if ((declaration.kind === 229 /* ClassDeclaration */ || - (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 230 /* ClassDeclaration */ || + (declaration.kind === 229 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 2097152 /* Ambient */)) { return declaration; } } @@ -43042,7 +45102,7 @@ var ts; if (produceDiagnostics) { // Grammar checking var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContext = node.flags & 2097152 /* Ambient */; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -43054,7 +45114,7 @@ var ts; // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node)) { if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -43082,7 +45142,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 229 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 230 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -43133,23 +45193,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 237 /* ImportEqualsDeclaration */: - case 238 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 239 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 176 /* BindingElement */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 227 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -43160,12 +45220,12 @@ var ts; break; } // falls through - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 228 /* FunctionDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 229 /* FunctionDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -43188,12 +45248,12 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: do { node = node.left; } while (node.kind !== 71 /* Identifier */); return node; - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 71 /* Identifier */); @@ -43206,9 +45266,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 235 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 269 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 245 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -43241,16 +45301,16 @@ var ts; (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 246 /* ExportSpecifier */ ? + var message = node.kind === 247 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 246 /* ExportSpecifier */ + && node.kind === 247 /* ExportSpecifier */ && !(target.flags & 107455 /* Value */) - && !ts.isInAmbientContext(node)) { + && !(node.flags & 2097152 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } @@ -43266,7 +45326,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -43276,7 +45336,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 241 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -43291,13 +45351,13 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.moduleReference.kind !== 249 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 107455 /* Value */) { @@ -43313,7 +45373,7 @@ var ts; } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152 /* Ambient */)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -43325,7 +45385,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -43333,10 +45393,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 /* ModuleBlock */ && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 235 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 235 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 2097152 /* Ambient */; + if (node.parent.kind !== 269 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -43353,7 +45413,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 /* SourceFile */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 233 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 269 /* SourceFile */ || node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 234 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -43361,13 +45421,16 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { markExportAsReferenced(node); @@ -43379,8 +45442,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 234 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -43390,20 +45453,23 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } } else { checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 2097152 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (node.isExportEquals && !(node.flags & 2097152 /* Ambient */)) { if (modulekind >= ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); @@ -43430,31 +45496,33 @@ var ts; } // Checks for export * conflicts var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. - // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); - if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { - // it is legal to merge type alias with other values - // so count should be either 1 (just type alias) or 2 (type alias + merged value) - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (exports) { + exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } - } - }); + }); + } links.exportsChecked = true; } } @@ -43463,7 +45531,7 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || + return (declaration.kind !== 229 /* FunctionDeclaration */ && declaration.kind !== 152 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { @@ -43481,144 +45549,200 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return checkTypeParameter(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return checkParameter(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return checkPropertyDeclaration(node); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return checkSignatureDeclaration(node); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return checkMethodDeclaration(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return checkConstructorDeclaration(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return checkAccessorDeclaration(node); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return checkTypeReferenceNode(node); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return checkTypePredicate(node); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return checkTypeQuery(node); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return checkTypeLiteral(node); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return checkArrayType(node); - case 165 /* TupleType */: + case 166 /* TupleType */: return checkTupleType(node); - case 166 /* UnionType */: - case 167 /* IntersectionType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: + case 169 /* ParenthesizedType */: return checkSourceElement(node.type); - case 283 /* JSDocTypedefTag */: + case 171 /* TypeOperator */: + return checkTypeOperator(node); + case 282 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 288 /* JSDocTypedefTag */: return checkJSDocTypedefTag(node); - case 279 /* JSDocParameterTag */: - return checkSourceElement(node.typeExpression); - case 273 /* JSDocFunctionType */: + case 284 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 277 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 274 /* JSDocVariadicType */: - case 271 /* JSDocNonNullableType */: - case 270 /* JSDocNullableType */: - case 268 /* JSDocAllType */: - case 269 /* JSDocUnknownType */: - if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); - } + case 275 /* JSDocNonNullableType */: + case 274 /* JSDocNullableType */: + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); return; - case 267 /* JSDocTypeExpression */: + case 278 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 271 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 172 /* MappedType */: + case 173 /* MappedType */: return checkMappedType(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 207 /* Block */: - case 234 /* ModuleBlock */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return checkBlock(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return checkVariableStatement(node); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return checkExpressionStatement(node); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return checkIfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return checkDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return checkWhileStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return checkForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return checkForInStatement(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return checkForOfStatement(node); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return checkReturnStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return checkWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return checkSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return checkLabeledStatement(node); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return checkThrowStatement(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return checkTryStatement(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return checkBindingElement(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return checkClassDeclaration(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return checkImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return checkExportDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return checkExportAssignment(node); - case 209 /* EmptyStatement */: + case 210 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 225 /* DebuggerStatement */: + case 226 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 247 /* MissingDeclaration */: + case 248 /* MissingDeclaration */: return checkMissingDeclaration(node); } } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJavaScriptFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag. + var parent = node.parent; + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = parent.parent; + if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (param) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + /* + Only return an array type if the corresponding parameter is marked as a rest parameter. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = host_1 && ts.last(host_1.parameters); + if (lastParamDeclaration.symbol === param && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + return addOptionality(type); + } // Function and class expression bodies are checked after all statements in the enclosing body. This is // to ensure constructs like the following are permitted: // const foo = function () { @@ -43637,17 +45761,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: checkClassExpressionDeferred(node); break; } @@ -43678,7 +45802,7 @@ var ts; flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); - if (ts.isExternalModule(node)) { + if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile) { @@ -43751,19 +45875,8 @@ var ts; } } // Language service support - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 /* WithStatement */ && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { + if (location.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return []; } @@ -43777,13 +45890,13 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -43791,17 +45904,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064 /* Type */); } break; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -43849,28 +45962,28 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 145 /* TypeParameter */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: + case 146 /* TypeParameter */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: return true; } } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 143 /* QualifiedName */) { + while (node.parent && node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 159 /* TypeReference */; + return node.parent && node.parent.kind === 160 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 179 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 180 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 201 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 202 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -43883,17 +45996,28 @@ var ts; } return result; } + function isNodeWithinConstructorOfClass(node, classDeclaration) { + return ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + return true; + } + else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } function isNodeWithinClass(node, classDeclaration) { return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 144 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 237 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 238 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 243 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 244 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -43918,7 +46042,7 @@ var ts; return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 /* PropertyAccessExpression */ && + entityName.parent.kind === 180 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -43926,13 +46050,13 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 243 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 244 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } - if (entityName.kind !== 179 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + if (entityName.kind !== 180 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 237 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 238 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -43942,7 +46066,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 201 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 202 /* ExpressionWithTypeArguments */) { meaning = 793064 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -43958,15 +46082,15 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 279 /* JSDocParameterTag */) { + if (entityName.parent.kind === 284 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 145 /* TypeParameter */ && entityName.parent.parent.kind === 282 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 146 /* TypeParameter */ && entityName.parent.parent.kind === 287 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } - if (ts.isPartOfExpression(entityName)) { + if (ts.isExpressionNode(entityName)) { if (ts.nodeIsMissing(entityName)) { // Missing entity name. return undefined; @@ -43977,12 +46101,12 @@ var ts; } return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 179 /* PropertyAccessExpression */ || entityName.kind === 143 /* QualifiedName */) { + else if (entityName.kind === 180 /* PropertyAccessExpression */ || entityName.kind === 144 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 179 /* PropertyAccessExpression */) { + if (entityName.kind === 180 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -43992,23 +46116,23 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 159 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 160 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 253 /* JsxAttribute */) { + else if (entityName.parent.kind === 257 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 158 /* TypePredicate */) { + if (entityName.parent.kind === 159 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -44023,8 +46147,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 176 /* BindingElement */ && - node.parent.parent.kind === 174 /* ObjectBindingPattern */ && + else if (node.parent.kind === 177 /* BindingElement */ && + node.parent.parent.kind === 175 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); @@ -44035,8 +46159,8 @@ var ts; } switch (node.kind) { case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -44050,14 +46174,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 169 /* ThisType */: + case 170 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 97 /* SuperKeyword */: return checkExpression(node).symbol; case 123 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 153 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -44066,7 +46190,7 @@ var ts; // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } @@ -44080,6 +46204,8 @@ var ts; : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: + case 89 /* FunctionKeyword */: + case 36 /* EqualsGreaterThanToken */: return getSymbolOfNode(node.parent); default: return undefined; @@ -44089,7 +46215,7 @@ var ts; // The function returns a value symbol of an identifier in the short-hand property assignment. // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. - if (location && location.kind === 262 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 266 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -44101,7 +46227,7 @@ var ts; resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } @@ -44114,7 +46240,7 @@ var ts; } return typeFromTypeNode; } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -44160,28 +46286,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 /* ObjectLiteralExpression */ || expr.kind === 177 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 179 /* ObjectLiteralExpression */ || expr.kind === 178 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 216 /* ForOfStatement */) { + if (expr.parent.kind === 217 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 194 /* BinaryExpression */) { + if (expr.parent.kind === 195 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 261 /* PropertyAssignment */) { + if (expr.parent.kind === 265 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 177 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 178 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; @@ -44219,7 +46345,7 @@ var ts; function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { + if (typeHasCallOrConstructSignatures(type)) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); @@ -44228,12 +46354,15 @@ var ts; } return getNamedMembers(propsByName); } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { var symbols_4 = []; - var name_3 = symbol.escapedName; + var name_4 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_3); + var symbol = getPropertyOfType(t, name_4); if (symbol) { symbols_4.push(symbol); } @@ -44264,7 +46393,7 @@ var ts; if (!ts.isGeneratedIdentifier(node)) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -44321,7 +46450,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 265 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 269 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -44376,7 +46505,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 207 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 208 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -44417,16 +46546,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -44436,7 +46565,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 269 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -44462,6 +46591,11 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } + var target = getSymbolLinks(symbol).target; + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 107455 /* Value */) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } } if (checkChildren) { return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); @@ -44509,15 +46643,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 264 /* EnumMember */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 268 /* EnumMember */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 264 /* EnumMember */) { + if (node.kind === 268 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -44530,7 +46664,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -44567,7 +46701,7 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + else if (isTypeAssignableToKind(type, 2048 /* Void */ | 12288 /* Nullable */ | 16384 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { @@ -44576,13 +46710,13 @@ var ts; else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 262178 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 524322 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 512 /* ESSymbol */)) { + else if (isTypeAssignableToKind(type, 1536 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -44601,8 +46735,12 @@ var ts; var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (type.flags & 1024 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 131072 /* AllowUniqueESSymbolType */; + } if (flags & 8192 /* AddUndefined */) { - type = getNullableType(type, 2048 /* Undefined */); + type = getOptionalType(type); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -44648,7 +46786,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 2097152 /* FreshLiteral */); } return false; } @@ -44716,6 +46854,11 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, writeLiteralConstValue: writeLiteralConstValue, getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; @@ -44728,7 +46871,7 @@ var ts; // property access can only be used as values // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 179 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) + var meaning = (node.kind === 180 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ : 793064 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -44779,7 +46922,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 269 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -44799,7 +46942,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 265 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 269 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -44856,6 +46999,10 @@ var ts; globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); @@ -44863,11 +47010,11 @@ var ts; function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152 /* Ambient */)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 32768 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455 /* Value */); @@ -44899,6 +47046,7 @@ var ts; case 8192 /* AsyncDelegator */: return "__asyncDelegator"; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; default: ts.Debug.fail("Unrecognized helper"); } } @@ -44909,19 +47057,22 @@ var ts; return externalHelpersModule; } // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } function checkGrammarDecorators(node) { if (!node.decorators) { return false; } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 152 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */) { + else if (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -44939,16 +47090,16 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 131 /* ReadonlyKeyword */) { - if (node.kind === 148 /* PropertySignature */ || node.kind === 150 /* MethodSignature */) { + if (node.kind === 149 /* PropertySignature */ || node.kind === 151 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 76 /* ConstKeyword */: - if (node.kind !== 232 /* EnumDeclaration */ && node.parent.kind === 229 /* ClassDeclaration */) { + if (node.kind !== 233 /* EnumDeclaration */ && node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); } break; @@ -44968,7 +47119,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + else if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -44991,10 +47142,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + else if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -45007,7 +47158,7 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */ && node.kind !== 157 /* IndexSignature */ && node.kind !== 146 /* Parameter */) { + else if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */ && node.kind !== 158 /* IndexSignature */ && node.kind !== 147 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } @@ -45027,17 +47178,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 79 /* DefaultKeyword */: - var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 234 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -45049,13 +47200,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234 /* ModuleBlock */) { + else if ((node.parent.flags & 2097152 /* Ambient */) && node.parent.kind === 235 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -45065,14 +47216,14 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 229 /* ClassDeclaration */) { - if (node.kind !== 151 /* MethodDeclaration */ && - node.kind !== 149 /* PropertyDeclaration */ && - node.kind !== 153 /* GetAccessor */ && - node.kind !== 154 /* SetAccessor */) { + if (node.kind !== 230 /* ClassDeclaration */) { + if (node.kind !== 152 /* MethodDeclaration */ && + node.kind !== 150 /* PropertyDeclaration */ && + node.kind !== 154 /* GetAccessor */ && + node.kind !== 155 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 230 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -45088,10 +47239,10 @@ var ts; if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 /* Ambient */ || node.parent.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -45099,7 +47250,7 @@ var ts; break; } } - if (node.kind === 152 /* Constructor */) { + if (node.kind === 153 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -45114,13 +47265,13 @@ var ts; } return; } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 239 /* ImportDeclaration */ || node.kind === 238 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 147 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 147 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -45140,37 +47291,37 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 233 /* ModuleDeclaration */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 146 /* Parameter */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 234 /* ModuleDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 147 /* Parameter */: return false; default: - if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return false; } switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 230 /* InterfaceDeclaration */: - case 208 /* VariableStatement */: - case 231 /* TypeAliasDeclaration */: + case 231 /* InterfaceDeclaration */: + case 209 /* VariableStatement */: + case 232 /* TypeAliasDeclaration */: return true; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); default: ts.Debug.fail(); @@ -45183,10 +47334,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 151 /* MethodDeclaration */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -45241,7 +47392,7 @@ var ts; function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarClassLikeDeclaration(node) { @@ -45249,7 +47400,7 @@ var ts; return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 187 /* ArrowFunction */) { + if (node.kind === 188 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -45293,7 +47444,7 @@ var ts; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -45311,7 +47462,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 200 /* OmittedExpression */) { + if (arg.kind === 201 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -45337,7 +47488,7 @@ var ts; function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; if (heritageClause.token === 85 /* ExtendsKeyword */) { @@ -45387,20 +47538,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 144 /* ComputedPropertyName */) { + if (node.kind !== 145 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 195 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 /* FunctionDeclaration */ || - node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */); - if (ts.isInAmbientContext(node)) { + ts.Debug.assert(node.kind === 229 /* FunctionDeclaration */ || + node.kind === 187 /* FunctionExpression */ || + node.kind === 152 /* MethodDeclaration */); + if (node.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -45414,22 +47565,25 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); var seen = ts.createUnderscoreEscapedMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */) { + if (prop.kind === 267 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 262 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 266 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -45438,7 +47592,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 151 /* MethodDeclaration */) { + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 152 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -45452,25 +47606,26 @@ var ts; // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */) { - // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151 /* MethodDeclaration */) { - currentKind = Property; - } - else if (prop.kind === 153 /* GetAccessor */) { - currentKind = GetAccessor; - } - else if (prop.kind === 154 /* SetAccessor */) { - currentKind = SetAccessor; - } - else { - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + switch (prop.kind) { + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 152 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 154 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 155 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -45481,11 +47636,11 @@ var ts; seen.set(effectiveName, currentKind); } else { - if (currentKind === Property && existingKind === Property) { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { @@ -45502,7 +47657,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 255 /* JsxSpreadAttribute */) { + if (attr.kind === 259 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; @@ -45514,7 +47669,7 @@ var ts; return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 260 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -45523,12 +47678,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 216 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 217 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 228 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -45543,20 +47698,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -45570,7 +47725,7 @@ var ts; if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (ts.isInAmbientContext(accessor)) { + else if (accessor.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { @@ -45583,11 +47738,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 154 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 154 /* SetAccessor */) { + else if (kind === 155 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -45610,15 +47765,50 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 154 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 154 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 140 /* UniqueKeyword */) { + if (node.type.kind !== 137 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(137 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 227 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 71 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 150 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 149 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -45628,7 +47818,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (node.parent.kind === 179 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } @@ -45642,18 +47832,18 @@ var ts; // However, property declarations disallow computed names in general, // and accessors are not allowed in ambient contexts in general, // so this error only really matters for methods. - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + if (node.flags & 2097152 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 231 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 163 /* TypeLiteral */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 164 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } function checkGrammarBreakOrContinueStatement(node) { @@ -45663,11 +47853,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 217 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 218 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -45675,8 +47865,8 @@ var ts; return false; } break; - case 221 /* SwitchStatement */: - if (node.kind === 218 /* BreakStatement */ && !node.label) { + case 222 /* SwitchStatement */: + if (node.kind === 219 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -45691,13 +47881,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 218 /* BreakStatement */ + var message = node.kind === 219 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 218 /* BreakStatement */ + var message = node.kind === 219 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -45709,7 +47899,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 175 /* ArrayBindingPattern */ || node.name.kind === 174 /* ObjectBindingPattern */) { + if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -45720,12 +47910,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.kind === 193 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 /* ForInStatement */ && node.parent.parent.kind !== 216 /* ForOfStatement */) { - if (ts.isInAmbientContext(node)) { + if (node.parent.parent.kind !== 216 /* ForInStatement */ && node.parent.parent.kind !== 217 /* ForOfStatement */) { + if (node.flags & 2097152 /* Ambient */) { if (node.initializer) { if (ts.isConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { @@ -45753,8 +47943,11 @@ var ts; } } } + if (node.exclamationToken && (node.parent.parent.kind !== 209 /* VariableStatement */ || !node.type || node.initializer || node.flags & 2097152 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + !(node.parent.parent.flags & 2097152 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); @@ -45768,7 +47961,7 @@ var ts; } function checkESModuleMarker(name) { if (name.kind === 71 /* Identifier */) { - if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } } @@ -45809,15 +48002,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return false; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -45865,40 +48058,47 @@ var ts; } } function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } } function checkGrammarProperty(node) { if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 231 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 163 /* TypeLiteral */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 164 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (ts.isInAmbientContext(node) && node.initializer) { + if (node.flags & 2097152 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } + if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace @@ -45913,13 +48113,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 230 /* InterfaceDeclaration */ || - node.kind === 231 /* TypeAliasDeclaration */ || - node.kind === 238 /* ImportDeclaration */ || - node.kind === 237 /* ImportEqualsDeclaration */ || - node.kind === 244 /* ExportDeclaration */ || - node.kind === 243 /* ExportAssignment */ || - node.kind === 236 /* NamespaceExportDeclaration */ || + if (node.kind === 231 /* InterfaceDeclaration */ || + node.kind === 232 /* TypeAliasDeclaration */ || + node.kind === 239 /* ImportDeclaration */ || + node.kind === 238 /* ImportEqualsDeclaration */ || + node.kind === 245 /* ExportDeclaration */ || + node.kind === 244 /* ExportAssignment */ || + node.kind === 237 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -45928,7 +48128,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 209 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -45936,10 +48136,10 @@ var ts; } } function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 2097152 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152 /* Ambient */) { // An accessors is already reported about the ambient context if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; @@ -45954,7 +48154,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 207 /* Block */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + if (node.parent.kind === 208 /* Block */ || node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -45970,15 +48170,15 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.numericLiteralFlags & 4 /* Octal */) { + if (node.numericLiteralFlags & 32 /* Octal */) { var diagnosticMessage = void 0; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 173 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 174 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 264 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 268 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -45997,13 +48197,16 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -46027,8 +48230,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return true; default: return ts.isDeclarationName(name); @@ -46036,18 +48239,31 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 239 /* ImportClause */: // For default import - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */:// For rename import `x as y` + case 240 /* ImportClause */: // For default import + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */:// For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 242 /* ImportSpecifier */; + return decl.parent.kind === 243 /* ImportSpecifier */; default: return false; } } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); })(ts || (ts = {})); /// /// @@ -46063,9 +48279,6 @@ var ts; if (updated !== original) { setOriginalNode(updated, original); setTextRange(updated, original); - if (original.startsOnNewLine) { - updated.startsOnNewLine = true; - } ts.aggregateTransformFlags(updated); } return updated; @@ -46098,6 +48311,9 @@ var ts; // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -46117,7 +48333,7 @@ var ts; if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } - if (typeof value === "string") { + if (ts.isString(value)) { return createStringLiteral(value); } return createLiteralFromNode(value); @@ -46154,7 +48370,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -46189,12 +48405,12 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - /** Create a unique name generated for a node. */ - function getGeneratedNameForNode(node) { + function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateKind = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; + name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; nextAutoGenerateId++; return name; } @@ -46227,7 +48443,7 @@ var ts; ts.createFalse = createFalse; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(143 /* QualifiedName */); + var node = createSynthesizedNode(144 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -46241,7 +48457,7 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function createComputedPropertyName(expression) { - var node = createSynthesizedNode(144 /* ComputedPropertyName */); + var node = createSynthesizedNode(145 /* ComputedPropertyName */); node.expression = expression; return node; } @@ -46254,7 +48470,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(145 /* TypeParameter */); + var node = createSynthesizedNode(146 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -46270,7 +48486,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(146 /* Parameter */); + var node = createSynthesizedNode(147 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -46294,7 +48510,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(147 /* Decorator */); + var node = createSynthesizedNode(148 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -46307,7 +48523,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148 /* PropertySignature */); + var node = createSynthesizedNode(149 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -46327,7 +48543,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* PropertyDeclaration */); + var node = createSynthesizedNode(150 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -46349,7 +48565,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(151 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -46366,7 +48582,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(151 /* MethodDeclaration */); + var node = createSynthesizedNode(152 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -46394,7 +48610,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(152 /* Constructor */); + var node = createSynthesizedNode(153 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -46414,7 +48630,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(153 /* GetAccessor */); + var node = createSynthesizedNode(154 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -46437,7 +48653,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(154 /* SetAccessor */); + var node = createSynthesizedNode(155 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -46458,7 +48674,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(156 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -46466,7 +48682,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(157 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -46474,7 +48690,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(157 /* IndexSignature */); + var node = createSynthesizedNode(158 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -46513,7 +48729,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(158 /* TypePredicate */); + var node = createSynthesizedNode(159 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -46527,7 +48743,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(159 /* TypeReference */); + var node = createSynthesizedNode(160 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -46541,7 +48757,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -46549,7 +48765,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(162 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -46557,7 +48773,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(162 /* TypeQuery */); + var node = createSynthesizedNode(163 /* TypeQuery */); node.exprName = exprName; return node; } @@ -46569,7 +48785,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(163 /* TypeLiteral */); + var node = createSynthesizedNode(164 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -46581,7 +48797,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(164 /* ArrayType */); + var node = createSynthesizedNode(165 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -46593,7 +48809,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(165 /* TupleType */); + var node = createSynthesizedNode(166 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -46605,7 +48821,7 @@ var ts; } ts.updateTypleTypeNode = updateTypleTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(167 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -46613,7 +48829,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(168 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -46632,7 +48848,7 @@ var ts; : node; } function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); + var node = createSynthesizedNode(169 /* ParenthesizedType */); node.type = type; return node; } @@ -46644,22 +48860,22 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); + return createSynthesizedNode(170 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; - function createTypeOperatorNode(type) { - var node = createSynthesizedNode(170 /* TypeOperator */); - node.operator = 127 /* KeyOfKeyword */; - node.type = ts.parenthesizeElementTypeMember(type); + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(171 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } ts.createTypeOperatorNode = createTypeOperatorNode; function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(171 /* IndexedAccessType */); + var node = createSynthesizedNode(172 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -46673,7 +48889,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(172 /* MappedType */); + var node = createSynthesizedNode(173 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -46691,7 +48907,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(173 /* LiteralType */); + var node = createSynthesizedNode(174 /* LiteralType */); node.literal = literal; return node; } @@ -46704,7 +48920,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(174 /* ObjectBindingPattern */); + var node = createSynthesizedNode(175 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -46716,7 +48932,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(175 /* ArrayBindingPattern */); + var node = createSynthesizedNode(176 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -46728,7 +48944,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(176 /* BindingElement */); + var node = createSynthesizedNode(177 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -46747,7 +48963,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(178 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -46761,7 +48977,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(179 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -46775,7 +48991,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(179 /* PropertyAccessExpression */); + var node = createSynthesizedNode(180 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); setEmitFlags(node, 131072 /* NoIndentation */); @@ -46792,7 +49008,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(180 /* ElementAccessExpression */); + var node = createSynthesizedNode(181 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -46806,7 +49022,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(181 /* CallExpression */); + var node = createSynthesizedNode(182 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -46822,7 +49038,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(182 /* NewExpression */); + var node = createSynthesizedNode(183 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -46838,7 +49054,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(183 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(184 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); node.template = template; return node; @@ -46852,7 +49068,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(184 /* TypeAssertionExpression */); + var node = createSynthesizedNode(185 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -46866,7 +49082,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(185 /* ParenthesizedExpression */); + var node = createSynthesizedNode(186 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -46878,7 +49094,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(186 /* FunctionExpression */); + var node = createSynthesizedNode(187 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -46902,7 +49118,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(187 /* ArrowFunction */); + var node = createSynthesizedNode(188 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -46936,7 +49152,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(188 /* DeleteExpression */); + var node = createSynthesizedNode(189 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46948,7 +49164,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(189 /* TypeOfExpression */); + var node = createSynthesizedNode(190 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46960,7 +49176,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(190 /* VoidExpression */); + var node = createSynthesizedNode(191 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46972,7 +49188,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(191 /* AwaitExpression */); + var node = createSynthesizedNode(192 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46984,7 +49200,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(192 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(193 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -46997,7 +49213,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(193 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(194 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -47010,7 +49226,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(194 /* BinaryExpression */); + var node = createSynthesizedNode(195 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -47027,7 +49243,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(195 /* ConditionalExpression */); + var node = createSynthesizedNode(196 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -47057,7 +49273,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(196 /* TemplateExpression */); + var node = createSynthesizedNode(197 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -47095,7 +49311,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(197 /* YieldExpression */); + var node = createSynthesizedNode(198 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; @@ -47109,7 +49325,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(198 /* SpreadElement */); + var node = createSynthesizedNode(199 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -47121,7 +49337,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(199 /* ClassExpression */); + var node = createSynthesizedNode(200 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47142,11 +49358,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(200 /* OmittedExpression */); + return createSynthesizedNode(201 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(201 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(202 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -47160,7 +49376,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(202 /* AsExpression */); + var node = createSynthesizedNode(203 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -47174,7 +49390,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(203 /* NonNullExpression */); + var node = createSynthesizedNode(204 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -47186,7 +49402,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(204 /* MetaProperty */); + var node = createSynthesizedNode(205 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -47200,7 +49416,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(205 /* TemplateSpan */); + var node = createSynthesizedNode(206 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -47214,12 +49430,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(206 /* SemicolonClassElement */); + return createSynthesizedNode(207 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(207 /* Block */); + var block = createSynthesizedNode(208 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -47233,7 +49449,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(208 /* VariableStatement */); + var node = createSynthesizedNode(209 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -47248,11 +49464,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(209 /* EmptyStatement */); + return createSynthesizedNode(210 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(210 /* ExpressionStatement */); + var node = createSynthesizedNode(211 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -47264,7 +49480,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(211 /* IfStatement */); + var node = createSynthesizedNode(212 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -47280,7 +49496,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(212 /* DoStatement */); + var node = createSynthesizedNode(213 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -47294,7 +49510,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(213 /* WhileStatement */); + var node = createSynthesizedNode(214 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -47308,7 +49524,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(214 /* ForStatement */); + var node = createSynthesizedNode(215 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -47326,7 +49542,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(215 /* ForInStatement */); + var node = createSynthesizedNode(216 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -47342,7 +49558,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(216 /* ForOfStatement */); + var node = createSynthesizedNode(217 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -47360,7 +49576,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(217 /* ContinueStatement */); + var node = createSynthesizedNode(218 /* ContinueStatement */); node.label = asName(label); return node; } @@ -47372,7 +49588,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(218 /* BreakStatement */); + var node = createSynthesizedNode(219 /* BreakStatement */); node.label = asName(label); return node; } @@ -47384,7 +49600,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(219 /* ReturnStatement */); + var node = createSynthesizedNode(220 /* ReturnStatement */); node.expression = expression; return node; } @@ -47396,7 +49612,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(220 /* WithStatement */); + var node = createSynthesizedNode(221 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -47410,7 +49626,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(221 /* SwitchStatement */); + var node = createSynthesizedNode(222 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -47424,7 +49640,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(222 /* LabeledStatement */); + var node = createSynthesizedNode(223 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -47438,7 +49654,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(223 /* ThrowStatement */); + var node = createSynthesizedNode(224 /* ThrowStatement */); node.expression = expression; return node; } @@ -47450,7 +49666,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(224 /* TryStatement */); + var node = createSynthesizedNode(225 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -47466,11 +49682,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(225 /* DebuggerStatement */); + return createSynthesizedNode(226 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); + var node = createSynthesizedNode(227 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -47486,7 +49702,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); + var node = createSynthesizedNode(228 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -47499,7 +49715,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(228 /* FunctionDeclaration */); + var node = createSynthesizedNode(229 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -47525,7 +49741,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(229 /* ClassDeclaration */); + var node = createSynthesizedNode(230 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47547,7 +49763,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + var node = createSynthesizedNode(231 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47569,7 +49785,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(232 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47589,7 +49805,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(232 /* EnumDeclaration */); + var node = createSynthesizedNode(233 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47607,7 +49823,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(233 /* ModuleDeclaration */); + var node = createSynthesizedNode(234 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -47626,7 +49842,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(234 /* ModuleBlock */); + var node = createSynthesizedNode(235 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -47638,7 +49854,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(235 /* CaseBlock */); + var node = createSynthesizedNode(236 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -47650,7 +49866,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(237 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -47662,7 +49878,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(238 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47680,7 +49896,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(238 /* ImportDeclaration */); + var node = createSynthesizedNode(239 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -47698,7 +49914,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(239 /* ImportClause */); + var node = createSynthesizedNode(240 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -47712,7 +49928,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(240 /* NamespaceImport */); + var node = createSynthesizedNode(241 /* NamespaceImport */); node.name = name; return node; } @@ -47724,7 +49940,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(241 /* NamedImports */); + var node = createSynthesizedNode(242 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -47736,7 +49952,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(242 /* ImportSpecifier */); + var node = createSynthesizedNode(243 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -47750,11 +49966,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(243 /* ExportAssignment */); + var node = createSynthesizedNode(244 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = expression; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -47767,7 +49983,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(244 /* ExportDeclaration */); + var node = createSynthesizedNode(245 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -47785,7 +50001,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(245 /* NamedExports */); + var node = createSynthesizedNode(246 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -47797,7 +50013,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246 /* ExportSpecifier */); + var node = createSynthesizedNode(247 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -47812,7 +50028,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(248 /* ExternalModuleReference */); + var node = createSynthesizedNode(249 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -47825,7 +50041,7 @@ var ts; ts.updateExternalModuleReference = updateExternalModuleReference; // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(249 /* JsxElement */); + var node = createSynthesizedNode(250 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -47841,7 +50057,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(250 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(251 /* JsxSelfClosingElement */); node.tagName = tagName; node.attributes = attributes; return node; @@ -47855,7 +50071,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(251 /* JsxOpeningElement */); + var node = createSynthesizedNode(252 /* JsxOpeningElement */); node.tagName = tagName; node.attributes = attributes; return node; @@ -47869,7 +50085,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(252 /* JsxClosingElement */); + var node = createSynthesizedNode(253 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -47880,8 +50096,24 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(254 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(253 /* JsxAttribute */); + var node = createSynthesizedNode(257 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -47895,7 +50127,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(254 /* JsxAttributes */); + var node = createSynthesizedNode(258 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -47907,7 +50139,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(259 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -47919,7 +50151,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(256 /* JsxExpression */); + var node = createSynthesizedNode(260 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -47933,7 +50165,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(257 /* CaseClause */); + var node = createSynthesizedNode(261 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -47947,7 +50179,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(258 /* DefaultClause */); + var node = createSynthesizedNode(262 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -47959,7 +50191,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); + var node = createSynthesizedNode(263 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -47972,8 +50204,8 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(260 /* CatchClause */); - node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + var node = createSynthesizedNode(264 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; } @@ -47987,7 +50219,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(261 /* PropertyAssignment */); + var node = createSynthesizedNode(265 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -48002,7 +50234,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(262 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(266 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -48016,7 +50248,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(263 /* SpreadAssignment */); + var node = createSynthesizedNode(267 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; return node; } @@ -48029,7 +50261,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(264 /* EnumMember */); + var node = createSynthesizedNode(268 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -48045,7 +50277,7 @@ var ts; // Top-level nodes function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createSynthesizedNode(265 /* SourceFile */); + var updated = createSynthesizedNode(269 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -48124,7 +50356,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(287 /* NotEmittedStatement */); + var node = createSynthesizedNode(291 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -48136,7 +50368,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(291 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(295 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -48148,7 +50380,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(290 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(294 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -48163,7 +50395,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(288 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(292 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -48179,7 +50411,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 289 /* CommaListExpression */) { + if (node.kind === 293 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -48189,7 +50421,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(289 /* CommaListExpression */); + var node = createSynthesizedNode(293 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -48201,7 +50433,7 @@ var ts; } ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { - var node = ts.createNode(266 /* Bundle */); + var node = ts.createNode(270 /* Bundle */); node.sourceFiles = sourceFiles; return node; } @@ -48293,10 +50525,10 @@ var ts; } ts.createExternalModuleExport = createExternalModuleExport; function asName(name) { - return typeof name === "string" ? createIdentifier(name) : name; + return ts.isString(name) ? createIdentifier(name) : name; } function asExpression(value) { - return typeof value === "string" || typeof value === "number" ? createLiteral(value) : value; + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -48337,7 +50569,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -48364,6 +50596,16 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; /** * Gets a custom text range to use when emitting source maps. */ @@ -48380,6 +50622,7 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -48407,6 +50650,24 @@ var ts; return node; } ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; /** * Gets a custom text range to use when emitting comments. */ @@ -48562,7 +50823,7 @@ var ts; } ts.setOriginalNode = setOriginalNode; function mergeEmitNode(sourceEmitNode, destEmitNode) { - var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; if (!destEmitNode) destEmitNode = {}; // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. @@ -48582,6 +50843,8 @@ var ts; destEmitNode.constantValue = constantValue; if (helpers) destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -48680,12 +50943,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); + return createReactNamespace(ts.idText(jsxFactory), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -48705,7 +50968,7 @@ var ts; if (children.length > 1) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; - child.startsOnNewLine = true; + startOnNewLine(child); argumentsList.push(child); } } @@ -48717,6 +50980,26 @@ var ts; /*typeArguments*/ undefined, argumentsList), location); } ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; // Helpers function getHelperName(name) { return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); @@ -48787,7 +51070,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 222 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 223 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -48805,13 +51088,13 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -48837,7 +51120,7 @@ var ts; } else { switch (callee.kind) { - case 179 /* PropertyAccessExpression */: { + case 180 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -48850,7 +51133,7 @@ var ts; } break; } - case 180 /* ElementAccessExpression */: { + case 181 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -48907,14 +51190,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -49115,8 +51398,8 @@ var ts; var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); - if (node.startsOnNewLine) { - updated.startsOnNewLine = true; + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); } ts.aggregateTransformFlags(updated); return updated; @@ -49182,7 +51465,7 @@ var ts; while (statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { break; @@ -49238,7 +51521,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 185 /* ParenthesizedExpression */) { + if (skipped.kind === 186 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -49272,8 +51555,8 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(194 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(195 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(195 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { @@ -49282,7 +51565,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 197 /* YieldExpression */) { + && operand.kind === 198 /* YieldExpression */) { return false; } return true; @@ -49370,7 +51653,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -49385,7 +51668,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(196 /* ConditionalExpression */, 55 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -49398,11 +51681,32 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 194 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ ? ts.createParen(e) : e; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + return (check.kind === 200 /* ClassExpression */ || + check.kind === 187 /* FunctionExpression */ || + check.kind === 293 /* CommaListExpression */ || + ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) + ? ts.createParen(e) + : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** * Wraps an expression in parentheses if it is needed in order to use the expression * as the expression of a NewExpression node. @@ -49410,14 +51714,14 @@ var ts; * @param expression The Expression node. */ function parenthesizeForNew(expression) { - var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); - switch (emittedExpression.kind) { - case 181 /* CallExpression */: + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 182 /* CallExpression */: return ts.createParen(expression); - case 182 /* NewExpression */: - return emittedExpression.arguments - ? expression - : ts.createParen(expression); + case 183 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; } return parenthesizeForAccess(expression); } @@ -49437,7 +51741,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 182 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 183 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -49475,7 +51779,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(195 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -49486,14 +51790,14 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 186 /* FunctionExpression */ || kind === 187 /* ArrowFunction */) { + if (kind === 187 /* FunctionExpression */ || kind === 188 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 /* ObjectLiteralExpression */ || leftmostExpressionKind === 186 /* FunctionExpression */) { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 179 /* ObjectLiteralExpression */ || leftmostExpressionKind === 187 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; @@ -49501,10 +51805,10 @@ var ts; ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return ts.createParenthesizedType(member); } return member; @@ -49512,8 +51816,8 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 162 /* TypeQuery */: - case 170 /* TypeOperator */: + case 163 /* TypeQuery */: + case 171 /* TypeOperator */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -49536,24 +51840,28 @@ var ts; } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function getLeftmostExpression(node) { + function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: node = node.operand; continue; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: node = node.left; continue; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: node = node.condition; continue; - case 181 /* CallExpression */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: + case 182 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 181 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: node = node.expression; continue; - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -49561,7 +51869,7 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body).kind === 178 /* ObjectLiteralExpression */) { + if (!ts.isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 179 /* ObjectLiteralExpression */) { return ts.setTextRange(ts.createParen(body), body); } return body; @@ -49577,13 +51885,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - case 203 /* NonNullExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 204 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -49608,14 +51916,14 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 185 /* ParenthesizedExpression */) { + while (node.kind === 186 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 203 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 204 /* NonNullExpression */) { node = node.expression; } return node; @@ -49623,11 +51931,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 185 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 184 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 202 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 203 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 186 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 185 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 203 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 204 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 292 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -49645,7 +51953,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 185 /* ParenthesizedExpression */ + return node.kind === 186 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -49661,8 +51969,7 @@ var ts; } ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { - node.startsOnNewLine = true; - return node; + return ts.setStartsOnNewLine(node, /*newLine*/ true); } ts.startOnNewLine = startOnNewLine; function getExternalHelpersModuleName(node) { @@ -49709,12 +52016,12 @@ var ts; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { var name = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 238 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 239 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 244 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 245 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -49832,7 +52139,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -49844,11 +52151,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -49880,12 +52187,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 146 /* Parameter */: - case 176 /* BindingElement */: + case 147 /* Parameter */: + case 177 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 198 /* SpreadElement */: - case 263 /* SpreadAssignment */: + case 199 /* SpreadElement */: + case 267 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -49897,7 +52204,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 176 /* BindingElement */: + case 177 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -49909,7 +52216,7 @@ var ts; : propertyName; } break; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -49921,7 +52228,7 @@ var ts; : propertyName; } break; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -49939,13 +52246,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -49985,11 +52292,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 174 /* ObjectBindingPattern */: - case 178 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 179 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -50152,264 +52459,266 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 143 /* LastToken */) || kind === 170 /* ThisType */) { return node; } switch (kind) { // Names case 71 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 146 /* Parameter */: + case 147 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 147 /* Decorator */: + case 148 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 148 /* PropertySignature */: + case 149 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* MethodSignature */: + case 151 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: + case 153 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 155 /* CallSignature */: + case 156 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 160 /* FunctionType */: + case 161 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: + case 162 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 165 /* TupleType */: + case 166 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 166 /* UnionType */: + case 167 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 172 /* MappedType */: + case 173 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 202 /* AsExpression */: + case 203 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 207 /* Block */: + case 208 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 241 /* NamedImports */: + case 242 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 245 /* NamedExports */: + case 246 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 246 /* ExportSpecifier */: + case 247 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 249 /* JsxElement */: + case 250 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 251 /* JsxOpeningElement */: + case 252 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 253 /* JsxAttribute */: + case 254 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 257 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 257 /* CaseClause */: + case 261 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 264 /* EnumMember */: + case 268 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 265 /* SourceFile */: + case 269 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -50451,58 +52760,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 143 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 158 /* TypePredicate */ && kind <= 173 /* LiteralType */)) { + if ((kind >= 159 /* TypePredicate */ && kind <= 174 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 287 /* NotEmittedStatement */: + case 207 /* SemicolonClassElement */: + case 210 /* EmptyStatement */: + case 201 /* OmittedExpression */: + case 226 /* DebuggerStatement */: + case 291 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 146 /* Parameter */: + case 147 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 147 /* Decorator */: + case 148 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 148 /* PropertySignature */: + case 149 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50511,12 +52820,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 152 /* Constructor */: + case 153 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50524,7 +52833,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50532,49 +52841,49 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 176 /* BindingElement */: + case 177 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 181 /* CallExpression */: + case 182 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 182 /* NewExpression */: + case 183 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -50582,123 +52891,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 185 /* ParenthesizedExpression */: - case 188 /* DeleteExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 191 /* AwaitExpression */: - case 197 /* YieldExpression */: - case 198 /* SpreadElement */: - case 203 /* NonNullExpression */: + case 186 /* ParenthesizedExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 192 /* AwaitExpression */: + case 198 /* YieldExpression */: + case 199 /* SpreadElement */: + case 204 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 202 /* AsExpression */: + case 203 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 207 /* Block */: + case 208 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 211 /* IfStatement */: + case 212 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 212 /* DoStatement */: + case 213 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 213 /* WhileStatement */: - case 220 /* WithStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 214 /* ForStatement */: + case 215 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219 /* ReturnStatement */: - case 223 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* TryStatement */: + case 225 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50707,7 +53016,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50715,134 +53024,139 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 239 /* ImportClause */: + case 240 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 249 /* JsxElement */: + case 250 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: + case 254 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 257 /* CaseClause */: + case 261 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 260 /* CatchClause */: + case 264 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 264 /* EnumMember */: + case 268 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 265 /* SourceFile */: + case 269 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -50915,7 +53229,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 201 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 202 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -50960,12 +53274,12 @@ var ts; return; // Add additional properties in debug mode to assist with debugging. Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, - "__debugObjectFlags": { get: function () { return this.flags & 32768 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, - "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 65536 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ ts.objectAllocator.getNodeConstructor(), @@ -50977,11 +53291,11 @@ var ts; var ctor = nodeConstructors_1[_i]; if (!ctor.prototype.hasOwnProperty("__debugKind")) { Object.defineProperties(ctor.prototype, { - "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, - "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, - "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, - "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, - "__debugGetText": { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { value: function (includeTrivia) { if (ts.nodeIsSynthesized(this)) return ""; @@ -51018,20 +53332,20 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); break; - case 237 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + case 238 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -51047,27 +53361,27 @@ var ts; // export { x, y } for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + if (!uniqueExports.get(ts.idText(specifier.name))) { var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + exportSpecifiers.add(ts.idText(name), specifier); var decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + uniqueExports.set(ts.idText(specifier.name), true); exportedNames = ts.append(exportedNames, specifier.name); } } } break; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -51075,7 +53389,7 @@ var ts; } } break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -51087,15 +53401,15 @@ var ts; else { // export function x() { } var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (!uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } } break; - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -51107,9 +53421,9 @@ var ts; else { // export class x { } var name = node.name; - if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } @@ -51137,8 +53451,9 @@ var ts; } } else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { - uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); exportedNames = ts.append(exportedNames, decl.name); } } @@ -51155,6 +53470,19 @@ var ts; } return values; } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 /* StringLiteral */ || + expression.kind === 8 /* NumericLiteral */ || + expression.kind === 13 /* NoSubstitutionTemplateLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); /// /// @@ -51514,7 +53842,7 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); + var name = ts.createIdentifier(ts.idText(propertyName)); return ts.createPropertyAccess(value, name); } } @@ -51626,7 +53954,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -51637,6 +53965,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); // Save the previous transformation hooks. @@ -51646,8 +53975,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(180 /* ElementAccessExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -51669,6 +53998,11 @@ var ts; * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; return transformSourceFile; /** * Transform TypeScript-specific syntax in a SourceFile. @@ -51711,15 +54045,15 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 265 /* SourceFile */: - case 235 /* CaseBlock */: - case 234 /* ModuleBlock */: - case 207 /* Block */: + case 269 /* SourceFile */: + case 236 /* CaseBlock */: + case 235 /* ModuleBlock */: + case 208 /* Block */: currentScope = node; currentScopeFirstDeclarationsOfName = undefined; break; - case 229 /* ClassDeclaration */: - case 228 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + case 229 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -51731,7 +54065,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 229 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 230 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } break; } @@ -51775,10 +54109,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -51789,16 +54123,23 @@ var ts; if (parsed !== node) { // If the node has been transformed by a `before` transformer, perform no ellision on it // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node return node; } switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -51818,11 +54159,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 244 /* ExportDeclaration */ || - node.kind === 238 /* ImportDeclaration */ || - node.kind === 239 /* ImportClause */ || - (node.kind === 237 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 248 /* ExternalModuleReference */)) { + if (node.kind === 245 /* ExportDeclaration */ || + node.kind === 239 /* ImportDeclaration */ || + node.kind === 240 /* ImportClause */ || + (node.kind === 238 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 249 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -51852,19 +54193,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 149 /* PropertyDeclaration */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 206 /* SemicolonClassElement */: + case 207 /* SemicolonClassElement */: return node; default: ts.Debug.failBadSyntaxKind(node); @@ -51904,11 +54245,11 @@ var ts; case 124 /* DeclareKeyword */: case 131 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 163 /* TypeLiteral */: - case 158 /* TypePredicate */: - case 145 /* TypeParameter */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 164 /* TypeLiteral */: + case 159 /* TypePredicate */: + case 146 /* TypeParameter */: case 119 /* AnyKeyword */: case 122 /* BooleanKeyword */: case 136 /* StringKeyword */: @@ -51916,37 +54257,39 @@ var ts; case 130 /* NeverKeyword */: case 105 /* VoidKeyword */: case 137 /* SymbolKeyword */: - case 161 /* ConstructorType */: - case 160 /* FunctionType */: - case 162 /* TypeQuery */: - case 159 /* TypeReference */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - case 169 /* ThisType */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 173 /* LiteralType */: + case 162 /* ConstructorType */: + case 161 /* FunctionType */: + case 163 /* TypeQuery */: + case 160 /* TypeReference */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + case 170 /* ThisType */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 174 /* LiteralType */: // TypeScript type nodes are elided. - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: // TypeScript index signatures are elided. - case 147 /* Decorator */: + case 148 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 231 /* TypeAliasDeclaration */: - // TypeScript type-only declarations are elided. - case 149 /* PropertyDeclaration */: - // TypeScript property declarations are elided. - case 236 /* NamespaceExportDeclaration */: + case 232 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 150 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 237 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 152 /* Constructor */: + case 153 /* Constructor */: return visitConstructor(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -51957,7 +54300,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -51968,35 +54311,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 146 /* Parameter */: + case 147 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -52006,33 +54349,33 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return visitNewExpression(node); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -52041,7 +54384,7 @@ var ts; } } function visitSourceFile(node) { - var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } @@ -52068,8 +54411,9 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - if (ts.getClassExtendsHeritageClauseElement(node)) - facts |= 64 /* HasExtendsClause */; + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; if (ts.childIsDecorated(node)) @@ -52096,6 +54440,8 @@ var ts; * @param node The node to transform. */ function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { @@ -52106,6 +54452,11 @@ var ts; ? createClassDeclarationHeadWithDecorators(node, name, facts) : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: @@ -52193,7 +54544,7 @@ var ts; : undefined; var classDeclaration = ts.createClassDeclaration( /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); @@ -52302,7 +54653,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -52328,6 +54679,8 @@ var ts; * @param node The node to transform. */ function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); @@ -52336,7 +54689,7 @@ var ts; /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, node); - if (staticProperties.length > 0) { + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; var temp = ts.createTempVariable(hoistVariableDeclaration); if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { @@ -52348,21 +54701,25 @@ var ts; // the body of a class with static initializers. ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } + pendingExpressions = savedPendingExpressions; return classExpression; } /** * Transforms the members of a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } @@ -52373,9 +54730,9 @@ var ts; * Transforms (or creates) a constructor for a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it @@ -52388,7 +54745,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); // constructor(${parameters}) { // ${body} // } @@ -52401,7 +54758,6 @@ var ts; * parameter property assignments or instance property initializers. * * @param constructor The constructor declaration. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ function transformConstructorParameters(constructor) { // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: @@ -52428,9 +54784,9 @@ var ts; * * @param node The current class. * @param constructor The current class constructor. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -52451,7 +54807,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { // Add a synthetic `super` call: // // super(...arguments); @@ -52498,7 +54854,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -52569,7 +54925,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 149 /* PropertyDeclaration */ + return member.kind === 150 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -52599,7 +54955,7 @@ var ts; for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); expressions.push(expression); @@ -52613,7 +54969,10 @@ var ts; * @param receiver The object receiving the property assignment. */ function transformInitializedProperty(property, receiver) { - var propertyName = visitPropertyNameOfClassElement(property); + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); return ts.createAssignment(memberAccess, initializer); @@ -52627,7 +54986,7 @@ var ts; * the class. */ function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); } /** * Determines whether a class member is a static member of a class that is decorated, or @@ -52635,8 +54994,8 @@ var ts; * * @param member The class member. */ - function isStaticDecoratedClassElement(member) { - return isDecoratedClassElement(member, /*isStatic*/ true); + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); } /** * Determines whether a class member is an instance member of a class that is decorated, @@ -52644,8 +55003,8 @@ var ts; * * @param member The class member. */ - function isInstanceDecoratedClassElement(member) { - return isDecoratedClassElement(member, /*isStatic*/ false); + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); } /** * Determines whether a class member is either a static or an instance member of a class @@ -52653,8 +55012,8 @@ var ts; * * @param member The class member. */ - function isDecoratedClassElement(member, isStatic) { - return ts.nodeOrChildIsDecorated(member) + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) && isStatic === ts.hasModifier(member, 32 /* Static */); } /** @@ -52704,12 +55063,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -52803,8 +55162,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { - var member = members_3[_i]; + for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { + var member = members_4[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -52862,8 +55221,12 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 149 /* PropertyDeclaration */ + ? member.kind === 150 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. : ts.createNull() : undefined; var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); @@ -52981,10 +55344,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 149 /* PropertyDeclaration */; + return kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 150 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -52994,7 +55357,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 151 /* MethodDeclaration */; + return node.kind === 152 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -53005,12 +55368,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return true; } return false; @@ -53022,15 +55385,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 149 /* PropertyDeclaration */: - case 146 /* Parameter */: - case 153 /* GetAccessor */: + case 150 /* PropertyDeclaration */: + case 147 /* Parameter */: + case 154 /* GetAccessor */: return serializeTypeNode(node.type); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 151 /* MethodDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 152 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -53067,7 +55430,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 153 /* GetAccessor */) { + if (container && node.kind === 154 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -53117,22 +55480,22 @@ var ts; case 95 /* NullKeyword */: case 130 /* NeverKeyword */: return ts.createVoidZero(); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return ts.createIdentifier("Function"); - case 164 /* ArrayType */: - case 165 /* TupleType */: + case 165 /* ArrayType */: + case 166 /* TupleType */: return ts.createIdentifier("Array"); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: case 122 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); case 136 /* StringKeyword */: return ts.createIdentifier("String"); case 134 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 173 /* LiteralType */: + case 174 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); @@ -53152,18 +55515,18 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return serializeTypeReferenceNode(node); - case 167 /* IntersectionType */: - case 166 /* UnionType */: + case 168 /* IntersectionType */: + case 167 /* UnionType */: return serializeUnionOrIntersectionType(node); - case 162 /* TypeQuery */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 163 /* TypeLiteral */: + case 163 /* TypeQuery */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 164 /* TypeLiteral */: case 119 /* AnyKeyword */: - case 169 /* ThisType */: + case 170 /* ThisType */: break; default: ts.Debug.failBadSyntaxKind(node); @@ -53177,6 +55540,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately @@ -53196,7 +55568,7 @@ var ts; } } // If we were able to find common type, use it - return serializedUnion; + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never } /** * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with @@ -53255,7 +55627,7 @@ var ts; return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } return name; - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -53287,6 +55659,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } /** * Gets an expression that represents a property name. For a computed property, a * name is generated for the node. @@ -53296,17 +55677,36 @@ var ts; function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; if (ts.isComputedPropertyName(name)) { - return generateNameForComputedPropertyName + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? ts.getGeneratedNameForNode(name) : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.getSynthesizedClone(name); } } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } /** * Visits the property name of a class element, for use when emitting property * initializers. For a computed property on a node with decorators, a temporary @@ -53316,14 +55716,14 @@ var ts; */ function visitPropertyNameOfClassElement(member) { var name = member.name; - if (ts.isComputedPropertyName(name)) { - var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - if (member.decorators) { - var generatedName = ts.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); - expression = ts.createAssignment(generatedName, expression); + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; } - return ts.updateComputedPropertyName(name, expression); + return ts.updateComputedPropertyName(name, expr); } else { return name; @@ -53366,6 +55766,13 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -53378,7 +55785,7 @@ var ts; * This function will be called when one of the following conditions are met: * - The node is an overload * - The node is marked as abstract, public, private, protected, or readonly - * - The node has both a decorator and a computed property name + * - The node has a computed property name * * @param node The method node. */ @@ -53413,7 +55820,7 @@ var ts; * * This function will be called when one of the following conditions are met: * - The node is marked as abstract, public, private, or protected - * - The node has both a decorator and a computed property name + * - The node has a computed property name * * @param node The get accessor node. */ @@ -53437,7 +55844,7 @@ var ts; * * This function will be called when one of the following conditions are met: * - The node is marked as abstract, public, private, or protected - * - The node has both a decorator and a computed property name + * - The node has a computed property name * * @param node The set accessor node. */ @@ -53795,12 +56202,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentScope.kind === 269 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 232 /* EnumDeclaration */) { + if (node.kind === 233 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -53919,7 +56326,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 234 /* ModuleBlock */) { + if (body.kind === 235 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -53965,13 +56372,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 234 /* ModuleBlock */) { + if (body.kind !== 235 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 233 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 234 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -54012,7 +56419,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 240 /* NamespaceImport */) { + if (node.kind === 241 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -54208,7 +56615,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -54244,16 +56651,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(262 /* ShorthandPropertyAssignment */); + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(233 /* ModuleDeclaration */); + context.enableEmitNotification(234 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 233 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 234 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 232 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 233 /* EnumDeclaration */; } /** * Hook for node emit. @@ -54314,9 +56721,9 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -54354,9 +56761,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 265 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 233 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 232 /* EnumDeclaration */); + if (container && container.kind !== 269 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 234 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 233 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -54494,15 +56901,15 @@ var ts; case 120 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return visitAwaitExpression(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -54587,7 +56994,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 187 /* ArrowFunction */; + var isArrowFunction = node.kind === 188 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -54652,15 +57059,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(181 /* CallExpression */); - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(180 /* ElementAccessExpression */); + context.enableSubstitution(182 /* CallExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(229 /* ClassDeclaration */); - context.enableEmitNotification(151 /* MethodDeclaration */); - context.enableEmitNotification(153 /* GetAccessor */); - context.enableEmitNotification(154 /* SetAccessor */); - context.enableEmitNotification(152 /* Constructor */); + context.enableEmitNotification(230 /* ClassDeclaration */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(153 /* Constructor */); } } /** @@ -54700,18 +57107,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -54736,11 +57143,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 /* ClassDeclaration */ - || kind === 152 /* Constructor */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */; + return kind === 230 /* ClassDeclaration */ + || kind === 153 /* Constructor */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -54769,7 +57176,7 @@ var ts; /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getHelperName("__awaiter"), /*typeArguments*/ undefined, [ ts.createThis(), @@ -54838,45 +57245,45 @@ var ts; return node; } switch (node.kind) { - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return visitAwaitExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return visitVoidExpression(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return visitConstructorDeclaration(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return visitArrowFunction(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return visitParameter(node); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return visitExpressionStatement(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -54899,7 +57306,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 216 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); @@ -54911,7 +57318,7 @@ var ts; var objects = []; for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { var e = elements_3[_i]; - if (e.kind === 263 /* SpreadAssignment */) { + if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -54923,7 +57330,7 @@ var ts; if (!chunkObject) { chunkObject = []; } - if (e.kind === 261 /* PropertyAssignment */) { + if (e.kind === 265 /* PropertyAssignment */) { var p = e; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } @@ -54945,7 +57352,7 @@ var ts; // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 178 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 179 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -55253,15 +57660,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(181 /* CallExpression */); - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(180 /* ElementAccessExpression */); + context.enableSubstitution(182 /* CallExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(229 /* ClassDeclaration */); - context.enableEmitNotification(151 /* MethodDeclaration */); - context.enableEmitNotification(153 /* GetAccessor */); - context.enableEmitNotification(154 /* SetAccessor */); - context.enableEmitNotification(152 /* Constructor */); + context.enableEmitNotification(230 /* ClassDeclaration */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(153 /* Constructor */); } } /** @@ -55301,18 +57708,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -55337,11 +57744,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 /* ClassDeclaration */ - || kind === 152 /* Constructor */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */; + return kind === 230 /* ClassDeclaration */ + || kind === 153 /* Constructor */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -55427,6 +57834,7 @@ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; return transformSourceFile; /** * Transform JSX-specific syntax in a SourceFile. @@ -55437,6 +57845,7 @@ var ts; if (node.isDeclarationFile) { return node; } + currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; @@ -55451,11 +57860,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 249 /* JsxElement */: + case 250 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 256 /* JsxExpression */: + case 254 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 260 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -55465,12 +57876,14 @@ var ts; switch (node.kind) { case 10 /* JsxText */: return visitJsxText(node); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return visitJsxExpression(node); - case 249 /* JsxElement */: + case 250 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 254 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); default: ts.Debug.failBadSyntaxKind(node); return undefined; @@ -55482,6 +57895,9 @@ var ts; function visitJsxSelfClosingElement(node, isChild) { return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } function visitJsxOpeningLikeElement(node, children, isChild, location) { var tagName = getTagName(node); var objectProperties; @@ -55514,6 +57930,13 @@ var ts; } return element; } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -55527,10 +57950,13 @@ var ts; return ts.createTrue(); } else if (node.kind === 9 /* StringLiteral */) { - var decoded = tryDecodeEntities(node.text); - return decoded ? ts.setTextRange(ts.createLiteral(decoded), node) : node; + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); } - else if (node.kind === 256 /* JsxExpression */) { + else if (node.kind === 260 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -55588,7 +58014,9 @@ var ts; } } return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it : acc; } function addLineOfJsxText(acc, trimmedLine) { @@ -55622,13 +58050,13 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 249 /* JsxElement */) { + if (node.kind === 250 /* JsxElement */) { return getTagName(node.openingElement); } else { var name = node.tagName; if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.createExpressionFromEntityName(name); @@ -55642,11 +58070,12 @@ var ts; */ function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { return name; } else { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(text); } } function visitJsxExpression(node) { @@ -55655,259 +58084,259 @@ var ts; } ts.transformJsx = transformJsx; var entities = ts.createMapFromTemplate({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 }); })(ts || (ts = {})); /// @@ -55929,7 +58358,7 @@ var ts; return node; } switch (node.kind) { - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -56114,6 +58543,10 @@ var ts; var currentSourceFile; var currentText; var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } /** * Used to track if we are emitting body of the converted loop */ @@ -56135,6 +58568,7 @@ var ts; ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; currentText = undefined; + taggedTemplateStringDeclarations = undefined; hierarchyFacts = 0 /* None */; return visited; } @@ -56160,13 +58594,13 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ - && node.kind === 219 /* ReturnStatement */ + && node.kind === 220 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 207 /* Block */))) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 208 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } @@ -56194,63 +58628,63 @@ var ts; switch (node.kind) { case 115 /* StaticKeyword */: return undefined; // elide static keyword - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return visitClassExpression(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return visitParameter(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return visitArrowFunction(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); case 71 /* Identifier */: return visitIdentifier(node); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return visitCaseBlock(node); - case 207 /* Block */: + case 208 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return visitExpressionStatement(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitCatchClause(node); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return visitNewExpression(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); case 13 /* NoSubstitutionTemplateLiteral */: case 14 /* TemplateHead */: @@ -56261,28 +58695,28 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return visitTemplateExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return visitSpreadElement(node); case 97 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 99 /* ThisKeyword */: return visitThisKeyword(node); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return visitMetaProperty(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return visitAccessorDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -56296,6 +58730,9 @@ var ts; addCaptureThisForNodeIfNeeded(statements, node); statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } ts.addRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); @@ -56366,13 +58803,13 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 218 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || + var jump = node.kind === 219 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 218 /* BreakStatement */) { + if (node.kind === 219 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -56383,13 +58820,13 @@ var ts; } } else { - if (node.kind === 218 /* BreakStatement */) { + if (node.kind === 219 /* BreakStatement */) { labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); } else { labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -56510,9 +58947,7 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (ts.getEmitFlags(node) & 65536 /* Indented */) { - ts.setEmitFlags(classFunction, 65536 /* Indented */); - } + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); @@ -56685,17 +59120,17 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 219 /* ReturnStatement */) { + if (statement.kind === 220 /* ReturnStatement */) { return true; } - else if (statement.kind === 211 /* IfStatement */) { + else if (statement.kind === 212 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 207 /* Block */) { + else if (statement.kind === 208 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -56753,7 +59188,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -56763,8 +59198,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 194 /* BinaryExpression */ - || superCallExpression.left.kind !== 181 /* CallExpression */) { + if (superCallExpression.kind !== 195 /* BinaryExpression */ + || superCallExpression.left.kind !== 182 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -56895,7 +59330,7 @@ var ts; var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter)) ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); - statement.startsOnNewLine = true; + ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); statements.push(statement); @@ -56961,7 +59396,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 187 /* ArrowFunction */) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 188 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -56981,22 +59416,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return statements; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 152 /* Constructor */: + case 153 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); @@ -57028,20 +59463,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 206 /* SemicolonClassElement */: + case 207 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 152 /* Constructor */: + case 153 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -57140,7 +59575,7 @@ var ts; ts.createObjectLiteral(properties, /*multiLine*/ true) ]); if (startsOnNewLine) { - call.startsOnNewLine = true; + ts.startOnNewLine(call); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; @@ -57233,7 +59668,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 229 /* FunctionDeclaration */ || node.kind === 187 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -57281,7 +59716,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 187 /* ArrowFunction */); + ts.Debug.assert(node.kind === 188 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -57348,9 +59783,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -57369,9 +59804,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -57557,10 +59992,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); + convertedLoopState.labels.set(ts.idText(node.label), true); } function resetLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); + convertedLoopState.labels.set(ts.idText(node.label), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -57573,14 +60008,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -57768,7 +60203,7 @@ var ts; && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 144 /* ComputedPropertyName */) { + if (property.name.kind === 145 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -57784,7 +60219,7 @@ var ts; var expressions = []; var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); if (node.multiLine) { - assignment.startsOnNewLine = true; + ts.startOnNewLine(assignment); } expressions.push(assignment); addObjectLiteralMembers(expressions, node, temp, numInitialProperties); @@ -57840,11 +60275,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 227 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 228 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -58104,7 +60539,7 @@ var ts; else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -58124,20 +60559,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); } break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -58157,7 +60592,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -58172,7 +60607,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -58188,7 +60623,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; @@ -58247,7 +60682,7 @@ var ts; if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 153 /* GetAccessor */) { + if (node.kind === 154 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -58522,7 +60957,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 178 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -58577,7 +61012,7 @@ var ts; * @param node A string literal. */ function visitNumericLiteral(node) { - if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { return ts.setTextRange(ts.createNumericLiteral(node.text), node); } return node; @@ -58590,10 +61025,10 @@ var ts; function visitTaggedTemplateExpression(node) { // Visit the tag expression var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - // Allocate storage for the template site object - var temp = ts.createTempVariable(hoistVariableDeclaration); // Build up the template arguments and the raw and cooked strings for the template. - var templateArguments = [temp]; + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; var cookedStrings = []; var rawStrings = []; var template = node.template; @@ -58611,14 +61046,19 @@ var ts; templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); } } - // NOTE: The parentheses here is entirely optional as we are now able to auto- - // parenthesize when rebuilding the tree. This should be removed in a - // future version. It is here for now to match our existing emit. - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) - ])); + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); } /** * Creates an ES5 compatible literal from an ES6 template literal. @@ -58780,13 +61220,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(152 /* Constructor */); - context.enableEmitNotification(151 /* MethodDeclaration */); - context.enableEmitNotification(153 /* GetAccessor */); - context.enableEmitNotification(154 /* SetAccessor */); - context.enableEmitNotification(187 /* ArrowFunction */); - context.enableEmitNotification(186 /* FunctionExpression */); - context.enableEmitNotification(228 /* FunctionDeclaration */); + context.enableEmitNotification(153 /* Constructor */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(188 /* ArrowFunction */); + context.enableEmitNotification(187 /* FunctionExpression */); + context.enableEmitNotification(229 /* FunctionDeclaration */); } } /** @@ -58828,10 +61268,10 @@ var ts; function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 176 /* BindingElement */: - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 227 /* VariableDeclaration */: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -58913,11 +61353,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 210 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 211 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 181 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 182 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -58925,7 +61365,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 198 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 199 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -58941,12 +61381,26 @@ var ts; ts.createIdentifier("_super") ]); } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } var extendsHelper = { name: "typescript:extends", scoped: false, priority: 0, text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; })(ts || (ts = {})); /// /// @@ -58966,15 +61420,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(251 /* JsxOpeningElement */); - context.enableEmitNotification(252 /* JsxClosingElement */); - context.enableEmitNotification(250 /* JsxSelfClosingElement */); + context.enableEmitNotification(252 /* JsxOpeningElement */); + context.enableEmitNotification(253 /* JsxClosingElement */); + context.enableEmitNotification(251 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(261 /* PropertyAssignment */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(265 /* PropertyAssignment */); return transformSourceFile; /** * Transforms an ES5 source file to ES3. @@ -58993,9 +61447,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 251 /* JsxOpeningElement */: - case 252 /* JsxClosingElement */: - case 250 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -59051,7 +61505,7 @@ var ts; * @param name An Identifier */ function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -59328,13 +61782,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 212 /* DoStatement */: + case 213 /* DoStatement */: return visitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return visitWhileStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -59347,24 +61801,24 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return visitAccessorDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return visitBreakStatement(node); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return visitContinueStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitReturnStatement(node); default: if (node.transformFlags & 16777216 /* ContainsYield */) { @@ -59385,21 +61839,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return visitConditionalExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -59412,9 +61866,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -59642,7 +62096,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -59654,7 +62108,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -59938,7 +62392,7 @@ var ts; var visited = ts.visitNode(expression, visitor, ts.isExpression); if (visited) { if (multiLine) { - visited.startsOnNewLine = true; + ts.startOnNewLine(visited); } expressions.push(visited); } @@ -59969,7 +62423,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { // [source] // a.b(1, yield, 2); // @@ -60030,35 +62484,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 207 /* Block */: + case 208 /* Block */: return transformAndEmitBlock(node); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return transformAndEmitIfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return transformAndEmitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return transformAndEmitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return transformAndEmitWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -60381,7 +62835,7 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, /*location*/ node); } @@ -60392,7 +62846,7 @@ var ts; } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findContinueTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -60400,7 +62854,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, /*location*/ node); } @@ -60411,7 +62865,7 @@ var ts; } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findBreakTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -60488,7 +62942,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 258 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 262 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -60501,7 +62955,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 257 /* CaseClause */) { + if (clause.kind === 261 /* CaseClause */) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -60562,7 +63016,7 @@ var ts; // /*body*/ // .endlabeled // .mark endLabel - beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginLabeledBlock(ts.idText(node.label)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -60572,7 +63026,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginScriptLabeledBlock(ts.idText(node.label)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -60657,7 +63111,7 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); @@ -60808,7 +63262,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); + var text = ts.idText(variable.name); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -61282,8 +63736,7 @@ var ts; if (clauses) { var labelExpression = ts.createPropertyAccess(state, "label"); var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); - switchStatement.startsOnNewLine = true; - return [switchStatement]; + return [ts.startOnNewLine(switchStatement)]; } if (statements) { return statements; @@ -61722,7 +64175,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -61733,11 +64186,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(194 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(192 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(193 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(262 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(265 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(269 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -61751,7 +64204,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } currentSourceFile = node; @@ -61779,7 +64232,7 @@ var ts; function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); @@ -62041,23 +64494,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return visitExportDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 290 /* MergeDeclarationMarker */: + case 294 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 291 /* EndOfDeclarationMarker */: + case 295 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, importCallExpressionVisitor, context); @@ -62077,17 +64530,19 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { // (function (factory) { // ... (regular UMD) // } @@ -62102,12 +64557,22 @@ var ts; // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ // }); needUMDDynamicImportHelper = true; - return ts.createConditional( - /*condition*/ ts.createIdentifier("__syncRequire"), - /*whenTrue*/ transformImportCallExpressionCommonJS(node), - /*whenFalse*/ transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { // improt("./blah") // emit as // define(["require", "exports", "blah"], function (require, exports) { @@ -62116,30 +64581,71 @@ var ts; // }); var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], - /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), - /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") // emit as // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - /*parameters*/ undefined, - /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } /** * Visits an ImportDeclaration node. @@ -62295,10 +64801,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -62430,7 +64936,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -62485,10 +64991,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241 /* NamedImports */: + case 242 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -62590,7 +65096,7 @@ var ts; */ function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -62687,7 +65193,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -62751,10 +65257,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return substituteBinaryExpression(node); - case 193 /* PostfixUnaryExpression */: - case 192 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -62775,7 +65281,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 265 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 269 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -62850,7 +65356,7 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 /* PostfixUnaryExpression */ + var expression = node.kind === 194 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; @@ -62917,10 +65423,10 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(194 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(192 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(193 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(265 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(269 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -63010,8 +65516,8 @@ var ts; function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); if (externalModuleName) { var text = externalModuleName.text; @@ -63084,7 +65590,7 @@ var ts; // only in the outer module body and not in the inner one. startLexicalEnvironment(); // Add any prologue directives. - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); // var __moduleName = context_1 && context_1.id; statements.push(ts.createVariableStatement( @@ -63141,7 +65647,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 244 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 245 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -63166,7 +65672,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 244 /* ExportDeclaration */) { + if (externalImport.kind !== 245 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -63177,7 +65683,7 @@ var ts; for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; // write name of indirectly exported entry, i.e. 'export {x} from ...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -63245,19 +65751,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -63271,7 +65777,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); @@ -63307,15 +65813,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -63491,7 +65997,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 265 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 269 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -63505,7 +66011,7 @@ var ts; return ts.isBindingPattern(node.name) ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, /*needsValue*/ false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; } /** * Creates an assignment expression for an exported variable declaration. @@ -63555,7 +66061,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -63611,10 +66117,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241 /* NamedImports */: + case 242 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -63688,7 +66194,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); + excludeName = ts.idText(decl.name); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -63732,7 +66238,7 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; @@ -63794,43 +66300,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return visitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return visitWhileStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return visitWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return visitCaseBlock(node); - case 257 /* CaseClause */: + case 261 /* CaseClause */: return visitCaseClause(node); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return visitDefaultClause(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return visitTryStatement(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitCatchClause(node); - case 207 /* Block */: + case 208 /* Block */: return visitBlock(node); - case 290 /* MergeDeclarationMarker */: + case 294 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 291 /* EndOfDeclarationMarker */: + case 295 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -63896,6 +66402,9 @@ var ts; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } } return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); } @@ -64013,7 +66522,7 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 194 /* BinaryExpression */) { + && node.kind === 195 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -64038,7 +66547,7 @@ var ts; // }; // }); return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), - /*typeArguments*/ undefined, node.arguments); + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. @@ -64078,7 +66587,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 265 /* SourceFile */; + return container !== undefined && container.kind === 269 /* SourceFile */; } else { return false; @@ -64111,7 +66620,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -64158,10 +66667,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return substituteBinaryExpression(node); - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -64254,14 +66763,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 /* PostfixUnaryExpression */ + var expression = node.kind === 194 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 193 /* PostfixUnaryExpression */) { + if (node.kind === 194 /* PostfixUnaryExpression */) { expression = node.operator === 43 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -64283,7 +66792,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 265 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 269 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -64324,7 +66833,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(265 /* SourceFile */); + context.enableEmitNotification(269 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; return transformSourceFile; @@ -64351,10 +66860,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -64460,7 +66969,7 @@ var ts; if (jsx === 2 /* React */) { transformers.push(ts.transformJsx); } - if (languageVersion < 5 /* ESNext */) { + if (languageVersion < 6 /* ESNext */) { transformers.push(ts.transformESNext); } if (languageVersion < 4 /* ES2017 */) { @@ -64494,7 +67003,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(292 /* Count */); + var enabledSyntaxKindFeatures = new Array(296 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -64834,7 +67343,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 265 /* SourceFile */) { + if (sourceFileOrBundle.kind === 269 /* SourceFile */) { // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); @@ -64979,7 +67488,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 287 /* NotEmittedStatement */ + if (node.kind !== 291 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -64996,7 +67505,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 287 /* NotEmittedStatement */ + if (node.kind !== 291 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -65173,7 +67682,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 291 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -65194,7 +67703,7 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 227 /* VariableDeclarationList */) { + if (node.kind === 228 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -65341,7 +67850,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -65355,7 +67864,7 @@ var ts; if (hasTrailingNewLine) { writer.writeLine(); } - else { + else if (kind === 3 /* MultiLineCommentTrivia */) { writer.write(" "); } } @@ -65498,8 +68007,8 @@ var ts; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 266 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 266 /* Bundle */; + var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var isBundledEmit = sourceFileOrBundle.kind === 270 /* Bundle */; var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -65573,7 +68082,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 238 /* ImportDeclaration */); + ts.Debug.assert(aliasEmitInfo.node.kind === 239 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -65611,7 +68120,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -65626,6 +68135,7 @@ var ts; var writer = ts.createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; + writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; @@ -65649,10 +68159,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 226 /* VariableDeclaration */) { + if (declaration.kind === 227 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 241 /* NamedImports */ || declaration.kind === 242 /* ImportSpecifier */ || declaration.kind === 239 /* ImportClause */) { + else if (declaration.kind === 242 /* NamedImports */ || declaration.kind === 243 /* ImportSpecifier */ || declaration.kind === 240 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -65670,7 +68180,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 238 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 239 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -65680,12 +68190,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 233 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 234 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 233 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 234 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -65740,10 +68250,16 @@ var ts; emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } function reportInaccessibleThisError() { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -65753,7 +68269,7 @@ var ts; // for optional parameter properties // and also for non-optional initialized parameters that aren't a parameter property // these types may need to add `undefined`. - var shouldUseResolverType = declaration.kind === 146 /* Parameter */ && + var shouldUseResolverType = declaration.kind === 147 /* Parameter */ && (resolver.isRequiredInitializedParameter(declaration) || resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { @@ -65828,41 +68344,41 @@ var ts; case 139 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 130 /* NeverKeyword */: - case 169 /* ThisType */: - case 173 /* LiteralType */: + case 170 /* ThisType */: + case 174 /* LiteralType */: return writeTextOfNode(currentText, type); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return emitTypeReference(type); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return emitTypeQuery(type); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return emitArrayType(type); - case 165 /* TupleType */: + case 166 /* TupleType */: return emitTupleType(type); - case 166 /* UnionType */: + case 167 /* UnionType */: return emitUnionType(type); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return emitIntersectionType(type); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return emitParenType(type); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return emitTypeOperator(type); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return emitIndexedAccessType(type); - case 172 /* MappedType */: + case 173 /* MappedType */: return emitMappedType(type); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return emitTypeLiteral(type); case 71 /* Identifier */: return emitEntityName(type); - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return emitEntityName(type); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { @@ -65870,8 +68386,8 @@ var ts; writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 143 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 143 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 144 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 144 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); @@ -65880,14 +68396,14 @@ var ts; function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 237 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 238 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 179 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 180 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -66050,10 +68566,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 237 /* ImportEqualsDeclaration */ || - (node.parent.kind === 265 /* SourceFile */ && isCurrentFileExternalModule)) { + else if (node.kind === 238 /* ImportEqualsDeclaration */ || + (node.parent.kind === 269 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 265 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 269 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -66063,7 +68579,7 @@ var ts; }); } else { - if (node.kind === 238 /* ImportDeclaration */) { + if (node.kind === 239 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -66081,23 +68597,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return writeVariableStatement(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return writeClassDeclaration(node); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -66105,7 +68621,7 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 265 /* SourceFile */) { + if (node.parent.kind === 269 /* SourceFile */) { var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { @@ -66114,7 +68630,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { + else if (node.kind !== 231 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -66166,7 +68682,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings.kind === 241 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -66190,7 +68706,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 241 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -66211,13 +68727,13 @@ var ts; // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 233 /* ModuleDeclaration */; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 234 /* ModuleDeclaration */; var moduleSpecifier; - if (parent.kind === 237 /* ImportEqualsDeclaration */) { + if (parent.kind === 238 /* ImportEqualsDeclaration */) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 233 /* ModuleDeclaration */) { + else if (parent.kind === 234 /* ModuleDeclaration */) { moduleSpecifier = parent.name; } else { @@ -66287,7 +68803,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 234 /* ModuleBlock */) { + while (node.body && node.body.kind !== 235 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -66357,7 +68873,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 151 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 152 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -66368,15 +68884,15 @@ var ts; // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 163 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 151 /* MethodDeclaration */ || - node.parent.kind === 150 /* MethodSignature */ || - node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - node.parent.kind === 155 /* CallSignature */ || - node.parent.kind === 156 /* ConstructSignature */); + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 164 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 152 /* MethodDeclaration */ || + node.parent.kind === 151 /* MethodSignature */ || + node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.kind === 156 /* CallSignature */ || + node.parent.kind === 157 /* ConstructSignature */); emitType(node.constraint); } else { @@ -66385,15 +68901,15 @@ var ts; } if (node.default && !isPrivateMethodTypeParameter(node)) { write(" = "); - if (node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 163 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 151 /* MethodDeclaration */ || - node.parent.kind === 150 /* MethodSignature */ || - node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - node.parent.kind === 155 /* CallSignature */ || - node.parent.kind === 156 /* ConstructSignature */); + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 164 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 152 /* MethodDeclaration */ || + node.parent.kind === 151 /* MethodSignature */ || + node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.kind === 156 /* CallSignature */ || + node.parent.kind === 157 /* ConstructSignature */); emitType(node.default); } else { @@ -66404,34 +68920,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 155 /* CallSignature */: + case 156 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 230 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -66465,7 +68981,7 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 229 /* ClassDeclaration */) { + if (node.parent.parent.kind === 230 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -66504,7 +69020,7 @@ var ts; diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + }, !ts.findAncestor(node, function (n) { return n.kind === 234 /* ModuleDeclaration */; })); } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -66561,7 +69077,7 @@ var ts; enclosingDeclaration = prevEnclosingDeclaration; } function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } emitJsDocComments(node); @@ -66570,25 +69086,28 @@ var ts; write(";"); writeLine(); } + function bindingNameContainsVisibleBindingElement(node) { + return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); + } + function isVariableDeclarationVisible(node) { + return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); + } function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 226 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 227 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - // If this node is a computed name, it can only be a symbol, because we've already skipped - // it if it's not a well known symbol. In that case, the text of the name will be exactly - // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor // we don't want to emit property declaration with "?" - if ((node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || - (node.kind === 146 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */ || + (node.kind === 147 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) && node.parent.kind === 163 /* TypeLiteral */) { + if ((node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */) && node.parent.kind === 164 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -66601,15 +69120,15 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 226 /* VariableDeclaration */) { + if (node.kind === 227 /* VariableDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || - (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */ || + (node.kind === 147 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -66618,7 +69137,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { + else if (node.parent.kind === 230 /* ClassDeclaration */ || node.kind === 147 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -66642,7 +69161,7 @@ var ts; } : undefined; } function emitBindingPattern(bindingPattern) { - // Only select non-omitted expression from the bindingPattern's elements. + // Only select visible, non-omitted expression from the bindingPattern's elements. // We have to do this to avoid emitting trailing commas. // For example: // original: var [, c,,] = [ 2,3,4] @@ -66650,7 +69169,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 200 /* OmittedExpression */) { + if (element.kind !== 201 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { elements.push(element); } } @@ -66686,7 +69205,7 @@ var ts; } } function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { // If binding pattern doesn't have name, then there is nothing to be emitted for declaration file i.e. const [,] = [1,2]. @@ -66704,12 +69223,12 @@ var ts; else { write("var "); } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, resolver.isDeclarationVisible); + emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); write(";"); writeLine(); } function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -66718,13 +69237,13 @@ var ts; emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getAccessorNameVisibilityError); if (!ts.hasModifier(node, 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 153 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 154 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -66737,86 +69256,161 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 153 /* GetAccessor */ + return accessor.kind === 154 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type : undefined; } } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 154 /* SetAccessor */) { - // Setters have to have type named and cannot infer it so, the type should always be named - if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) { + if (accessorWithTypeAnnotation.kind === 155 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - // TODO(jfreeman): Investigate why we are passing node.name instead of node.parameters[0].name - typeName: accessorWithTypeAnnotation.name - }; } else { if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: accessorWithTypeAnnotation.name + }; } } function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 228 /* FunctionDeclaration */) { + if (node.kind === 229 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 151 /* MethodDeclaration */ || node.kind === 152 /* Constructor */) { + else if (node.kind === 152 /* MethodDeclaration */ || node.kind === 153 /* Constructor */) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 228 /* FunctionDeclaration */) { + if (node.kind === 229 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 152 /* Constructor */) { + else if (node.kind === 153 /* Constructor */) { write("constructor"); } else { - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getMethodNameVisibilityError); if (ts.hasQuestionToken(node)) { write("?"); } } emitSignatureDeclaration(node); } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + if (ts.hasDynamicName(node)) { + // If this node has a dynamic name, it can only be an identifier or property access because + // we've already skipped it otherwise. + ts.Debug.assert(resolver.isLateBound(node)); + writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); + } + else { + // If this node is a computed name, it can only be a symbol, because we've already skipped + // it if it's not a well known symbol. In that case, the text of the name will be exactly + // what we want, namely the name expression enclosed in brackets. + writeTextOfNode(currentText, node.name); + } + } + function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + var entityName = node.name.expression; + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + writeTextOfNode(currentText, node.name); } function emitSignatureDeclarationWithJsDocComments(node) { emitJsDocComments(node); @@ -66826,22 +69420,22 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { // Index signature can have readonly modifier emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + if (node.kind === 153 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { write("();"); writeLine(); return; } // Construct signature or constructor type write new Signature - if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { + if (node.kind === 157 /* ConstructSignature */ || node.kind === 162 /* ConstructorType */) { write("new "); } - else if (node.kind === 160 /* FunctionType */) { + else if (node.kind === 161 /* FunctionType */) { var currentOutput = writer.getText(); // Do not generate incorrect type when function type with type parameters is type argument // This could happen if user used space between two '<' making it error free @@ -66856,22 +69450,22 @@ var ts; } // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 160 /* FunctionType */ || node.kind === 161 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 163 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 161 /* FunctionType */ || node.kind === 162 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 164 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 152 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { + else if (node.kind !== 153 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -66885,26 +69479,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 155 /* CallSignature */: + case 156 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -66912,7 +69506,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -66926,7 +69520,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -66961,9 +69555,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - node.parent.parent.kind === 163 /* TypeLiteral */) { + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.parent.kind === 164 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8 /* Private */)) { @@ -66979,29 +69573,29 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 155 /* CallSignature */: + case 156 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -67009,7 +69603,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 230 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -67022,7 +69616,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -67034,12 +69628,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -67050,7 +69644,7 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 200 /* OmittedExpression */) { + if (bindingElement.kind === 201 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -67059,7 +69653,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 176 /* BindingElement */) { + else if (bindingElement.kind === 177 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -67098,40 +69692,40 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 233 /* ModuleDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 230 /* InterfaceDeclaration */: - case 229 /* ClassDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: + case 229 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 231 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return emitExportDeclaration(node); - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return writeFunctionDeclaration(node); - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 157 /* IndexSignature */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return emitAccessorDeclaration(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return emitPropertyDeclaration(node); - case 264 /* EnumMember */: + case 268 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return emitExportAssignment(node); - case 265 /* SourceFile */: + case 269 /* SourceFile */: return emitSourceFile(node); } } @@ -67159,7 +69753,7 @@ var ts; return addedBundledEmitReference; function getDeclFileName(emitFileNames, sourceFileOrBundle) { // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path - var isBundledEmit = sourceFileOrBundle.kind === 266 /* Bundle */; + var isBundledEmit = sourceFileOrBundle.kind === 270 /* Bundle */; if (isBundledEmit && !addBundledFileReference) { return; } @@ -67174,7 +69768,7 @@ var ts; var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { - var sourceFiles = sourceFileOrBundle.kind === 266 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); @@ -67259,7 +69853,7 @@ var ts; return ".js" /* Js */; } function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266 /* Bundle */) { + if (sourceFileOrBundle.kind === 270 /* Bundle */) { return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); } return ts.getOriginalSourceFile(sourceFileOrBundle); @@ -67336,8 +69930,8 @@ var ts; } } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 266 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 265 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 269 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); if (bundle) { @@ -67377,7 +69971,7 @@ var ts; } function emitHelpers(node, writeLines) { var helpersEmitted = false; - var bundle = node.kind === 266 /* Bundle */ ? node : undefined; + var bundle = node.kind === 270 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -67458,8 +70052,8 @@ var ts; break; } switch (node.kind) { - case 265 /* SourceFile */: return printFile(node); - case 266 /* Bundle */: return printBundle(node); + case 269 /* SourceFile */: return printFile(node); + case 270 /* Bundle */: return printBundle(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -67618,204 +70212,222 @@ var ts; return emitIdentifier(node); // Parse tree nodes // Names - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return emitQualifiedName(node); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return emitTypeParameter(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return emitParameter(node); - case 147 /* Decorator */: + case 148 /* Decorator */: return emitDecorator(node); // Type members - case 148 /* PropertySignature */: + case 149 /* PropertySignature */: return emitPropertySignature(node); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 150 /* MethodSignature */: + case 151 /* MethodSignature */: return emitMethodSignature(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return emitConstructor(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return emitAccessorDeclaration(node); - case 155 /* CallSignature */: + case 156 /* CallSignature */: return emitCallSignature(node); - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: return emitConstructSignature(node); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return emitIndexSignature(node); // Types - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return emitTypePredicate(node); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return emitTypeReference(node); - case 160 /* FunctionType */: + case 161 /* FunctionType */: return emitFunctionType(node); - case 161 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 162 /* ConstructorType */: return emitConstructorType(node); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return emitTypeQuery(node); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return emitTypeLiteral(node); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return emitArrayType(node); - case 165 /* TupleType */: + case 166 /* TupleType */: return emitTupleType(node); - case 166 /* UnionType */: + case 167 /* UnionType */: return emitUnionType(node); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return emitIntersectionType(node); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return emitParenthesizedType(node); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 169 /* ThisType */: + case 170 /* ThisType */: return emitThisType(); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return emitTypeOperator(node); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 172 /* MappedType */: + case 173 /* MappedType */: return emitMappedType(node); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return emitLiteralType(node); + case 272 /* JSDocAllType */: + write("*"); + return; + case 273 /* JSDocUnknownType */: + write("?"); + return; + case 274 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 275 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 276 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 278 /* JSDocVariadicType */: + return emitJSDocVariadicType(node); // Binding patterns - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return emitBindingElement(node); // Misc - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return emitTemplateSpan(node); - case 206 /* SemicolonClassElement */: + case 207 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 207 /* Block */: + case 208 /* Block */: return emitBlock(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return emitVariableStatement(node); - case 209 /* EmptyStatement */: + case 210 /* EmptyStatement */: return emitEmptyStatement(); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return emitExpressionStatement(node); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return emitIfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return emitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return emitWhileStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return emitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return emitForInStatement(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return emitForOfStatement(node); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return emitContinueStatement(node); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return emitBreakStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return emitReturnStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return emitWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return emitSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return emitLabeledStatement(node); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return emitThrowStatement(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return emitTryStatement(node); - case 225 /* DebuggerStatement */: + case 226 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return emitClassDeclaration(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return emitModuleBlock(node); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return emitCaseBlock(node); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return emitImportDeclaration(node); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return emitImportClause(node); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return emitNamespaceImport(node); - case 241 /* NamedImports */: + case 242 /* NamedImports */: return emitNamedImports(node); - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return emitImportSpecifier(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return emitExportAssignment(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return emitExportDeclaration(node); - case 245 /* NamedExports */: + case 246 /* NamedExports */: return emitNamedExports(node); - case 246 /* ExportSpecifier */: + case 247 /* ExportSpecifier */: return emitExportSpecifier(node); - case 247 /* MissingDeclaration */: + case 248 /* MissingDeclaration */: return; // Module references - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 10 /* JsxText */: return emitJsxText(node); - case 251 /* JsxOpeningElement */: - return emitJsxOpeningElement(node); - case 252 /* JsxClosingElement */: - return emitJsxClosingElement(node); - case 253 /* JsxAttribute */: + case 252 /* JsxOpeningElement */: + case 255 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 253 /* JsxClosingElement */: + case 256 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 257 /* JsxAttribute */: return emitJsxAttribute(node); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return emitJsxAttributes(node); - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 257 /* CaseClause */: + case 261 /* CaseClause */: return emitCaseClause(node); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return emitDefaultClause(node); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return emitHeritageClause(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 264 /* EnumMember */: + case 268 /* EnumMember */: return emitEnumMember(node); } // If the node is an expression, try to emit it as an expression with @@ -67851,69 +70463,71 @@ var ts; writeTokenNode(node); return; // Expressions - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return emitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return emitNewExpression(node); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return emitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return emitArrowFunction(node); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return emitDeleteExpression(node); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return emitVoidExpression(node); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return emitAwaitExpression(node); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return emitBinaryExpression(node); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return emitConditionalExpression(node); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return emitTemplateExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return emitYieldExpression(node); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return emitSpreadExpression(node); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return emitClassExpression(node); - case 200 /* OmittedExpression */: + case 201 /* OmittedExpression */: return; - case 202 /* AsExpression */: + case 203 /* AsExpression */: return emitAsExpression(node); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return emitNonNullExpression(node); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 249 /* JsxElement */: + case 250 /* JsxElement */: return emitJsxElement(node); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); + case 254 /* JsxFragment */: + return emitJsxFragment(node); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return emitCommaList(node); } } @@ -67988,9 +70602,16 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); - emit(node.name); + if (node.name) { + emit(node.name); + } emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); + if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitWithPrefix(": ", node.type); + } emitExpressionWithPrefix(" = ", node.initializer); } function emitDecorator(decorator) { @@ -68043,7 +70664,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 153 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -68092,6 +70713,24 @@ var ts; write(" => "); emit(node.type); } + function emitJSDocFunctionType(node) { + write("function"); + emitParameters(node, node.parameters); + write(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + write("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + write("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + write("="); + } function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); @@ -68113,6 +70752,10 @@ var ts; emit(node.elementType); write("[]"); } + function emitJSDocVariadicType(node) { + write("..."); + emit(node.type); + } function emitTupleType(node) { write("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); @@ -68255,7 +70898,7 @@ var ts; // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23 /* DotToken */)) < 0; + && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -68351,7 +70994,7 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 192 /* PrefixUnaryExpression */ + return operand.kind === 193 /* PrefixUnaryExpression */ && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); } @@ -68470,7 +71113,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); - if (node.elseStatement.kind === 211 /* IfStatement */) { + if (node.elseStatement.kind === 212 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -68533,7 +71176,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 227 /* VariableDeclarationList */) { + if (node.kind === 228 /* VariableDeclarationList */) { emit(node); } else { @@ -68644,26 +71287,15 @@ var ts; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + pushNameGenerationScope(node); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { - pushNameGenerationScope(); - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } - popNameGenerationScope(); + emitBlockFunctionBody(body); } + popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); } @@ -68760,11 +71392,9 @@ var ts; } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 65 /* ClassMembers */); write("}"); - popNameGenerationScope(); if (indentedFlag) { decreaseIndent(); } @@ -68794,11 +71424,9 @@ var ts; emitModifiers(node, node.modifiers); write("enum "); emit(node.name); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 81 /* EnumMembers */); write("}"); - popNameGenerationScope(); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); @@ -68807,7 +71435,7 @@ var ts; } emit(node.name); var body = node.body; - while (body.kind === 233 /* ModuleDeclaration */) { + while (body.kind === 234 /* ModuleDeclaration */) { write("."); emit(body.name); body = body.body; @@ -68816,11 +71444,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - pushNameGenerationScope(); + pushNameGenerationScope(node); write("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); write("}"); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitCaseBlock(node) { writeToken(17 /* OpenBraceToken */, node.pos); @@ -68925,7 +71553,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementChildren */); + emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -68938,22 +71566,31 @@ var ts; } write("/>"); } - function emitJsxOpeningElement(node) { + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { write("<"); - emitJsxTagName(node.tagName); - writeIfAny(node.attributes.properties, " "); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap + if (node.attributes.properties && node.attributes.properties.length > 0) { + write(" "); + emit(node.attributes); + } } write(">"); } function emitJsxText(node) { writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } - function emitJsxClosingElement(node) { + function emitJsxClosingElementOrFragment(node) { write(""); } function emitJsxAttributes(node) { @@ -69104,11 +71741,11 @@ var ts; } function emitSourceFileWorker(node) { var statements = node.statements; - pushNameGenerationScope(); + pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); - popNameGenerationScope(); + popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { @@ -69402,11 +72039,6 @@ var ts; function decreaseIndent() { writer.decreaseIndent(); } - function writeIfAny(nodes, text) { - if (ts.some(nodes)) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -69437,8 +72069,9 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = guessIndentation(lines); - for (var i = 0; i < lines.length; i++) { - var line = indentation ? lines[i].slice(indentation) : lines[i]; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var lineText = lines_1[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); @@ -69448,8 +72081,8 @@ var ts; } function guessIndentation(lines) { var indentation; - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var line = lines_1[_a]; + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { if (indentation === undefined || i < indentation) { @@ -69521,7 +72154,7 @@ var ts; } } else { - return nextNode.startsOnNewLine; + return ts.getStartsOnNewLine(nextNode); } } function shouldWriteClosingLineTerminator(parentNode, children, format) { @@ -69549,7 +72182,7 @@ var ts; } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { - var startsOnNewLine = node.startsOnNewLine; + var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { return (format & 32768 /* PreferNewLine */) !== 0; } @@ -69562,7 +72195,7 @@ var ts; node1 = skipSynthesizedParentheses(node1); node2 = skipSynthesizedParentheses(node2); // Always use a newline for synthesized code if the synthesizer desires it. - if (node2.startsOnNewLine) { + if (ts.getStartsOnNewLine(node2)) { return true; } return !ts.nodeIsSynthesized(parent) @@ -69575,7 +72208,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 185 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 186 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -69585,7 +72218,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -69612,14 +72245,20 @@ var ts; /** * Push a new name generation scope. */ - function pushNameGenerationScope() { + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } tempFlagsStack.push(tempFlags); tempFlags = 0; } /** * Pop the current name generation scope. */ - function popNameGenerationScope() { + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } tempFlags = tempFlagsStack.pop(); } /** @@ -69629,8 +72268,17 @@ var ts; if (name.autoGenerateKind === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - var node = getNodeForGeneratedName(name); - return generateNameCached(node); + if (name.skipNameGenerationScope) { + var savedTempFlags = tempFlags; + popNameGenerationScope(/*node*/ undefined); + var result = generateNameCached(getNodeForGeneratedName(name)); + pushNameGenerationScope(/*node*/ undefined); + tempFlags = savedTempFlags; + return result; + } + else { + return generateNameCached(getNodeForGeneratedName(name)); + } } else { // Auto, Loop, and Unique names are cached based on their unique @@ -69757,21 +72405,21 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return makeUniqueName(getTextOfNode(node)); - case 233 /* ModuleDeclaration */: - case 232 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 238 /* ImportDeclaration */: - case 244 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: - case 243 /* ExportAssignment */: + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + case 244 /* ExportAssignment */: return generateNameForExportDefault(); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return generateNameForClassExpression(); - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -69787,7 +72435,7 @@ var ts; case 2 /* Loop */: return makeTempVariableName(268435456 /* _i */); case 3 /* Unique */: - return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); + return makeUniqueName(ts.idText(name)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -69907,7 +72555,7 @@ var ts; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; @@ -69919,26 +72567,410 @@ var ts; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; + function createBuilder(options) { + var isModuleEmit; + var fileInfos = ts.createMap(); + var semanticDiagnosticsPerFile = ts.createMap(); + /** The map has key by source file's path that has been changed */ + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; + var emitHandler; + return { + updateProgram: updateProgram, + getFilesAffectedBy: getFilesAffectedBy, + emitChangedFiles: emitChangedFiles, + getSemanticDiagnostics: getSemanticDiagnostics, + clear: clear + }; + function createProgramGraph(program) { + var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; + if (isModuleEmit !== currentIsModuleEmit) { + isModuleEmit = currentIsModuleEmit; + emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; + ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { + // Add new file info + createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, + // Remove existing file info + onDeleteValue: removeExistingFileInfo, + // We will update in place instead of deleting existing value and adding new one + onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } + }); + } + function registerChangedFile(path) { + changedFilesSet.set(path, true); + // All changed files need to re-evaluate its semantic diagnostics + semanticDiagnosticsPerFile.delete(path); + } + function addNewFileInfo(program, sourceFile) { + registerChangedFile(sourceFile.path); + emitHandler.onAddSourceFile(program, sourceFile); + return { version: sourceFile.version, signature: undefined }; + } + function removeExistingFileInfo(_existingFileInfo, path) { + // Since we dont need to track removed file as changed file + // We can just remove its diagnostics + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); + emitHandler.onRemoveSourceFile(path); + } + function updateExistingFileInfo(program, existingInfo, sourceFile) { + if (existingInfo.version !== sourceFile.version) { + registerChangedFile(sourceFile.path); + existingInfo.version = sourceFile.version; + emitHandler.onUpdateSourceFile(program, sourceFile); + } + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + registerChangedFile(sourceFile.path); + } + } + function ensureProgramGraph(program) { + if (!emitHandler) { + createProgramGraph(program); + } + } + function updateProgram(newProgram) { + if (emitHandler) { + createProgramGraph(newProgram); + } + } + function getFilesAffectedBy(program, path) { + ensureProgramGraph(program); + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); + } + function emitChangedFiles(program, writeFileCallback) { + ensureProgramGraph(program); + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + // With --out or --outFile all outputs go into single file, do it only once + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; + } + var seenFiles = ts.createMap(); + var result; + changedFilesSet.forEach(function (_true, path) { + // Get the affected Files by this program + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + // Affected files shouldnt have cached diagnostics + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + // Emit the affected file + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); + } + }); + }); + changedFilesSet.clear(); + return result || ts.emptyArray; + } + function getSemanticDiagnostics(program, cancellationToken) { + ensureProgramGraph(program); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + // We dont need to cache the diagnostics just return them from program + return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + var diagnostics; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + function clear() { + isModuleEmit = undefined; + emitHandler = undefined; + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * @return {boolean} indicates if the shape signature has changed since last update. + */ + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + info.signature = latestSignature; + } + else { + var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = options.computeHash(emitOutput.outputFiles[0].text); + info.signature = latestSignature; + } + else { + latestSignature = prevSignature; + } + } + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + // Use cached result + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getNonModuleEmitHandler() { + return { + onAddSourceFile: ts.noop, + onRemoveSourceFile: ts.noop, + onUpdateSourceFile: ts.noop, + onUpdateSourceFileWithSameVersion: ts.returnFalse, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function getFilesAffectedByUpdatedShape(program, sourceFile) { + var options = program.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (options && (options.out || options.outFile)) { + return [sourceFile]; + } + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + } + function getModuleEmitHandler() { + var references = ts.createMap(); + return { + onAddSourceFile: setReferences, + onRemoveSourceFile: onRemoveSourceFile, + onUpdateSourceFile: updateReferences, + onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function setReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + } + function updateReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + else { + references.delete(sourceFile.path); + } + } + function updateReferencesTrackingChangedReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (!newReferences) { + // Changed if we had references + return references.delete(sourceFile.path); + } + var oldReferences = references.get(sourceFile.path); + references.set(sourceFile.path, newReferences); + if (!oldReferences || oldReferences.size !== newReferences.size) { + return true; + } + // If there are any new references that werent present previously there is change + return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || + // Otherwise its changed if there are more references previously than now + !!oldReferences.size; + } + function onRemoveSourceFile(removedFilePath) { + // Remove existing references + references.forEach(function (referencesInFile, filePath) { + if (referencesInFile.has(removedFilePath)) { + // add files referencing the removedFilePath, as changed files too + var referencedByInfo = fileInfos.get(filePath); + if (referencedByInfo) { + registerChangedFile(filePath); + } + } + }); + // Delete the entry for the removed file path + references.delete(removedFilePath); + } + function getReferencedByPaths(referencedFilePath) { + return ts.mapDefinedIter(references.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + }); + } + function getFilesAffectedByUpdatedShape(program, sourceFile) { + if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFile]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + var path = sourceFile.path; + seenFileNamesMap.set(path, sourceFile); + var queue = getReferencedByPaths(path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = program.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { + queue.push.apply(queue, getReferencedByPaths(currentPath)); + } + } + } + // Return array of values that needs emit + return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); + } + } + } + ts.createBuilder = createBuilder; +})(ts || (ts = {})); /// /// /// +/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } - while (true) { - var fileName = ts.combinePaths(searchPath, configName); - if (fileExists(fileName)) { - return fileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); } ts.findConfigFile = findConfigFile; function resolveTripleslashReference(moduleName, containingFile) { @@ -70106,18 +73138,23 @@ var ts; var output = ""; for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { var diagnostic = diagnostics_1[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + output += formatDiagnostic(diagnostic, host); } return output; } ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; @@ -70145,6 +73182,7 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; + var context = ""; if (diagnostic.file) { var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; @@ -70156,12 +73194,12 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += host.getNewLine(); + context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -70170,27 +73208,26 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + host.getNewLine(); + context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; + context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += redForegroundEscapeSequence; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { // Squiggle the entire line. - output += lineContent.replace(/./g, "~"); + context += lineContent.replace(/./g, "~"); } - output += resetEscapeSequence; - output += host.getNewLine(); + context += resetEscapeSequence; } output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; @@ -70198,13 +73235,17 @@ var ts; var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += context; + } output += host.getNewLine(); } return output; } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { - if (typeof messageText === "string") { + if (ts.isString(messageText)) { return messageText; } else { @@ -70245,6 +73286,61 @@ var ts; } return resolutions; } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + // If we haven't create a program yet or has changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + /** + * Determined if source file needs to be re-created even if its text hasnt changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + // If any of these options change, we cant reuse old source file even if version match + // The change in options like these could result in change in syntax tree change + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' * that represent a compilation unit. @@ -70297,8 +73393,9 @@ var ts; var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -70330,9 +73427,11 @@ var ts; // See `sourceFileIsRedirectedTo`. var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); + var missingFilePaths; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); @@ -70363,10 +73462,22 @@ var ts; }); } } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); } - var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + ts.Debug.assert(!!missingFilePaths); // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks moduleResolutionCache = undefined; + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; program = { @@ -70398,7 +73509,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -70431,8 +73542,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var sourceFile = files_2[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var sourceFile = files_1[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -70454,13 +73565,13 @@ var ts; // which per above occured during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_3 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_3.push(resolvedModule); } - return result_4; + return result_3; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -70478,19 +73589,20 @@ var ts; * * ResolvedModuleFull instance: can be reused. */ var result; + var reusedNames; /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // If we want to reuse resolutions more aggressively, we can refine this to check for whether the - // text of the corresponding modulenames has changed. - if (file === oldSourceFile) { + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); if (oldResolvedModule) { if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); } (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); continue; } } @@ -70517,7 +73629,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -70591,6 +73703,12 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } var oldSourceFiles = oldProgram.getSourceFiles(); var SeenPackageName; (function (SeenPackageName) { @@ -70598,11 +73716,11 @@ var ts; SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; })(SeenPackageName || (SeenPackageName = {})); var seenPackageNames = ts.createMap(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) - : host.getSourceFile(oldSourceFile.fileName, options.target); + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } @@ -70674,6 +73792,12 @@ var ts; // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } @@ -70716,28 +73840,22 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - // If a file has ceased to be missing, then we need to discard some of the old - // structure in order to pick it up. - // Caution: if the file has created and then deleted between since it was discovered to - // be missing, then the corresponding file watcher will have been closed and no new one - // will be created until we encounter a change that prevents complete structure reuse. - // During this interval, creation of the file will go unnoticed. We expect this to be - // both rare and low-impact. - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + if (host.hasChangedAutomaticTypeDirectiveNames) { return oldProgram.structureIsReused = 1 /* SafeModules */; } - for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { - var p = _d[_c]; - filesByName.set(p, undefined); - } + missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { - var modifiedFile = modifiedSourceFiles_2[_e]; + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -70767,10 +73885,18 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); @@ -70864,9 +73990,6 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - if (ts.isCheckJsEnabledForFile(sourceFile, options)) { - sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); - } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -70906,13 +74029,18 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); + if (isCheckJs) { + diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + } return ts.filter(diagnostics, shouldReportDiagnostic); }); } @@ -70950,22 +74078,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 226 /* VariableDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 227 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -70973,41 +74101,41 @@ var ts; } } switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 108 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 202 /* AsExpression */: + case 203 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -71020,28 +74148,28 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } switch (parent.kind) { - case 229 /* ClassDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: + case 230 /* ClassDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 208 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 209 /* VariableStatement */); } break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -71053,16 +74181,16 @@ var ts; return; } break; - case 146 /* Parameter */: + case 147 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 201 /* ExpressionWithTypeArguments */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 202 /* ExpressionWithTypeArguments */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -71195,9 +74323,9 @@ var ts; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; @@ -71212,7 +74340,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); @@ -71274,7 +74402,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } return sourceFile; @@ -71365,7 +74493,7 @@ var ts; else { fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } - }); + }, shouldCreateNewSourceFile); if (packageId) { var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); @@ -71652,7 +74780,7 @@ var ts; if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } - if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0 /* ES3 */; @@ -71859,7 +74987,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -71957,31 +75085,32 @@ var ts; name: "target", shortName: "t", type: ts.createMapFromTemplate({ - "es3": 0 /* ES3 */, - "es5": 1 /* ES5 */, - "es6": 2 /* ES2015 */, - "es2015": 2 /* ES2015 */, - "es2016": 3 /* ES2016 */, - "es2017": 4 /* ES2017 */, - "esnext": 5 /* ESNext */, + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, }), paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", shortName: "m", type: ts.createMapFromTemplate({ - "none": ts.ModuleKind.None, - "commonjs": ts.ModuleKind.CommonJS, - "amd": ts.ModuleKind.AMD, - "system": ts.ModuleKind.System, - "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES2015, - "es2015": ts.ModuleKind.ES2015, - "esnext": ts.ModuleKind.ESNext + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -72001,6 +75130,7 @@ var ts; "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", // Host only "dom": "lib.dom.d.ts", @@ -72022,6 +75152,7 @@ var ts; "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", + "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -72149,6 +75280,20 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, { name: "noImplicitThis", type: "boolean", @@ -72196,8 +75341,8 @@ var ts; { name: "moduleResolution", type: ts.createMapFromTemplate({ - "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic, + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, }), paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, @@ -72388,8 +75533,8 @@ var ts; { name: "newLine", type: ts.createMapFromTemplate({ - "crlf": 0 /* CarriageReturnLineFeed */, - "lf": 1 /* LineFeed */ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ }), paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Advanced_Options, @@ -72744,7 +75889,7 @@ var ts; */ function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; /** @@ -72766,7 +75911,7 @@ var ts; */ function readJsonConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; function tryReadFile(fileName, readFile) { @@ -72857,7 +76002,7 @@ var ts; var result = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 261 /* PropertyAssignment */) { + if (element.kind !== 265 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -72919,9 +76064,9 @@ var ts; if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); var text = valueExpression.text; - if (option && typeof option.type !== "string") { + if (option && !ts.isString(option.type)) { var customOption = option; // Validate custom option type if (!customOption.type.has(text.toLowerCase())) { @@ -72932,7 +76077,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 178 /* ObjectLiteralExpression */: + case 193 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 179 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -72949,7 +76100,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -72968,13 +76119,13 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : - typeof option.type === "string" ? option.type : "string"; + ts.isString(option.type) ? option.type : "string"; } function isCompilerOptionsValue(option, value) { if (option) { @@ -72983,7 +76134,7 @@ var ts; if (option.type === "list") { return ts.isArray(value); } - var expectedType = typeof option.type === "string" ? option.type : "string"; + var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } } @@ -73188,12 +76339,13 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -73201,14 +76353,15 @@ var ts; raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec }; function getFileNames() { - var fileNames; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - fileNames = raw["files"]; - if (fileNames.length === 0) { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -73217,35 +76370,35 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } } - if (fileNames === undefined && includeSpecs === undefined) { + if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } return result; } @@ -73255,6 +76408,17 @@ var ts; } } } + /*@internal*/ + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + /*@internal*/ + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -73262,9 +76426,8 @@ var ts; * This *just* extracts options/include/exclude/files out of a config file. * It does *not* resolve the included files. */ - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); @@ -73305,11 +76468,11 @@ var ts; var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { - if (typeof json.extends !== "string") { + if (!ts.isString(json.extends)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { @@ -73379,7 +76542,7 @@ var ts; return undefined; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); @@ -73398,7 +76561,7 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } @@ -73423,7 +76586,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -73483,7 +76646,7 @@ var ts; if (optType === "list" && ts.isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors); } - else if (typeof optType !== "string") { + else if (!ts.isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); } return normalizeNonListOptionValue(opt, basePath, value); @@ -73497,13 +76660,13 @@ var ts; return undefined; if (option.type === "list") { var listOption_1 = option; - if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else if (typeof option.type !== "string") { - return option.type.get(typeof value === "string" ? value.toLowerCase() : value); + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -73604,19 +76767,47 @@ var ts; /** * Expands an array of file specifications. * - * @param fileNames The literal file names to include. - * @param include The wildcard file specifications to include. - * @param exclude The wildcard file specifications to exclude. + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. * @param basePath The base path for any relative file specifications. * @param options Compiler options. * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; // Literal file names (provided via the "files" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including @@ -73626,31 +76817,21 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); - if (include) { - include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); - } - if (exclude) { - exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); - } - // Wildcard directories (provided as part of a wildcard path) are stored in a - // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), - // or a recursive directory. This information is used by filesystem watchers to monitor for - // new entries in these paths. - var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. - if (fileNames) { - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } - if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, /*depth*/ undefined); _a < _b.length; _a++) { + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { var file = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. @@ -73676,9 +76857,11 @@ var ts; var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); return { fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + spec: spec }; } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter(function (spec) { var diag = specToDiagnostic(spec, allowTrailingRecursion); @@ -74111,7 +77294,7 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -74122,36 +77305,36 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 146 /* Parameter */: - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 260 /* CatchClause */: - case 253 /* JsxAttribute */: + case 147 /* Parameter */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 264 /* CatchClause */: + case 257 /* JsxAttribute */: return 1 /* Value */; - case 145 /* TypeParameter */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 163 /* TypeLiteral */: + case 146 /* TypeParameter */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 164 /* TypeLiteral */: return 2 /* Type */; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 264 /* EnumMember */: - case 229 /* ClassDeclaration */: + case 268 /* EnumMember */: + case 230 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -74161,26 +77344,26 @@ var ts; else { return 4 /* Namespace */; } - case 232 /* EnumDeclaration */: - case 241 /* NamedImports */: - case 242 /* ImportSpecifier */: - case 237 /* ImportEqualsDeclaration */: - case 238 /* ImportDeclaration */: - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: + case 233 /* EnumDeclaration */: + case 242 /* NamedImports */: + case 243 /* ImportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 239 /* ImportDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 265 /* SourceFile */: + case 269 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 243 /* ExportAssignment */) { + else if (node.parent.kind === 244 /* ExportAssignment */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -74209,15 +77392,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 143 /* QualifiedName */ && + if (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 237 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 238 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 143 /* QualifiedName */) { + while (node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -74229,27 +77412,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 143 /* QualifiedName */) { - while (root.parent && root.parent.kind === 143 /* QualifiedName */) { + if (root.parent.kind === 144 /* QualifiedName */) { + while (root.parent && root.parent.kind === 144 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 159 /* TypeReference */ && !isLastClause; + return root.parent.kind === 160 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 179 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 179 /* PropertyAccessExpression */) { + if (root.parent.kind === 180 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 180 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 201 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 259 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 202 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 263 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 229 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 230 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 230 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || + (decl.kind === 231 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); } return false; } @@ -74259,24 +77442,24 @@ var ts; } switch (node.kind) { case 99 /* ThisKeyword */: - return !ts.isPartOfExpression(node); - case 169 /* ThisType */: + return !ts.isExpressionNode(node); + case 170 /* ThisType */: return true; } switch (node.parent.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return true; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 181 /* CallExpression */); + return isCallOrNewExpressionTarget(node, 182 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 182 /* NewExpression */); + return isCallOrNewExpressionTarget(node, 183 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -74289,7 +77472,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 223 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -74299,13 +77482,13 @@ var ts; ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && - (node.parent.kind === 218 /* BreakStatement */ || node.parent.kind === 217 /* ContinueStatement */) && + (node.parent.kind === 219 /* BreakStatement */ || node.parent.kind === 218 /* ContinueStatement */) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { return node.kind === 71 /* Identifier */ && - node.parent.kind === 222 /* LabeledStatement */ && + node.parent.kind === 223 /* LabeledStatement */ && node.parent.label === node; } function isLabelName(node) { @@ -74313,15 +77496,15 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 143 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 233 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 234 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { @@ -74331,22 +77514,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 264 /* EnumMember */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 233 /* ModuleDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 268 /* EnumMember */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 234 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return true; - case 173 /* LiteralType */: - return node.parent.parent.kind === 171 /* IndexedAccessType */; + case 174 /* LiteralType */: + return node.parent.parent.kind === 172 /* IndexedAccessType */; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -74356,7 +77539,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 283 /* JSDocTypedefTag */) { + if (node.kind === 288 /* JSDocTypedefTag */) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -74368,17 +77551,17 @@ var ts; return undefined; } switch (node.kind) { - case 265 /* SourceFile */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return node; } } @@ -74386,48 +77569,48 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return "class" /* classElement */; - case 230 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 231 /* TypeAliasDeclaration */: return "type" /* typeElement */; - case 232 /* EnumDeclaration */: return "enum" /* enumElement */; - case 226 /* VariableDeclaration */: + case 231 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 232 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 233 /* EnumDeclaration */: return "enum" /* enumElement */; + case 227 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return "function" /* functionElement */; - case 153 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 154 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 154 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 155 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return "property" /* memberVariableElement */; - case 157 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 156 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 155 /* CallSignature */: return "call" /* callSignatureElement */; - case 152 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 145 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 264 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 146 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 237 /* ImportEqualsDeclaration */: - case 242 /* ImportSpecifier */: - case 239 /* ImportClause */: - case 246 /* ExportSpecifier */: - case 240 /* NamespaceImport */: + case 158 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 157 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 156 /* CallSignature */: return "call" /* callSignatureElement */; + case 153 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 146 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 268 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 147 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 238 /* ImportEqualsDeclaration */: + case 243 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 247 /* ExportSpecifier */: + case 241 /* NamespaceImport */: return "alias" /* alias */; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { @@ -74438,7 +77621,7 @@ var ts; var rightKind = getNodeKind(right); return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; case 3 /* PrototypeProperty */: - return "method" /* memberFunctionElement */; // instance method + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; case 4 /* ThisProperty */: return "property" /* memberVariableElement */; // property case 5 /* Property */: @@ -74468,7 +77651,7 @@ var ts; return true; case 71 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 146 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 147 /* Parameter */; default: return false; } @@ -74504,8 +77687,12 @@ var ts; return start < end; } ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + /** + * Assumes `candidate.start <= position` holds. + */ function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { @@ -74513,42 +77700,42 @@ var ts; return false; } switch (n.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: - case 174 /* ObjectBindingPattern */: - case 163 /* TypeLiteral */: - case 207 /* Block */: - case 234 /* ModuleBlock */: - case 235 /* CaseBlock */: - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 179 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 164 /* TypeLiteral */: + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 236 /* CaseBlock */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 182 /* NewExpression */: + case 183 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 181 /* CallExpression */: - case 185 /* ParenthesizedExpression */: - case 168 /* ParenthesizedType */: + case 182 /* CallExpression */: + case 186 /* ParenthesizedExpression */: + case 169 /* ParenthesizedType */: return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 187 /* ArrowFunction */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 188 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -74558,67 +77745,67 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 211 /* IfStatement */: + case 212 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 25 /* SemicolonToken */); - case 177 /* ArrayLiteralExpression */: - case 175 /* ArrayBindingPattern */: - case 180 /* ElementAccessExpression */: - case 144 /* ComputedPropertyName */: - case 165 /* TupleType */: + case 178 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 181 /* ElementAccessExpression */: + case 145 /* ComputedPropertyName */: + case 166 /* TupleType */: return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 257 /* CaseClause */: - case 258 /* DefaultClause */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 213 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 212 /* DoStatement */: + case 213 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 106 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 189 /* TypeOfExpression */: - case 188 /* DeleteExpression */: - case 190 /* VoidExpression */: - case 197 /* YieldExpression */: - case 198 /* SpreadElement */: + case 190 /* TypeOfExpression */: + case 189 /* DeleteExpression */: + case 191 /* VoidExpression */: + case 198 /* YieldExpression */: + case 199 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 244 /* ExportDeclaration */: - case 238 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -74632,11 +77819,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { + var last_2 = ts.lastOrUndefined(children); + if (last_2.kind === expectedLastToken) { return true; } - else if (last.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -74770,8 +77957,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { - var child = children_2[_i]; + for (var _i = 0, children_3 = children; _i < children_3.length; _i++) { + var child = children_3[_i]; var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || @@ -74829,7 +78016,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 269 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -74890,17 +78077,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 256 /* JsxExpression */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 260 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 256 /* JsxExpression */) { + if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 260 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 252 /* JsxClosingElement */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 253 /* JsxClosingElement */) { return true; } return false; @@ -74956,16 +78143,16 @@ var ts; result.push("abstract" /* abstractModifier */); if (flags & 1 /* Export */) result.push("export" /* exportedModifier */); - if (ts.isInAmbientContext(node)) + if (node.flags & 2097152 /* Ambient */) result.push("declare" /* ambientModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 159 /* TypeReference */ || node.kind === 181 /* CallExpression */) { + if (node.kind === 160 /* TypeReference */ || node.kind === 182 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 229 /* ClassDeclaration */ || node.kind === 230 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 230 /* ClassDeclaration */ || node.kind === 231 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -75016,38 +78203,19 @@ var ts; return result; } ts.cloneCompilerOptions = cloneCompilerOptions; - function compareDataObjects(dst, src) { - if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { - return false; - } - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { - return false; - } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; - } - } - } - return true; - } - ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 177 /* ArrayLiteralExpression */ || - node.kind === 178 /* ObjectLiteralExpression */) { + if (node.kind === 178 /* ArrayLiteralExpression */ || + node.kind === 179 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 194 /* BinaryExpression */ && + if (node.parent.kind === 195 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 216 /* ForOfStatement */ && + if (node.parent.kind === 217 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -75055,7 +78223,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 261 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 265 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -75089,20 +78257,18 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + ts.typeKeywords = [ + 119 /* AnyKeyword */, + 122 /* BooleanKeyword */, + 130 /* NeverKeyword */, + 133 /* NumberKeyword */, + 134 /* ObjectKeyword */, + 136 /* StringKeyword */, + 137 /* SymbolKeyword */, + 105 /* VoidKeyword */, + ]; function isTypeKeyword(kind) { - switch (kind) { - case 119 /* AnyKeyword */: - case 122 /* BooleanKeyword */: - case 130 /* NeverKeyword */: - case 133 /* NumberKeyword */: - case 134 /* ObjectKeyword */: - case 136 /* StringKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - return true; - default: - return false; - } + return ts.contains(ts.typeKeywords, kind); } ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ @@ -75125,7 +78291,7 @@ var ts; /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 146 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 147 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -75150,6 +78316,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { @@ -75304,7 +78471,7 @@ var ts; function getDeclaredName(typeChecker, symbol, location) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144 /* ComputedPropertyName */) { + if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { return ts.getTextOfIdentifierOrLiteral(location); } // Try to get the local symbol if we're dealing with an 'export default' @@ -75315,7 +78482,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 242 /* ImportSpecifier */ || location.parent.kind === 246 /* ExportSpecifier */) && + (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -75326,9 +78493,7 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -75349,6 +78514,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -75365,163 +78534,153 @@ var ts; return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; -})(ts || (ts = {})); -var ts; -(function (ts) { - /// Classifier - function createClassifier() { - var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false); - /// We do not have a full parser support to know when we should parse a regex or not - /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where - /// we have a series of divide operator. this list allows us to be more accurate by ruling out - /// locations where a regexp cannot exist. - var noRegexTable = []; - noRegexTable[71 /* Identifier */] = true; - noRegexTable[9 /* StringLiteral */] = true; - noRegexTable[8 /* NumericLiteral */] = true; - noRegexTable[12 /* RegularExpressionLiteral */] = true; - noRegexTable[99 /* ThisKeyword */] = true; - noRegexTable[43 /* PlusPlusToken */] = true; - noRegexTable[44 /* MinusMinusToken */] = true; - noRegexTable[20 /* CloseParenToken */] = true; - noRegexTable[22 /* CloseBracketToken */] = true; - noRegexTable[18 /* CloseBraceToken */] = true; - noRegexTable[101 /* TrueKeyword */] = true; - noRegexTable[86 /* FalseKeyword */] = true; - // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) - // classification on template strings. Because of the context free nature of templates, - // the only precise way to classify a template portion would be by propagating the stack across - // lines, just as we do with the end-of-line state. However, this is a burden for implementers, - // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead - // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. - // Situations in which this fails are - // 1) When template strings are nested across different lines: - // `hello ${ `world - // ` }` - // - // Where on the second line, you will get the closing of a template, - // a closing curly, and a new template. - // - // 2) When substitution expressions have curly braces and the curly brace falls on the next line: - // `hello ${ () => { - // return "world" } } ` - // - // Where on the second line, you will get the 'return' keyword, - // a string literal, and a template end consisting of '} } `'. - var templateStack = []; - /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 125 /* GetKeyword */ || - keyword2 === 135 /* SetKeyword */ || - keyword2 === 123 /* ConstructorKeyword */ || - keyword2 === 115 /* StaticKeyword */) { - // Allow things like "public get", "public constructor" and "public static". - // These are all legal. - return true; + function getSourceFileImportLocation(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } } - // Any other keyword following "public" is actually an identifier an not a real - // keyword. - return false; } - // Assume any other keyword combination is legal. This can be refined in the future - // if there are more cases we want the classifier to be better at. - return true; } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0; i < dense.length; i += 3) { - var start = dense[i]; - var length_6 = dense[i + 1]; - var type = dense[i + 2]; - // Make a whitespace entry between the last item and this one. - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); - } - } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1 /* comment */: return ts.TokenClass.Comment; - case 3 /* keyword */: return ts.TokenClass.Keyword; - case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; - case 5 /* operator */: return ts.TokenClass.Operator; - case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; - case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; - case 10 /* punctuation */: return ts.TokenClass.Punctuation; - case 2 /* identifier */: - case 11 /* className */: - case 12 /* enumName */: - case 13 /* interfaceName */: - case 14 /* moduleName */: - case 15 /* typeParameterName */: - case 16 /* typeAliasName */: - case 9 /* text */: - case 17 /* parameterName */: - default: - return ts.TokenClass.Identifier; + } + ts.getSourceFileImportLocation = getSourceFileImportLocation; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_7 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_7)) { + clone_7.textSourceNode = node; } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + /* @internal */ + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512 /* NoLeadingComments */); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + if (firstChild) { + suppressLeading(firstChild); + } + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024 /* NoTrailingComments */); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + // As an optimization, jump straight to the end of the list. + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + if (lastChild) { + suppressTrailing(lastChild); + } + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createClassifier() { + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); } // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), // we will be more conservative in order to avoid conflicting with the syntactic classifier. function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; var token = 0 /* Unknown */; var lastNonTriviaToken = 0 /* Unknown */; - // Empty out the template stack for reuse. - while (templateStack.length > 0) { - templateStack.pop(); - } - // If we're in a string literal, then prepend: "\ - // (and a newline). That way when we lex we'll think we're still in a string literal. + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` // - // If we're in a multiline comment, then prepend: /* - // (and a newline). That way when we lex we'll think we're still in a multiline comment. - switch (lexState) { - case 3 /* InDoubleQuoteStringLiteral */: - text = "\"\\\n" + text; - offset = 3; - break; - case 2 /* InSingleQuoteStringLiteral */: - text = "'\\\n" + text; - offset = 3; - break; - case 1 /* InMultiLineCommentTrivia */: - text = "/*\n" + text; - offset = 3; - break; - case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: - text = "`\n" + text; - offset = 2; - break; - case 5 /* InTemplateMiddleOrTail */: - text = "}\n" + text; - offset = 2; - // falls through - case 6 /* InTemplateSubstitutionPosition */: - templateStack.push(14 /* TemplateHead */); - break; + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(14 /* TemplateHead */); } scanner.setText(text); - var result = { - endOfLineState: 0 /* None */, - spans: [] - }; + var endOfLineState = 0 /* None */; + var spans = []; // We can run into an unfortunate interaction between the lexical and syntactic classifier // when the user is typing something generic. Consider the case where the user types: // @@ -75545,55 +78704,63 @@ var ts; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { token = 12 /* RegularExpressionLiteral */; } - } - else if (lastNonTriviaToken === 23 /* DotToken */ && isKeyword(token)) { - token = 71 /* Identifier */; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - // We have two keywords in a row. Only treat the second as a keyword if - // it's a sequence that could legally occur in the language. Otherwise - // treat it as an identifier. This way, if someone writes "private var" - // we recognize that 'var' is actually an identifier here. - token = 71 /* Identifier */; - } - else if (lastNonTriviaToken === 71 /* Identifier */ && - token === 27 /* LessThanToken */) { - // Could be the start of something generic. Keep track of that by bumping - // up the current count of generic contexts we may be in. - angleBracketStack++; - } - else if (token === 29 /* GreaterThanToken */ && angleBracketStack > 0) { - // If we think we're currently in something generic, then mark that that - // generic entity is complete. - angleBracketStack--; - } - else if (token === 119 /* AnyKeyword */ || - token === 136 /* StringKeyword */ || - token === 133 /* NumberKeyword */ || - token === 122 /* BooleanKeyword */ || - token === 137 /* SymbolKeyword */) { + break; + case 27 /* LessThanToken */: + if (lastNonTriviaToken === 71 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 29 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, // causing a noisy experience for the user. token = 71 /* Identifier */; } - } - else if (token === 14 /* TemplateHead */) { + break; + case 14 /* TemplateHead */: templateStack.push(token); - } - else if (token === 17 /* OpenBraceToken */) { + break; + case 17 /* OpenBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } - } - else if (token === 18 /* CloseBraceToken */) { + break; + case 18 /* CloseBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { @@ -75613,183 +78780,279 @@ var ts; templateStack.pop(); } } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1 /* EndOfFileToken */); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9 /* StringLiteral */) { - // Check to see if we finished up on a multiline string literal. - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { - numBackslashes++; - } - // If we have an odd number of backslashes, then the multiline string is unclosed - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 /* doubleQuote */ - ? 3 /* InDoubleQuoteStringLiteral */ - : 2 /* InSingleQuoteStringLiteral */; - } + break; + default: + if (!ts.isKeyword(token)) { + break; } - } - else if (token === 3 /* MultiLineCommentTrivia */) { - // Check to see if the multiline comment was unclosed. - if (scanner.isUnterminated()) { - result.endOfLineState = 1 /* InMultiLineCommentTrivia */; + if (lastNonTriviaToken === 23 /* DotToken */) { + token = 71 /* Identifier */; } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 16 /* TemplateTail */) { - result.endOfLineState = 5 /* InTemplateMiddleOrTail */; - } - else if (token === 13 /* NoSubstitutionTemplateLiteral */) { - result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 71 /* Identifier */; } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 14 /* TemplateHead */) { - result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; - } } } - function addResult(start, end, classification) { - if (classification === 8 /* whiteSpace */) { - // Don't bother with whitespace classifications. They're not needed. - return; - } - if (start === 0 && offset > 0) { - // We're classifying the first token, and this was a case where we prepended - // text. We should consider the start of this token to be at the start of - // the original text. - start += offset; + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 71 /* Identifier */, + 9 /* StringLiteral */, + 8 /* NumericLiteral */, + 12 /* RegularExpressionLiteral */, + 99 /* ThisKeyword */, + 43 /* PlusPlusToken */, + 44 /* MinusMinusToken */, + 20 /* CloseParenToken */, + 22 /* CloseBracketToken */, + 18 /* CloseBraceToken */, + 101 /* TrueKeyword */, + 86 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 9 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 16 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 13 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } } - // All our tokens are in relation to the augmented text. Move them back to be - // relative to the original text. - start -= offset; - end -= offset; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); + return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_6 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 48 /* AmpersandToken */: - case 50 /* CaretToken */: - case 49 /* BarToken */: - case 53 /* AmpersandAmpersandToken */: - case 54 /* BarBarToken */: - case 69 /* BarEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return true; - default: - return false; - } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - return true; - default: - return false; - } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; } - function isKeyword(token) { - return token >= 72 /* FirstKeyword */ && token <= 142 /* LastKeyword */; + switch (keyword2) { + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. } - function classFromKind(token) { - if (isKeyword(token)) { - return 3 /* keyword */; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5 /* operator */; - } - else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { - return 10 /* punctuation */; - } - switch (token) { - case 8 /* NumericLiteral */: - return 4 /* numericLiteral */; - case 9 /* StringLiteral */: + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + throw ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 48 /* AmpersandToken */: + case 50 /* CaretToken */: + case 49 /* BarToken */: + case 53 /* AmpersandAmpersandToken */: + case 54 /* BarBarToken */: + case 69 /* BarEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 59 /* PlusEqualsToken */: + case 60 /* MinusEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 58 /* EqualsToken */: + case 26 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* StringLiteral */: + return 6 /* stringLiteral */; + case 12 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 71 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; - case 12 /* RegularExpressionLiteral */: - return 7 /* regularExpressionLiteral */; - case 7 /* ConflictMarkerTrivia */: - case 3 /* MultiLineCommentTrivia */: - case 2 /* SingleLineCommentTrivia */: - return 1 /* comment */; - case 5 /* WhitespaceTrivia */: - case 4 /* NewLineTrivia */: - return 8 /* whiteSpace */; - case 71 /* Identifier */: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6 /* stringLiteral */; - } - return 2 /* identifier */; - } + } + return 2 /* identifier */; } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; } - ts.createClassifier = createClassifier; /* @internal */ function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); } ts.getSemanticClassifications = getSemanticClassifications; function checkForClassificationCancellation(cancellationToken, kind) { @@ -75804,90 +79067,78 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } /* @internal */ function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - var result = []; - processNode(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (flags & 32 /* Class */) { - return 11 /* className */; - } - else if (flags & 384 /* Enum */) { - return 12 /* enumName */; - } - else if (flags & 524288 /* TypeAlias */) { - return 16 /* typeAliasName */; - } - else if (meaningAtPosition & 2 /* Type */) { - if (flags & 64 /* Interface */) { - return 13 /* interfaceName */; - } - else if (flags & 262144 /* TypeParameter */) { - return 15 /* typeParameterName */; - } - } - else if (flags & 1536 /* Module */) { - // Only classify a module as such if - // - It appears in a namespace context. - // - There exists a module declaration which actually impacts the value side. - if (meaningAtPosition & 4 /* Namespace */ || - (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { - return 14 /* moduleName */; + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); } } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { return undefined; - /** - * Returns true if there exists a module that introduces entities on the value side. - */ - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 233 /* ModuleDeclaration */ && - ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; - }); - } } - function processNode(node) { - // Only walk into nodes that intersect the requested span. - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(cancellationToken, kind); - if (kind === 71 /* Identifier */ && !ts.nodeIsMissing(node)) { - var identifier = node; - // Only bother calling into the typechecker if this is an identifier that - // could possibly resolve to a type name. This makes classification run - // in a third of the time it would normally take. - if (classifiableNames.has(identifier.escapedText)) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; } } - ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } function getClassificationTypeName(type) { switch (type) { case 1 /* comment */: return "comment" /* comment */; @@ -75915,7 +79166,7 @@ var ts; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; } } - function convertClassifications(classifications) { + function convertClassificationsToSpans(classifications) { ts.Debug.assert(classifications.spans.length % 3 === 0); var dense = classifications.spans; var result = []; @@ -75929,7 +79180,7 @@ var ts; } /* @internal */ function getSyntacticClassifications(cancellationToken, sourceFile, span) { - return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); } ts.getSyntacticClassifications = getSyntacticClassifications; /* @internal */ @@ -75937,8 +79188,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -76023,16 +79274,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 279 /* JSDocParameterTag */: + case 284 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 282 /* JSDocTemplateTag */: + case 287 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 281 /* JSDocTypeTag */: + case 286 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 280 /* JSDocReturnTag */: + case 285 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -76119,22 +79370,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 251 /* JsxOpeningElement */: + case 252 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -76162,17 +79413,17 @@ var ts; if (token) { if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 226 /* VariableDeclaration */ || - token.parent.kind === 149 /* PropertyDeclaration */ || - token.parent.kind === 146 /* Parameter */ || - token.parent.kind === 253 /* JsxAttribute */) { + if (token.parent.kind === 227 /* VariableDeclaration */ || + token.parent.kind === 150 /* PropertyDeclaration */ || + token.parent.kind === 147 /* Parameter */ || + token.parent.kind === 257 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 194 /* BinaryExpression */ || - token.parent.kind === 192 /* PrefixUnaryExpression */ || - token.parent.kind === 193 /* PostfixUnaryExpression */ || - token.parent.kind === 195 /* ConditionalExpression */) { + if (token.parent.kind === 195 /* BinaryExpression */ || + token.parent.kind === 193 /* PrefixUnaryExpression */ || + token.parent.kind === 194 /* PostfixUnaryExpression */ || + token.parent.kind === 196 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -76182,7 +79433,7 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { - return token.parent.kind === 253 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token.parent.kind === 257 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -76198,32 +79449,32 @@ var ts; else if (tokenKind === 71 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 146 /* Parameter */: + case 147 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -76259,46 +79510,39 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); - var entries; if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); } else { - entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); } } else { // Check for node modules - entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); } - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries - }; } - PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames; + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already - rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within - var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; }); // Now find a path for each potential directory that is to be merged with the one containing the script - return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); @@ -76343,8 +79587,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var filePath = files_2[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -76361,8 +79605,8 @@ var ts; // If possible, get folder completion as well var directories = tryGetDirectories(host, baseDirectory); if (directories) { - for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { - var directory = directories_2[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var directory = directories_1[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); result.push(createCompletionEntryForModule(directoryName, "directory" /* directory */, span)); } @@ -76379,42 +79623,56 @@ var ts; */ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result; + var result = []; + var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { - var fileExtensions = ts.getSupportedExtensions(compilerOptions); var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host); - if (paths) { - for (var path in paths) { - if (paths.hasOwnProperty(path)) { - if (path === "*") { - if (paths[path]) { - for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { - var pattern = _a[_i]; - for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { - var match = _c[_b]; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - } - } - } - } - else if (ts.startsWith(path, fragment)) { - var entry = paths[path] && paths[path].length === 1 && paths[path][0]; - if (entry) { - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + var _loop_6 = function (path) { + if (!paths.hasOwnProperty(path)) + return "continue"; + var patterns = paths[path]; + if (!patterns) + return "continue"; + if (path === "*") { + for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { + var pattern = patterns_1[_i]; + var _loop_7 = function (match) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (result.some(function (entry) { return entry.name === match; })) + return "continue"; + result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); + }; + for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { + var match = _b[_a]; + _loop_7(match); } } } + else if (ts.startsWith(path, fragment)) { + if (patterns.length === 1) { + if (result.some(function (entry) { return entry.name === path; })) + return "continue"; + result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); + } + } + }; + for (var path in paths) { + _loop_6(path); } } - else { - result = []; + if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (host.directoryExists(nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + } + }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { - var moduleName = _e[_d]; + for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { + var moduleName = _a[_i]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; @@ -76428,7 +79686,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); @@ -76460,7 +79718,7 @@ var ts; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); @@ -76493,53 +79751,36 @@ var ts; } } } - return ts.deduplicate(nonRelativeModuleNames); + return ts.deduplicate(nonRelativeModuleNames, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - if (!token) { - return undefined; - } var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - if (!commentRanges || !commentRanges.length) { - return undefined; - } - var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { return undefined; } - var completionInfo = { - /** - * We don't want the editor to offer any other completions, such as snippets, inside a comment. - */ - isGlobalCompletion: false, - isMemberCompletion: false, - /** - * The user may type in a path that doesn't yet exist, creating a "new identifier" - * with respect to the collection of identifiers the server is aware of. - */ - isNewIdentifierLocation: true, - entries: [] - }; - var text = sourceFile.text.substr(range.pos, position - range.pos); + var text = sourceFile.text.slice(range.pos, position); var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - if (kind === "path") { + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + switch (kind) { + case "path": { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); + return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); } - else { + case "types": { // Give completions based on the typings available - var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + var span_11 = ts.createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); + return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } + default: + return undefined; } - return completionInfo; } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { @@ -76554,21 +79795,20 @@ var ts; else if (host.getDirectories) { var typeRoots = void 0; try { - // Wrap in try catch because getEffectiveTypeRoots touches the filesystem typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (e) { } + catch (_b) { } if (typeRoots) { - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; + for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { + var root = typeRoots_2[_c]; getCompletionEntriesFromDirectories(host, root, span, result); } } } if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories - for (var _c = 0, _d = findPackageJsons(scriptPath, host); _c < _d.length; _c++) { - var packageJson = _d[_c]; + for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { + var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); getCompletionEntriesFromDirectories(host, typesDir, span, result); } @@ -76579,32 +79819,23 @@ var ts; if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); } } } } - function findPackageJsons(currentDir, host) { + function findPackageJsons(directory, host) { var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent = ts.getDirectoryPath(currentDir); - if (currentDir === parent) { - break; - } - currentDir = parent; - } - else { - break; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out } - } + paths.push(currentConfigPath); + }); return paths; } function enumerateNodeModulesVisibleToScript(host, scriptPath) { @@ -76704,7 +79935,7 @@ var ts; try { return ts.directoryProbablyExists(path, host); } - catch (e) { } + catch (_a) { } return undefined; } function tryIOAndConsumeErrors(host, toApply) { @@ -76715,7 +79946,7 @@ var ts; try { return toApply && toApply.apply(host, args); } - catch (e) { } + catch (_a) { } return undefined; } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); @@ -76733,20 +79964,21 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries_2 && pathCompletionsInfo(entries_2); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { + location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: @@ -76761,23 +79993,25 @@ var ts; }] }; } if (request) { - var entries_2 = request.kind === "JsDocTagName" + var entries_3 = request.kind === "JsDocTagName" + // If the current position is a jsDoc tag name, only tag names should be provided for completion ? ts.JsDoc.getJSDocTagNameCompletions() : request.kind === "JsDocTag" + // If the current position is a jsDoc tag, only tags should be provided for completion ? ts.JsDoc.getJSDocTagCompletions() : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -76796,7 +80030,7 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName)) { + if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { return; } uniqueNames.set(realName, true); @@ -76811,11 +80045,11 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); if (!displayName) { return undefined; } @@ -76831,34 +80065,57 @@ var ts; kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(origin !== undefined), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && ts.stripQuotes(origin.moduleSymbol.name); + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); - var uniqueNames = ts.createMap(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); - if (entry) { - var id = entry.name; - if (!uniqueNames.has(id)) { - entries.push(entry); - uniqueNames.set(id, true); - } + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); + } + entries.push(entry); } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniqueNames; + return uniques; } function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { var node = ts.findPrecedingToken(position, sourceFile); if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 261 /* PropertyAssignment */ && - node.parent.parent.kind === 178 /* ObjectLiteralExpression */ && + if (node.parent.kind === 265 /* PropertyAssignment */ && + node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -76883,12 +80140,17 @@ var ts; // a['/*completion position*/'] return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); } - else if (node.parent.kind === 238 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ + || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) + || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); - return Completions.PathCompletions.getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker); + // export * from "/*completion position*/"; + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + return pathCompletionsInfo(entries); } else if (isEqualityExpression(node.parent)) { // Get completions from the type of the other operand @@ -76915,6 +80177,17 @@ var ts; return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); } } + function pathCompletionsInfo(entries) { + return { + // We don't want the editor to offer any other completions, such as snippets, inside a comment. + isGlobalCompletion: false, + isMemberCompletion: false, + // The user may type in a path that doesn't yet exist, creating a "new identifier" + // with respect to the collection of identifiers the server is aware of. + isNewIdentifierLocation: true, + entries: entries, + }; + } function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; @@ -76962,13 +80235,13 @@ var ts; } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } - if (type && type.flags & 16384 /* TypeParameter */) { + if (type && type.flags & 32768 /* TypeParameter */) { type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; } - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); @@ -76987,59 +80260,133 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; - // Find the symbol with the matching entry name. - // We don't need to perform character checks here because we're only comparing the - // name against 'entryName' (which is known to be good), not building a new - // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); - if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; - } - } - // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined - }; - } - return undefined; - } - Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { + var name = _a.name, source = _a.source; + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); if (!completionData) { - return undefined; + return { type: "none" }; + } + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; + if (request) { + return { type: "request", request: request }; } - var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); + var symbol = ts.find(symbols, function (s) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; + return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name + && getSourceFromOrigin(origin) === source; + }); + return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + } + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var name = entryId.name; + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case "JsDocTagName": + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case "JsDocTag": + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case "JsDocParameterName": + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); + var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; + } + case "none": { + // Didn't find a symbol with this name. See if we can find a keyword instead. + if (ts.some(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; })) { + return { + name: name, + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined, + tags: undefined, + codeActions: undefined, + source: undefined, + }; + } + return undefined; + } + } + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); + ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + formatContext: formatContext, + symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), + getCanonicalFileName: getCanonicalFileName, + symbolToken: undefined, + kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + }); + return { sourceDisplay: sourceDisplay, codeActions: codeActions }; + } + function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { + var result = []; + ts.codefix.forEachExternalModule(checker, allSourceFiles, function (module) { + for (var _i = 0, _a = checker.getExportsOfModule(module); _i < _a.length; _i++) { + var exported = _a[_i]; + if (ts.skipAlias(exported, checker) === exportedSymbol) { + result.push(module); + } + } + }); + return result; + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { + var completion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + function getRecommendedCompletion(currentToken, checker /*, symbolToOriginInfoMap: SymbolOriginInfoMap*/) { + var ty = checker.getContextualType(currentToken); + var symbol = ty && ty.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return isModuleSymbol(symbol.parent) ? symbol : symbol.parent && getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); + } + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 @@ -77088,11 +80435,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 284 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 289 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -77103,7 +80450,19 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { + symbols: ts.emptyArray, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0 /* None */, + symbolToOriginInfoMap: undefined, + recommendedCompletion: undefined, + }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -77141,11 +80500,11 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 179 /* PropertyAccessExpression */) { + if (parent.kind === 180 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent.kind === 143 /* QualifiedName */) { + else if (parent.kind === 144 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -77159,26 +80518,26 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 179 /* PropertyAccessExpression */) { + if (parent && parent.kind === 180 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } switch (parent.kind) { - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { // It has a left-hand side, so we're not in an opening JSX tag. break; } // falls through - case 250 /* JsxSelfClosingElement */: - case 249 /* JsxElement */: - case 251 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 250 /* JsxElement */: + case 252 /* JsxOpeningElement */: if (contextToken.kind === 27 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; @@ -77194,6 +80553,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -77226,15 +80586,15 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 277 /* JSDocAugmentsTag */: - case 279 /* JSDocParameterTag */: - case 284 /* JSDocPropertyTag */: - case 280 /* JSDocReturnTag */: - case 281 /* JSDocTypeTag */: - case 283 /* JSDocTypedefTag */: + case 284 /* JSDocParameterTag */: + case 289 /* JSDocPropertyTag */: + case 285 /* JSDocReturnTag */: + case 286 /* JSDocTypeTag */: + case 288 /* JSDocTypedefTag */: return true; } } @@ -77266,7 +80626,7 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 /* SourceFile */ && d.kind !== 233 /* ModuleDeclaration */ && d.kind !== 232 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 269 /* SourceFile */ && d.kind !== 234 /* ModuleDeclaration */ && d.kind !== 233 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -77278,23 +80638,21 @@ var ts; } } function addTypeProperties(type) { - // Filter private properties - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - } - if (isJavaScriptFile && type.flags & 65536 /* Union */) { + if (ts.isSourceFileJavaScript(sourceFile)) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part // of the individual types to a higher status since we know what they are. - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); + } + else { + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } } } } @@ -77327,7 +80685,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { + if ((jsxContainer.kind === 251 /* JsxSelfClosingElement */) || (jsxContainer.kind === 252 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { @@ -77375,17 +80733,22 @@ var ts; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; if (scopeNode) { isGlobalCompletion = - scopeNode.kind === 265 /* SourceFile */ || - scopeNode.kind === 196 /* TemplateExpression */ || - scopeNode.kind === 256 /* JsxExpression */ || + scopeNode.kind === 269 /* SourceFile */ || + scopeNode.kind === 197 /* TemplateExpression */ || + scopeNode.kind === 260 /* JsxExpression */ || + scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions ts.isStatement(scopeNode); } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + if (options.includeExternalModuleExports) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); + } + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -77413,22 +80776,22 @@ var ts; function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 /* TypeOfKeyword */ && - contextToken.parent.kind === 162 /* TypeQuery */; + contextToken.parent.kind === 163 /* TypeQuery */; } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 56 /* ColonToken */: - return parentKind === 149 /* PropertyDeclaration */ || - parentKind === 148 /* PropertySignature */ || - parentKind === 146 /* Parameter */ || - parentKind === 226 /* VariableDeclaration */ || + return parentKind === 150 /* PropertyDeclaration */ || + parentKind === 149 /* PropertySignature */ || + parentKind === 147 /* Parameter */ || + parentKind === 227 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 58 /* EqualsToken */: - return parentKind === 231 /* TypeAliasDeclaration */; + return parentKind === 232 /* TypeAliasDeclaration */; case 118 /* AsKeyword */: - return parentKind === 202 /* AsExpression */; + return parentKind === 203 /* AsExpression */; } } } @@ -77446,6 +80809,57 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + // Don't add a completion for a re-export, only for the original. + // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + continue; + } + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + else { + name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); + } + } + if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -77471,11 +80885,11 @@ var ts; return true; } if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 251 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 252 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 252 /* JsxClosingElement */ || contextToken.parent.kind === 250 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 249 /* JsxElement */; + if (contextToken.parent.kind === 253 /* JsxClosingElement */ || contextToken.parent.kind === 251 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 250 /* JsxElement */; } } return false; @@ -77485,40 +80899,40 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 26 /* CommaToken */: - return containingNodeKind === 181 /* CallExpression */ // func( a, | - || containingNodeKind === 152 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 182 /* NewExpression */ // new C(a, | - || containingNodeKind === 177 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 194 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 160 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 182 /* CallExpression */ // func( a, | + || containingNodeKind === 153 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 183 /* NewExpression */ // new C(a, | + || containingNodeKind === 178 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 195 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 161 /* FunctionType */; // var x: (s: string, list| case 19 /* OpenParenToken */: - return containingNodeKind === 181 /* CallExpression */ // func( | - || containingNodeKind === 152 /* Constructor */ // constructor( | - || containingNodeKind === 182 /* NewExpression */ // new C(a| - || containingNodeKind === 185 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 168 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 182 /* CallExpression */ // func( | + || containingNodeKind === 153 /* Constructor */ // constructor( | + || containingNodeKind === 183 /* NewExpression */ // new C(a| + || containingNodeKind === 186 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 169 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 21 /* OpenBracketToken */: - return containingNodeKind === 177 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 157 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 144 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 178 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 158 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 145 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 128 /* ModuleKeyword */: // module | case 129 /* NamespaceKeyword */:// namespace | return true; case 23 /* DotToken */: - return containingNodeKind === 233 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 234 /* ModuleDeclaration */; // module A.| case 17 /* OpenBraceToken */: - return containingNodeKind === 229 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 230 /* ClassDeclaration */; // class A{ | case 58 /* EqualsToken */: - return containingNodeKind === 226 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 194 /* BinaryExpression */; // x = a| + return containingNodeKind === 227 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 195 /* BinaryExpression */; // x = a| case 14 /* TemplateHead */: - return containingNodeKind === 196 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 197 /* TemplateExpression */; // `aa ${| case 15 /* TemplateMiddle */: - return containingNodeKind === 205 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 206 /* TemplateSpan */; // `aa ${10} dd ${| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 150 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -77562,18 +80976,18 @@ var ts; allowStringLiteral = true; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 174 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 175 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -77584,12 +80998,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 146 /* Parameter */) { + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 147 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 151 /* MethodDeclaration */ || rootDeclaration.parent.kind === 154 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 152 /* MethodDeclaration */ || rootDeclaration.parent.kind === 155 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -77624,9 +81038,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 241 /* NamedImports */ ? - 238 /* ImportDeclaration */ : - 244 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 242 /* NamedImports */ ? + 239 /* ImportDeclaration */ : + 245 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -77718,8 +81132,8 @@ var ts; case 17 /* OpenBraceToken */: // import { | case 26 /* CommaToken */:// import { a as 0, | switch (contextToken.parent.kind) { - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return contextToken.parent; } } @@ -77762,6 +81176,11 @@ var ts; if (ts.isClassLike(location)) { return location; } + // class c { method() { } b| } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -77772,7 +81191,7 @@ var ts; } } // class c { method() { } | method2() { } } - if (location && location.kind === 286 /* SyntaxList */ && ts.isClassLike(location.parent)) { + if (location && location.kind === 290 /* SyntaxList */ && ts.isClassLike(location.parent)) { return location.parent; } return undefined; @@ -77802,14 +81221,14 @@ var ts; case 28 /* LessThanSlashToken */: case 41 /* SlashToken */: case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 254 /* JsxAttributes */: - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 250 /* JsxSelfClosingElement */ || parent.kind === 251 /* JsxOpeningElement */)) { + case 180 /* PropertyAccessExpression */: + case 258 /* JsxAttributes */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 251 /* JsxSelfClosingElement */ || parent.kind === 252 /* JsxOpeningElement */)) { return parent; } - else if (parent.kind === 253 /* JsxAttribute */) { + else if (parent.kind === 257 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77821,7 +81240,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent && ((parent.kind === 253 /* JsxAttribute */) || (parent.kind === 255 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 257 /* JsxAttribute */) || (parent.kind === 259 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77831,8 +81250,8 @@ var ts; break; case 18 /* CloseBraceToken */: if (parent && - parent.kind === 256 /* JsxExpression */ && - parent.parent && parent.parent.kind === 253 /* JsxAttribute */) { + parent.kind === 260 /* JsxExpression */ && + parent.parent && parent.parent.kind === 257 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77840,7 +81259,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 255 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 259 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77859,57 +81278,57 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 26 /* CommaToken */: - return containingNodeKind === 226 /* VariableDeclaration */ || - containingNodeKind === 227 /* VariableDeclarationList */ || - containingNodeKind === 208 /* VariableStatement */ || - containingNodeKind === 232 /* EnumDeclaration */ || // enum a { foo, | + return containingNodeKind === 227 /* VariableDeclaration */ || + containingNodeKind === 228 /* VariableDeclarationList */ || + containingNodeKind === 209 /* VariableStatement */ || + containingNodeKind === 233 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 230 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 23 /* DotToken */: - return containingNodeKind === 175 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 176 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: - return containingNodeKind === 176 /* BindingElement */; // var {x :html| + return containingNodeKind === 177 /* BindingElement */; // var {x :html| case 21 /* OpenBracketToken */: - return containingNodeKind === 175 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 176 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: - return containingNodeKind === 260 /* CatchClause */ || + return containingNodeKind === 264 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 232 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 230 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 163 /* TypeLiteral */; // const x : { | + return containingNodeKind === 233 /* EnumDeclaration */ || // enum a { | + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface a { | + containingNodeKind === 164 /* TypeLiteral */; // const x : { | case 25 /* SemicolonToken */: - return containingNodeKind === 148 /* PropertySignature */ && + return containingNodeKind === 149 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 230 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 163 /* TypeLiteral */); // const x : { a; | + (contextToken.parent.parent.kind === 231 /* InterfaceDeclaration */ || // interface a { f; | + contextToken.parent.parent.kind === 164 /* TypeLiteral */); // const x : { a; | case 27 /* LessThanToken */: - return containingNodeKind === 229 /* ClassDeclaration */ || // class A< | - containingNodeKind === 199 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 230 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 231 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 230 /* ClassDeclaration */ || // class A< | + containingNodeKind === 200 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 232 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 150 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: - return containingNodeKind === 146 /* Parameter */ || + return containingNodeKind === 147 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 175 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 176 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 146 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 147 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118 /* AsKeyword */: - return containingNodeKind === 242 /* ImportSpecifier */ || - containingNodeKind === 246 /* ExportSpecifier */ || - containingNodeKind === 240 /* NamespaceImport */; + return containingNodeKind === 243 /* ImportSpecifier */ || + containingNodeKind === 247 /* ExportSpecifier */ || + containingNodeKind === 241 /* NamespaceImport */; case 125 /* GetKeyword */: case 135 /* SetKeyword */: if (isFromClassElementDeclaration(contextToken)) { @@ -77967,7 +81386,7 @@ var ts; return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 152 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -78015,12 +81434,12 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 261 /* PropertyAssignment */ && - m.kind !== 262 /* ShorthandPropertyAssignment */ && - m.kind !== 176 /* BindingElement */ && - m.kind !== 151 /* MethodDeclaration */ && - m.kind !== 153 /* GetAccessor */ && - m.kind !== 154 /* SetAccessor */) { + if (m.kind !== 265 /* PropertyAssignment */ && + m.kind !== 266 /* ShorthandPropertyAssignment */ && + m.kind !== 177 /* BindingElement */ && + m.kind !== 152 /* MethodDeclaration */ && + m.kind !== 154 /* GetAccessor */ && + m.kind !== 155 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -78028,7 +81447,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 176 /* BindingElement */ && m.propertyName) { + if (m.kind === 177 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -78055,10 +81474,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 149 /* PropertyDeclaration */ && - m.kind !== 151 /* MethodDeclaration */ && - m.kind !== 153 /* GetAccessor */ && - m.kind !== 154 /* SetAccessor */) { + if (m.kind !== 150 /* PropertyDeclaration */ && + m.kind !== 152 /* MethodDeclaration */ && + m.kind !== 154 /* GetAccessor */ && + m.kind !== 155 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -78113,7 +81532,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 253 /* JsxAttribute */) { + if (attr.kind === 257 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -78128,19 +81547,30 @@ var ts; * * @return undefined if the name is of external module */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { - var name = symbol.name; + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + var name = getSymbolName(symbol, origin, target); if (!name) return undefined; // First check of the displayName is not external module; if it is an external module, it is not valid entry if (symbol.flags & 1920 /* Namespace */) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } + // If the symbol is for a member of an object type and is the internal name of an ES + // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + if (symbol.flags & 106500 /* ClassMember */) { + var escapedName = symbol.escapedName; + if (escapedName.length >= 3 && + escapedName.charCodeAt(0) === 95 /* _ */ && + escapedName.charCodeAt(1) === 95 /* _ */ && + escapedName.charCodeAt(2) === 64 /* at */) { + return undefined; + } + } return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } /** @@ -78178,7 +81608,10 @@ var ts; } function getAllKeywordCompletions() { var allKeywordsCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 142 /* LastKeyword */; i++) { + for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { + // "undefined" is a global variable, so don't need a keyword completion for it. + if (i === 139 /* UndefinedKeyword */) + continue; allKeywordsCompletions.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -78266,13 +81699,15 @@ var ts; * tries to only include those types which declare properties, not methods. * This ensures that we don't try providing completions for all the methods on e.g. Array. */ - function getPropertiesForCompletion(type, checker) { - if (!(type.flags & 65536 /* Union */)) { - return checker.getPropertiesOfType(type); + function getPropertiesForCompletion(type, checker, isForAccess) { + if (!(type.flags & 131072 /* Union */)) { + return type.getApparentProperties(); } var types = type.types; - var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 /* Primitive */ || checker.isArrayLikeType(memberType)); }); - // If there are no property-only types, just provide completions for every type as usual. + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + var filteredTypes = isForAccess ? types : types.filter(function (memberType) { + return !(memberType.flags & 16382 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); + }); return checker.getAllPossiblePropertiesOfTypes(filteredTypes); } })(Completions = ts.Completions || (ts.Completions = {})); @@ -78334,89 +81769,44 @@ var ts; } return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - // returns true if 'node' is defined and has a matching 'kind'. - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - // Null-propagating 'parent' function. - function parent(node) { - return node && node.parent; - } function getHighlightSpans(node, sourceFile) { - if (!node) { - return undefined; - } switch (node.kind) { case 90 /* IfKeyword */: case 82 /* ElseKeyword */: - if (hasKind(node.parent, 211 /* IfStatement */)) { - return getIfElseOccurrences(node.parent, sourceFile); - } - break; + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; case 96 /* ReturnKeyword */: - if (hasKind(node.parent, 219 /* ReturnStatement */)) { - return highlightSpans(getReturnOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); case 100 /* ThrowKeyword */: - if (hasKind(node.parent, 223 /* ThrowStatement */)) { - return highlightSpans(getThrowOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); case 102 /* TryKeyword */: case 74 /* CatchKeyword */: case 87 /* FinallyKeyword */: - var tryStatement = node.kind === 74 /* CatchKeyword */ ? parent(parent(node)) : parent(node); - if (hasKind(tryStatement, 224 /* TryStatement */)) { - return highlightSpans(getTryCatchFinallyOccurrences(tryStatement, sourceFile)); - } - break; + var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); case 98 /* SwitchKeyword */: - if (hasKind(node.parent, 221 /* SwitchStatement */)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 73 /* CaseKeyword */: case 79 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 221 /* SwitchStatement */)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent.parent.parent)); - } - break; + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 72 /* BreakKeyword */: case 77 /* ContinueKeyword */: - if (hasKind(node.parent, 218 /* BreakStatement */) || hasKind(node.parent, 217 /* ContinueStatement */)) { - return highlightSpans(getBreakOrContinueStatementOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); case 88 /* ForKeyword */: - if (hasKind(node.parent, 214 /* ForStatement */) || - hasKind(node.parent, 215 /* ForInStatement */) || - hasKind(node.parent, 216 /* ForOfStatement */)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; case 106 /* WhileKeyword */: case 81 /* DoKeyword */: - if (hasKind(node.parent, 213 /* WhileStatement */) || hasKind(node.parent, 212 /* DoStatement */)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); case 123 /* ConstructorKeyword */: - if (hasKind(node.parent, 152 /* Constructor */)) { - return highlightSpans(getConstructorOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isConstructorDeclaration, getConstructorOccurrences); case 125 /* GetKeyword */: case 135 /* SetKeyword */: - if (hasKind(node.parent, 153 /* GetAccessor */) || hasKind(node.parent, 154 /* SetAccessor */)) { - return highlightSpans(getGetAndSetOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isAccessor, getGetAndSetOccurrences); default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 208 /* VariableStatement */)) { - return highlightSpans(getModifierOccurrences(node.kind, node.parent)); - } + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; } function highlightSpans(nodes) { return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); @@ -78431,21 +81821,20 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 223 /* ThrowStatement */) { + if (ts.isThrowStatement(node)) { statementAccumulator.push(node); } - else if (node.kind === 224 /* TryStatement */) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); + else if (ts.isTryStatement(node)) { + if (node.catchClause) { + aggregate(node.catchClause); } else { // Exceptions thrown within a try block lacking a catch clause // are "owned" in the current context. - aggregate(tryStatement.tryBlock); + aggregate(node.tryBlock); } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); + if (node.finallyBlock) { + aggregate(node.finallyBlock); } } else if (!ts.isFunctionLike(node)) { @@ -78461,19 +81850,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_2 = child.parent; - if (ts.isFunctionBlock(parent_2) || parent_2.kind === 265 /* SourceFile */) { - return parent_2; + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 269 /* SourceFile */) { + return parent; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_2.kind === 224 /* TryStatement */) { - var tryStatement = parent_2; + if (parent.kind === 225 /* TryStatement */) { + var tryStatement = parent; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_2; + child = parent; } return undefined; } @@ -78482,7 +81871,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 218 /* BreakStatement */ || node.kind === 217 /* ContinueStatement */) { + if (node.kind === 219 /* BreakStatement */ || node.kind === 218 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -78495,123 +81884,100 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node = statement.parent; node; node = node.parent) { + return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 221 /* SwitchStatement */: - if (statement.kind === 217 /* ContinueStatement */) { - continue; + case 222 /* SwitchStatement */: + if (statement.kind === 218 /* ContinueStatement */) { + return false; } // falls through - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: - if (!statement.label || isLabeledBy(node, statement.label.text)) { - return node; - } - break; + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.text); default: // Don't cross function boundaries. - if (ts.isFunctionLike(node)) { - return undefined; - } - break; + // TODO: GH#20090 + return (ts.isFunctionLike(node) && "quit"); } - } - return undefined; + }); } function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 229 /* ClassDeclaration */ || - container.kind === 199 /* ClassExpression */ || - (declaration.kind === 146 /* Parameter */ && hasKind(container, 152 /* Constructor */)))) { - return undefined; - } - } - else if (modifier === 115 /* StaticKeyword */) { - if (!(container.kind === 229 /* ClassDeclaration */ || container.kind === 199 /* ClassExpression */)) { - return undefined; - } - } - else if (modifier === 84 /* ExportKeyword */ || modifier === 124 /* DeclareKeyword */) { - if (!(container.kind === 234 /* ModuleBlock */ || container.kind === 265 /* SourceFile */)) { - return undefined; - } - } - else if (modifier === 117 /* AbstractKeyword */) { - if (!(container.kind === 229 /* ClassDeclaration */ || declaration.kind === 229 /* ClassDeclaration */)) { - return undefined; - } - } - else { - // unsupported modifier + if (!isLegalModifier(modifier, declaration)) { return undefined; } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; + var modifierFlag = ts.modifierToFlag(modifier); + return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { + if (ts.getModifierFlags(node) & modifierFlag) { + var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); + ts.Debug.assert(!!mod); + return mod; + } + }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + var container = declaration.parent; switch (container.kind) { - case 234 /* ModuleBlock */: - case 265 /* SourceFile */: + case 235 /* ModuleBlock */: + case 269 /* SourceFile */: + case 208 /* Block */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { - nodes = declaration.members.concat([declaration]); + return declaration.members.concat([declaration]); } else { - nodes = container.statements; + return container.statements; } - break; - case 152 /* Constructor */: - nodes = container.parameters.concat(container.parent.members); - break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - nodes = container.members; + case 153 /* Constructor */: + return container.parameters.concat(container.parent.members); + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. if (modifierFlag & 28 /* AccessibilityModifier */) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 152 /* Constructor */ && member; - }); + var constructor = ts.find(container.members, ts.isConstructorDeclaration); if (constructor) { - nodes = nodes.concat(constructor.parameters); + return nodes.concat(constructor.parameters); } } else if (modifierFlag & 128 /* Abstract */) { - nodes = nodes.concat([container]); + return nodes.concat([container]); } - break; + return nodes; default: ts.Debug.fail("Invalid container kind."); } - ts.forEach(nodes, function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return keywords; - function getFlagFromModifier(modifier) { - switch (modifier) { - case 114 /* PublicKeyword */: - return 4 /* Public */; - case 112 /* PrivateKeyword */: - return 8 /* Private */; - case 113 /* ProtectedKeyword */: - return 16 /* Protected */; - case 115 /* StaticKeyword */: - return 32 /* Static */; - case 84 /* ExportKeyword */: - return 1 /* Export */; - case 124 /* DeclareKeyword */: - return 2 /* Ambient */; - case 117 /* AbstractKeyword */: - return 128 /* Abstract */; - default: - ts.Debug.fail(); - } + } + function isLegalModifier(modifier, declaration) { + var container = declaration.parent; + switch (modifier) { + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + switch (container.kind) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + return true; + case 153 /* Constructor */: + return declaration.kind === 147 /* Parameter */; + default: + return false; + } + case 115 /* StaticKeyword */: + return container.kind === 230 /* ClassDeclaration */ || container.kind === 200 /* ClassExpression */; + case 84 /* ExportKeyword */: + case 124 /* DeclareKeyword */: + return container.kind === 235 /* ModuleBlock */ || container.kind === 269 /* SourceFile */; + case 117 /* AbstractKeyword */: + return container.kind === 230 /* ClassDeclaration */ || declaration.kind === 230 /* ClassDeclaration */; + default: + return false; } } function pushKeywordIf(keywordList, token) { @@ -78627,8 +81993,8 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 153 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 154 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 154 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 155 /* SetAccessor */); return keywords; function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); @@ -78651,7 +82017,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 212 /* DoStatement */) { + if (loopNode.kind === 213 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { @@ -78672,13 +82038,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -78731,12 +82097,11 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 207 /* Block */))) { + if (!func) { return undefined; } var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { pushKeywordIf(keywords, returnStatement.getFirstToken(), 96 /* ReturnKeyword */); }); // Include 'throw' statements that do not occur within a try block. @@ -78746,26 +82111,7 @@ var ts; return keywords; } function getIfElseOccurrences(ifStatement, sourceFile) { - var keywords = []; - // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 211 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); - // Generally the 'else' keyword is second-to-last, so we traverse backwards. - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 211 /* IfStatement */)) { - break; - } - ifStatement = ifStatement.elseStatement; - } + var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). @@ -78773,15 +82119,15 @@ var ts; if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. - var shouldCombindElseAndIf = true; + var shouldCombineElseAndIf = true; // Avoid recalculating getStart() by iterating backwards. - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; + shouldCombineElseAndIf = false; break; } } - if (shouldCombindElseAndIf) { + if (shouldCombineElseAndIf) { result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), @@ -78796,12 +82142,35 @@ var ts; } return result; } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } /** * Whether or not a 'node' is preceded by a label of the given string. * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 222 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 223 /* LabeledStatement */; owner = owner.parent) { if (owner.label.escapedText === labelName) { return true; } @@ -78983,10 +82352,10 @@ var ts; } cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 181 /* CallExpression */: + case 182 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 226 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 227 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 71 /* Identifier */) { directImports.push(name); @@ -78997,19 +82366,19 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); break; - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name); } else { directImports.push(direct); } break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -79030,7 +82399,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 265 /* SourceFile */ || sourceFileLike.kind === 233 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 269 /* SourceFile */ || sourceFileLike.kind === 234 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -79085,7 +82454,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 237 /* ImportEqualsDeclaration */) { + if (decl.kind === 238 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -79099,7 +82468,7 @@ var ts; if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { return; } - if (decl.kind === 244 /* ExportDeclaration */) { + if (decl.kind === 245 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } @@ -79108,7 +82477,7 @@ var ts; return; } var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImportLike(namedBindings.name); return; } @@ -79160,7 +82529,7 @@ var ts; } } else { - var localSymbol = element.kind === 246 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 247 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -79176,7 +82545,7 @@ var ts; function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 244 /* ExportDeclaration */) + if (statement.kind !== 245 /* ExportDeclaration */) return; var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; if (moduleSpecifier || !exportClause) @@ -79195,7 +82564,7 @@ var ts; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 265 /* SourceFile */) { + if (searchSourceFile.kind === 269 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -79242,7 +82611,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 265 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 269 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -79257,18 +82626,18 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 244 /* ExportDeclaration */: - case 238 /* ImportDeclaration */: { + case 245 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9 /* StringLiteral */) { action(decl, decl.moduleSpecifier); } break; } - case 237 /* ImportEqualsDeclaration */: { + case 238 /* ImportEqualsDeclaration */: { var decl = statement; var moduleReference = decl.moduleReference; - if (moduleReference.kind === 248 /* ExternalModuleReference */ && + if (moduleReference.kind === 249 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */) { action(decl, moduleReference.expression); } @@ -79281,11 +82650,11 @@ var ts; function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; switch (decl.kind) { - case 181 /* CallExpression */: - case 238 /* ImportDeclaration */: - case 244 /* ExportDeclaration */: + case 182 /* CallExpression */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return decl; - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return decl.parent; default: ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); @@ -79303,7 +82672,7 @@ var ts; function getExport() { var parent = node.parent; if (symbol.exportSymbol) { - if (parent.kind === 179 /* PropertyAccessExpression */) { + if (parent.kind === 180 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) @@ -79413,10 +82782,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 226 /* VariableDeclaration */) { + if (parent.kind === 227 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 260 /* CatchClause */ ? undefined : p.parent.parent.kind === 208 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 264 /* CatchClause */ ? undefined : p.parent.parent.kind === 209 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -79425,15 +82794,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return parent.propertyName ? undefined : { isNamedImport: true }; - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -79451,9 +82820,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.escapedText; }); @@ -79475,22 +82841,22 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 181 /* CallExpression */) { + if (node.kind === 182 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 265 /* SourceFile */) { + if (parent.kind === 269 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 234 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); + ts.Debug.assert(parent.kind === 235 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); return parent.parent; } function isAmbientModuleDeclaration(node) { - return node.kind === 233 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 234 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; } function isExternalModuleImportEquals(_a) { var moduleReference = _a.moduleReference; - return moduleReference.kind === 248 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; + return moduleReference.kind === 249 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -79530,16 +82896,16 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_5 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); - return result_5; + if (node.parent.kind === 266 /* ShorthandPropertyAssignment */) { + var result_4 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); + return result_4; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -79573,29 +82939,29 @@ var ts; var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_2 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var symbol = def.symbol, node_3 = def.node; + var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + var node_4 = def.node; + return { node: node_4, name: node_4.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { - var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var node_5 = def.node; + var name_6 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_6, kind: "keyword" /* keyword */, displayParts: [{ text: name_6, kind: "keyword" /* keyword */ }] }; } case "this": { - var node_5 = def.node; - var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + var node_6 = def.node; + var symbol = checker.getSymbolAtLocation(node_6); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts; + return { node: node_6, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { - var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + var node_7 = def.node; + return { node: node_7, name: node_7.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -79648,13 +83014,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, node, checker); } - else if (node.kind === 178 /* ObjectLiteralExpression */) { + else if (node.kind === 179 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } - else if (node.kind === 199 /* ClassExpression */) { + else if (node.kind === 200 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] @@ -79705,7 +83071,7 @@ var ts; /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return undefined; } if (!options.implementations) { @@ -79736,12 +83102,12 @@ var ts; return false; } switch (node.parent.kind) { - case 233 /* ModuleDeclaration */: - case 248 /* ExternalModuleReference */: - case 238 /* ImportDeclaration */: - case 244 /* ExportDeclaration */: + case 234 /* ModuleDeclaration */: + case 249 /* ExternalModuleReference */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return true; - case 181 /* CallExpression */: + case 182 /* CallExpression */: return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; @@ -79764,10 +83130,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: references.push({ type: "node", node: decl.name }); break; default: @@ -79812,19 +83178,25 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79 /* DefaultKeyword */) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -79892,7 +83264,7 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -79984,9 +83356,9 @@ var ts; checker.getPropertySymbolOfDestructuringAssignment(location); } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 177 /* BindingElement */); if (bindingElement && - bindingElement.parent.kind === 174 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 175 /* ObjectBindingPattern */ && !bindingElement.propertyName) { return bindingElement; } @@ -80016,7 +83388,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 186 /* FunctionExpression */ || valueDeclaration.kind === 199 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 187 /* FunctionExpression */ || valueDeclaration.kind === 200 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -80026,7 +83398,7 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 229 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 230 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -80055,7 +83427,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 269 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -80090,8 +83462,8 @@ var ts; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5 /* Latest */))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } @@ -80336,12 +83708,12 @@ var ts; for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 152 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 153 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 151 /* MethodDeclaration */) { + if (decl && decl.kind === 152 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { @@ -80362,7 +83734,7 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 152 /* Constructor */); + ts.Debug.assert(decl.kind === 153 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { @@ -80382,7 +83754,7 @@ var ts; if (refNode.kind !== 71 /* Identifier */) { return; } - if (refNode.parent.kind === 262 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 266 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -80401,7 +83773,7 @@ var ts; } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { var body = parent.body; - if (body.kind === 207 /* Block */) { + if (body.kind === 208 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); @@ -80424,7 +83796,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 196608 /* UnionOrIntersection */) { + if (componentType.getFlags() & 393216 /* UnionOrIntersection */) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -80442,12 +83814,12 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 201 /* ExpressionWithTypeArguments */ - && node.parent.kind === 259 /* HeritageClause */ + if (node.kind === 202 /* ExpressionWithTypeArguments */ + && node.parent.kind === 263 /* HeritageClause */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 71 /* Identifier */ || node.kind === 179 /* PropertyAccessExpression */) { + else if (node.kind === 71 /* Identifier */ || node.kind === 180 /* PropertyAccessExpression */) { return getContainingClassIfInHeritageClause(node.parent); } } @@ -80458,13 +83830,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 187 /* ArrowFunction */: - case 186 /* FunctionExpression */: - case 178 /* ObjectLiteralExpression */: - case 199 /* ClassExpression */: - case 177 /* ArrayLiteralExpression */: + case 188 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 179 /* ObjectLiteralExpression */: + case 200 /* ClassExpression */: + case 178 /* ArrayLiteralExpression */: return true; default: return false; @@ -80518,7 +83890,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 230 /* InterfaceDeclaration */) { + else if (declaration.kind === 231 /* InterfaceDeclaration */) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -80546,13 +83918,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -80583,27 +83955,27 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -80612,7 +83984,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 265 /* SourceFile */) { + if (searchSpaceNode.kind === 269 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); @@ -80636,28 +84008,28 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 265 /* SourceFile */: - if (container.kind === 265 /* SourceFile */ && !ts.isExternalModule(container)) { + case 269 /* SourceFile */: + if (container.kind === 269 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(FindAllReferences.nodeEntry(node)); } break; @@ -80680,9 +84052,9 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); - if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { - references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); + var node_8 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + if (node_8 && node_8.kind === 9 /* StringLiteral */ && node_8.text === searchText) { + references.push(FindAllReferences.nodeEntry(node_8, /*isInString*/ true)); } } } @@ -80697,7 +84069,7 @@ var ts; // If the location is name of property symbol from object literal destructuring pattern // Search the property symbol // for ( { property: p2 } of elems) { } - if (containingObjectLiteralElement.kind !== 262 /* ShorthandPropertyAssignment */) { + if (containingObjectLiteralElement.kind !== 266 /* ShorthandPropertyAssignment */) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); if (propertySymbol) { result.push(propertySymbol); @@ -80729,10 +84101,7 @@ var ts; // we should include both parameter declaration symbol and property declaration symbol // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 146 /* Parameter */ && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - ts.addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } + ts.addRange(result, getParameterPropertySymbols(symbol, checker)); // If this is symbol of binding element without propertyName declaration in Object binding pattern // Include the property in the search var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); @@ -80757,6 +84126,11 @@ var ts; } } } + function getParameterPropertySymbols(symbol, checker) { + return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isParameterPropertyDeclaration(symbol.valueDeclaration) + ? checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name) + : undefined; + } /** * Find symbol of the given property-name and add the symbol to the given result array * @param symbol a symbol to start searching for the given propertyName @@ -80789,7 +84163,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 230 /* InterfaceDeclaration */) { + else if (declaration.kind === 231 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -80811,16 +84185,24 @@ var ts; } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; if (search.includes(referenceSymbol)) { return referenceSymbol; } + if (referenceSymbol.flags & 1 /* FunctionScopedVariable */) { + ts.Debug.assert(!(referenceSymbol.flags & 4 /* Property */)); + var paramProps = getParameterPropertySymbols(referenceSymbol, checker); + if (paramProps) { + return getRelatedSymbol(search, ts.find(paramProps, function (x) { return !!(x.flags & 4 /* Property */); }), referenceLocation, state); + } + } // If the reference location is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this symbol to // compare to our searchSymbol var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, state.checker), function (contextualSymbol) { - return ts.find(state.checker.getRootSymbols(contextualSymbol), search.includes); + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { + return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); }); if (contextualSymbol) { return contextualSymbol; @@ -80829,7 +84211,7 @@ var ts; // Get the property symbol from the object literal's type and look if thats the search symbol // In below eg. get 'property' from type of elems iterating type // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, state.checker); + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, checker); if (propertySymbol && search.includes(propertySymbol)) { return propertySymbol; } @@ -80837,7 +84219,7 @@ var ts; // If the reference location is the binding element and doesn't have property name // then include the binding element in the related symbols // let { a } : { a }; - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, checker); if (bindingElementPropertySymbol) { var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); if (fromBindingElement) @@ -80869,7 +84251,7 @@ var ts; } } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { @@ -80885,20 +84267,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; + var result_5 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } - if (contextualType.flags & 65536 /* Union */) { + if (contextualType.flags & 131072 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -80939,7 +84321,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 226 /* VariableDeclaration */) { + else if (node.kind === 227 /* VariableDeclaration */) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } @@ -80949,18 +84331,18 @@ var ts; } else { switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 208 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 227 /* VariableDeclarationList */); + if (node.parent && node.parent.parent && node.parent.parent.kind === 209 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 228 /* VariableDeclarationList */); return node.parent.parent; } } @@ -81013,7 +84395,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== symbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 196608 /* UnionOrIntersection */) { + else if (localParentType.flags & 393216 /* UnionOrIntersection */) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -81078,7 +84460,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 266 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -81142,14 +84524,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_7 = []; + if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_7; + return result_6; } if (!type.symbol) { return undefined; @@ -81157,6 +84539,24 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (comment) { + return { + definitions: definitions, + textSpan: ts.createTextSpanFromBounds(comment.pos, comment.end) + }; + } + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; // Go to the original declaration for cases: // // (1) when the aliased symbol was declared in the location(parent). @@ -81170,11 +84570,11 @@ var ts; return true; } switch (declaration.kind) { - case 239 /* ImportClause */: - case 237 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 238 /* ImportEqualsDeclaration */: return true; - case 242 /* ImportSpecifier */: - return declaration.parent.kind === 241 /* NamedImports */; + case 243 /* ImportSpecifier */: + return declaration.parent.kind === 242 /* NamedImports */; default: return false; } @@ -81222,7 +84622,7 @@ var ts; var definition; for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 152 /* Constructor */ : isSignatureDeclaration(d)) { + if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { declarations.push(d); if (d.body) definition = d; @@ -81237,10 +84637,10 @@ var ts; } function isSignatureDeclaration(node) { switch (node.kind) { - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return true; default: return false; @@ -81320,6 +84720,7 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { + var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -81339,6 +84740,7 @@ var ts; "fileOverview", "function", "ignore", + "inheritDoc", "inner", "lends", "link", @@ -81390,14 +84792,36 @@ var ts; forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - if (tag.kind === 276 /* JSDocTag */) { - tags.push({ name: tag.tagName.text, text: tag.comment }); - } + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 282 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 287 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 286 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 288 /* JSDocTypedefTag */: + case 289 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return node.getText() + " " + comment; + } + function withList(list) { + return list.map(function (x) { return x.getText(); }) + " " + 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. @@ -81427,6 +84851,7 @@ var ts; })); } JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; function getJSDocTagCompletions() { return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -81438,6 +84863,18 @@ var ts; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; function getJSDocParameterNameCompletions(tag) { if (!ts.isIdentifier(tag.name)) { return ts.emptyArray; @@ -81459,16 +84896,24 @@ var ts; }); } JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. - * Valid positions are - * - outside of comments, statements, and expressions, and - * - preceding a: - * - function/constructor/method declaration - * - class declarations - * - variable statements - * - namespace declarations + * Invalid positions are + * - within comments, strings (including template literals and regex), and JSXText + * - within a token * * Hosts should ideally check that: * - The line is all whitespace up to 'position' before performing the insertion. @@ -81491,32 +84936,29 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - return undefined; + // if climbing the tree did not find a declaration with parameters, complete to a single line comment + return singleLineTemplate; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.getStart() < position) { + if (commentOwner.kind === 10 /* JsxText */) { return undefined; } + if (commentOwner.getStart() < position || parameters.length === 0) { + // if climbing the tree found a declaration with parameters but the request was made inside it + // or if there are no parameters, complete to a single line comment + return singleLineTemplate; + } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = ""; - if (parameters) { - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 /* Identifier */ ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; - } - } - } + var docParams = parameters.map(function (_a, i) { + var name = _a.name; + var nameText = ts.isIdentifier(name) ? name.text : "param" + i; + var type = isJavaScriptFile ? "{any} " : ""; + return indentationStr + " * @param " + type + nameText + newLine; + }).join(""); // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -81534,36 +84976,25 @@ var ts; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; function getCommentOwnerInfo(tokenAtPos) { - // TODO: add support for: - // - enums/enum members - // - interfaces - // - property declarations - // - potentially property assignments for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 151 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 229 /* ClassDeclaration */: - return { commentOwner: commentOwner }; - case 208 /* VariableStatement */: { + case 209 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return { commentOwner: commentOwner, parameters: parameters_1 }; + return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; } - case 265 /* SourceFile */: + case 269 /* SourceFile */: return undefined; - case 233 /* ModuleDeclaration */: - // If in walking up the tree, we hit a a nested namespace declaration, - // then we must be somewhere within a dotted namespace name; however we don't - // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 233 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 194 /* BinaryExpression */: { + case 195 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { return undefined; @@ -81571,6 +85002,10 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } + case 10 /* JsxText */: { + var parameters_3 = ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_3 }; + } } } } @@ -81583,17 +85018,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 185 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 186 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return rightHandSide.parameters; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152 /* Constructor */) { + if (member.kind === 153 /* Constructor */) { return member.parameters; } } @@ -81678,7 +85113,7 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); addInferredTypings(module, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed @@ -81741,7 +85176,7 @@ var ts; if (!ts.hasJavaScriptFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); }); if (fromFileNames.length) { @@ -81765,19 +85200,19 @@ var ts; return; } // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); if (log) log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); var packageNames = []; - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; var normalizedFileName = ts.normalizePath(fileName); var baseFileName = ts.getBaseFileName(normalizedFileName); if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_8.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -81805,6 +85240,66 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + throw ts.Debug.fail(); // Shouldn't have called this. + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ @@ -81815,7 +85310,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_8 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -81827,7 +85322,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_6(sourceFile); + _loop_8(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -81864,9 +85359,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 239 /* ImportClause */: - case 242 /* ImportSpecifier */: - case 237 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 243 /* ImportSpecifier */: + case 238 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -81893,7 +85388,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (name.kind === 144 /* ComputedPropertyName */) { + else if (name.kind === 145 /* ComputedPropertyName */) { return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); } else { @@ -81915,7 +85410,7 @@ var ts; } return true; } - if (expression.kind === 179 /* PropertyAccessExpression */) { + if (expression.kind === 180 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -81929,7 +85424,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } @@ -81958,12 +85453,8 @@ var ts; } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. - // Right now we just sort by kind first, and then by name of the item. - // We first sort case insensitively. So "Aaa" will come before "bar". - // Then we sort case sensitively, so "aaa" will come before "Aaa". - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -82114,7 +85605,7 @@ var ts; return; } switch (node.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -82126,21 +85617,21 @@ var ts; } } break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 151 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 239 /* ImportClause */: + case 240 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -82152,7 +85643,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings.kind === 241 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -82163,8 +85654,8 @@ var ts; } } break; - case 176 /* BindingElement */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 227 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -82185,12 +85676,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -82200,9 +85691,9 @@ var ts; } endNode(); break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -82210,22 +85701,39 @@ var ts; } endNode(); break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 246 /* ExportSpecifier */: - case 237 /* ImportEqualsDeclaration */: - case 157 /* IndexSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 231 /* TypeAliasDeclaration */: + case 247 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 158 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 232 /* TypeAliasDeclaration */: addLeafNode(node); break; + case 195 /* BinaryExpression */: { + var special = ts.getSpecialPropertyAssignmentKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + addNodeWithRecursiveChild(node, node.right); + break; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through default: if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283 /* JSDocTypedefTag */) { + if (tag.kind === 288 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -82267,57 +85775,58 @@ var ts; nameToItems.set(name, [itemWithSameName, child]); return true; } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { - merge(a, b); - return true; - } - return false; - } }); - /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - return a.kind === b.kind && (a.kind !== 233 /* ModuleDeclaration */ || areSameModule(a, b)); - // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. - // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! - function areSameModule(a, b) { - if (a.body.kind !== b.body.kind) { - return false; - } - if (a.body.kind !== 233 /* ModuleDeclaration */) { - return true; - } - return areSameModule(a.body, b.body); - } + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); + return true; } - /** Merge source into target. Source should be thrown away after this is called. */ - function merge(target, source) { - target.additionalNodes = target.additionalNodes || []; - target.additionalNodes.push(source.node); - if (source.additionalNodes) { - (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); - } - target.children = ts.concatenate(target.children, source.children); - if (target.children) { - mergeChildren(target.children); - sortChildren(target.children); - } - var _a; + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + if (a.kind !== b.kind) { + return false; + } + switch (a.kind) { + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 234 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; } } + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + return a.body.kind === b.body.kind && (a.body.kind !== 234 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + } + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { children.sort(compareChildren); } function compareChildren(child1, child2) { - var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); - if (name1 && name2) { - var cmp = ts.compareStringsCaseInsensitive(name1, name2); - return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); - } - else { - return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); - } + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** * This differs from getItemName because this is just used for sorting. @@ -82325,7 +85834,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 233 /* ModuleDeclaration */) { + if (node.kind === 234 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -82333,18 +85842,18 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 199 /* ClassExpression */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 200 /* ClassExpression */: return getFunctionOrClassName(node); - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 233 /* ModuleDeclaration */) { + if (node.kind === 234 /* ModuleDeclaration */) { return getModuleName(node); } var name = ts.getNameOfDeclaration(node); @@ -82355,16 +85864,16 @@ var ts; } } switch (node.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -82372,15 +85881,15 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return "constructor"; - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: return "new()"; - case 155 /* CallSignature */: + case 156 /* CallSignature */: return "()"; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return "[]"; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -82392,7 +85901,7 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 208 /* VariableStatement */) { + if (parentNode && parentNode.kind === 209 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; if (nameIdentifier.kind === 71 /* Identifier */) { @@ -82421,24 +85930,24 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 232 /* EnumDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 265 /* SourceFile */: - case 231 /* TypeAliasDeclaration */: - case 283 /* JSDocTypedefTag */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 232 /* TypeAliasDeclaration */: + case 288 /* JSDocTypedefTag */: return true; - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 226 /* VariableDeclaration */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 227 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -82448,10 +85957,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 234 /* ModuleBlock */: - case 265 /* SourceFile */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: + case 235 /* ModuleBlock */: + case 269 /* SourceFile */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -82460,7 +85969,7 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 226 /* VariableDeclaration */ && childKind !== 176 /* BindingElement */; + return childKind !== 227 /* VariableDeclaration */ && childKind !== 177 /* BindingElement */; }); } } @@ -82516,7 +86025,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 233 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 234 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -82527,18 +86036,18 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 233 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 234 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 144 /* ComputedPropertyName */; + return !member.name || member.name.kind === 145 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 265 /* SourceFile */ + return node.kind === 269 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 226 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 227 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -82547,14 +86056,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 226 /* VariableDeclaration */) { + else if (node.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } - else if (node.parent.kind === 194 /* BinaryExpression */ && + else if (node.parent.kind === 195 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 261 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 265 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512 /* Default */) { @@ -82566,9 +86075,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 187 /* ArrowFunction */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: return true; default: return false; @@ -82581,206 +86090,168 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { - var collapseText = "..."; - var maxDepth = 20; - var defaultLabel = "#region"; - var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { - var elements = []; - var depth = 0; + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + sourceFile.forEachChild(function walk(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + n.forEachChild(walk); + depthRemaining++; + }); + } + function addRegionOutliningSpans(sourceFile, out) { var regions = []; - walk(sourceFile); - gatherRegions(); - return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); - /** If useFullStart is true, then the collapsing span includes leading whitespace, including linebreaks. */ - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { - if (hintSpanNode && startElement && endElement) { - var span_13 = { - textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), - hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_13); + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?$/); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; + } + if (!result[1]) { + var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span_13, span_13, /*autoCollapse*/ false, result[2] || "#region")); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); + } } } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span_14 = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_14); - } - } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var currentComment = comments_3[_i]; - cancellationToken.throwIfCancellationRequested(); + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var _a = comments_3[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + cancellationToken.throwIfCancellationRequested(); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last - if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; - } - else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, /*autoCollapse*/ false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; } - } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); } } - function combineAndAddMultipleSingleLineComments(count, start, end) { + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments - if (count > 1) { - var multipleSingleLineComments = { - kind: 2 /* SingleLineCommentTrivia */, - pos: start, - end: end, - }; - addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); - } - } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 187 /* ArrowFunction */; - } - function gatherRegions() { - var lineStarts = sourceFile.getLineStarts(); - for (var i = 0; i < lineStarts.length; i++) { - var currentLineStart = lineStarts[i]; - var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); - var comment = sourceFile.text.substring(currentLineStart, lineEnd); - var result = comment.match(regionMatch); - if (result && !ts.isInComment(sourceFile, currentLineStart)) { - if (!result[1]) { - var start = sourceFile.getFullText().indexOf("//", currentLineStart); - var textSpan = ts.createTextSpanFromBounds(start, lineEnd); - var region = { - textSpan: textSpan, - hintSpan: textSpan, - bannerText: result[2] || defaultLabel, - autoCollapse: false - }; - regions.push(region); - } - else { - var region = regions.pop(); - if (region) { - region.textSpan.length = lineEnd - region.textSpan.start; - region.hintSpan.length = lineEnd - region.textSpan.start; - elements.push(region); + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + } + } + } + function createOutliningSpanFromBounds(pos, end) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 208 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 188 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 213 /* DoStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 212 /* IfStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 264 /* CatchClause */: + return spanForNode(n.parent); + case 225 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); } - } - } - } - } - function walk(n) { - cancellationToken.throwIfCancellationRequested(); - if (depth > maxDepth) { - return; - } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); - } - switch (n.kind) { - case 207 /* Block */: - if (!ts.isFunctionBlock(n)) { - var parent = n.parent; - var openBrace_1 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace_1 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - // Check if the block is standalone, or 'attached' to some parent statement. - // If the latter, we want to collapse the block, but consider its hint span - // to be the entire span of the parent. - if (parent.kind === 212 /* DoStatement */ || - parent.kind === 215 /* ForInStatement */ || - parent.kind === 216 /* ForOfStatement */ || - parent.kind === 214 /* ForStatement */ || - parent.kind === 211 /* IfStatement */ || - parent.kind === 213 /* WhileStatement */ || - parent.kind === 220 /* WithStatement */ || - parent.kind === 260 /* CatchClause */) { - addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); - break; - } - if (parent.kind === 224 /* TryStatement */) { - // Could be the try-block, or the finally-block. - var tryStatement = parent; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); - break; - } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); - break; - } - } - // fall through. + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); } + // falls through + default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - var span_15 = ts.createTextSpanFromNode(n); - elements.push({ - textSpan: span_15, - hintSpan: span_15, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); - break; - } - // falls through - case 234 /* ModuleBlock */: { - var openBrace_2 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace_2 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), /*useFullStart*/ true); - break; - } - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 235 /* CaseBlock */: { - var openBrace_3 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace_3 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), /*useFullStart*/ true); - break; - } - // If the block has no leading keywords and is inside an array literal, - // we only want to collapse the span of the block. - // Otherwise, the collapsed section will include the end of the previous line. - case 178 /* ObjectLiteralExpression */: - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); - break; - case 177 /* ArrayLiteralExpression */: - var openBracket = ts.findChildOfKind(n, 21 /* OpenBracketToken */, sourceFile); - var closeBracket = ts.findChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); - break; + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + } + case 235 /* ModuleBlock */: + return spanForNode(n.parent); + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 236 /* CaseBlock */: + return spanForNode(n); + case 179 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 178 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 17 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 17 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; } - depth++; - ts.forEachChild(n, walk); - depth--; + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - OutliningElementsCollector.collectElements = collectElements; + function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); /* @internal */ @@ -82895,10 +86366,10 @@ var ts; // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span_16 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_16, chunk.text, /*ignoreCase:*/ true)) { + var span_14 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_16, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false)); } } } @@ -83125,7 +86596,7 @@ var ts; if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -83138,7 +86609,7 @@ var ts; if (ch >= 97 /* a */ && ch <= 122 /* z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -83147,19 +86618,19 @@ var ts; return str === str.toLowerCase(); } // Assumes 'value' is already lowercase. - function indexOfIgnoringCase(string, value) { - var n = string.length - value.length; + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; for (var i = 0; i <= n; i++) { - if (startsWithIgnoringCase(string, value, i)) { + if (startsWithIgnoringCase(str, value, i)) { return i; } } return -1; } // Assumes 'value' is already lowercase. - function startsWithIgnoringCase(string, value, start) { + function startsWithIgnoringCase(str, value, start) { for (var i = 0; i < value.length; i++) { - var ch1 = toLowerCase(string.charCodeAt(i + start)); + var ch1 = toLowerCase(str.charCodeAt(i + start)); var ch2 = value.charCodeAt(i); if (ch1 !== ch2) { return false; @@ -83446,7 +86917,7 @@ var ts; else { if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import d from "mod"; @@ -83477,7 +86948,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import {a as A} from "mod"; @@ -83493,7 +86964,7 @@ var ts; token = nextToken(); if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import * as NS from "mod" @@ -83523,7 +86994,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export {a as A} from "mod"; @@ -83535,7 +87006,7 @@ var ts; } else if (token === 39 /* AsteriskToken */) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export * from "mod" @@ -83818,7 +87289,7 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 181 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 182 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -83826,7 +87297,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 71 /* Identifier */ ? expression - : expression.kind === 179 /* PropertyAccessExpression */ + : expression.kind === 180 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.escapedText) { @@ -83904,25 +87375,25 @@ var ts; var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 183 /* TaggedTemplateExpression */) { + else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 184 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 183 /* TaggedTemplateExpression */) { + else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 184 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 197 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 205 /* TemplateSpan */ && node.parent.parent.parent.kind === 183 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 206 /* TemplateSpan */ && node.parent.parent.parent.kind === 184 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 197 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -84059,7 +87530,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 196 /* TemplateExpression */) { + if (template.kind === 197 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -84068,7 +87539,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 265 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 269 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -84137,7 +87608,7 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(), + documentation: candidateSignature.getDocumentationComment(typeChecker), tags: candidateSignature.getJsDocTags() }; }); @@ -84153,7 +87624,7 @@ var ts; }); return { name: parameter.name, - documentation: parameter.getDocumentationComment(), + documentation: parameter.getDocumentationComment(typeChecker), displayParts: displayParts, isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) }; @@ -84181,7 +87652,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 199 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -84261,10 +87732,16 @@ var ts; } return unionPropertyKind; } - if (location.parent && ts.isJsxAttribute(location.parent)) { - return "JSX attribute" /* jsxAttribute */; + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 252 /* JsxOpeningElement */: + return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 257 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; } - return "property" /* memberVariableElement */; } return "" /* unknown */; } @@ -84293,7 +87770,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 180 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -84314,11 +87791,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - // Use the first candidate: - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 183 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -84355,13 +87828,14 @@ var ts; // If it is call or construct signature of lambda's write type name displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); + if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); - } addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); break; default: @@ -84372,7 +87846,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 153 /* Constructor */)) { // 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 @@ -84380,21 +87854,21 @@ var ts; return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 152 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 153 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 152 /* Constructor */) { + if (functionDeclaration_1.kind === 153 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 156 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -84403,7 +87877,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 199 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -84447,7 +87921,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 233 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -84468,23 +87942,23 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 145 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 146 /* TypeParameter */); ts.Debug.assert(decl !== undefined); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 156 /* ConstructSignature */) { + if (declaration.kind === 157 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 155 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 231 /* TypeAliasDeclaration */) { + else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -84501,7 +87975,7 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 264 /* EnumMember */) { + if (declaration.kind === 268 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -84513,18 +87987,24 @@ var ts; } if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + switch (symbol.declarations[0].kind) { + case 237 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); + break; + case 244 /* ExportAssignment */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 237 /* ImportEqualsDeclaration */) { + if (declaration.kind === 238 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -84595,23 +88075,23 @@ var ts; } } if (!documentation) { - documentation = symbol.getDocumentationComment(); + documentation = symbol.getDocumentationComment(typeChecker); tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbolFlags & 4 /* Property */) { // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 265 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 269 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 194 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 195 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); if (!rhsSymbol) { continue; } - documentation = rhsSymbol.getDocumentationComment(); + documentation = rhsSymbol.getDocumentationComment(typeChecker); tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; @@ -84639,8 +88119,10 @@ var ts; addNewLineIfDisplayPartsExist(); if (symbolKind) { pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); + if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } } } function pushTypePart(symbolKind) { @@ -84670,7 +88152,7 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(); + documentation = signature.getDocumentationComment(typeChecker); tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -84687,16 +88169,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 186 /* FunctionExpression */) { + if (declaration.kind === 187 /* FunctionExpression */) { return true; } - if (declaration.kind !== 226 /* VariableDeclaration */ && declaration.kind !== 228 /* FunctionDeclaration */) { + if (declaration.kind !== 227 /* VariableDeclaration */ && declaration.kind !== 229 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 265 /* SourceFile */ || parent.kind === 234 /* ModuleBlock */) { + if (parent.kind === 269 /* SourceFile */ || parent.kind === 235 /* ModuleBlock */) { return false; } } @@ -84808,13 +88290,13 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_7 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } var value = options[opt.name]; // Value should be a key of opt.type - if (typeof value === "string") { + if (ts.isString(value)) { // If value is not a string, this will fail options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } @@ -84827,12 +88309,102 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_7(opt); + _loop_9(opt); } return options; } ts.fixupCompilerOptions = fixupCompilerOptions; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); + ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); + ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); + ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); + ts.Debug.assert(commonParent !== undefined, "commonParent is null"); + this.currentTokenSpan = currentRange; + this.currentTokenParent = currentTokenParent; + this.nextTokenSpan = nextRange; + this.nextTokenParent = nextTokenParent; + this.contextNode = commonParent; + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -84840,8 +88412,8 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); - var jsxScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -84916,10 +88488,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 253 /* JsxAttribute */: - case 251 /* JsxOpeningElement */: - case 252 /* JsxClosingElement */: - case 250 /* JsxSelfClosingElement */: + case 257 /* JsxAttribute */: + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; } @@ -85069,129 +88641,12 @@ var ts; formatting.getFormattingScanner = getFormattingScanner; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var FormattingContext = /** @class */ (function () { - function FormattingContext(sourceFile, formattingRequestKind, options) { - this.sourceFile = sourceFile; - this.formattingRequestKind = formattingRequestKind; - this.options = options; - } - FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; - // drop cached results - this.contextNodeAllOnSameLine = undefined; - this.nextNodeAllOnSameLine = undefined; - this.tokensAreOnSameLine = undefined; - this.contextNodeBlockIsOnOneLine = undefined; - this.nextNodeBlockIsOnOneLine = undefined; - }; - FormattingContext.prototype.ContextNodeAllOnSameLine = function () { - if (this.contextNodeAllOnSameLine === undefined) { - this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); - } - return this.contextNodeAllOnSameLine; - }; - FormattingContext.prototype.NextNodeAllOnSameLine = function () { - if (this.nextNodeAllOnSameLine === undefined) { - this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); - } - return this.nextNodeAllOnSameLine; - }; - FormattingContext.prototype.TokensAreOnSameLine = function () { - if (this.tokensAreOnSameLine === undefined) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine === endLine); - } - return this.tokensAreOnSameLine; - }; - FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { - if (this.contextNodeBlockIsOnOneLine === undefined) { - this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); - } - return this.contextNodeBlockIsOnOneLine; - }; - FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { - if (this.nextNodeBlockIsOnOneLine === undefined) { - this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); - } - return this.nextNodeBlockIsOnOneLine; - }; - FormattingContext.prototype.NodeIsOnOneLine = function (node) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine === endLine; - }; - FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); - if (openBrace && closeBrace) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; - return startLine === endLine; - } - return false; - }; - return FormattingContext; - }()); - formatting.FormattingContext = FormattingContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var FormattingRequestKind; - (function (FormattingRequestKind) { - FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; - FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; - FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; - FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; - })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rule = /** @class */ (function () { - function Rule(Descriptor, Operation, Flag) { - if (Flag === void 0) { Flag = 0 /* None */; } - this.Descriptor = Descriptor; - this.Operation = Operation; - this.Flag = Flag; - } - return Rule; - }()); - formatting.Rule = Rule; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { + formatting.anyContext = ts.emptyArray; var RuleAction; (function (RuleAction) { RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; @@ -85199,46 +88654,6 @@ var ts; RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; RuleAction[RuleAction["Delete"] = 8] = "Delete"; })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleDescriptor = /** @class */ (function () { - function RuleDescriptor(LeftTokenRange, RightTokenRange) { - this.LeftTokenRange = LeftTokenRange; - this.RightTokenRange = RightTokenRange; - } - RuleDescriptor.prototype.toString = function () { - return "[leftRange=" + this.LeftTokenRange + "," + - "rightRange=" + this.RightTokenRange + "]"; - }; - RuleDescriptor.create1 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create2 = function (left, right) { - return RuleDescriptor.create4(left, formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create3 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), right); - }; - RuleDescriptor.create4 = function (left, right) { - return new RuleDescriptor(left, right); - }; - return RuleDescriptor; - }()); - formatting.RuleDescriptor = RuleDescriptor; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { var RuleFlags; (function (RuleFlags) { RuleFlags[RuleFlags["None"] = 0] = "None"; @@ -85246,971 +88661,691 @@ var ts; })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleOperation = /** @class */ (function () { - function RuleOperation(Context, Action) { - this.Context = Context; - this.Action = Action; - } - RuleOperation.prototype.toString = function () { - return "[context=" + this.Context + "," + - "action=" + this.Action + "]"; - }; - RuleOperation.create1 = function (action) { - return RuleOperation.create2(formatting.RuleOperationContext.Any, action); - }; - RuleOperation.create2 = function (context, action) { - return new RuleOperation(context, action); - }; - return RuleOperation; - }()); - formatting.RuleOperation = RuleOperation; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperationContext = /** @class */ (function () { - function RuleOperationContext() { - var funcs = []; - for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i] = arguments[_i]; - } - this.customContextChecks = funcs; + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { + allTokens.push(token); } - RuleOperationContext.prototype.IsAny = function () { - return this === RuleOperationContext.Any; - }; - RuleOperationContext.prototype.InContext = function (context) { - if (this.IsAny()) { - return true; - } - for (var _i = 0, _a = this.customContextChecks; _i < _a.length; _i++) { - var check = _a[_i]; - if (!check(context)) { - return false; - } - } - return true; - }; - RuleOperationContext.Any = new RuleOperationContext(); - return RuleOperationContext; - }()); - formatting.RuleOperationContext = RuleOperationContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rules = /** @class */ (function () { - function Rules() { - /// - /// Common Rules - /// + function anyTokenExcept(token) { + return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 143 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 143 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]; + var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; + var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; + var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ // Leave comments alone - this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); - this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); - // Space after keyword but not before ; or : or ? - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - // Space after }. - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* CloseBraceToken */, formatting.Shared.TokenRange.FromRange(0 /* FirstToken */, 142 /* LastToken */, [20 /* CloseParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); - // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseBraceToken */, 82 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseBraceToken */, 106 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // No space for dot - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // No space before and after indexer - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); - // Place a space before open brace in a function declaration - this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); - // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); - // Place a space before open brace in a control flow construct - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); - // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenBraceToken */, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); - // Insert new line after { and before } in multi-line contexts. - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); - // For functions and control block place } on a new line [multi-line rule] - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(44 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 43 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 44 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(43 /* PlusPlusToken */, 37 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* PlusToken */, 37 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* PlusToken */, 43 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(44 /* MinusMinusToken */, 38 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(38 /* MinusToken */, 38 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38 /* MinusToken */, 44 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* NewKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8 /* Delete */)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110 /* LetKeyword */, 76 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96 /* ReturnKeyword */, 25 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. - // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); - // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([102 /* TryKeyword */, 87 /* FinallyKeyword */]), 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* GetKeyword */, 135 /* SetKeyword */]), 71 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 135 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. - this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - // TypeScript-specific higher priority rules - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123 /* ConstructorKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123 /* ConstructorKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // template string + rule("NoSpaceBetweenTagAndTemplateString", 71 /* Identifier */, [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128 /* ModuleKeyword */, 132 /* RequireKeyword */]), 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("NoSpaceAfterModuleImport", [128 /* ModuleKeyword */, 132 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117 /* AbstractKeyword */, 75 /* ClassKeyword */, 124 /* DeclareKeyword */, 79 /* DefaultKeyword */, 83 /* EnumKeyword */, 84 /* ExportKeyword */, 85 /* ExtendsKeyword */, 125 /* GetKeyword */, 108 /* ImplementsKeyword */, 91 /* ImportKeyword */, 109 /* InterfaceKeyword */, 128 /* ModuleKeyword */, 129 /* NamespaceKeyword */, 112 /* PrivateKeyword */, 114 /* PublicKeyword */, 113 /* ProtectedKeyword */, 131 /* ReadonlyKeyword */, 135 /* SetKeyword */, 115 /* StaticKeyword */, 138 /* TypeKeyword */, 140 /* FromKeyword */, 127 /* KeyOfKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 140 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceAfterCertainTypeScriptKeywords", [ + 117 /* AbstractKeyword */, + 75 /* ClassKeyword */, + 124 /* DeclareKeyword */, + 79 /* DefaultKeyword */, + 83 /* EnumKeyword */, + 84 /* ExportKeyword */, + 85 /* ExtendsKeyword */, + 125 /* GetKeyword */, + 108 /* ImplementsKeyword */, + 91 /* ImportKeyword */, + 109 /* InterfaceKeyword */, + 128 /* ModuleKeyword */, + 129 /* NamespaceKeyword */, + 112 /* PrivateKeyword */, + 114 /* PublicKeyword */, + 113 /* ProtectedKeyword */, + 131 /* ReadonlyKeyword */, + 135 /* SetKeyword */, + 115 /* StaticKeyword */, + 138 /* TypeKeyword */, + 141 /* FromKeyword */, + 127 /* KeyOfKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 141 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); + rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 36 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(36 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Optional parameters and let args - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(24 /* DotDotDotToken */, 71 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 26 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - // generics and type assertions - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 27 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(20 /* CloseParenToken */, 27 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 29 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(29 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // Remove spaces in empty interface literals. e.g.: x: {} - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenBraceToken */, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), // decorators - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(57 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([117 /* AbstractKeyword */, 71 /* Identifier */, 84 /* ExportKeyword */, 79 /* DefaultKeyword */, 75 /* ClassKeyword */, 115 /* StaticKeyword */, 114 /* PublicKeyword */, 112 /* PrivateKeyword */, 113 /* ProtectedKeyword */, 125 /* GetKeyword */, 135 /* SetKeyword */, 21 /* OpenBracketToken */, 39 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(89 /* FunctionKeyword */, 39 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(39 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(116 /* YieldKeyword */, 39 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116 /* YieldKeyword */, 39 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); - // Async-await - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(120 /* AsyncKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(120 /* AsyncKeyword */, 89 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - // template string - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(71 /* Identifier */, formatting.Shared.TokenRange.FromTokens([13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // jsx opening element - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 71 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 41 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* SlashToken */, 29 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // No space before non-null assertion operator - this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51 /* ExclamationToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8 /* Delete */)); - /// - /// Rules controlled by user options - /// - // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); - // Insert space before and after binary operators - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + rule("SpaceBeforeAt", anyToken, 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 117 /* AbstractKeyword */, + 71 /* Identifier */, + 84 /* ExportKeyword */, + 79 /* DefaultKeyword */, + 75 /* ClassKeyword */, + 115 /* StaticKeyword */, + 114 /* PublicKeyword */, + 112 /* PrivateKeyword */, + 113 /* ProtectedKeyword */, + 125 /* GetKeyword */, + 135 /* SetKeyword */, + 21 /* OpenBracketToken */, + 39 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), // Insert space after keywords in control flow statements - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2 /* Space */)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8 /* Delete */)); - // Open Brace braces after function - // TypeScript: Function can have return types, which can be made of tons of different token kinds - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); - // Open Brace braces after TypeScript module/class/interface - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); - // Open Brace braces after control block - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); - // Insert space after semicolon in for statement - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), // Insert space after opening and before closing nonempty parenthesis - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing nonempty brackets - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21 /* OpenBracketToken */, 22 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing template string braces - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14 /* TemplateHead */, 15 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14 /* TemplateHead */, 15 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15 /* TemplateMiddle */, 16 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15 /* TemplateMiddle */, 16 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - // Insert space after function keyword for anonymous functions - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89 /* FunctionKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89 /* FunctionKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8 /* Delete */)); - // No space after type assertion - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); - // These rules are higher in priority than user-configurable rules. - this.HighPriorityCommonRules = [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, - // TypeScript-specific rules - this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceBeforeArrow, this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator, - this.NoSpaceAfterNewKeywordOnConstructorSignature - ]; - // These rules are applied after high priority rules. - this.UserConfigurableRules = [ - this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, - this.SpaceAfterComma, this.NoSpaceAfterComma, - this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, - this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, - this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, - this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, - this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, - this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, - this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, - this.NewLineBeforeOpenBraceInControl, - this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, - this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion - ]; - // These rules are lower in priority than user-configurable rules. - this.LowPriorityCommonRules = [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; - if (ts.Debug.isDebugging) { - var o = this; - for (var name in o) { - var rule = o[name]; - if (rule instanceof formatting.Rule) { - rule.debugName = name; - } - } + rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); } } - /// - /// Contexts - /// - Rules.IsOptionEnabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; - }; - Rules.IsOptionDisabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; - }; - Rules.IsOptionDisabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; - }; - Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; - }; - Rules.IsOptionEnabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; - }; - Rules.IsForContext = function (context) { - return context.contextNode.kind === 214 /* ForStatement */; - }; - Rules.IsNotForContext = function (context) { - return !Rules.IsForContext(context); - }; - Rules.IsBinaryOpContext = function (context) { - switch (context.contextNode.kind) { - case 194 /* BinaryExpression */: - case 195 /* ConditionalExpression */: - case 202 /* AsExpression */: - case 246 /* ExportSpecifier */: - case 242 /* ImportSpecifier */: - case 158 /* TypePredicate */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - return true; - // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 176 /* BindingElement */: - // equals in type X = ... - case 231 /* TypeAliasDeclaration */: - // equal in import a = module('a'); - case 237 /* ImportEqualsDeclaration */: - // equal in let a = 0; - case 226 /* VariableDeclaration */: - // equal in p = 0; - case 146 /* Parameter */: - case 264 /* EnumMember */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; - // "in" keyword in for (let x in []) { } - case 215 /* ForInStatement */: - // "in" keyword in [P in keyof T]: T[P] - case 145 /* TypeParameter */: - return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; - // Technically, "of" is not a binary operator, but format it the same way as "in" - case 216 /* ForOfStatement */: - return context.currentTokenSpan.kind === 142 /* OfKeyword */ || context.nextTokenSpan.kind === 142 /* OfKeyword */; - } - return false; - }; - Rules.IsNotBinaryOpContext = function (context) { - return !Rules.IsBinaryOpContext(context); - }; - Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 195 /* ConditionalExpression */; - }; - Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { - return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); - }; - Rules.IsBraceWrappedContext = function (context) { - return context.contextNode.kind === 174 /* ObjectBindingPattern */ || Rules.IsSingleLineBlockContext(context); - }; - // This check is done before an open brace in a control construct, a function, or a typescript block declaration - Rules.IsBeforeMultilineBlockContext = function (context) { - return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); - }; - Rules.IsMultilineBlockContext = function (context) { - return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsSingleLineBlockContext = function (context) { - return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.contextNode); - }; - Rules.IsBeforeBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.nextTokenParent); - }; - // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children - Rules.NodeIsBlockContext = function (node) { - if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) { - // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 215 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 195 /* BinaryExpression */: + case 196 /* ConditionalExpression */: + case 203 /* AsExpression */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 159 /* TypePredicate */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return true; - } - switch (node.kind) { - case 207 /* Block */: - case 235 /* CaseBlock */: - case 178 /* ObjectLiteralExpression */: - case 234 /* ModuleBlock */: - return true; - } - return false; - }; - Rules.IsFunctionDeclContext = function (context) { - switch (context.contextNode.kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - // case SyntaxKind.MemberFunctionDeclaration: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - // case SyntaxKind.MethodSignature: - case 155 /* CallSignature */: - case 186 /* FunctionExpression */: - case 152 /* Constructor */: - case 187 /* ArrowFunction */: - // case SyntaxKind.ConstructorDeclaration: - // case SyntaxKind.SimpleArrowFunctionExpression: - // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 230 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one - return true; - } - return false; - }; - Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 228 /* FunctionDeclaration */ || context.contextNode.kind === 186 /* FunctionExpression */; - }; - Rules.IsTypeScriptDeclWithBlockContext = function (context) { - return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); - }; - Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { - switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 163 /* TypeLiteral */: - case 233 /* ModuleDeclaration */: - case 244 /* ExportDeclaration */: - case 245 /* NamedExports */: - case 238 /* ImportDeclaration */: - case 241 /* NamedImports */: - return true; - } - return false; - }; - Rules.IsAfterCodeBlockContext = function (context) { - switch (context.currentTokenParent.kind) { - case 229 /* ClassDeclaration */: - case 233 /* ModuleDeclaration */: - case 232 /* EnumDeclaration */: - case 260 /* CatchClause */: - case 234 /* ModuleBlock */: - case 221 /* SwitchStatement */: + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 177 /* BindingElement */: + // equals in type X = ... + case 232 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 238 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 227 /* VariableDeclaration */: + // equal in p = 0; + case 147 /* Parameter */: + case 268 /* EnumMember */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 216 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 146 /* TypeParameter */: + return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 217 /* ForOfStatement */: + return context.currentTokenSpan.kind === 143 /* OfKeyword */ || context.nextTokenSpan.kind === 143 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 196 /* ConditionalExpression */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 175 /* ObjectBindingPattern */ || isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 208 /* Block */: + case 236 /* CaseBlock */: + case 179 /* ObjectLiteralExpression */: + case 235 /* ModuleBlock */: + return true; + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 156 /* CallSignature */: + case 187 /* FunctionExpression */: + case 153 /* Constructor */: + case 188 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 231 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 229 /* FunctionDeclaration */ || context.contextNode.kind === 187 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 164 /* TypeLiteral */: + case 234 /* ModuleDeclaration */: + case 245 /* ExportDeclaration */: + case 246 /* NamedExports */: + case 239 /* ImportDeclaration */: + case 242 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 230 /* ClassDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 264 /* CatchClause */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + return true; + case 208 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 188 /* ArrowFunction */ && blockParent.kind !== 187 /* FunctionExpression */) { return true; - case 207 /* Block */: { - var blockParent = context.currentTokenParent.parent; - // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 187 /* ArrowFunction */ && blockParent.kind !== 186 /* FunctionExpression */) { - return true; - } } } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 221 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 264 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 179 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 182 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 183 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 26 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 188 /* ArrowFunction */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + } + function isNonJsxElementContext(context) { + return context.contextNode.kind !== 250 /* JsxElement */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 260 /* JsxExpression */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 257 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 257 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 251 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 148 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 228 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 234 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 164 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 157 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { return false; - }; - Rules.IsControlDeclContext = function (context) { - switch (context.contextNode.kind) { - case 211 /* IfStatement */: - case 221 /* SwitchStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 213 /* WhileStatement */: - case 224 /* TryStatement */: - case 212 /* DoStatement */: - case 220 /* WithStatement */: - // TODO - // case SyntaxKind.ElseClause: - case 260 /* CatchClause */: - return true; - default: - return false; - } - }; - Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 178 /* ObjectLiteralExpression */; - }; - Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 181 /* CallExpression */; - }; - Rules.IsNewContext = function (context) { - return context.contextNode.kind === 182 /* NewExpression */; - }; - Rules.IsFunctionCallOrNewContext = function (context) { - return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); - }; - Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 26 /* CommaToken */; - }; - Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; - }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 187 /* ArrowFunction */; - }; - Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; - }; - Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 249 /* JsxElement */; - }; - Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 256 /* JsxExpression */; - }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 253 /* JsxAttribute */; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 253 /* JsxAttribute */; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 250 /* JsxSelfClosingElement */; - }; - Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { - return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); - }; - Rules.IsEndOfDecoratorContextOnSameLine = function (context) { - return context.TokensAreOnSameLine() && - context.contextNode.decorators && - Rules.NodeIsInDecoratorContext(context.currentTokenParent) && - !Rules.NodeIsInDecoratorContext(context.nextTokenParent); - }; - Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isPartOfExpression(node)) { - node = node.parent; - } - return node.kind === 147 /* Decorator */; - }; - Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 227 /* VariableDeclarationList */ && - context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; - }; - Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind !== 2 /* FormatOnEnter */; - }; - Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 233 /* ModuleDeclaration */; - }; - Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 163 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; - }; - Rules.IsConstructorSignatureContext = function (context) { - return context.contextNode.kind === 156 /* ConstructSignature */; - }; - Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { + } + switch (parent.kind) { + case 160 /* TypeReference */: + case 185 /* TypeAssertionExpression */: + case 232 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 202 /* ExpressionWithTypeArguments */: + return true; + default: return false; - } - switch (parent.kind) { - case 159 /* TypeReference */: - case 184 /* TypeAssertionExpression */: - case 231 /* TypeAliasDeclaration */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 201 /* ExpressionWithTypeArguments */: - return true; - default: - return false; - } - }; - Rules.IsTypeArgumentOrParameterOrAssertionContext = function (context) { - return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || - Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); - }; - Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 184 /* TypeAssertionExpression */; - }; - Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 190 /* VoidExpression */; - }; - Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 197 /* YieldExpression */ && context.contextNode.expression !== undefined; - }; - Rules.IsNonNullAssertionContext = function (context) { - return context.contextNode.kind === 203 /* NonNullExpression */; - }; - return Rules; - }()); - formatting.Rules = Rules; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 185 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 191 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 198 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 204 /* NonNullExpression */; + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// +/// /* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesMap = /** @class */ (function () { - function RulesMap() { - this.map = []; - this.mapRowLength = 0; - } - RulesMap.create = function (rules) { - var result = new RulesMap(); - result.Initialize(rules); - return result; - }; - RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 142 /* LastToken */ + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); - // This array is used only during construction of the rulesbucket in the map - var rulesBucketConstructionStateList = new Array(this.map.length); // new Array(this.map.length); - this.FillRules(rules, rulesBucketConstructionStateList); - return this.map; - }; - RulesMap.prototype.FillRules = function (rules, rulesBucketConstructionStateList) { - var _this = this; - rules.forEach(function (rule) { - _this.FillRule(rule, rulesBucketConstructionStateList); - }); - }; - RulesMap.prototype.GetRuleBucketIndex = function (row, column) { - ts.Debug.assert(row <= 142 /* LastKeyword */ && column <= 142 /* LastKeyword */, "Must compute formatting context from tokens"); - var rulesBucketIndex = (row * this.mapRowLength) + column; - return rulesBucketIndex; + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); }; - RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { - var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); - rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { - rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { - var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); - var rulesBucket = _this.map[rulesBucketIndex]; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; if (rulesBucket === undefined) { - rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); - } - rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); - }); - }); - }; - RulesMap.prototype.GetRule = function (context) { - var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); - var bucket = this.map[bucketIndex]; - if (bucket) { - for (var _i = 0, _a = bucket.Rules(); _i < _a.length; _i++) { - var rule = _a[_i]; - if (rule.Operation.Context.InContext(context)) { - return rule; + rulesBucket = map[index] = []; } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); } } - return undefined; - }; - return RulesMap; - }()); - formatting.RulesMap = RulesMap; - var MaskBitSize = 5; - var Mask = 0x1f; + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 143 /* LastKeyword */ && column <= 143 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 143 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; - RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; - RulesPosition[RulesPosition["ContextRulesSpecific"] = MaskBitSize * 2] = "ContextRulesSpecific"; - RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; - RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; - RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesBucketConstructionState = /** @class */ (function () { - function RulesBucketConstructionState() { - //// The Rules list contains all the inserted rules into a rulebucket in the following order: - //// 1- Ignore rules with specific token combination - //// 2- Ignore rules with any token combination - //// 3- Context rules with specific token combination - //// 4- Context rules with any token combination - //// 5- Non-context rules with specific token combination - //// 6- Non-context rules with any token combination - //// - //// The member rulesInsertionIndexBitmap is used to describe the number of rules - //// in each sub-bucket (above) hence can be used to know the index of where to insert - //// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. - //// - //// Example: - //// In order to insert a rule to the end of sub-bucket (3), we get the index by adding - //// the values in the bitmap segments 3rd, 2nd, and 1st. - this.rulesInsertionIndexBitmap = 0; - } - RulesBucketConstructionState.prototype.GetInsertionIndex = function (maskPosition) { - var index = 0; - var pos = 0; - var indexBitmap = this.rulesInsertionIndexBitmap; - while (pos <= maskPosition) { - index += (indexBitmap & Mask); - indexBitmap >>= MaskBitSize; - pos += MaskBitSize; - } - return index; - }; - RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { - var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; - value++; - ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); - var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); - temp |= value << maskPosition; - this.rulesInsertionIndexBitmap = temp; - }; - return RulesBucketConstructionState; - }()); - formatting.RulesBucketConstructionState = RulesBucketConstructionState; - var RulesBucket = /** @class */ (function () { - function RulesBucket() { - this.rules = []; - } - RulesBucket.prototype.Rules = function () { - return this.rules; - }; - RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { - var position; - if (rule.Operation.Action === 1 /* Ignore */) { - position = specificTokens ? - RulesPosition.IgnoreRulesSpecific : - RulesPosition.IgnoreRulesAny; - } - else if (!rule.Operation.Context.IsAny()) { - position = specificTokens ? - RulesPosition.ContextRulesSpecific : - RulesPosition.ContextRulesAny; - } - else { - position = specificTokens ? - RulesPosition.NoContextRulesSpecific : - RulesPosition.NoContextRulesAny; - } - var state = constructionState[rulesBucketIndex]; - if (state === undefined) { - state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); - } - var index = state.GetInsertionIndex(position); - this.rules.splice(index, 0, rule); - state.IncreaseInsertionIndex(position); - }; - return RulesBucket; - }()); - formatting.RulesBucket = RulesBucket; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Shared; - (function (Shared) { - var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - allTokens.push(token); + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; } - var TokenValuesAccess = /** @class */ (function () { - function TokenValuesAccess(tokens) { - if (tokens === void 0) { tokens = []; } - this.tokens = tokens; - } - TokenValuesAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenValuesAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - TokenValuesAccess.prototype.isSpecific = function () { return true; }; - return TokenValuesAccess; - }()); - var TokenSingleValueAccess = /** @class */ (function () { - function TokenSingleValueAccess(token) { - this.token = token; - } - TokenSingleValueAccess.prototype.GetTokens = function () { - return [this.token]; - }; - TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue === this.token; - }; - TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; - return TokenSingleValueAccess; - }()); - var TokenAllAccess = /** @class */ (function () { - function TokenAllAccess() { - } - TokenAllAccess.prototype.GetTokens = function () { - return allTokens; - }; - TokenAllAccess.prototype.Contains = function () { - return true; - }; - TokenAllAccess.prototype.toString = function () { - return "[allTokens]"; - }; - TokenAllAccess.prototype.isSpecific = function () { return false; }; - return TokenAllAccess; - }()); - var TokenAllExceptAccess = /** @class */ (function () { - function TokenAllExceptAccess(except) { - this.except = except; - } - TokenAllExceptAccess.prototype.GetTokens = function () { - var _this = this; - return allTokens.filter(function (t) { return t !== _this.except; }); - }; - TokenAllExceptAccess.prototype.Contains = function (token) { - return token !== this.except; - }; - TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; - return TokenAllExceptAccess; - }()); - var TokenRange; - (function (TokenRange) { - function FromToken(token) { - return new TokenSingleValueAccess(token); - } - TokenRange.FromToken = FromToken; - function FromTokens(tokens) { - return new TokenValuesAccess(tokens); - } - TokenRange.FromTokens = FromTokens; - function FromRange(from, to, except) { - if (except === void 0) { except = []; } - var tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - tokens.push(token); - } - } - return new TokenValuesAccess(tokens); - } - TokenRange.FromRange = FromRange; - function AnyExcept(token) { - return new TokenAllExceptAccess(token); - } - TokenRange.AnyExcept = AnyExcept; - TokenRange.Any = new TokenAllAccess(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ - 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ - ]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ - 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ - ]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ - 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, - 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ - ]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([ - 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, - 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ - ]); - })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); - })(Shared = formatting.Shared || (formatting.Shared = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RulesProvider = /** @class */ (function () { - function RulesProvider() { - this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); - this.rulesMap = formatting.RulesMap.create(activeRules); - } - RulesProvider.prototype.getRulesMap = function () { - return this.rulesMap; - }; - RulesProvider.prototype.getFormatOptions = function () { - return this.options; - }; - RulesProvider.prototype.ensureUpToDate = function (options) { - if (!this.options || !ts.compareDataObjects(this.options, options)) { - this.options = ts.clone(options); - } - }; - return RulesProvider; - }()); - formatting.RulesProvider = RulesProvider; + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/// -/// -/// +/// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -86220,7 +89355,7 @@ var ts; (function (Constants) { Constants[Constants["Unknown"] = -1] = "Unknown"; })(Constants || (Constants = {})); - function formatOnEnter(position, sourceFile, rulesProvider, options) { + function formatOnEnter(position, sourceFile, formatContext) { var line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { return []; @@ -86246,15 +89381,15 @@ var ts; // end value is exclusive so add 1 to the result end: endOfFormatSpan + 1 }; - return formatSpan(span, sourceFile, options, rulesProvider, 2 /* FormatOnEnter */); + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); } formatting.formatOnEnter = formatOnEnter; - function formatOnSemicolon(position, sourceFile, rulesProvider, options) { + function formatOnSemicolon(position, sourceFile, formatContext) { var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; - function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + function formatOnOpeningCurly(position, sourceFile, formatContext) { var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; @@ -86277,29 +89412,29 @@ var ts; pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), end: position }; - return formatSpan(textRange, sourceFile, options, rulesProvider, 4 /* FormatOnOpeningCurlyBrace */); + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); } formatting.formatOnOpeningCurly = formatOnOpeningCurly; - function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { + function formatOnClosingCurly(position, sourceFile, formatContext) { var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5 /* FormatOnClosingCurlyBrace */); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; - function formatDocument(sourceFile, rulesProvider, options) { + function formatDocument(sourceFile, formatContext) { var span = { pos: 0, end: sourceFile.text.length }; - return formatSpan(span, sourceFile, options, rulesProvider, 0 /* FormatDocument */); + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); } formatting.formatDocument = formatDocument; - function formatSelection(start, end, sourceFile, rulesProvider, options) { + function formatSelection(start, end, sourceFile, formatContext) { // format from the beginning of the line var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), end: end, }; - return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */); + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); } formatting.formatSelection = formatSelection; /** @@ -86339,17 +89474,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 234 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 265 /* SourceFile */: - case 207 /* Block */: - case 234 /* ModuleBlock */: + return body && body.kind === 235 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 269 /* SourceFile */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -86463,13 +89598,13 @@ var ts; return 0; } /* @internal */ - function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; - function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + function formatNodeLines(node, sourceFile, formatContext, requestKind) { if (!node) { return []; } @@ -86477,14 +89612,15 @@ var ts; pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), end: node.end }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + return formatSpan(span, sourceFile, formatContext, requestKind); } - function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } - function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRange; @@ -86568,19 +89704,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 229 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 230 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 228 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 232 /* EnumDeclaration */: return 232 /* EnumDeclaration */; - case 153 /* GetAccessor */: return 125 /* GetKeyword */; - case 154 /* SetAccessor */: return 135 /* SetKeyword */; - case 151 /* MethodDeclaration */: + case 230 /* ClassDeclaration */: return 75 /* ClassKeyword */; + case 231 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; + case 229 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; + case 233 /* EnumDeclaration */: return 233 /* EnumDeclaration */; + case 154 /* GetAccessor */: return 125 /* GetKeyword */; + case 155 /* SetAccessor */: return 135 /* SetKeyword */; + case 152 /* MethodDeclaration */: if (node.asteriskToken) { return 39 /* AsteriskToken */; } // falls through - case 149 /* PropertyDeclaration */: - case 146 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 147 /* Parameter */: return ts.getNameOfDeclaration(node).kind; } } @@ -86618,16 +89754,16 @@ var ts; return indentation; case 41 /* SlashToken */: case 29 /* GreaterThanToken */: { - if (container.kind === 251 /* JsxOpeningElement */ || - container.kind === 252 /* JsxClosingElement */ || - container.kind === 250 /* JsxSelfClosingElement */) { + if (container.kind === 252 /* JsxOpeningElement */ || + container.kind === 253 /* JsxClosingElement */ || + container.kind === 251 /* JsxSelfClosingElement */) { return indentation; } break; } case 21 /* OpenBracketToken */: case 22 /* CloseBracketToken */: { - if (container.kind !== 172 /* MappedType */) { + if (container.kind !== 173 /* MappedType */) { return indentation; } break; @@ -86699,9 +89835,9 @@ var ts; if (child.decorators) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } - // if child is a list item - try to get its indentation + // if child is a list item - try to get its indentation, only if parent is within the original range. var childIndentationAmount = -1 /* Unknown */; - if (isListItem) { + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); if (childIndentationAmount !== -1 /* Unknown */) { inheritedIndentation = childIndentationAmount; @@ -86737,11 +89873,15 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 147 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 148 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 10 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } childContextNode = node; - if (isFirstListItem && parent.kind === 177 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 178 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -86799,27 +89939,24 @@ var ts; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } - var lineAdded; + var lineAction = 0 /* None */; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); // save previousRange since processRange will overwrite this value with current one var savePreviousRange = previousRange; - lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); - if (rangeHasError) { - // do not indent comments\token if token range overlaps with some error - indentToken = false; - } - else { - if (lineAdded !== undefined) { - indentToken = lineAdded; - } - else { + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { // indent token only if end line of previous range does not match start line of the token var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } + else { + indentToken = lineAction === 1 /* LineAdded */; + } } } if (currentTokenInfo.trailingTrivia) { @@ -86838,7 +89975,7 @@ var ts; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -86856,7 +89993,7 @@ var ts; } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { - insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } @@ -86876,7 +90013,7 @@ var ts; } function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); - var lineAdded; + var lineAction = 0 /* None */; if (!rangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line @@ -86884,32 +90021,32 @@ var ts; trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { - lineAdded = + lineAction = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - return lineAdded; + return lineAction; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); - var rule = rulesProvider.getRulesMap().GetRule(formattingContext); + var rule = getRule(formattingContext); var trimTrailingWhitespaces; - var lineAdded; + var lineAction = 0 /* None */; if (rule) { applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.Operation.Action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAdded = false; + if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { + lineAction = 2 /* LineRemoved */; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); } } - else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAdded = true; + else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { + lineAction = 1 /* LineAdded */; // Handle the case where token2 is moved to the new line. // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. @@ -86918,7 +90055,7 @@ var ts; } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -86927,7 +90064,7 @@ var ts; // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } - return lineAdded; + return lineAction; } function insertIndentation(pos, indentation, lineAdded) { var indentationString = getIndentationString(indentation, options); @@ -86959,7 +90096,8 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; @@ -86979,7 +90117,9 @@ var ts; parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } - parts.push({ pos: startPos, end: commentRange.end }); + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } } var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); @@ -87060,7 +90200,7 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - switch (rule.Operation.Action) { + switch (rule.action) { case 1 /* Ignore */: // no action required return; @@ -87074,7 +90214,7 @@ var ts; // exit early if we on different lines and rule cannot change number of newlines // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines - if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } // edit should not be applied if we have one line feed between elements @@ -87085,7 +90225,7 @@ var ts; break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines - if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } var posDelta = currentRange.pos - previousRange.end; @@ -87096,6 +90236,12 @@ var ts; } } } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); /** * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ @@ -87143,12 +90289,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 187 /* ArrowFunction */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 188 /* ArrowFunction */: if (node.typeParameters === list) { return 27 /* LessThanToken */; } @@ -87156,8 +90302,8 @@ var ts; return 19 /* OpenParenToken */; } break; - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -87165,7 +90311,7 @@ var ts; return 19 /* OpenParenToken */; } break; - case 159 /* TypeReference */: + case 160 /* TypeReference */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -87233,7 +90379,6 @@ var ts; formatting.getIndentationString = getIndentationString; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -87246,16 +90391,19 @@ var ts; Value[Value["Unknown"] = -1] = "Unknown"; })(Value || (Value = {})); /** - * Computed indentation for a given position in source file - * @param position - position in file - * @param sourceFile - target source file - * @param options - set of editor options that control indentation - * @param assumeNewLineBeforeCloseBrace - false when getIndentation is called on the text from the real source file. - * true - when we need to assume that position is on the newline. This is usefult for codefixes, i.e. + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` * function f() { * |} - * when inserting some text after open brace we would like to get the value of indentation as if newline was already there. - * However by default indentation at position | will be 0 so 'assumeNewLineBeforeCloseBrace' allows to override this behavior, + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. */ function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } @@ -87270,19 +90418,7 @@ var ts; var precedingToken = ts.findPrecedingToken(position, sourceFile); var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword if (enclosingCommentRange) { - var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; - var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; - ts.Debug.assert(commentStartLine >= 0); - if (previousLine <= commentStartLine) { - return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); - } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; - if (column === 0) { - return column; - } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); - return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { return getBaseIndentation(options); @@ -87297,44 +90433,61 @@ var ts; // for block indentation, we should look for a line which contains something that's not // whitespace. if (options.indentStyle === ts.IndentStyle.Block) { - // move backwards until we find a line with a non-whitespace character, - // then find the first non-whitespace character for that line. - var current_1 = position; - while (current_1 > 0) { - var char = sourceFile.text.charCodeAt(current_1); - if (!ts.isWhiteSpaceLike(char)) { - break; - } - current_1--; - } - var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); - return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); + return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 194 /* BinaryExpression */) { + if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 195 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' // if such node is found - compute initial indentation for 'position' inside this node var previous; var current = precedingToken; - var currentStart; - var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { - currentStart = getStartLineAndCharacterForNode(current, sourceFile); + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); - if (nextTokenKind !== 0 /* Unknown */) { + var indentationDelta = nextTokenKind !== 0 /* Unknown */ // handle cases when codefix is about to be inserted before the close brace - indentationDelta = assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0; - } - else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; - } - break; + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -87348,27 +90501,23 @@ var ts; previous = current; current = current.parent; } - if (!current) { - // no parent was found - return the base indentation of the SourceFile - return getBaseIndentation(options); - } - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); } - SmartIndenter.getIndentation = getIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); - return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; function getBaseIndentation(options) { return options.baseIndentSize || 0; } SmartIndenter.getBaseIndentation = getBaseIndentation; - function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { var parent = current.parent; - var parentStart; - // walk upwards and collect indentations for pairs of parent-child nodes - // indentation is not added if parent and child nodes start on the same line or if parent is IfStatement and child starts on the same line with 'else clause' + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. while (parent) { var useActualIndentation = true; if (ignoreActualIndentationRange) { @@ -87382,8 +90531,8 @@ var ts; return actualIndentation + indentationDelta; } } - parentStart = getParentStart(parent, current, sourceFile); - var parentAndChildShareLine = parentStart.line === currentStart.line || + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // try to fetch actual indentation for current node from source text @@ -87397,21 +90546,28 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current, isNextChild) && !parentAndChildShareLine) { indentationDelta += options.indentSize; } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); current = parent; - currentStart = parentStart; parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; } return indentationDelta + getBaseIndentation(options); } - function getParentStart(parent, child, sourceFile) { + function getContainingListOrParentStart(parent, child, sourceFile) { var containingList = getContainingList(child, sourceFile); - if (containingList) { - return sourceFile.getLineAndCharacterOfPosition(containingList.pos); - } - return sourceFile.getLineAndCharacterOfPosition(parent.getStart(sourceFile)); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); } /* * Function returns Value.Unknown if indentation cannot be determined @@ -87435,7 +90591,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 265 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 269 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -87473,8 +90629,17 @@ var ts; function getStartLineAndCharacterForNode(n, sourceFile) { return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 211 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 212 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -87489,37 +90654,37 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return node.parent.properties; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return node.parent.elements; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 152 /* Constructor */: - case 161 /* ConstructorType */: - case 156 /* ConstructSignature */: { + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 153 /* Constructor */: + case 162 /* ConstructorType */: + case 157 /* ConstructSignature */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); } - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); - case 182 /* NewExpression */: - case 181 /* CallExpression */: { + case 183 /* NewExpression */: + case 182 /* CallExpression */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); } - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); } } @@ -87557,10 +90722,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: node = node.expression; break; default: @@ -87624,90 +90789,122 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 210 /* ExpressionStatement */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 177 /* ArrayLiteralExpression */: - case 207 /* Block */: - case 234 /* ModuleBlock */: - case 178 /* ObjectLiteralExpression */: - case 163 /* TypeLiteral */: - case 172 /* MappedType */: - case 165 /* TupleType */: - case 235 /* CaseBlock */: - case 258 /* DefaultClause */: - case 257 /* CaseClause */: - case 185 /* ParenthesizedExpression */: - case 179 /* PropertyAccessExpression */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 208 /* VariableStatement */: - case 226 /* VariableDeclaration */: - case 243 /* ExportAssignment */: - case 219 /* ReturnStatement */: - case 195 /* ConditionalExpression */: - case 175 /* ArrayBindingPattern */: - case 174 /* ObjectBindingPattern */: - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - case 256 /* JsxExpression */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 146 /* Parameter */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 168 /* ParenthesizedType */: - case 183 /* TaggedTemplateExpression */: - case 191 /* AwaitExpression */: - case 245 /* NamedExports */: - case 241 /* NamedImports */: - case 246 /* ExportSpecifier */: - case 242 /* ImportSpecifier */: - case 261 /* PropertyAssignment */: - case 149 /* PropertyDeclaration */: + case 211 /* ExpressionStatement */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 178 /* ArrayLiteralExpression */: + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 179 /* ObjectLiteralExpression */: + case 164 /* TypeLiteral */: + case 173 /* MappedType */: + case 166 /* TupleType */: + case 236 /* CaseBlock */: + case 262 /* DefaultClause */: + case 261 /* CaseClause */: + case 186 /* ParenthesizedExpression */: + case 180 /* PropertyAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 209 /* VariableStatement */: + case 227 /* VariableDeclaration */: + case 244 /* ExportAssignment */: + case 220 /* ReturnStatement */: + case 196 /* ConditionalExpression */: + case 176 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 260 /* JsxExpression */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 147 /* Parameter */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 169 /* ParenthesizedType */: + case 184 /* TaggedTemplateExpression */: + case 192 /* AwaitExpression */: + case 246 /* NamedExports */: + case 242 /* NamedImports */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: return true; } return false; } - /* @internal */ function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 214 /* ForStatement */: - case 211 /* IfStatement */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 187 /* ArrowFunction */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return childKind !== 207 /* Block */; - case 244 /* ExportDeclaration */: - return childKind !== 245 /* NamedExports */; - case 238 /* ImportDeclaration */: - return childKind !== 239 /* ImportClause */ || - (child.namedBindings && child.namedBindings.kind !== 241 /* NamedImports */); - case 249 /* JsxElement */: - return childKind !== 252 /* JsxClosingElement */; + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 212 /* IfStatement */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 188 /* ArrowFunction */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return childKind !== 208 /* Block */; + case 245 /* ExportDeclaration */: + return childKind !== 246 /* NamedExports */; + case 239 /* ImportDeclaration */: + return childKind !== 240 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 242 /* NamedImports */); + case 250 /* JsxElement */: + return childKind !== 253 /* JsxClosingElement */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; } SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; - /* - Function returns true when the parent node should indent the given child by an explicit rule - */ - function shouldIndentChildNode(parent, child) { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false); + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: + switch (parent.kind) { + case 208 /* Block */: + var grandParent = parent.parent; + switch (grandParent && grandParent.kind) { + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + // We may want to write inner functions after this. + return false; + default: + return true; + } + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 269 /* SourceFile */: + case 235 /* ModuleBlock */: + return true; + default: + throw ts.Debug.fail(); + } + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: + return true; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(parent, child, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false)) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -87723,22 +90920,22 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -87815,7 +91012,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 178 /* ObjectLiteralExpression */)); + return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 179 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -87825,15 +91022,20 @@ var ts; return s; } var ChangeTracker = /** @class */ (function () { - function ChangeTracker(newLine, rulesProvider, validator) { + function ChangeTracker(newLine, formatContext, validator) { this.newLine = newLine; - this.rulesProvider = rulesProvider; + this.formatContext = formatContext; this.validator = validator; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -87955,9 +91157,9 @@ var ts; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } if ((ts.isStatementButNotDeclaration(after)) || - after.kind === 149 /* PropertyDeclaration */ || - after.kind === 148 /* PropertySignature */ || - after.kind === 150 /* MethodSignature */) { + after.kind === 150 /* PropertyDeclaration */ || + after.kind === 149 /* PropertySignature */ || + after.kind === 151 /* MethodSignature */) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { @@ -88086,7 +91288,7 @@ var ts; options: {} }); // use the same indentation as 'after' item - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.rulesProvider.getFormatOptions()); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { @@ -88170,7 +91372,7 @@ var ts; if (this.validator) { this.validator(nonformattedText); } - var formatOptions = this.rulesProvider.getFormatOptions(); + var formatOptions = this.formatContext.options; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; var initialIndentation = options.indentation !== undefined ? options.indentation @@ -88182,7 +91384,7 @@ var ts; : ts.formatting.SmartIndenter.shouldIndentChildNode(node) ? (formatOptions.indentSize || 0) : 0; - return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext); }; ChangeTracker.normalize = function (changes) { // order changes by start position @@ -88203,14 +91405,14 @@ var ts; printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { + function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { text: nonFormattedText.text, lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(nonFormattedText.text, changes); } function applyChanges(text, changes) { @@ -88396,7 +91598,7 @@ var ts; refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { return ts.flatMapIter(refactors.values(), function (refactor) { - return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); }); } refactor_1.getApplicableRefactors = getApplicableRefactors; @@ -88413,6 +91615,29 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decorator = ts.getAncestor(token, 148 /* Decorator */); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -88421,7 +91646,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var qualifiedName = ts.getAncestor(token, 143 /* QualifiedName */); + var qualifiedName = ts.getAncestor(token, 144 /* QualifiedName */); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); if (!ts.isIdentifier(qualifiedName.left)) { return undefined; @@ -88536,7 +91761,7 @@ var ts; var checker = context.program.getTypeChecker(); var leftExpression = token.parent.expression; var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 32768 /* Object */) { + if (leftExpressionType.flags & 65536 /* Object */) { var symbol = leftExpressionType.symbol; if (symbol.flags & 32 /* Class */) { classDeclaration = symbol.declarations && symbol.declarations[0]; @@ -88562,13 +91787,13 @@ var ts; actions = [methodCodeAction]; } if (makeStatic) { - if (classDeclaration.kind === 199 /* ClassExpression */) { + if (classDeclaration.kind === 200 /* ClassExpression */) { return actions; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -88583,7 +91808,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -88599,7 +91824,7 @@ var ts; actions = [methodCodeAction]; } var typeNode; - if (token.parent.parent.kind === 194 /* BinaryExpression */) { + if (token.parent.parent.kind === 195 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); @@ -88614,8 +91839,9 @@ var ts; /*initializer*/ undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - (actions || (actions = [])).push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; + actions = ts.append(actions, { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: propertyChangeTracker.getChanges() }); if (!makeStatic) { @@ -88640,15 +91866,14 @@ var ts; return actions; } function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 181 /* CallExpression */) { + if (token.parent.parent.kind === 182 /* CallExpression */) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? - ts.Diagnostics.Declare_method_0 : - ts.Diagnostics.Declare_static_method_0), [tokenName]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: methodDeclarationChangeTracker.getChanges() }; } @@ -88681,7 +91906,9 @@ var ts; } else { var meaning = ts.getMeaningFromLocation(node); - suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } if (suggestion) { return [{ @@ -88713,6 +91940,41 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); // These errors should only happen on the module name. + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, sourceFile.fileName, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + // If !registry, registry not available yet, can't do anything. + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + changes: [], + commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -88778,10 +92040,11 @@ var ts; } // figure out if the `this` access is actually inside the supercall // i.e. super(this.a), since in that case we won't suggest a fix - if (superCall.expression && superCall.expression.kind === 181 /* CallExpression */) { + if (superCall.expression && superCall.expression.kind === 182 /* CallExpression */) { var expressionArguments = superCall.expression.arguments; - for (var i = 0; i < expressionArguments.length; i++) { - if (expressionArguments[i].expression === token) { + for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { + var arg = expressionArguments_1[_i]; + if (arg.expression === token) { return undefined; } } @@ -88794,7 +92057,7 @@ var ts; changes: changeTracker.getChanges() }]; function findSuperCall(n) { - if (n.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + if (n.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { return n; } if (ts.isFunctionLike(n)) { @@ -88914,9 +92177,9 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - return deleteIdentifierOrPrefixWithUnderscore(token); - case 149 /* PropertyDeclaration */: - case 240 /* NamespaceImport */: + return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); + case 150 /* PropertyDeclaration */: + case 241 /* NamespaceImport */: return [deleteNode(token.parent)]; default: return deleteDefault(); @@ -88945,12 +92208,12 @@ var ts; }] }; } - function deleteIdentifierOrPrefixWithUnderscore(identifier) { + function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { var parent = identifier.parent; switch (parent.kind) { - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); @@ -88962,15 +92225,17 @@ var ts; else { return [deleteNodeInList(parent)]; } - case 146 /* Parameter */: + case 147 /* Parameter */: var functionDeclaration = parent.parent; - return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), - prefixIdentifierWithUnderscore(identifier)]; + var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); + return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code + ? [deleteAction] + : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 237 /* ImportEqualsDeclaration */); + case 238 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); return [deleteNode(importEquals)]; - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: var namedImports = parent.parent; if (namedImports.elements.length === 1) { return deleteNamedImportBinding(namedImports); @@ -88979,10 +92244,10 @@ var ts; // delete import specifier return [deleteNodeInList(parent)]; } - case 239 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' var importClause = parent; if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + var importDecl = ts.getAncestor(importClause, 239 /* ImportDeclaration */); return [deleteNode(importDecl)]; } else { @@ -88997,7 +92262,7 @@ var ts; return [deleteNode(importClause.name)]; } } - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return deleteNamedImportBinding(parent); default: return deleteDefault(); @@ -89018,26 +92283,26 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 238 /* ImportDeclaration */); + var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); return [deleteNode(importDecl)]; } } // token.parent is a variableDeclaration function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { - case 214 /* ForStatement */: + case 215 /* ForStatement */: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; return [ replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), prefixIdentifierWithUnderscore(identifier) ]; - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: // There is no valid fix in the case of: // for .. in return [prefixIdentifierWithUnderscore(identifier)]; @@ -89091,22 +92356,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments var decl = ts.findAncestor(node, function (n) { - return n.kind === 202 /* AsExpression */ || - n.kind === 155 /* CallSignature */ || - n.kind === 156 /* ConstructSignature */ || - n.kind === 228 /* FunctionDeclaration */ || - n.kind === 153 /* GetAccessor */ || - n.kind === 157 /* IndexSignature */ || - n.kind === 172 /* MappedType */ || - n.kind === 151 /* MethodDeclaration */ || - n.kind === 150 /* MethodSignature */ || - n.kind === 146 /* Parameter */ || - n.kind === 149 /* PropertyDeclaration */ || - n.kind === 148 /* PropertySignature */ || - n.kind === 154 /* SetAccessor */ || - n.kind === 231 /* TypeAliasDeclaration */ || - n.kind === 184 /* TypeAssertionExpression */ || - n.kind === 226 /* VariableDeclaration */; + return n.kind === 203 /* AsExpression */ || + n.kind === 156 /* CallSignature */ || + n.kind === 157 /* ConstructSignature */ || + n.kind === 229 /* FunctionDeclaration */ || + n.kind === 154 /* GetAccessor */ || + n.kind === 158 /* IndexSignature */ || + n.kind === 173 /* MappedType */ || + n.kind === 152 /* MethodDeclaration */ || + n.kind === 151 /* MethodSignature */ || + n.kind === 147 /* Parameter */ || + n.kind === 150 /* PropertyDeclaration */ || + n.kind === 149 /* PropertySignature */ || + n.kind === 155 /* SetAccessor */ || + n.kind === 232 /* TypeAliasDeclaration */ || + n.kind === 185 /* TypeAssertionExpression */ || + n.kind === 227 /* VariableDeclaration */; }); if (!decl) return; @@ -89117,10 +92382,10 @@ var ts; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; - if (jsdocType.kind === 270 /* JSDocNullableType */) { + if (jsdocType.kind === 274 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); } return actions; @@ -89144,6 +92409,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -89164,9 +92430,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -89185,7 +92448,7 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0 /* Better */: // the new one is not worth considering if it is a new import. // However if it is instead a insertion into existing import, the user might want to use // the module specifier even it is worse by our standards. So keep it. @@ -89193,7 +92456,7 @@ var ts; return; } // falls through - case ModuleSpecifierComparison.Equal: + case 1 /* Equal */: // the current one is safe. But it is still possible that the new one is worse // than another existing one. For example, you may have new imports from "./foo/bar" // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new @@ -89201,7 +92464,7 @@ var ts; // but the new one is worse than the other one, so should not add to the list. updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2 /* Worse */: // the existing one is worse, remove from the list. continue; } @@ -89225,14 +92488,14 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; } // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0 /* Better */; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2 /* Worse */; } // if both are relative paths, and ms1 has fewer levels, then it is better if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { @@ -89240,515 +92503,605 @@ var ts; var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 /* Better */ : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 /* Equal */ + : 2 /* Worse */; } // the equal cases include when the two specifiers are not comparable. - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName = void 0; - if (umdSymbol.flags & 2097152 /* Alias */) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); - symbolName = symbol.name; - } - else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + formatContext: context.formatContext, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbols, context) { + moduleSymbols = ts.toArray(moduleSymbols); + var declarations = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + }); + var actions = []; + if (context.symbolToken) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } - return getCodeActionForImport(symbol, symbolName, /*isDefault*/ false, /*isNamespaceImport*/ true); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); - } + return actions.concat(getCodeActionsForAddImport(moduleSymbols, context, declarations)); + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 239 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 241 /* NamespaceImport */ ? namedBindings.name : undefined; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); - } - } - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(name !== "default"); - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } + else { + return declaration.name; } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + } + // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238 /* ImportDeclaration */: - return parent; - case 248 /* ExternalModuleReference */: - return parent.parent; - default: - return undefined; - } - } } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 239 /* ImportDeclaration */: + return parent; + case 249 /* ExternalModuleReference */: + return parent.parent; + case 245 /* ExportDeclaration */: + case 182 /* CallExpression */:// For "require()" calls + // Ignore these, can't add imports to them. + return undefined; + default: + ts.Debug.fail(); } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var importDecl = kind !== 3 /* Equals */ + ? ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createImportClauseOfKind(kind, symbolName), quotedModuleSpecifier) + : ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - return [getCodeActionForNewImport()]; + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } - } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); - } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + }); + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + var id = ts.createIdentifier(symbolName); + switch (kind) { + case 1 /* Default */: + return ts.createImportClause(id, /*namedBindings*/ undefined); + case 2 /* Namespace */: + return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id)); + case 0 /* Named */: + return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; } - else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) + return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + } + codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + function getRelativePathNParents(relativePath) { + var count = 0; + for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { + count++; + } + return count; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); - } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } - } - } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSourceFileImportLocation(node) { - // For a source file, it is possible there are detached comments we should not skip - var text = node.text; - var ranges = ts.getLeadingCommentRanges(text, 0); - if (!ranges) - return 0; - var position = 0; - // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end + 1; - ranges = ranges.slice(1); - } - // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { - position = range.end + 1; - continue; + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } - break; } - return position; } - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } - }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } - return undefined; - } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + else { + state = 3 /* PackageContent */; } - return fileName; + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName, options) { + var noExtension = ts.removeFileExtension(fileName); + return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionsForAddImport(moduleSymbols, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 239 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + }); + if (fromExistingImport) { + return [fromExistingImport]; + } + var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 239 /* ImportDeclaration */ + ? node.moduleSpecifier + : node.moduleReference.kind === 249 /* ExternalModuleReference */ + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile, kind = context.kind; + var name = importClause.name; + var namedBindings = (importClause.kind !== 238 /* ImportEqualsDeclaration */ && importClause).namedBindings; + switch (kind) { + case 1 /* Default */: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0 /* Named */: { + var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 242 /* NamedImports */ && namedBindings.elements.length !== 0) { + // There are already named imports; add another. + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 242 /* NamedImports */ && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); + }); } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + return undefined; + } + case 2 /* Namespace */: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + case 3 /* Equals */: + return undefined; + default: + ts.Debug.assertNever(kind); + } + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", + /*moduleSpecifier*/ undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken, compilerOptions = context.compilerOptions; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; + } + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbolName = symbol.name; + } + else { + throw ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: getUmdImportKind(compilerOptions) })); + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + throw ts.Debug.assertNever(moduleKind); + } + } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) + && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); } } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol, sourceFile); + } } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + } + codefix.forEachExternalModule = forEachExternalModule; + /** + * 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) { + // 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)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var res = ""; + var lastCharWasValid = true; + var firstCharCode = moduleSpecifier.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < moduleSpecifier.length; i++) { + var ch = moduleSpecifier.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -89887,17 +93240,17 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 148 /* PropertySignature */: - case 149 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 149 /* PropertySignature */: + case 150 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); var property = ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined); return property; - case 150 /* MethodSignature */: - case 151 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 152 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -89915,8 +93268,8 @@ var ts; return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); } var signatureDeclarations = []; - for (var i = 0; i < signatures.length; i++) { - var signature = signatures[i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); if (methodDeclaration) { signatureDeclarations.push(methodDeclaration); @@ -89939,7 +93292,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -89993,8 +93346,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var i = 0; i < signatures.length; i++) { - var sig = signatures[i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -90041,10 +93394,580 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + // Allowed + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + // Get Accessor declarations + 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + return true; + case 187 /* FunctionExpression */: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 153 /* Constructor */; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 153 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 194 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 193 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 195 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 180 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 181 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + usageContext.isNumber = true; + break; + case 37 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 40 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + // ShiftOperator + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 48 /* AmpersandToken */: + case 49 /* BarToken */: + case 50 /* CaretToken */: + // CompoundAssignmentOperator + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 69 /* BarEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 38 /* MinusToken */: + // RelationalOperator + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59 /* PlusEqualsToken */: + case 37 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 524322 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 58 /* EqualsToken */: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 54 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 227 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + case 93 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 182 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + var members_5 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + var numberIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + members_5.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + } + return checker.createAnonymousType(/*symbol*/ undefined, members_5, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 16384 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// /// +/// /// /// /// @@ -90055,6 +93978,237 @@ var ts; /// /// /// +/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var annotateWithTypeFromJSDoc; + (function (annotateWithTypeFromJSDoc) { + var actionName = "annotate"; + var annotateTypeFromJSDoc = { + name: "Annotate with type from JSDoc", + description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(annotateTypeFromJSDoc); + function getAvailableActions(context) { + if (ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { + return [{ + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, + actions: [ + { + description: annotateTypeFromJSDoc.description, + name: actionName + } + ] + }]; + } + } + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { + if (actionName !== action) { + return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 147 /* Parameter */) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(token, isDeclarationWithType); + var jsdocType = ts.getJSDocType(decl); + if (!decl || !jsdocType || decl.type) { + return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var declarationWithType = addType(decl, transformJSDocType(jsdocType)); + ts.suppressLeadingAndTrailingTrivia(declarationWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, declarationWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function getEditsForFunctionAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var functionWithType = addTypesToFunctionLike(decl); + ts.suppressLeadingAndTrailingTrivia(functionWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, functionWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 227 /* VariableDeclaration */ || + node.kind === 147 /* Parameter */ || + node.kind === 149 /* PropertySignature */ || + node.kind === 150 /* PropertyDeclaration */; + } + function addTypesToFunctionLike(decl) { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true); + var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); }); + var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true)); + switch (decl.kind) { + case 229 /* FunctionDeclaration */: + return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 153 /* Constructor */: + return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); + case 187 /* FunctionExpression */: + return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 188 /* ArrowFunction */: + return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); + case 152 /* MethodDeclaration */: + return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); + case 154 /* GetAccessor */: + return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); + case 155 /* SetAccessor */: + return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body); + default: + return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind); + } + } + function addType(decl, jsdocType) { + switch (decl.kind) { + case 227 /* VariableDeclaration */: + return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); + case 149 /* PropertySignature */: + return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + case 150 /* PropertyDeclaration */: + return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + default: + return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind); + } + } + function transformJSDocType(node) { + if (node === undefined) { + return undefined; + } + switch (node.kind) { + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 276 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 275 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 274 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 278 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 277 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 147 /* Parameter */: + return transformJSDocParameter(node); + case 160 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + var parameters = node.parameters && node.parameters.map(transformJSDocType); + return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 278 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -90074,14 +94228,14 @@ var ts; if (!ts.isInJavaScriptFile(context.file)) { return undefined; } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + var symbol = getConstructorSymbol(context); + if (!symbol) { + return undefined; + } + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { symbol = symbol.valueDeclaration.initializer.symbol; } - if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { + if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { name: convertFunctionToES6Class.name, @@ -90101,12 +94255,9 @@ var ts; if (actionName !== action) { return undefined; } - var start = context.startPosition; var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var ctorSymbol = getConstructorSymbol(context); + var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { @@ -90117,12 +94268,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: precedingNode = ctorDeclaration; deleteNode(ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; if (ctorDeclaration.parent.declarations.length === 1) { deleteNode(precedingNode); @@ -90198,7 +94349,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 211 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; deleteNode(nodeToDelete); if (!assignmentBinaryExpression.right) { @@ -90206,26 +94357,28 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186 /* FunctionExpression */: { + case 187 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; } - case 187 /* ArrowFunction */: { + case 188 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 207 /* Block */) { + if (arrowFunctionBody.kind === 208 /* Block */) { bodyBlock = arrowFunctionBody; } else { var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; @@ -90260,7 +94413,7 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 187 /* FunctionExpression */) { return undefined; } if (node.name.kind !== 71 /* Identifier */) { @@ -90270,7 +94423,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -90280,11 +94434,21 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + } + function getConstructorSymbol(_a) { + var startPosition = _a.startPosition, file = _a.file, program = _a.program; + var checker = program.getTypeChecker(); + var token = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return checker.getSymbolAtLocation(token); } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -90296,16 +94460,19 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var extractMethod; - (function (extractMethod_1) { - var extractMethod = { - name: "Extract Method", - description: ts.Diagnostics.Extract_function.message, + var extractSymbol; + (function (extractSymbol_1) { + var extractSymbol = { + name: "Extract Symbol", + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction, }; - refactor.registerRefactor(extractMethod); - /** Compute the associated code actions */ + refactor.registerRefactor(extractSymbol); + /** + * Compute the associated code actions + * Exported for tests. + */ function getAvailableActions(context) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -90317,69 +94484,111 @@ var ts; // No extractions possible return undefined; } - var actions = []; - var usedNames = ts.createMap(); + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; // Skip these since we don't have a way to report errors yet - if (errors.length) { - continue; + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } } - // Don't issue refactorings with duplicated names. - // Scopes come back in "innermost first" order, so extractions will - // preferentially go into nearer scopes - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); - if (!usedNames.has(description)) { - usedNames.set(description, true); - actions.push({ - description: description, - name: "scope_" + i - }); + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } } // *do* increment i anyway because we'll look for the i-th scope // later when actually doing the refactoring if the user requests it i++; } - if (actions.length === 0) { - return undefined; + var infos = []; + if (functionActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); } - return [{ - name: extractMethod.name, - description: extractMethod.description, - inlineable: true, - actions: actions - }]; + if (constantActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : undefined; } + extractSymbol_1.getAvailableActions = getAvailableActions; + /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; - var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); - ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); - var index = +parsedIndexMatch[1]; - ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - return getExtractionAtIndex(targetRange, context, index); + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); } + extractSymbol_1.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { function createMessage(message) { return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; } - Messages.CannotExtractFunction = createMessage("Cannot extract function."); - Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages.InsufficientSelection = createMessage("Select more than a single identifier."); - Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); - Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - })(Messages || (Messages = {})); + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -90402,7 +94611,7 @@ var ts; function getRangeToExtract(sourceFile, span) { var length = span.length; if (length === 0) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) @@ -90415,46 +94624,24 @@ var ts; var rangeFacts = RangeFacts.None; if (!start || !end) { // cannot find either start or end node - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start.parent !== end.parent) { - // handle cases like 1 + [2 + 3] + 4 - // user selection is marked with []. - // in this case 2 + 3 does not belong to the same tree node - // instead the shape of the tree looks like this: - // + - // / \ - // + 4 - // / \ - // + 3 - // / \ - // 1 2 - // in this case there is no such one node that covers ends of selection and is located inside the selection - // to handle this we check if both start and end of the selection belong to some binary operation - // and start node is parented by the parent of the end node - // if this is the case - expand the selection to the entire parent of end node (in this case it will be [1 + 2 + 3] + 4) - var startParent = ts.skipParentheses(start.parent); - var endParent = ts.skipParentheses(end.parent); - if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { - start = end = endParent; - } - else { - // start and end nodes belong to different subtrees - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); - } + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start !== end) { // start and end should be statements and parent should be either block or a source file if (!isBlockLike(start.parent)) { - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { - var errors = checkNode(statement); - if (errors) { - return { errors: errors }; + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; } statements.push(statement); } @@ -90464,40 +94651,72 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - else { - // We have a single node (start) - var errors = checkRootNode(start) || checkNode(start); - if (errors) { - return { errors: errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; } - function createErrorResult(sourceFile, start, length, message) { - return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = undefined; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; } function checkRootNode(node) { if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { - return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; } return undefined; } function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 149 /* PropertyDeclaration */) { + if (current.kind === 150 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 146 /* Parameter */) { + else if (current.kind === 147 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 152 /* Constructor */) { + if (ctorOrMethod.kind === 153 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 151 /* MethodDeclaration */) { + else if (current.kind === 152 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -90514,11 +94733,11 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; } - if (ts.isInAmbientContext(nodeToCheck)) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + if (nodeToCheck.flags & 2097152 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; } // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) var containingClass = ts.getContainingClass(nodeToCheck); @@ -90536,26 +94755,26 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 226 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 227 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { - case 238 /* ImportDeclaration */: - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + case 239 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; case 97 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 181 /* CallExpression */) { + if (node.parent.kind === 182 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; } } @@ -90564,13 +94783,13 @@ var ts; } break; } - if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: - if (node.parent.kind === 265 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + if (node.parent.kind === 269 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } break; } @@ -90579,20 +94798,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 211 /* IfStatement */: + case 212 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 224 /* TryStatement */: + case 225 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 207 /* Block */: - if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + case 208 /* Block */: + if (node.parent && node.parent.kind === 225 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 257 /* CaseClause */: + case 261 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -90604,11 +94823,11 @@ var ts; break; } switch (node.kind) { - case 169 /* ThisType */: + case 170 /* ThisType */: case 99 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -90616,36 +94835,36 @@ var ts; seenLabels.pop(); break; } - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { // attempts to jump to label that is not in range to be extracted - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } } else { - if (!(permittedJumps & (node.kind === 218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 219 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } else { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); } break; default: @@ -90656,12 +94875,12 @@ var ts; } } } - extractMethod_1.getRangeToExtract = getRangeToExtract; + extractSymbol_1.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; } - else if (ts.isPartOfExpression(node)) { + else if (ts.isExpressionNode(node)) { // If our selection is the expression in an ExpressionStatement, expand // the selection to include the enclosing Statement (this stops us // from trying to care about the return value of the extracted function @@ -90670,9 +94889,8 @@ var ts; } return undefined; } - function isValidExtractionTarget(node) { - // Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method - return (node.kind === 228 /* FunctionDeclaration */) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); } /** * Computes possible places we could extract the function into. For example, @@ -90680,127 +94898,174 @@ var ts; * depending on what's in the extracted body. */ function collectEnclosingScopes(range) { - var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; if (range.facts & RangeFacts.UsesThis) { // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 147 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. // Walk up to the closest parent of a place where we can logically put a sibling: // * Function declaration // * Class declaration or expression // * Module/namespace or source file - if (current !== start && isValidExtractionTarget(current)) { - (scopes = scopes || []).push(current); - } - // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current && current.parent && current.parent.kind === 146 /* Parameter */) { - // Skip all the way to the outer scope of the function that declared this parameter - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; - } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 269 /* SourceFile */) { + return scopes; + } } } - return scopes; } - // exported only for tests - function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; - ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); } - extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; /** * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes * or an error explaining why we can't extract into that scope. */ - // exported only for tests function getPossibleExtractions(targetRange, context) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 - return scopes.map(function (scope, i) { - return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; }); + return extractions; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; } - function getDescriptionForScope(scope) { + function getDescriptionForFunctionInScope(scope) { return ts.isFunctionLikeDeclaration(scope) - ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + ? "inner function" : ts.isClassLike(scope) - ? "method in " + getDescriptionForClassLikeDeclaration(scope) - : "function in " + getDescriptionForModuleLikeDeclaration(scope); + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: return "constructor"; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return scope.name ? "function expression '" + scope.name.text + "'" : "anonymous function expression"; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return "function '" + scope.name.text + "'"; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return "arrow function"; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return "method '" + scope.name.getText(); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 229 /* ClassDeclaration */ + return scope.kind === 230 /* ClassDeclaration */ ? "class '" + scope.name.text + "'" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 234 /* ModuleBlock */ + return scope.kind === 235 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" - : scope.externalModuleIndicator ? "module scope" : "global scope"; + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } - function getUniqueName(fileText) { - var functionNameText = "newFunction"; - for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { - functionNameText = "newFunction_" + i; + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + function getUniqueName(baseName, fileText) { + var nameText = baseName; + for (var i = 1; ts.stringContains(fileText, nameText); i++) { + nameText = baseName + "_" + i; } - return functionNameText; + return nameText; } /** * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors */ - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(file.text); + var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType = undefined; @@ -90813,7 +95078,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -90841,9 +95106,10 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -90863,13 +95129,16 @@ var ts; /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; - var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; // replace range with function call @@ -90882,33 +95151,89 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { // has both writes and return, need to create variable declaration to hold return value; newNodes.push(ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } // propagate writes back if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { // emit e.g. // { a, b, __return } = newFunction(a, b); // return __return; - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -90925,40 +95250,165 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter // insert newline only when replacing statements - }); + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var isJS = ts.isInJavaScriptFile(scope); + var variableType = isJS + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(131 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + // Consume + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line + changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + else if (node.parent.kind === 211 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + // If we're at the beginning of the file, we need to take care not to insert before header comments + // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved + // for imports. + var insertionPos = ts.getSourceFileImportLocation(file); + changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { + prefix: insertionPos === 0 ? undefined : context.newLineCharacter, + suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter + }); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + // Consume + if (node.parent.kind === 211 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.deleteRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + } } var edits = changeTracker.getChanges(); - var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; - var renameFilename = renameRange.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function getRenameLocation(edits, renameFilename, functionNameText) { + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode = undefined; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, functionNameText, isDeclaredBeforeUse) { var delta = 0; + var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { var change = textChanges_2[_b]; - var span_17 = change.span, newText = change.newText; - // TODO(acasey): We are assuming that the call expression comes before the function declaration, - // because we want the new cursor to be on the call expression, - // which is closer to where the user was before extracting the function. + var span_15 = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - return span_17.start + delta + index; + lastPos = span_15.start + delta + index; + // If the reference comes first, return immediately. + if (!isDeclaredBeforeUse) { + return lastPos; + } } - delta += newText.length - span_17.length; + delta += newText.length - span_15.length; } } - throw new Error(); // Didn't find the text we inserted? + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(lastPos >= 0); + return lastPos; } function getFirstDeclaration(type) { var firstDeclaration = undefined; @@ -90976,28 +95426,9 @@ var ts; function compareTypesByDeclarationOrder(_a, _b) { var type1 = _a.type, declaration1 = _a.declaration; var type2 = _b.type, declaration2 = _b.declaration; - if (declaration1) { - if (declaration2) { - var positionDiff = declaration1.pos - declaration2.pos; - if (positionDiff !== 0) { - return positionDiff; - } - } - else { - return 1; // Sort undeclared type parameters to the front. - } - } - else if (declaration2) { - return -1; // Sort undeclared type parameters to the front. - } - var name1 = type1.symbol ? type1.symbol.getName() : ""; - var name2 = type2.symbol ? type2.symbol.getName() : ""; - var nameDiff = ts.compareStrings(name1, name2); - if (nameDiff !== 0) { - return nameDiff; - } - // IDs are guaranteed to be unique, so this ensures a total ordering. - return type1.id - type2.id; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); } function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); @@ -91009,21 +95440,22 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { // add return at the end to propagate writes back in case if control flow falls out of the function body // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -91037,8 +95469,8 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 220 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -91054,16 +95486,25 @@ var ts; } else { var oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } } } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } function getStatementsOrClassElements(scope) { - if (ts.isFunctionLike(scope)) { + if (ts.isFunctionLikeDeclaration(scope)) { var body = scope.body; if (ts.isBlock(body)) { return body.statements; @@ -91084,13 +95525,70 @@ var ts; * If `scope` contains a function after `minPos`, then return the first such function. * Otherwise, return `undefined`. */ - function getNodeToInsertBefore(minPos, scope) { + function getNodeToInsertFunctionBefore(minPos, scope) { return ts.find(getStatementsOrClassElements(scope), function (child) { - return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); }); } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember = undefined; + var allProperties = true; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope = undefined; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = undefined; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + // There must be at least one statement since we started in one. + ts.Debug.assert(prevStatement !== undefined); + return prevStatement; + } + if (curr === scope) { + ts.Debug.fail("Didn't encounter a block-like before encountering scope"); + break; + } + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); @@ -91106,7 +95604,7 @@ var ts; */ function getEnclosingTextRange(targetRange, sourceFile) { return isReadonlyArray(targetRange.range) - ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } : targetRange.range; } var Usage; @@ -91120,19 +95618,51 @@ var ts; var allTypeParameterUsages = ts.createMap(); // Key is type ID var usagesPerScope = []; var substitutionsPerScope = []; - var errorsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic = undefined; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } // initialize results for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { - var _ = scopes_1[_i]; + var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - errorsPerScope.push([]); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 229 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); - var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); // Unfortunately, this code takes advantage of the knowledge that the generated method @@ -91169,7 +95699,23 @@ var ts; // copy allTypeParameterUsages into all remaining scopes. ts.Debug.assert(i_1 === scopes.length); } - var _loop_8 = function (i) { + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_10 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } var hasWrite = false; var readonlyClassPropertyWrite = undefined; usagesPerScope[i].usages.forEach(function (value) { @@ -91182,22 +95728,28 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } }; for (var i = 0; i < scopes.length; i++) { - _loop_8(i); - } - // If there are any declarations in the extracted block that are used in the same enclosing - // lexical scope, we can't move the extraction "up" as those declarations will become unreachable - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + _loop_10(i); } - return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -91219,7 +95771,7 @@ var ts; var visitedTypes = symbolWalker.walkType(type).visitedTypes; for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { var visitedType = visitedTypes_1[_i]; - if (visitedType.flags & 16384 /* TypeParameter */) { + if (visitedType.flags & 32768 /* TypeParameter */) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); } } @@ -91231,7 +95783,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { // use 'write' as default usage for values @@ -91266,19 +95818,15 @@ var ts; if (symbolId) { for (var i = 0; i < scopes.length; i++) { // push substitution from map to map to simplify rewriting - var substitition = substitutionsPerScope[i].get(symbolId); - if (substitition) { - usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); } } } } function recordUsagebySymbol(identifier, usage, isTypeName) { - // If the identifier is both a property name and its value, we're only interested in its value - // (since the name is a declaration and will be included in the extracted range). - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -91319,9 +95867,14 @@ var ts; if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { // this is write to a reference located outside of the target scope and range is extracted into generator // currently this is unsupported scenario - for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { - var errors = errorsPerScope_1[_a]; - errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); } } for (var i = 0; i < scopes.length; i++) { @@ -91339,7 +95892,9 @@ var ts; // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument // so there's no problem. if (!(symbol.flags & 262144 /* TypeParameter */)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } } else { @@ -91355,17 +95910,37 @@ var ts; return; } // Otherwise check and recurse. - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { - var scope = errorsPerScope_2[_i]; - scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { @@ -91378,7 +95953,9 @@ var ts; if (prefix === undefined) { return undefined; } - return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -91404,40 +95981,205 @@ var ts; */ function isExtractableExpression(node) { switch (node.parent.kind) { - case 264 /* EnumMember */: + case 268 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 238 /* ImportDeclaration */ && - node.parent.kind !== 242 /* ImportSpecifier */; - case 198 /* SpreadElement */: - case 174 /* ObjectBindingPattern */: - case 176 /* BindingElement */: + return node.parent.kind !== 239 /* ImportDeclaration */ && + node.parent.kind !== 243 /* ImportSpecifier */; + case 199 /* SpreadElement */: + case 175 /* ObjectBindingPattern */: + case 177 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 176 /* BindingElement */ && - node.parent.kind !== 242 /* ImportSpecifier */ && - node.parent.kind !== 246 /* ExportSpecifier */; + return node.parent.kind !== 177 /* BindingElement */ && + node.parent.kind !== 243 /* ImportSpecifier */ && + node.parent.kind !== 247 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 207 /* Block */: - case 265 /* SourceFile */: - case 234 /* ModuleBlock */: - case 257 /* CaseClause */: + case 208 /* Block */: + case 269 /* SourceFile */: + case 235 /* ModuleBlock */: + case 261 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { + // Then it will be available via `fixCannotFindModule`. + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); // Should be defined if we said there was an action available. + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) { + return undefined; + } + var resolvedTo = ts.getResolvedModule(file, node.text); + // Still offer to install types if it resolved to e.g. a ".js" file. + // `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name, + // so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings. + if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) { + return undefined; + } + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text); + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 239 /* ImportDeclaration */: + case 249 /* ExternalModuleReference */: return true; default: return false; } } - })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage) { + var actionName = "Convert to default import"; + var useDefaultImport = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(useDefaultImport); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition, program = context.program; + if (!program.getCompilerOptions().allowSyntheticDefaultImports) { + return undefined; + } + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); + var resolvedFile = program.getSourceFile(module.resolvedFileName); + if (!(resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { + return undefined; + } + return [ + { + name: useDefaultImport.name, + description: useDefaultImport.description, + actions: [ + { + description: useDefaultImport.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + var file = context.file, startPosition = context.startPosition; + ts.Debug.assertEqual(actionName, _actionName); + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier; + var newImportClause = ts.createImportClause(name, /*namedBindings*/ undefined); + var newImportStatement = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newImportClause, moduleSpecifier); + return { + edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }), + renameFilename: undefined, + renameLocation: undefined, + }; + } + function getConvertibleImportAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + while (true) { + switch (node.kind) { + case 238 /* ImportEqualsDeclaration */: + var eq = node; + var moduleReference = eq.moduleReference; + return moduleReference.kind === 249 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression) + ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } + : undefined; + case 239 /* ImportDeclaration */: + var d = node; + var importClause = d.importClause; + return !importClause.name && importClause.namedBindings.kind === 241 /* NamespaceImport */ && ts.isStringLiteral(d.moduleSpecifier) + ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier } + : undefined; + // For known child node kinds of convertible imports, try again with parent node. + case 241 /* NamespaceImport */: + case 249 /* ExternalModuleReference */: + case 91 /* ImportKeyword */: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 39 /* AsteriskToken */: + break; + default: + return undefined; + } + node = node.parent; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// -/// +/// +/// +/// /// /// /// @@ -91470,14 +96212,13 @@ var ts; var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.5"; - /* @internal */ - var ruleProvider; + ts.servicesVersion = "0.7"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; + node.flags = parent.flags & 6387712 /* ContextFlags */; return node; } var NodeObject = /** @class */ (function () { @@ -91489,31 +96230,43 @@ var ts; this.parent = undefined; this.kind = kind; } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); }; NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); }; NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); return this.pos; }; NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); return this.end; }; NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getStart(sourceFile) - this.pos; }; NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); if (!sourceFile) { sourceFile = this.getSourceFile(); } @@ -91535,7 +96288,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(290 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -91559,9 +96312,9 @@ var ts; } if (ts.isJSDocCommentContainingNode(this)) { /** Don't add trivia for "tokens" since this is in a comment. */ - var children_3 = []; - this.forEachChild(function (child) { children_3.push(child); }); - this._children = children_3; + var children_4 = []; + this.forEachChild(function (child) { children_4.push(child); }); + this._children = children_4; return; } var children = []; @@ -91598,37 +96351,42 @@ var ts; this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children.length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children[index]; }; NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); if (!this._children) this.createChildren(sourceFile); return this._children; }; NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 /* FirstJSDocNode */ || kid.kind > 285 /* LastJSDocNode */; }); - return child.kind < 143 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 271 /* FirstJSDocNode */ || kid.kind > 289 /* LastJSDocNode */; }); + return child.kind < 144 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); var child = ts.lastOrUndefined(children); if (!child) { return undefined; } - return child.kind < 143 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 144 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -91668,7 +96426,10 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; @@ -91700,7 +96461,7 @@ var ts; }; Object.defineProperty(SymbolObject.prototype, "name", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedName); + return ts.symbolName(this); }, enumerable: true, configurable: true @@ -91714,9 +96475,29 @@ var ts; SymbolObject.prototype.getDeclarations = function () { return this.declarations; }; - SymbolObject.prototype.getDocumentationComment = function () { + SymbolObject.prototype.getDocumentationComment = function (checker) { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.declarations) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.documentationComment.length === 0 || this.declarations.some(hasJSDocInheritDocTag)) { + if (checker) { + for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); + if (inheritedDocs.length > 0) { + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + break; + } + } + } + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -91744,7 +96525,7 @@ var ts; } Object.defineProperty(IdentifierObject.prototype, "text", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedText); + return ts.idText(this); }, enumerable: true, configurable: true @@ -91785,13 +96566,19 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & 32768 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) + return this.flags & 65536 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; TypeObject.prototype.getNonNullableType = function () { return this.checker.getNonNullableType(this); }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; return TypeObject; }()); var SignatureObject = /** @class */ (function () { @@ -91812,7 +96599,19 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; + if (this.declaration) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]); + if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { + var inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -91824,6 +96623,55 @@ var ts; }; return SignatureObject; }()); + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + var foundDocs = false; + return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + if (foundDocs) { + return ts.emptyArray; + } + var superType = typeChecker.getTypeAtLocation(superTypeNode); + if (!superType) { + return ts.emptyArray; + } + var baseProperty = typeChecker.getPropertyOfType(superType, propertyName); + if (!baseProperty) { + return ts.emptyArray; + } + var inheritedDocs = baseProperty.getDocumentationComment(typeChecker); + foundDocs = inheritedDocs.length > 0; + return inheritedDocs; + }); + } + /** + * Finds and returns the `TypeNode` for all super classes and implemented interfaces given a declaration. + * @param declaration The possibly-inherited declaration. + * @returns A filled array of `TypeNode`s containing all super classes and implemented interfaces if any exist, otherwise an empty array. + */ + function getAllSuperTypeNodes(declaration) { + var container = declaration.parent; + if (!container || (!ts.isClassDeclaration(container) && !ts.isInterfaceDeclaration(container))) { + return ts.emptyArray; + } + var extended = ts.getClassExtendsHeritageClauseElement(container); + var types = extended ? [extended] : ts.emptyArray; + return ts.isClassLike(container) ? ts.concatenate(types, ts.getClassImplementsHeritageClauseElements(container)) : types; + } var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -91881,13 +96729,13 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_9 = ts.getTextOfIdentifierOrLiteral(name); - if (result_9 !== undefined) { - return result_9; + var result_8 = ts.getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; - if (expr.kind === 179 /* PropertyAccessExpression */) { + if (expr.kind === 180 /* PropertyAccessExpression */) { return expr.name.text; } return ts.getTextOfIdentifierOrLiteral(expr); @@ -91897,10 +96745,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -91920,31 +96768,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 246 /* ExportSpecifier */: - case 242 /* ImportSpecifier */: - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 163 /* TypeLiteral */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 164 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 146 /* Parameter */: + case 147 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: { + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -91955,19 +96803,19 @@ var ts; } } // falls through - case 264 /* EnumMember */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 268 /* EnumMember */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: addDeclaration(node); break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -91979,7 +96827,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 241 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -91988,7 +96836,7 @@ var ts; } } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -92098,35 +96946,34 @@ var ts; scriptKind: ts.getScriptKind(fileName, this.host) }; } + else { + entry = fileName; + } this.fileNameToEntry.set(path, entry); return entry; }; HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.containsEntryByPath = function (path) { - return this.fileNameToEntry.has(path); + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.containsEntryByPath(path) - ? this.getEntryByPath(path) - : this.createEntry(fileName, path); + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - var fileNames = []; - this.fileNameToEntry.forEach(function (value) { - if (value) { - fileNames.push(value.hostFileName); - } + return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { + return ts.isString(entry) ? entry : entry.hostFileName; }); - return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.scriptSnapshot; }; return HostCache; @@ -92146,7 +96993,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -92273,7 +97120,6 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -92297,16 +97143,12 @@ var ts; } return sourceFile; } - function getRuleProvider(options) { - ruleProvider.ensureUpToDate(options); - return ruleProvider; - } function synchronizeHostData() { // perform fast check if host supports it if (host.getProjectVersion) { var hostProjectVersion = host.getProjectVersion(); if (hostProjectVersion) { - if (lastProjectVersion === hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { return; } lastProjectVersion = hostProjectVersion; @@ -92320,8 +97162,10 @@ var ts; } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (programUpToDate()) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -92329,18 +97173,7 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var shouldCreateNewSourceFiles = oldSettings && - (oldSettings.target !== newSettings.target || - oldSettings.module !== newSettings.module || - oldSettings.moduleResolution !== newSettings.moduleResolution || - oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || - oldSettings.baseUrl !== newSettings.baseUrl || - !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -92348,23 +97181,17 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: function (fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - return hostCache.containsEntryByPath(path) ? - !!hostCache.getEntryByPath(path) : - (host.fileExists && host.fileExists(fileName)); - }, + fileExists: fileExists, readFile: function (fileName) { // stub missing host functionality var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - if (hostCache.containsEntryByPath(path)) { - var entry = hostCache.getEntryByPath(path); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var entry = hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); } return host.readFile && host.readFile(fileName); }, @@ -92373,13 +97200,16 @@ var ts; }, getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; - } + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames }; if (host.trace) { compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; } if (host.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { @@ -92387,31 +97217,31 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - var newProgram = ts.createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program); - // Release any files we have acquired in the old program but are - // not part of the new program. - if (program) { - var oldSourceFiles = program.getSourceFiles(); - var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { - var oldSourceFile = oldSourceFiles_2[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); - } - } - } + program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; - program = newProgram; // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; - function getOrCreateSourceFile(fileName) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path) { + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { ts.Debug.assert(hostCache !== undefined); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined @@ -92423,7 +97253,7 @@ var ts; // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. - if (!shouldCreateNewSourceFiles) { + if (!shouldCreateNewSourceFile) { // Check if the old program had this file already var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { @@ -92459,43 +97289,6 @@ var ts; // Could not find this file in the old program, create a new SourceFile for it. return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } - function sourceFileUpToDate(sourceFile) { - if (!sourceFile) { - return false; - } - var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile.version === hostCache.getVersion(path); - } - function programUpToDate() { - // If we haven't create a program yet, then it is not up-to-date - if (!program) { - return false; - } - // If number of files in the program do not match, it is not up-to-date - var rootFileNames = hostCache.getRootFileNames(); - if (program.getSourceFiles().length !== rootFileNames.length) { - return false; - } - // If any file is not up-to-date, then the whole program is not up-to-date - for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { - var fileName = rootFileNames_2[_i]; - if (!sourceFileUpToDate(program.getSourceFile(fileName))) { - return false; - } - } - var currentOptions = program.getCompilerOptions(); - var newOptions = hostCache.compilationSettings(); - // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { - return false; - } - // If everything matches but the text of config file is changed, - // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } - return true; - } } function getProgram() { synchronizeHostData(); @@ -92539,17 +97332,18 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - function getCompletionsAtPosition(fileName, position) { + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = { includeExternalModuleExports: false }; } synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } - function getCompletionEntrySymbol(fileName, position, entryName) { + function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -92567,10 +97361,10 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: case 99 /* ThisKeyword */: - case 169 /* ThisType */: + case 170 /* ThisType */: case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -92580,7 +97374,7 @@ var ts; kindModifiers: "" /* none */, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } @@ -92616,6 +97410,10 @@ var ts; synchronizeHostData(); return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); @@ -92701,16 +97499,8 @@ var ts; function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var outputFiles = []; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { - outputFiles: outputFiles, - emitSkipped: emitOutput.emitSkipped - }; + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } // Signature help /** @@ -92736,15 +97526,15 @@ var ts; return; } switch (node.kind) { - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: case 9 /* StringLiteral */: case 86 /* FalseKeyword */: case 101 /* TrueKeyword */: case 95 /* NullKeyword */: case 97 /* SuperKeyword */: case 99 /* ThisKeyword */: - case 169 /* ThisType */: + case 170 /* ThisType */: case 71 /* Identifier */: break; // Cant create the text span @@ -92761,7 +97551,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 233 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 234 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -92876,29 +97666,24 @@ var ts; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsForDocument(fileName, options) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); if (!ts.isInComment(sourceFile, position)) { - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); } } return []; @@ -92908,12 +97693,26 @@ var ts; var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); - var rulesProvider = getRuleProvider(formatOptions); - return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function applyCodeActionCommand(fileName, actionOrUndefined) { + var action = typeof fileName === "string" ? actionOrUndefined : fileName; + return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + } + function applySingleCodeActionCommand(action) { + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -93071,8 +97870,7 @@ var ts; (char >= 48 /* _0 */ && char <= 57 /* _9 */); } function isNodeModulesFile(path) { - var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, "/node_modules/"); } } function getRenameInfo(fileName, position) { @@ -93088,8 +97886,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), - rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -93118,6 +97917,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, @@ -93142,6 +97942,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -93184,19 +97985,19 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 248 /* ExternalModuleReference */ || + node.parent.kind === 249 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return true; } return false; @@ -93209,13 +98010,13 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 144 /* ComputedPropertyName */) { + if (node.parent.kind === 145 /* ComputedPropertyName */) { return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: return isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 178 /* ObjectLiteralExpression */ || node.parent.parent.kind === 254 /* JsxAttributes */) && + (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -93232,20 +98033,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_10 = []; + var result_9 = []; var symbol = type.getProperty(name); - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_10.push(symbol); + result_9.push(symbol); } }); - return result_10; + return result_9; } if (symbol) { - result_10.push(symbol); - return result_10; + result_9.push(symbol); + return result_9; } } return undefined; @@ -93254,7 +98055,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 180 /* ElementAccessExpression */ && + node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -93303,7 +98104,7 @@ var ts; } } // Cannot set breakpoint in ambient declarations - if (ts.isInAmbientContext(tokenAtLocation)) { + if (tokenAtLocation.flags & 2097152 /* Ambient */) { return undefined; } // Get the span in the node based on its syntax @@ -93335,114 +98136,114 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 226 /* VariableDeclaration */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 227 /* VariableDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return spanInVariableDeclaration(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return spanInParameterDeclaration(node); - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 207 /* Block */: + case 208 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return spanInBlock(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return spanInBlock(node.block); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 212 /* DoStatement */: + case 213 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 225 /* DebuggerStatement */: + case 226 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 211 /* IfStatement */: + case 212 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return spanInForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 257 /* CaseClause */: - case 258 /* DefaultClause */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 224 /* TryStatement */: + case 225 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 176 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 177 /* BindingElement */: // span on complete node return textSpan(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 147 /* Decorator */: + case 148 /* Decorator */: return spanInNodeArray(node.parent.decorators); - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: return undefined; // Tokens: case 25 /* SemicolonToken */: @@ -93472,7 +98273,7 @@ var ts; case 74 /* CatchKeyword */: case 87 /* FinallyKeyword */: return spanInNextNode(node); - case 142 /* OfKeyword */: + case 143 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -93485,13 +98286,13 @@ var ts; // a or ...c or d: x from // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern if ((node.kind === 71 /* Identifier */ || - node.kind === 198 /* SpreadElement */ || - node.kind === 261 /* PropertyAssignment */ || - node.kind === 262 /* ShorthandPropertyAssignment */) && + node.kind === 199 /* SpreadElement */ || + node.kind === 265 /* PropertyAssignment */ || + node.kind === 266 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 194 /* BinaryExpression */) { + if (node.kind === 195 /* BinaryExpression */) { var binaryExpression = node; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -93512,24 +98313,24 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { switch (node.parent.kind) { - case 212 /* DoStatement */: + case 213 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 147 /* Decorator */: + case 148 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: return textSpan(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (node.parent.operatorToken.kind === 26 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -93538,13 +98339,13 @@ var ts; } } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 261 /* PropertyAssignment */ && + if (node.parent.kind === 265 /* PropertyAssignment */ && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 184 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 185 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNextNode(node.parent.type); } // return type of function go to previous token @@ -93552,8 +98353,8 @@ var ts; return spanInPreviousNode(node); } // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 226 /* VariableDeclaration */ || - node.parent.kind === 146 /* Parameter */)) { + if ((node.parent.kind === 227 /* VariableDeclaration */ || + node.parent.kind === 147 /* Parameter */)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -93561,7 +98362,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 194 /* BinaryExpression */) { + if (node.parent.kind === 195 /* BinaryExpression */) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -93575,7 +98376,7 @@ var ts; } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 227 /* VariableDeclarationList */ && + if (variableDeclaration.parent.kind === 228 /* VariableDeclarationList */ && variableDeclaration.parent.declarations[0] === variableDeclaration) { // First declaration - include let keyword return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); @@ -93587,7 +98388,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 215 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 216 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } // If this is a destructuring pattern, set breakpoint in binding pattern @@ -93598,10 +98399,10 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 216 /* ForOfStatement */) { + variableDeclaration.parent.parent.kind === 217 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 227 /* VariableDeclarationList */ && + if (variableDeclaration.parent.kind === 228 /* VariableDeclarationList */ && variableDeclaration.parent.declarations[0] !== variableDeclaration) { // If we cannot set breakpoint on this declaration, set it on previous one // Because the variable declaration may be binding pattern and @@ -93638,7 +98439,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 229 /* ClassDeclaration */ && functionDeclaration.kind !== 152 /* Constructor */); + (functionDeclaration.parent.kind === 230 /* ClassDeclaration */ && functionDeclaration.kind !== 153 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -93661,26 +98462,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 213 /* WhileStatement */: - case 211 /* IfStatement */: - case 215 /* ForInStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 216 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 227 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 228 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -93705,23 +98506,23 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 200 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 201 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 176 /* BindingElement */) { + if (bindingPattern.parent.kind === 177 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 175 /* ArrayBindingPattern */ && node.kind !== 174 /* ObjectBindingPattern */); - var elements = node.kind === 177 /* ArrayLiteralExpression */ ? + ts.Debug.assert(node.kind !== 176 /* ArrayBindingPattern */ && node.kind !== 175 /* ObjectBindingPattern */); + var elements = node.kind === 178 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 200 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 201 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -93729,18 +98530,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 194 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 195 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -93748,25 +98549,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 232 /* EnumDeclaration */: - case 229 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 207 /* Block */: + case 208 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 260 /* CatchClause */: + case 264 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -93774,7 +98575,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -93790,7 +98591,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -93805,12 +98606,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 212 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) { + if (node.parent.kind === 213 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 182 /* CallExpression */ || + node.parent.kind === 183 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 185 /* ParenthesizedExpression */) { + if (node.parent.kind === 186 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -93819,21 +98620,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 185 /* ParenthesizedExpression */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 186 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -93843,20 +98644,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 261 /* PropertyAssignment */ || - node.parent.kind === 146 /* Parameter */) { + node.parent.kind === 265 /* PropertyAssignment */ || + node.parent.kind === 147 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 184 /* TypeAssertionExpression */) { + if (node.parent.kind === 185 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 212 /* DoStatement */) { + if (node.parent.kind === 213 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -93864,7 +98665,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 216 /* ForOfStatement */) { + if (node.parent.kind === 217 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -94114,7 +98915,7 @@ var ts; if (logPerformance) { var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof result === "string") { + if (ts.isString(result)) { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -94296,6 +99097,14 @@ var ts; var _this = this; return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; /// GOTO Type /** * Computes the definition location of the type of the symbol @@ -94371,14 +99180,17 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/, source) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; @@ -94657,6 +99469,4 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.6"; - -//# sourceMappingURL=typescriptServices.js.map +var toolsVersion = ts.versionMajorMinor; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index cbf7ad062d225..7b78c4237d632 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -200,159 +200,163 @@ declare namespace ts { SymbolKeyword = 137, TypeKeyword = 138, UndefinedKeyword = 139, - FromKeyword = 140, - GlobalKeyword = 141, - OfKeyword = 142, - QualifiedName = 143, - ComputedPropertyName = 144, - TypeParameter = 145, - Parameter = 146, - Decorator = 147, - PropertySignature = 148, - PropertyDeclaration = 149, - MethodSignature = 150, - MethodDeclaration = 151, - Constructor = 152, - GetAccessor = 153, - SetAccessor = 154, - CallSignature = 155, - ConstructSignature = 156, - IndexSignature = 157, - TypePredicate = 158, - TypeReference = 159, - FunctionType = 160, - ConstructorType = 161, - TypeQuery = 162, - TypeLiteral = 163, - ArrayType = 164, - TupleType = 165, - UnionType = 166, - IntersectionType = 167, - ParenthesizedType = 168, - ThisType = 169, - TypeOperator = 170, - IndexedAccessType = 171, - MappedType = 172, - LiteralType = 173, - ObjectBindingPattern = 174, - ArrayBindingPattern = 175, - BindingElement = 176, - ArrayLiteralExpression = 177, - ObjectLiteralExpression = 178, - PropertyAccessExpression = 179, - ElementAccessExpression = 180, - CallExpression = 181, - NewExpression = 182, - TaggedTemplateExpression = 183, - TypeAssertionExpression = 184, - ParenthesizedExpression = 185, - FunctionExpression = 186, - ArrowFunction = 187, - DeleteExpression = 188, - TypeOfExpression = 189, - VoidExpression = 190, - AwaitExpression = 191, - PrefixUnaryExpression = 192, - PostfixUnaryExpression = 193, - BinaryExpression = 194, - ConditionalExpression = 195, - TemplateExpression = 196, - YieldExpression = 197, - SpreadElement = 198, - ClassExpression = 199, - OmittedExpression = 200, - ExpressionWithTypeArguments = 201, - AsExpression = 202, - NonNullExpression = 203, - MetaProperty = 204, - TemplateSpan = 205, - SemicolonClassElement = 206, - Block = 207, - VariableStatement = 208, - EmptyStatement = 209, - ExpressionStatement = 210, - IfStatement = 211, - DoStatement = 212, - WhileStatement = 213, - ForStatement = 214, - ForInStatement = 215, - ForOfStatement = 216, - ContinueStatement = 217, - BreakStatement = 218, - ReturnStatement = 219, - WithStatement = 220, - SwitchStatement = 221, - LabeledStatement = 222, - ThrowStatement = 223, - TryStatement = 224, - DebuggerStatement = 225, - VariableDeclaration = 226, - VariableDeclarationList = 227, - FunctionDeclaration = 228, - ClassDeclaration = 229, - InterfaceDeclaration = 230, - TypeAliasDeclaration = 231, - EnumDeclaration = 232, - ModuleDeclaration = 233, - ModuleBlock = 234, - CaseBlock = 235, - NamespaceExportDeclaration = 236, - ImportEqualsDeclaration = 237, - ImportDeclaration = 238, - ImportClause = 239, - NamespaceImport = 240, - NamedImports = 241, - ImportSpecifier = 242, - ExportAssignment = 243, - ExportDeclaration = 244, - NamedExports = 245, - ExportSpecifier = 246, - MissingDeclaration = 247, - ExternalModuleReference = 248, - JsxElement = 249, - JsxSelfClosingElement = 250, - JsxOpeningElement = 251, - JsxClosingElement = 252, - JsxAttribute = 253, - JsxAttributes = 254, - JsxSpreadAttribute = 255, - JsxExpression = 256, - CaseClause = 257, - DefaultClause = 258, - HeritageClause = 259, - CatchClause = 260, - PropertyAssignment = 261, - ShorthandPropertyAssignment = 262, - SpreadAssignment = 263, - EnumMember = 264, - SourceFile = 265, - Bundle = 266, - JSDocTypeExpression = 267, - JSDocAllType = 268, - JSDocUnknownType = 269, - JSDocNullableType = 270, - JSDocNonNullableType = 271, - JSDocOptionalType = 272, - JSDocFunctionType = 273, - JSDocVariadicType = 274, - JSDocComment = 275, - JSDocTag = 276, - JSDocAugmentsTag = 277, - JSDocClassTag = 278, - JSDocParameterTag = 279, - JSDocReturnTag = 280, - JSDocTypeTag = 281, - JSDocTemplateTag = 282, - JSDocTypedefTag = 283, - JSDocPropertyTag = 284, - JSDocTypeLiteral = 285, - SyntaxList = 286, - NotEmittedStatement = 287, - PartiallyEmittedExpression = 288, - CommaListExpression = 289, - MergeDeclarationMarker = 290, - EndOfDeclarationMarker = 291, - Count = 292, + UniqueKeyword = 140, + FromKeyword = 141, + GlobalKeyword = 142, + OfKeyword = 143, + QualifiedName = 144, + ComputedPropertyName = 145, + TypeParameter = 146, + Parameter = 147, + Decorator = 148, + PropertySignature = 149, + PropertyDeclaration = 150, + MethodSignature = 151, + MethodDeclaration = 152, + Constructor = 153, + GetAccessor = 154, + SetAccessor = 155, + CallSignature = 156, + ConstructSignature = 157, + IndexSignature = 158, + TypePredicate = 159, + TypeReference = 160, + FunctionType = 161, + ConstructorType = 162, + TypeQuery = 163, + TypeLiteral = 164, + ArrayType = 165, + TupleType = 166, + UnionType = 167, + IntersectionType = 168, + ParenthesizedType = 169, + ThisType = 170, + TypeOperator = 171, + IndexedAccessType = 172, + MappedType = 173, + LiteralType = 174, + ObjectBindingPattern = 175, + ArrayBindingPattern = 176, + BindingElement = 177, + ArrayLiteralExpression = 178, + ObjectLiteralExpression = 179, + PropertyAccessExpression = 180, + ElementAccessExpression = 181, + CallExpression = 182, + NewExpression = 183, + TaggedTemplateExpression = 184, + TypeAssertionExpression = 185, + ParenthesizedExpression = 186, + FunctionExpression = 187, + ArrowFunction = 188, + DeleteExpression = 189, + TypeOfExpression = 190, + VoidExpression = 191, + AwaitExpression = 192, + PrefixUnaryExpression = 193, + PostfixUnaryExpression = 194, + BinaryExpression = 195, + ConditionalExpression = 196, + TemplateExpression = 197, + YieldExpression = 198, + SpreadElement = 199, + ClassExpression = 200, + OmittedExpression = 201, + ExpressionWithTypeArguments = 202, + AsExpression = 203, + NonNullExpression = 204, + MetaProperty = 205, + TemplateSpan = 206, + SemicolonClassElement = 207, + Block = 208, + VariableStatement = 209, + EmptyStatement = 210, + ExpressionStatement = 211, + IfStatement = 212, + DoStatement = 213, + WhileStatement = 214, + ForStatement = 215, + ForInStatement = 216, + ForOfStatement = 217, + ContinueStatement = 218, + BreakStatement = 219, + ReturnStatement = 220, + WithStatement = 221, + SwitchStatement = 222, + LabeledStatement = 223, + ThrowStatement = 224, + TryStatement = 225, + DebuggerStatement = 226, + VariableDeclaration = 227, + VariableDeclarationList = 228, + FunctionDeclaration = 229, + ClassDeclaration = 230, + InterfaceDeclaration = 231, + TypeAliasDeclaration = 232, + EnumDeclaration = 233, + ModuleDeclaration = 234, + ModuleBlock = 235, + CaseBlock = 236, + NamespaceExportDeclaration = 237, + ImportEqualsDeclaration = 238, + ImportDeclaration = 239, + ImportClause = 240, + NamespaceImport = 241, + NamedImports = 242, + ImportSpecifier = 243, + ExportAssignment = 244, + ExportDeclaration = 245, + NamedExports = 246, + ExportSpecifier = 247, + MissingDeclaration = 248, + ExternalModuleReference = 249, + JsxElement = 250, + JsxSelfClosingElement = 251, + JsxOpeningElement = 252, + JsxClosingElement = 253, + JsxFragment = 254, + JsxOpeningFragment = 255, + JsxClosingFragment = 256, + JsxAttribute = 257, + JsxAttributes = 258, + JsxSpreadAttribute = 259, + JsxExpression = 260, + CaseClause = 261, + DefaultClause = 262, + HeritageClause = 263, + CatchClause = 264, + PropertyAssignment = 265, + ShorthandPropertyAssignment = 266, + SpreadAssignment = 267, + EnumMember = 268, + SourceFile = 269, + Bundle = 270, + JSDocTypeExpression = 271, + JSDocAllType = 272, + JSDocUnknownType = 273, + JSDocNullableType = 274, + JSDocNonNullableType = 275, + JSDocOptionalType = 276, + JSDocFunctionType = 277, + JSDocVariadicType = 278, + JSDocComment = 279, + JSDocTypeLiteral = 280, + JSDocTag = 281, + JSDocAugmentsTag = 282, + JSDocClassTag = 283, + JSDocParameterTag = 284, + JSDocReturnTag = 285, + JSDocTypeTag = 286, + JSDocTemplateTag = 287, + JSDocTypedefTag = 288, + JSDocPropertyTag = 289, + SyntaxList = 290, + NotEmittedStatement = 291, + PartiallyEmittedExpression = 292, + CommaListExpression = 293, + MergeDeclarationMarker = 294, + EndOfDeclarationMarker = 295, + Count = 296, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -360,15 +364,15 @@ declare namespace ts { FirstReservedWord = 72, LastReservedWord = 107, FirstKeyword = 72, - LastKeyword = 142, + LastKeyword = 143, FirstFutureReservedWord = 108, LastFutureReservedWord = 116, - FirstTypeNode = 158, - LastTypeNode = 173, + FirstTypeNode = 159, + LastTypeNode = 174, FirstPunctuation = 17, LastPunctuation = 70, FirstToken = 0, - LastToken = 142, + LastToken = 143, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -377,11 +381,11 @@ declare namespace ts { LastTemplateToken = 16, FirstBinaryOperator = 27, LastBinaryOperator = 70, - FirstNode = 143, - FirstJSDocNode = 267, - LastJSDocNode = 285, - FirstJSDocTagNode = 276, - LastJSDocTagNode = 285, + FirstNode = 144, + FirstJSDocNode = 271, + LastJSDocNode = 289, + FirstJSDocTagNode = 281, + LastJSDocTagNode = 289, } enum NodeFlags { None = 0, @@ -408,7 +412,7 @@ declare namespace ts { BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, - ContextFlags = 96256, + ContextFlags = 6387712, TypeExcludesFlags = 20480, } enum ModifierFlags { @@ -457,6 +461,7 @@ declare namespace ts { } type DotDotDotToken = Token; type QuestionToken = Token; + type ExclamationToken = Token; type ColonToken = Token; type EqualsToken = Token; type AsteriskToken = Token; @@ -467,7 +472,7 @@ declare namespace ts { type AwaitKeywordToken = Token; type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; type ModifiersArray = NodeArray; - interface Identifier extends PrimaryExpression { + interface Identifier extends PrimaryExpression, Declaration { kind: SyntaxKind.Identifier; /** * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) @@ -533,6 +538,7 @@ declare namespace ts { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -567,8 +573,9 @@ declare namespace ts { } interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; - questionToken?: QuestionToken; name: PropertyName; + questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -602,6 +609,7 @@ declare namespace ts { dotDotDotToken?: DotDotDotToken; name: DeclarationName; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; type?: TypeNode; initializer?: Expression; } @@ -664,13 +672,13 @@ declare namespace ts { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; - body: FunctionBody; + body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; - body: FunctionBody; + body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { @@ -736,7 +744,7 @@ declare namespace ts { } interface TypeOperatorNode extends TypeNode { kind: SyntaxKind.TypeOperator; - operator: SyntaxKind.KeyOfKeyword; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; type: TypeNode; } interface IndexedAccessTypeNode extends TypeNode { @@ -1061,6 +1069,20 @@ declare namespace ts { tagName: JsxTagNameExpression; attributes: JsxAttributes; } + interface JsxFragment extends PrimaryExpression { + kind: SyntaxKind.JsxFragment; + openingFragment: JsxOpeningFragment; + children: NodeArray; + closingFragment: JsxClosingFragment; + } + interface JsxOpeningFragment extends Expression { + kind: SyntaxKind.JsxOpeningFragment; + parent?: JsxFragment; + } + interface JsxClosingFragment extends Expression { + kind: SyntaxKind.JsxClosingFragment; + parent?: JsxFragment; + } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; parent?: JsxAttributes; @@ -1088,7 +1110,7 @@ declare namespace ts { containsOnlyWhiteSpaces: boolean; parent?: JsxElement; } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { _statementBrand: any; } @@ -1442,9 +1464,15 @@ declare namespace ts { interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; } + /** + * Note that `@extends` is a synonym of `@augments`. + * Both tags are represented by this interface. + */ interface JSDocAugmentsTag extends JSDocTag { kind: SyntaxKind.JSDocAugmentsTag; - typeExpression: JSDocTypeExpression; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; } interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; @@ -1471,7 +1499,7 @@ declare namespace ts { interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ isNameFirst: boolean; isBracketed: boolean; @@ -1586,8 +1614,8 @@ declare namespace ts { } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getSourceFileByPath(path: Path): SourceFile; + getSourceFile(fileName: string): SourceFile | undefined; + getSourceFileByPath(path: Path): SourceFile | undefined; getCurrentDirectory(): string; } interface ParseConfigHost { @@ -1600,9 +1628,7 @@ declare namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray): void; - } + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -1725,16 +1751,20 @@ declare namespace ts { signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + /** + * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead + * This will be removed in a future version. + */ getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; /** - * returns unknownSignature in the case of an error. Don't know when it returns undefined. + * returns unknownSignature in the case of an error. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: FunctionLike): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; @@ -1753,6 +1783,8 @@ declare namespace ts { getApparentType(type: Type): Type; getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; + getBaseConstraintOfType(type: Type): Type | undefined; + getDefaultFromTypeParameter(type: Type): Type | undefined; } enum NodeBuilderFlags { None = 0, @@ -1800,6 +1832,7 @@ declare namespace ts { trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; reportPrivateInBaseOfClassExpression(propertyName: string): void; + reportInaccessibleUniqueSymbolError(): void; } enum TypeFormatFlags { None = 0, @@ -1818,6 +1851,7 @@ declare namespace ts { WriteClassExpressionAsTypeLiteral = 16384, InArrayType = 32768, UseAliasDefinedOutsideCurrentScope = 65536, + AllowUniqueESSymbolType = 131072, } enum SymbolFormatFlags { None = 0, @@ -1869,6 +1903,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, + JSContainer = 67108864, Enum = 384, Variable = 3, Value = 107455, @@ -1971,31 +2006,34 @@ declare namespace ts { BooleanLiteral = 128, EnumLiteral = 256, ESSymbol = 512, - Void = 1024, - Undefined = 2048, - Null = 4096, - Never = 8192, - TypeParameter = 16384, - Object = 32768, - Union = 65536, - Intersection = 131072, - Index = 262144, - IndexedAccess = 524288, - NonPrimitive = 16777216, + UniqueESSymbol = 1024, + Void = 2048, + Undefined = 4096, + Null = 8192, + Never = 16384, + TypeParameter = 32768, + Object = 65536, + Union = 131072, + Intersection = 262144, + Index = 524288, + IndexedAccess = 1048576, + NonPrimitive = 33554432, + MarkerType = 134217728, Literal = 224, - Unit = 6368, + Unit = 13536, StringOrNumberLiteral = 96, - PossiblyFalsy = 7406, - StringLike = 262178, + PossiblyFalsy = 14574, + StringLike = 524322, NumberLike = 84, BooleanLike = 136, EnumLike = 272, - UnionOrIntersection = 196608, - StructuredType = 229376, - StructuredOrTypeVariable = 1032192, - TypeVariable = 540672, - Narrowable = 17810175, - NotUnionOrUnit = 16810497, + ESSymbolLike = 1536, + UnionOrIntersection = 393216, + StructuredType = 458752, + StructuredOrTypeVariable = 2064384, + TypeVariable = 1081344, + Narrowable = 35620607, + NotUnionOrUnit = 33620481, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2010,6 +2048,9 @@ declare namespace ts { freshType?: LiteralType; regularType?: LiteralType; } + interface UniqueESSymbolType extends Type { + symbol: Symbol; + } interface StringLiteralType extends LiteralType { value: string; } @@ -2029,6 +2070,7 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, + ContainsSpread = 1024, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2080,9 +2122,6 @@ declare namespace ts { interface TypeVariable extends Type { } interface TypeParameter extends TypeVariable { - /** Retrieve using getConstraintFromTypeParameter */ - constraint: Type; - default?: Type; } interface IndexedAccessType extends TypeVariable { objectType: Type; @@ -2111,9 +2150,11 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - NakedTypeVariable = 1, - MappedType = 2, - ReturnType = 4, + Contravariant = 1, + NakedTypeVariable = 2, + MappedType = 4, + ReturnType = 8, + NeverType = 16, } interface InferenceInfo { typeParameter: TypeParameter; @@ -2146,6 +2187,7 @@ declare namespace ts { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface DiagnosticMessage { key: string; @@ -2247,7 +2289,9 @@ declare namespace ts { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; + strictFunctionTypes?: boolean; strictNullChecks?: boolean; + strictPropertyInitialization?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; @@ -2293,6 +2337,7 @@ declare namespace ts { LineFeed = 1, } interface LineAndCharacter { + /** 0-based. */ line: number; character: number; } @@ -2311,8 +2356,9 @@ declare namespace ts { ES2015 = 2, ES2016 = 3, ES2017 = 4, - ESNext = 5, - Latest = 5, + ES2018 = 5, + ESNext = 6, + Latest = 6, } enum LanguageVariant { Standard = 0, @@ -2400,22 +2446,23 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", + Json = ".json", } interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModuleFull | undefined; + readonly resolvedModule: ResolvedModuleFull | undefined; } interface ResolvedTypeReferenceDirective { primary: boolean; - resolvedFileName?: string; + resolvedFileName: string | undefined; packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; - failedLookupLocations: string[]; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; - getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -2425,7 +2472,7 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ @@ -2656,7 +2703,7 @@ declare namespace ts { } } declare namespace ts { - const versionMajorMinor = "2.6"; + const versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ const version: string; } @@ -2678,14 +2725,26 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - interface System { - args: string[]; + /** + * Partial interface of the System thats needed to support the caching of directory structure + */ + interface DirectoryStructureHost { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + exit(exitCode?: number): void; + } + interface System extends DirectoryStructureHost { + args: string[]; + getFileSize?(path: string): number; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2693,13 +2752,7 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; getExecutingFilePath(): string; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2707,7 +2760,6 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; - exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; @@ -2715,17 +2767,11 @@ declare namespace ts { interface FileWatcher { close(): void; } - interface DirectoryWatcher extends FileWatcher { - directoryName: string; - referenceCount: number; - } function getNodeMajorVersion(): number; let sys: System; } declare namespace ts { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } + type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { getStartPos(): number; getToken(): SyntaxKind; @@ -2851,6 +2897,8 @@ declare namespace ts { * @returns The unescaped identifier text. */ function unescapeLeadingUnderscores(identifier: __String): string; + function idText(identifier: Identifier): string; + function symbolName(symbol: Symbol): string; /** * Remove extra underscore from escaped identifier text content. * @deprecated Use `id.text` for the unescaped text. @@ -2912,6 +2960,8 @@ declare namespace ts { function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray | undefined; + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3001,6 +3051,7 @@ declare namespace ts { function isForOfStatement(node: Node): node is ForOfStatement; function isContinueStatement(node: Node): node is ContinueStatement; function isBreakStatement(node: Node): node is BreakStatement; + function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; function isReturnStatement(node: Node): node is ReturnStatement; function isWithStatement(node: Node): node is WithStatement; function isSwitchStatement(node: Node): node is SwitchStatement; @@ -3035,6 +3086,9 @@ declare namespace ts { function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; function isJsxOpeningElement(node: Node): node is JsxOpeningElement; function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxFragment(node: Node): node is JsxFragment; + function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; + function isJsxClosingFragment(node: Node): node is JsxClosingFragment; function isJsxAttribute(node: Node): node is JsxAttribute; function isJsxAttributes(node: Node): node is JsxAttributes; function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; @@ -3104,6 +3158,8 @@ declare namespace ts { function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; + function isSetAccessor(node: Node): node is SetAccessorDeclaration; + function isGetAccessor(node: Node): node is GetAccessorDeclaration; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3133,10 +3189,11 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -3177,11 +3234,10 @@ declare namespace ts { } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; - function createLiteral(value: string): StringLiteral; + /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ + function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - /** Create a string literal whose source text is read from a source node during emit. */ - function createLiteral(sourceNode: StringLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; @@ -3256,6 +3312,7 @@ declare namespace ts { function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; @@ -3423,6 +3480,8 @@ declare namespace ts { function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; + function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function createJsxAttributes(properties: ReadonlyArray): JsxAttributes; @@ -3650,6 +3709,17 @@ declare namespace ts { declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -3661,6 +3731,7 @@ declare namespace ts { getNewLine(): string; } function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** @@ -3758,7 +3829,7 @@ declare namespace ts { getEscapedName(): __String; getName(): string; getDeclarations(): Declaration[] | undefined; - getDocumentationComment(): SymbolDisplayPart[]; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } interface Type { @@ -3773,13 +3844,15 @@ declare namespace ts { getNumberIndexType(): Type | undefined; getBaseTypes(): BaseType[] | undefined; getNonNullableType(): Type; + getConstraint(): Type | undefined; + getDefault(): Type | undefined; } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; + getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { @@ -3829,7 +3902,11 @@ declare namespace ts { interface HostCancellationToken { isCancellationRequested(): boolean; } - interface LanguageServiceHost { + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -3849,14 +3926,15 @@ declare namespace ts { readFile?(path: string, encoding?: string): string | undefined; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. */ getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; } interface LanguageService { cleanupSemanticCache(): void; @@ -3873,9 +3951,9 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; @@ -3883,6 +3961,7 @@ declare namespace ts { getRenameInfo(fileName: string, position: number): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; @@ -3904,12 +3983,27 @@ declare namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + applyCodeActionCommand(action: CodeActionCommand): Promise; + applyCodeActionCommand(action: CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; + /** @deprecated `fileName` will be ignored */ + applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } + interface GetCompletionsAtPositionOptions { + includeExternalModuleExports: boolean; + } + interface ApplyCodeActionCommandResult { + successMessage: string; + } interface Classifications { spans: number[]; endOfLineState: EndOfLineState; @@ -3974,6 +4068,14 @@ declare namespace ts { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + type CodeActionCommand = InstallPackageAction; + interface InstallPackageAction { } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. @@ -4022,6 +4124,7 @@ declare namespace ts { edits: FileTextChanges[]; renameFilename: string | undefined; renameLocation: number | undefined; + commands?: CodeActionCommand[]; } interface TextInsertion { newText: string; @@ -4133,6 +4236,10 @@ declare namespace ts { containerKind: ScriptElementKind; containerName: string; } + interface DefinitionInfoAndBoundSpan { + definitions: ReadonlyArray; + textSpan: TextSpan; + } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { displayParts: SymbolDisplayPart[]; } @@ -4236,11 +4343,14 @@ declare namespace ts { kindModifiers: string; sortText: string; /** - * An optional span that indicates the text to be replaced by this completion item. It will be - * set if the required span differs from the one generated by the default replacement behavior and should - * be used in that case + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; + hasAction?: true; + source?: string; + isRecommended?: true; } interface CompletionEntryDetails { name: string; @@ -4249,6 +4359,8 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; + codeActions?: CodeAction[]; + source?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -4263,20 +4375,11 @@ declare namespace ts { */ autoCollapse: boolean; } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, @@ -4549,7 +4652,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - const servicesVersion = "0.5"; + const servicesVersion = "0.7"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 4128b5d17fa8f..1fbae487f8038 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -34,6 +34,13 @@ var __extends = (this && this.__extends) || (function () { })(); var 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 = {})); // token > SyntaxKind.Identifer => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync var SyntaxKind; @@ -189,180 +196,184 @@ var ts; SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; + SyntaxKind[SyntaxKind["UniqueKeyword"] = 140] = "UniqueKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 141] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 142] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 143] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 144] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 145] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 146] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 147] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 148] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 149] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 150] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 151] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 152] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 153] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 154] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 155] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 156] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 157] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 158] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 159] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 160] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 161] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 162] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 163] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 164] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 165] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 166] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 167] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 168] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 169] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 170] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 171] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 172] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 173] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 174] = "LiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 175] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 176] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 177] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 178] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 179] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 180] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 181] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 182] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 183] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 184] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 185] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 186] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 187] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 188] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 189] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 190] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 191] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 192] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 193] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 194] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 195] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 196] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 197] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 198] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 199] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 200] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 201] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 202] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 203] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 204] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 205] = "MetaProperty"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 206] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 207] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 208] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 209] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 210] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 211] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 212] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 213] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 214] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 215] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 216] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 217] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 218] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 219] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 220] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 221] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 222] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 223] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 224] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 225] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 226] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 227] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 228] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 229] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 230] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 231] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 232] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 233] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 234] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 235] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 236] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 237] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 238] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 239] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 240] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 241] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 242] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 243] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 244] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 245] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 246] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 247] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 248] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 249] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 250] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 251] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 252] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 253] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 254] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 255] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 256] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 257] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 258] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 259] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 260] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 261] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 262] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 263] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 264] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 265] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 266] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 267] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 268] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; + SyntaxKind[SyntaxKind["SourceFile"] = 269] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 270] = "Bundle"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 271] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 272] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 270] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 273] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 274] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 275] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 276] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 277] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 278] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 279] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 280] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocTag"] = 281] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 282] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 283] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 284] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 285] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 286] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 287] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 288] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 289] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 290] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 291] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 292] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 293] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 294] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 295] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 296] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -371,15 +382,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 143] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 159] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 174] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 143] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -388,11 +399,13 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 144] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 271] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 289] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 281] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 289] = "LastJSDocTagNode"; + /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 143] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -427,11 +440,13 @@ var ts; /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 2097152] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 4194304] = "InWithStatement"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 6387712] = "ContextFlags"; // Exclude these flags when parsing a Type NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); @@ -483,16 +498,21 @@ var ts; GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); /* @internal */ - var NumericLiteralFlags; - (function (NumericLiteralFlags) { - NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; - NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; - NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; - NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; - NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; - })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); + var TokenFlags; + (function (TokenFlags) { + TokenFlags[TokenFlags["None"] = 0] = "None"; + TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape"; + TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific"; + TokenFlags[TokenFlags["Octal"] = 32] = "Octal"; + TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; + TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; + TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -576,6 +596,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; // even though `T` can't be accessed in the current scope. + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -658,6 +679,9 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; + SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + /* @internal */ + SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -697,7 +721,9 @@ var ts; /* @internal */ // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. - SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable"; + /* @internal */ + SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ var EnumKind; @@ -718,6 +744,7 @@ var ts; CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -776,55 +803,60 @@ var ts; TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 32768] = "Object"; - TypeFlags[TypeFlags["Union"] = 65536] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 262144] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 2048] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 8192] = "Null"; + TypeFlags[TypeFlags["Never"] = 16384] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 65536] = "Object"; + TypeFlags[TypeFlags["Union"] = 131072] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 524288] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 2097152] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsWideningType"] = 4194304] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 8388608] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 16777216] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["NonPrimitive"] = 33554432] = "NonPrimitive"; /* @internal */ - TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; + TypeFlags[TypeFlags["JsxAttributes"] = 67108864] = "JsxAttributes"; + TypeFlags[TypeFlags["MarkerType"] = 134217728] = "MarkerType"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; + TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; + TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; + TypeFlags[TypeFlags["Intrinsic"] = 33585807] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 524322] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; - TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; + TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; + TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 2064384] = "StructuredOrTypeVariable"; + TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 35620607] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 33620481] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 12582912] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + TypeFlags[TypeFlags["PropagatingFlags"] = 29360128] = "PropagatingFlags"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -838,8 +870,18 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); + /* @internal */ + var Variance; + (function (Variance) { + Variance[Variance["Invariant"] = 0] = "Invariant"; + Variance[Variance["Covariant"] = 1] = "Covariant"; + Variance[Variance["Contravariant"] = 2] = "Contravariant"; + Variance[Variance["Bivariant"] = 3] = "Bivariant"; + Variance[Variance["Independent"] = 4] = "Independent"; + })(Variance = ts.Variance || (ts.Variance = {})); var SignatureKind; (function (SignatureKind) { SignatureKind[SignatureKind["Call"] = 0] = "Call"; @@ -852,9 +894,11 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; + InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -942,8 +986,9 @@ var ts; ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; + ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; + ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; (function (LanguageVariant) { @@ -1097,6 +1142,7 @@ var ts; Extension["Dts"] = ".d.ts"; Extension["Js"] = ".js"; Extension["Jsx"] = ".jsx"; + Extension["Json"] = ".json"; })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ var TransformFlags; @@ -1226,6 +1272,9 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; + ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject"; + ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of @@ -1236,8 +1285,6 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1259,9 +1306,8 @@ var ts; (function (ts) { var performance; (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (_markName) { }; + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; var enabled = false; var profilerStart = 0; var counts; @@ -1348,7 +1394,7 @@ 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 = "2.6"; + ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); @@ -1363,18 +1409,14 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(/*locales*/ undefined, { usage: "sort", sensitivity: "accent" }) : undefined; - // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". - ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword // 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["__"]; + map.__ = undefined; + delete map.__; return map; } /** Create a new map. If a template object is provided, the map will copy entries from it. */ @@ -1411,7 +1453,7 @@ var ts; } ts.createMapFromTemplate = createMapFromTemplate; // Internet Explorer's Map doesn't support iteration, so don't use it. - // tslint:disable-next-line:no-in-operator + // tslint:disable-next-line no-in-operator variable-name var 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() { @@ -1487,12 +1529,6 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -1514,6 +1550,17 @@ var ts; return undefined; } ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1529,10 +1576,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1560,7 +1609,6 @@ var ts; return true; } ts.every = every; - /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ function find(array, predicate) { for (var i = 0; i < array.length; i++) { var value = array[i]; @@ -1571,6 +1619,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { @@ -1595,11 +1653,12 @@ var ts; Debug.fail(); } ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (equalityComparer(v, value)) { return true; } } @@ -1662,22 +1721,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1704,6 +1747,14 @@ var ts; return result; } ts.map = map; + function mapIterator(iter, mapFn) { + return { next: next }; + function next() { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + } + ts.mapIterator = mapIterator; function sameMap(array, f) { var result; if (array) { @@ -1733,8 +1784,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1780,8 +1831,14 @@ var ts; if (done) break; var res = mapfn(value); - if (res) - result.push.apply(result, res); + if (res) { + if (isArray(res)) { + result.push.apply(result, res); + } + else { + result.push(res); + } + } } return result; } @@ -1822,6 +1879,20 @@ var ts; return result; } ts.mapDefined = mapDefined; + function mapDefinedIter(iter, mapFn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapFn(value); + if (res !== undefined) { + result.push(res); + } + } + return result; + } + ts.mapDefinedIter = mapDefinedIter; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -1895,8 +1966,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1917,26 +1988,79 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. - function deduplicate(array, areEqual) { - var result; - if (array) { - result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } - } - result.push(item); - } + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } ts.deduplicate = deduplicate; - function arrayIsEqualTo(array1, array2, equaler) { + /** + * Deduplicates an array that has already been sorted. + */ + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (!array1 || !array2) { return array1 === array2; } @@ -1944,8 +2068,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { + if (!equalityComparer(array1[i], array2[i])) { return false; } } @@ -1990,34 +2113,51 @@ var ts; } ts.compact = compact; /** - * Gets the relative complement of `arrayA` with respect to `b`, returning the elements that + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted * based on the provided comparer. */ - function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { - if (comparer === void 0) { comparer = compareValues; } - if (offsetA === void 0) { offsetA = 0; } - if (offsetB === void 0) { offsetB = 0; } + function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; var result = []; - outer: for (; offsetB < arrayB.length; offsetB++) { - inner: for (; offsetA < arrayA.length; offsetA++) { + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1 /* LessThan */: break inner; - case 0 /* EqualTo */: continue outer; - case 1 /* GreaterThan */: continue inner; + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; } } - result.push(arrayB[offsetB]); } return result; } ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; // Note: we need the following type assertion because of GH #17069 result += v[prop]; } @@ -2059,15 +2199,14 @@ var ts; * @param end The offset in `from` at which to stop copying values (non-inclusive). */ function addRange(to, from, start, end) { - if (from === undefined) + if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); end = end === undefined ? from.length : toOffset(from, end); for (var i = start; i < end && i < from.length; i++) { - var v = from[i]; - if (v !== undefined) { + if (from[i] !== undefined) { to.push(from[i]); } } @@ -2077,8 +2216,8 @@ var ts; /** * @return Whether the value was added. */ - function pushIfUnique(array, toAdd) { - if (contains(array, toAdd)) { + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { return false; } else { @@ -2090,9 +2229,9 @@ var ts; /** * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. */ - function appendIfUnique(array, toAdd) { + function appendIfUnique(array, toAdd, equalityComparer) { if (array) { - pushIfUnique(array, toAdd); + pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -2100,15 +2239,54 @@ var ts; } } ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function best(iter, isBetter) { + var x = iter.next(); + if (x.done) { + return undefined; + } + var best = x.value; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return best; + } + if (isBetter(value, best)) { + best = value; + } + } + } + ts.best = best; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ function stableSort(array, comparer) { - if (comparer === void 0) { comparer = compareValues; } - return array - .map(function (_, i) { return i; }) // create array of indices - .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) // sort indices by value then position - .map(function (i) { return array[i]; }); // get sorted array + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); } ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { @@ -2142,6 +2320,11 @@ var ts; return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; /** * Returns the last element of an array if non-empty, `undefined` otherwise. */ @@ -2149,6 +2332,11 @@ var ts; return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; /** * Returns the only element of an array if it contains only one element, `undefined` otherwise. */ @@ -2171,32 +2359,35 @@ var ts; } ts.replaceElement = replaceElement; /** - * Performs a binary search, finding the index at which 'value' occurs in 'array'. + * Performs a binary search, finding the index at which `value` occurs in `array`. * If no such index is found, returns the 2's-complement of first index at which - * number[index] exceeds number. + * `array[index]` exceeds `value`. * @param array A sorted array whose first element must be no larger than number - * @param number The value to be searched for in the array. + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. */ - function binarySearch(array, value, comparer, offset) { + function binarySearch(array, value, keySelector, keyComparer, offset) { if (!array || array.length === 0) { return -1; } var low = offset || 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; + var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); - var midValue = array[middle]; - if (comparer(midValue, value) === 0) { - return middle; - } - else if (comparer(midValue, value) > 0) { - high = middle - 1; - } - else { - low = middle + 1; + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; } } return ~low; @@ -2226,30 +2417,6 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial, start, count) { - if (array) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start > size - 1 ? size - 1 : start; - var end = count === undefined || pos - count < 0 ? 0 : pos - count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos--; - } - else { - result = initial; - } - while (pos >= end) { - result = f(result, array[pos], pos); - pos--; - } - return result; - } - } - return initial; - } - ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Indicates whether a map-like contains an own property with the specified key. @@ -2357,6 +2524,7 @@ var ts; * @param right A map-like whose properties should be compared. */ function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (left === right) return true; if (!left || !right) @@ -2365,7 +2533,7 @@ var ts; if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + if (!equalityComparer(left[key], right[key])) return false; } } @@ -2380,13 +2548,22 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2455,6 +2632,17 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -2466,8 +2654,14 @@ var ts; } ts.cast = cast; /** Does nothing. */ - function noop() { } + function noop(_) { } // tslint:disable-line no-empty ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; @@ -2625,49 +2819,206 @@ var ts; return headChain; } ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ function compareValues(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + return compareComparableValues(a, b); } ts.compareValues = compareValues; - function compareStrings(a, b, ignoreCase) { + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { if (a === b) return 0 /* EqualTo */; if (a === undefined) return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; - if (ignoreCase) { - // Checking if "collator exists indicates that Intl is available. - // We still have to check if "collator.compare" is correct. If it is not, use "String.localeComapre" - if (ts.collator) { - var result = ts.localeCompareIsCorrect ? - ts.collator.compare(a, b) : - a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); // accent means a ≠ b, a ≠ á, a = A - return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - a = a.toUpperCase(); - b = b.toUpperCase(); + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { if (a === b) return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } } - return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; } - ts.compareStrings = compareStrings; - function compareStringsCaseInsensitive(a, b) { - return compareStrings(a, b, /*ignoreCase*/ true); + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } function compareDiagnostics(d1, d2) { - return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2678,14 +3029,14 @@ var ts; function compareMessageText(text1, text2) { while (text1 && text2) { // We still have both chains. - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + var string1 = isString(text1) ? text1 : text1.messageText; + var string2 = isString(text2) ? text2 : text2.messageText; + var res = compareStringsCaseSensitive(string1, string2); if (res) { return res; } - text1 = typeof text1 === "string" ? undefined : text1.next; - text2 = typeof text2 === "string" ? undefined : text2.next; + text1 = isString(text1) ? undefined : text1.next; + text2 = isString(text2) ? undefined : text2.next; } if (!text1 && !text2) { // if the chains are done, then these messages are the same. @@ -2695,26 +3046,9 @@ var ts; return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; } function sortAndDeduplicateDiagnostics(diagnostics) { - return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + return sortAndDeduplicate(diagnostics, compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function deduplicateSortedDiagnostics(diagnostics) { - if (diagnostics.length < 2) { - return diagnostics; - } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0 /* EqualTo */; - if (!isDupe) { - newDiagnostics.push(currentDiagnostic); - previousDiagnostic = currentDiagnostic; - } - } - return newDiagnostics; - } - ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; function normalizeSlashes(path) { return path.replace(/\\/g, "/"); } @@ -2737,7 +3071,6 @@ var ts; if (path.charCodeAt(1) === 58 /* colon */) { if (path.charCodeAt(2) === 47 /* slash */) return 3; - return 2; } // Per RFC 1738 'file' URI schema has the shape file:/// // if is omitted then it is assumed that host value is 'localhost', @@ -2809,7 +3142,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -2839,6 +3172,17 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2990,10 +3334,6 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; - /** - * Removes a trailing directory separator from a path. - * @param path The path. - */ function removeTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) === ts.directorySeparator) { return path.substr(0, path.length - 1); @@ -3024,8 +3364,9 @@ var ts; var aComponents = getNormalizedPathComponents(a, currentDirectory); var bComponents = getNormalizedPathComponents(b, currentDirectory); var sharedLength = Math.min(aComponents.length, bComponents.length); + var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; for (var i = 0; i < sharedLength; i++) { - var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + var result = comparer(aComponents[i], bComponents[i]); if (result !== 0 /* EqualTo */) { return result; } @@ -3047,9 +3388,9 @@ var ts; if (childComponents.length < parentComponents.length) { return false; } + var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { - var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); - if (result !== 0 /* EqualTo */) { + if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } } @@ -3069,8 +3410,16 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -3245,6 +3594,7 @@ var ts; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); + var comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive; var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var regexFlag = useCaseSensitiveFileNames ? "" : "i"; var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); @@ -3253,7 +3603,6 @@ var ts; // Associate an array of results with each include regex. This keeps results in order of the "include" order. // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -3261,7 +3610,6 @@ var ts; return flatten(results); function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - files = files.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -3279,8 +3627,8 @@ var ts; } } }; - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; + for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + var current = _b[_i]; _loop_1(current); } if (depth !== undefined) { @@ -3289,9 +3637,8 @@ var ts; return; } } - directories = directories.slice().sort(comparer); - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var current = directories_1[_b]; + for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && @@ -3320,7 +3667,7 @@ var ts; includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); @@ -3366,7 +3713,7 @@ var ts; return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; - case ".json": + case ".json" /* Json */: return 6 /* JSON */; default: return 0 /* Unknown */; @@ -3386,7 +3733,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3484,6 +3831,16 @@ var ts; return (removeFileExtension(path) + newExtension); } ts.changeExtension = changeExtension; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; function Symbol(flags, name) { this.flags = flags; this.escapedName = name; @@ -3495,8 +3852,7 @@ var ts; this.checker = checker; } } - function Signature() { - } + function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { this.id = 0; this.kind = kind; @@ -3744,6 +4100,16 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3752,8 +4118,182 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; - function assertTypeIsNever(_) { } + function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; + function createCachedDirectoryStructureHost(host) { + var cachedReadDirectoryResult = createMap(); + var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); + var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, + newLine: host.newLine, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + write: function (s) { return host.write(s); }, + writeFile: writeFile, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: createDirectory, + getCurrentDirectory: getCurrentDirectory, + getDirectories: getDirectories, + readDirectory: readDirectory, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache, + exit: function (code) { return host.exit(code); } + }; + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + } + else { + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (parentResult) { + var baseName = getBaseNameOfFileName(fileOrDirectory); + if (parentResult) { + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + } + } + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; })(ts || (ts = {})); /// var ts; @@ -3792,12 +4332,13 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { + var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); // One file can have multiple watchers @@ -3820,7 +4361,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3842,7 +4383,7 @@ var ts; } function fileEventHandler(eventName, relativeFileName, baseDirPath) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = typeof relativeFileName !== "string" + var fileName = !ts.isString(relativeFileName) ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations @@ -3877,6 +4418,82 @@ var ts; } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { + return; + } + callback(fileName, eventKind); + } + } + function fsWatchDirectory(directoryName, callback, recursive) { + var options; + /** Watcher for the directory depending on whether it is missing or present */ + var watcher = !directoryExists(directoryName) ? + watchMissingDirectory() : + watchPresentDirectory(); + return { + close: function () { + // Close the watcher (either existing directory watcher or missing directory watcher) + watcher.close(); + } + }; + /** + * Watch the directory that is currently present + * and when the watched directory is deleted, switch to missing directory watcher + */ + function watchPresentDirectory() { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + var dirWatcher = _fs.watch(directoryName, options, callback); + dirWatcher.on("error", function () { + if (!directoryExists(directoryName)) { + // Deleting directory + watcher = watchMissingDirectory(); + // Call the callback for current directory + callback("rename", ""); + } + }); + return dirWatcher; + } + /** + * Watch the directory that is missing + * and switch to existing directory when the directory is created + */ + function watchMissingDirectory() { + return fsWatchFile(directoryName, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { + watcher.close(); + watcher = watchPresentDirectory(); + // Call the callback for current directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + callback("rename", ""); + } + }); + } + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -3908,7 +4525,7 @@ var ts; function writeFile(fileName, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } var fd; try { @@ -3983,7 +4600,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } - var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -4001,42 +4617,13 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); - return { - close: function () { return _fs.unwatchFile(fileName, fileChanged); } - }; - } - function fileChanged(curr, prev) { - var isCurrZero = +curr.mtime === 0; - var isPrevZero = +prev.mtime === 0; - var created = !isCurrZero && isPrevZero; - var deleted = isCurrZero && !isPrevZero; - var eventKind = created - ? FileWatcherEventKind.Created - : deleted - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { - return; - } - callback(fileName, eventKind); + return fsWatchFile(fileName, callback, pollingInterval); } }, watchDirectory: function (directoryName, callback, recursive) { // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - var options; - if (!directoryExists(directoryName)) { - // do nothing if target folder does not exist - return noOpFileWatcher; - } - if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - return _fs.watch(directoryName, options, function (eventName, relativeFileName) { + return fsWatchDirectory(directoryName, function (eventName, relativeFileName) { // In watchDirectory we only care about adding and removing files (when event name is // "rename"); changes made within files are handled by corresponding fileWatchers (when // event name is "change") @@ -4044,7 +4631,7 @@ var ts; // When deleting a file, the passed baseFileName is null callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); } - }); + }, recursive); }, resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, @@ -4091,7 +4678,7 @@ var ts; return stat.size; } } - catch (e) { } + catch (_a) { } return 0; }, exit: function (exitCode) { @@ -4105,7 +4692,7 @@ var ts; try { require("source-map-support").install(); } - catch (e) { + catch (_a) { // Could not enable source maps. } }, @@ -4128,7 +4715,7 @@ var ts; writeFile: function (path, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } ChakraHost.writeFile(path, data); }, @@ -4150,7 +4737,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -4190,6 +4777,7 @@ var ts; } })(ts || (ts = {})); // +// generated from './diagnosticInformationMap.generated.ts' by '../../scripts/processDiagnosticMessages.js' /// /* @internal */ var ts; @@ -4197,6 +4785,7 @@ var ts; function diag(code, category, key, message) { return { code: code, category: category, key: key, message: message }; } + // tslint:disable-next-line variable-name ts.Diagnostics = { Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), @@ -4321,11 +4910,11 @@ var ts; An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), @@ -4406,6 +4995,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "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."), @@ -4425,6 +5015,13 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4626,7 +5223,7 @@ var ts; No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), - Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), @@ -4642,7 +5239,7 @@ var ts; await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), @@ -4671,14 +5268,16 @@ var ts; Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), - Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4752,6 +5351,11 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "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."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4775,16 +5379,16 @@ var ts; Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), @@ -4827,6 +5431,14 @@ var ts; Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4855,6 +5467,7 @@ var ts; File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -4868,7 +5481,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -4970,7 +5583,6 @@ var ts; Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), - The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), @@ -5026,6 +5638,8 @@ var ts; Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), 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."), @@ -5075,6 +5689,13 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5092,37 +5713,50 @@ var ts; super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), - Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), - Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), - Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), - Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), - Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), - Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), - Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), - Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), - Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), - Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), - Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), - Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), - Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), - Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), - Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), + Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), }; })(ts || (ts = {})); /// @@ -5134,6 +5768,11 @@ var ts; return token >= 71 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + /* @internal */ + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; var textToToken = ts.createMapFromTemplate({ "abstract": 117 /* AbstractKeyword */, "any": 119 /* AnyKeyword */, @@ -5158,7 +5797,7 @@ var ts; "false": 86 /* FalseKeyword */, "finally": 87 /* FinallyKeyword */, "for": 88 /* ForKeyword */, - "from": 140 /* FromKeyword */, + "from": 141 /* FromKeyword */, "function": 89 /* FunctionKeyword */, "get": 125 /* GetKeyword */, "if": 90 /* IfKeyword */, @@ -5183,7 +5822,7 @@ var ts; "public": 114 /* PublicKeyword */, "readonly": 131 /* ReadonlyKeyword */, "require": 132 /* RequireKeyword */, - "global": 141 /* GlobalKeyword */, + "global": 142 /* GlobalKeyword */, "return": 96 /* ReturnKeyword */, "set": 135 /* SetKeyword */, "static": 115 /* StaticKeyword */, @@ -5198,6 +5837,7 @@ var ts; "type": 138 /* TypeKeyword */, "typeof": 103 /* TypeOfKeyword */, "undefined": 139 /* UndefinedKeyword */, + "unique": 140 /* UniqueKeyword */, "var": 104 /* VarKeyword */, "void": 105 /* VoidKeyword */, "while": 106 /* WhileKeyword */, @@ -5205,7 +5845,7 @@ var ts; "yield": 116 /* YieldKeyword */, "async": 120 /* AsyncKeyword */, "await": 121 /* AwaitKeyword */, - "of": 142 /* OfKeyword */, + "of": 143 /* OfKeyword */, "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, @@ -5417,7 +6057,7 @@ var ts; * We assume the first line starts at position 0 and 'position' is non-negative. */ function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position); + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); if (lineNumber < 0) { // If the actual position was not found, // the binary search returns the 2's-complement of the next line start @@ -5835,10 +6475,7 @@ var ts; var tokenPos; var token; var tokenValue; - var precedingLineBreak; - var hasExtendedUnicodeEscape; - var tokenIsUnterminated; - var numericLiteralFlags; + var tokenFlags; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -5847,12 +6484,12 @@ var ts; getTokenPos: function () { return tokenPos; }, getTokenText: function () { return text.substring(tokenPos, pos); }, getTokenValue: function () { return tokenValue; }, - hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, - hasPrecedingLineBreak: function () { return precedingLineBreak; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; }, isIdentifier: function () { return token === 71 /* Identifier */ || token > 107 /* LastReservedWord */; }, isReservedWord: function () { return token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */; }, - isUnterminated: function () { return tokenIsUnterminated; }, - getNumericLiteralFlags: function () { return numericLiteralFlags; }, + isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, @@ -5889,7 +6526,7 @@ var ts; var end = pos; if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { pos++; - numericLiteralFlags = 2 /* Scientific */; + tokenFlags |= 16 /* Scientific */; if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; if (isDigit(text.charCodeAt(pos))) { @@ -5950,8 +6587,8 @@ var ts; } return value; } - function scanString(allowEscapes) { - if (allowEscapes === void 0) { allowEscapes = true; } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -5959,7 +6596,7 @@ var ts; while (true) { if (pos >= end) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -5969,15 +6606,15 @@ var ts; pos++; break; } - if (ch === 92 /* backslash */ && allowEscapes) { + if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; continue; } - if (isLineBreak(ch)) { + if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -5998,7 +6635,7 @@ var ts; while (true) { if (pos >= end) { contents += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_template_literal); resultingToken = startedWithBacktick ? 13 /* NoSubstitutionTemplateLiteral */ : 16 /* TemplateTail */; break; @@ -6073,7 +6710,7 @@ var ts; case 117 /* u */: // '\u{DDDDDDDD}' if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { - hasExtendedUnicodeEscape = true; + tokenFlags |= 8 /* ExtendedUnicodeEscape */; pos++; return scanExtendedUnicodeEscape(); } @@ -6222,10 +6859,7 @@ var ts; } function scan() { startPos = pos; - hasExtendedUnicodeEscape = false; - precedingLineBreak = false; - tokenIsUnterminated = false; - numericLiteralFlags = 0; + tokenFlags = 0; while (true) { tokenPos = pos; if (pos >= end) { @@ -6245,7 +6879,7 @@ var ts; switch (ch) { case 10 /* lineFeed */: case 13 /* carriageReturn */: - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; if (skipTrivia) { pos++; continue; @@ -6373,6 +7007,9 @@ var ts; // Multi-line comment if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { pos += 2; + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } var commentClosed = false; while (pos < end) { var ch_1 = text.charCodeAt(pos); @@ -6382,7 +7019,7 @@ var ts; break; } if (isLineBreak(ch_1)) { - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; } pos++; } @@ -6393,7 +7030,9 @@ var ts; continue; } else { - tokenIsUnterminated = !commentClosed; + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } return token = 3 /* MultiLineCommentTrivia */; } } @@ -6411,7 +7050,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 8 /* HexSpecifier */; + tokenFlags |= 64 /* HexSpecifier */; return token = 8 /* NumericLiteral */; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { @@ -6422,7 +7061,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 16 /* BinarySpecifier */; + tokenFlags |= 128 /* BinarySpecifier */; return token = 8 /* NumericLiteral */; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { @@ -6433,13 +7072,13 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 32 /* OctalSpecifier */; + tokenFlags |= 256 /* OctalSpecifier */; return token = 8 /* NumericLiteral */; } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); - numericLiteralFlags = 4 /* Octal */; + tokenFlags |= 32 /* Octal */; return token = 8 /* NumericLiteral */; } // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero @@ -6593,7 +7232,7 @@ var ts; continue; } else if (isLineBreak(ch)) { - precedingLineBreak = true; + tokenFlags |= 1 /* PrecedingLineBreak */; pos++; continue; } @@ -6634,13 +7273,13 @@ var ts; // If we reach the end of a file, or hit a newline, then this is an unterminated // regex. Report error and return what we have so far. if (p >= end) { - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } var ch = text.charCodeAt(p); if (isLineBreak(ch)) { - tokenIsUnterminated = true; + tokenFlags |= 4 /* Unterminated */; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } @@ -6760,7 +7399,7 @@ var ts; switch (text.charCodeAt(pos)) { case 34 /* doubleQuote */: case 39 /* singleQuote */: - tokenValue = scanString(/*allowEscapes*/ false); + tokenValue = scanString(/*jsxAttributeString*/ true); return token = 9 /* StringLiteral */; default: // If this scans anything other than `{`, it's a parse error. @@ -6805,6 +7444,12 @@ var ts; case 93 /* closeBracket */: pos++; return token = 22 /* CloseBracketToken */; + case 60 /* lessThan */: + pos++; + return token = 27 /* LessThanToken */; + case 62 /* greaterThan */: + pos++; + return token = 29 /* GreaterThanToken */; case 61 /* equals */: pos++; return token = 58 /* EqualsToken */; @@ -6813,13 +7458,24 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: pos++; + if (text.substr(tokenPos, pos + 2) === "...") { + pos += 2; + return token = 24 /* DotDotDotToken */; + } return token = 23 /* DotToken */; + case 33 /* exclamation */: + pos++; + return token = 51 /* ExclamationToken */; + case 63 /* question */: + pos++; + return token = 55 /* QuestionToken */; } - if (isIdentifierStart(ch, 5 /* Latest */)) { + if (isIdentifierStart(ch, 6 /* Latest */)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 5 /* Latest */) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } + tokenValue = text.substring(tokenPos, pos); return token = 71 /* Identifier */; } else { @@ -6832,7 +7488,7 @@ var ts; var saveTokenPos = tokenPos; var saveToken = token; var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; + var saveTokenFlags = tokenFlags; var result = callback(); // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. @@ -6842,7 +7498,7 @@ var ts; tokenPos = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; - precedingLineBreak = savePrecedingLineBreak; + tokenFlags = saveTokenFlags; } return result; } @@ -6852,10 +7508,8 @@ var ts; var saveStartPos = startPos; var saveTokenPos = tokenPos; var saveToken = token; - var savePrecedingLineBreak = precedingLineBreak; var saveTokenValue = tokenValue; - var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - var saveTokenIsUnterminated = tokenIsUnterminated; + var saveTokenFlags = tokenFlags; setText(text, start, length); var result = callback(); end = saveEnd; @@ -6863,10 +7517,8 @@ var ts; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; - precedingLineBreak = savePrecedingLineBreak; tokenValue = saveTokenValue; - hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; - tokenIsUnterminated = saveTokenIsUnterminated; + tokenFlags = saveTokenFlags; return result; } function lookAhead(callback) { @@ -6898,10 +7550,8 @@ var ts; startPos = textPos; tokenPos = textPos; token = 0 /* Unknown */; - precedingLineBreak = false; tokenValue = undefined; - hasExtendedUnicodeEscape = false; - tokenIsUnterminated = false; + tokenFlags = 0; } } ts.createScanner = createScanner; @@ -6948,6 +7598,7 @@ var ts; clear: function () { return str = ""; }, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; } @@ -7038,7 +7689,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 265 /* SourceFile */) { + while (node && node.kind !== 269 /* SourceFile */) { node = node.parent; } return node; @@ -7046,11 +7697,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 207 /* Block */: - case 235 /* CaseBlock */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 208 /* Block */: + case 236 /* CaseBlock */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return true; } return false; @@ -7159,7 +7810,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 290 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -7193,19 +7844,17 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } /** * Note: it is expected that the `nodeArray` and the `node` are within the same file. * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. */ function indexOfNode(nodeArray, node) { - return ts.binarySearch(nodeArray, node, compareNodePos); + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } ts.indexOfNode = indexOfNode; - function compareNodePos(_a, _b) { - var aPos = _a.pos; - var bPos = _b.pos; - return aPos < bPos ? -1 /* LessThan */ : bPos < aPos ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } /** * Gets flags that control emit behavior of a node. */ @@ -7234,8 +7883,10 @@ var ts; case 13 /* NoSubstitutionTemplateLiteral */: return "`" + escapeText(node.text, 96 /* backtick */) + "`"; case 14 /* TemplateHead */: + // tslint:disable-next-line no-invalid-template-strings return "`" + escapeText(node.text, 96 /* backtick */) + "${"; case 15 /* TemplateMiddle */: + // tslint:disable-next-line no-invalid-template-strings return "}" + escapeText(node.text, 96 /* backtick */) + "${"; case 16 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; @@ -7247,7 +7898,7 @@ var ts; } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { - return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' @@ -7276,15 +7927,18 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 226 /* VariableDeclaration */ && node.parent.kind === 260 /* CatchClause */; + return node.kind === 227 /* VariableDeclaration */ && node.parent.kind === 264 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 233 /* ModuleDeclaration */ && + return node && node.kind === 234 /* ModuleDeclaration */ && (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - /* @internal */ + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 9 /* StringLiteral */; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } @@ -7296,11 +7950,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 233 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 234 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 /* SourceFile */ || - node.kind === 233 /* ModuleDeclaration */ || + return node.kind === 269 /* SourceFile */ || + node.kind === 234 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -7316,37 +7970,36 @@ var ts; return false; } switch (node.parent.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: return ts.isExternalModule(node.parent); - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; - /* @internal */ function isBlockScope(node, parentNode) { switch (node.kind) { - case 265 /* SourceFile */: - case 235 /* CaseBlock */: - case 260 /* CatchClause */: - case 233 /* ModuleDeclaration */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 269 /* SourceFile */: + case 236 /* CaseBlock */: + case 264 /* CatchClause */: + case 234 /* ModuleDeclaration */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; - case 207 /* Block */: + case 208 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return parentNode && !ts.isFunctionLike(parentNode); @@ -7356,25 +8009,25 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 273 /* JSDocFunctionType */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 282 /* JSDocTemplateTag */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 287 /* JSDocTemplateTag */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; default: ts.assertTypeIsNever(node); @@ -7382,6 +8035,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -7412,7 +8075,7 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: if (isStringOrNumericLiteral(name.expression)) { return escapeLeadingUnderscores(name.expression.text); } @@ -7423,22 +8086,22 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71 /* Identifier */: - return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); - case 143 /* QualifiedName */: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 144 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); } } ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { @@ -7463,7 +8126,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207 /* Block */) { + if (node.body && node.body.kind === 208 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -7477,7 +8140,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -7486,23 +8149,23 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 231 /* TypeAliasDeclaration */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 232 /* TypeAliasDeclaration */: errorNode = node.name; break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -7521,7 +8184,7 @@ var ts; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isConstEnumDeclaration(node) { - return node.kind === 232 /* EnumDeclaration */ && isConst(node); + return node.kind === 233 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -7534,15 +8197,15 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 181 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 182 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 181 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 182 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isPrologueDirective(node) { - return node.kind === 210 /* ExpressionStatement */ + return node.kind === 211 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -7551,11 +8214,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 /* Parameter */ || - node.kind === 145 /* TypeParameter */ || - node.kind === 186 /* FunctionExpression */ || - node.kind === 187 /* ArrowFunction */ || - node.kind === 185 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 147 /* Parameter */ || + node.kind === 146 /* TypeParameter */ || + node.kind === 187 /* FunctionExpression */ || + node.kind === 188 /* ArrowFunction */ || + node.kind === 186 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -7571,7 +8234,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (158 /* FirstTypeNode */ <= node.kind && node.kind <= 173 /* LastTypeNode */) { + if (159 /* FirstTypeNode */ <= node.kind && node.kind <= 174 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -7584,27 +8247,27 @@ var ts; case 130 /* NeverKeyword */: return true; case 105 /* VoidKeyword */: - return node.parent.kind !== 190 /* VoidExpression */; - case 201 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 191 /* VoidExpression */; + case 202 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 71 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 143 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */ || node.kind === 179 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */ || node.kind === 180 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 143 /* QualifiedName */: - case 179 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: case 99 /* ThisKeyword */: var parent = node.parent; - if (parent.kind === 162 /* TypeQuery */) { + if (parent.kind === 163 /* TypeQuery */) { return false; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -7613,38 +8276,38 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (158 /* FirstTypeNode */ <= parent.kind && parent.kind <= 173 /* LastTypeNode */) { + if (159 /* FirstTypeNode */ <= parent.kind && parent.kind <= 174 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return node === parent.constraint; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 146 /* Parameter */: - case 226 /* VariableDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 147 /* Parameter */: + case 227 /* VariableDeclaration */: return node === parent.type; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return node === parent.type; - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return node === parent.type; - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return node === parent.type; - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -7668,23 +8331,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitor(node); - case 235 /* CaseBlock */: - case 207 /* Block */: - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 220 /* WithStatement */: - case 221 /* SwitchStatement */: - case 257 /* CaseClause */: - case 258 /* DefaultClause */: - case 222 /* LabeledStatement */: - case 224 /* TryStatement */: - case 260 /* CatchClause */: + case 236 /* CaseBlock */: + case 208 /* Block */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 221 /* WithStatement */: + case 222 /* SwitchStatement */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -7694,19 +8357,19 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 232 /* EnumDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -7714,7 +8377,7 @@ var ts; default: if (ts.isFunctionLike(node)) { var name = node.name; - if (name && name.kind === 144 /* ComputedPropertyName */) { + if (name && name.kind === 145 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(name.expression); @@ -7737,10 +8400,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 164 /* ArrayType */) { + if (node && node.kind === 165 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 159 /* TypeReference */) { + else if (node && node.kind === 160 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -7748,32 +8411,55 @@ var ts; } } ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 231 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 164 /* TypeLiteral */: + return node.members; + case 179 /* ObjectLiteralExpression */: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; function isVariableLike(node) { if (node) { switch (node.kind) { - case 176 /* BindingElement */: - case 264 /* EnumMember */: - case 146 /* Parameter */: - case 261 /* PropertyAssignment */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 262 /* ShorthandPropertyAssignment */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 268 /* EnumMember */: + case 147 /* Parameter */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 266 /* ShorthandPropertyAssignment */: + case 227 /* VariableDeclaration */: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 228 /* VariableDeclarationList */ + && node.parent.parent.kind === 209 /* VariableStatement */; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return true; } return false; @@ -7784,7 +8470,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 222 /* LabeledStatement */) { + if (node.statement.kind !== 223 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -7792,17 +8478,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 208 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 151 /* MethodDeclaration */ && node.parent.kind === 178 /* ObjectLiteralExpression */; + return node && node.kind === 152 /* MethodDeclaration */ && node.parent.kind === 179 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 /* MethodDeclaration */ && - (node.parent.kind === 178 /* ObjectLiteralExpression */ || - node.parent.kind === 199 /* ClassExpression */); + return node.kind === 152 /* MethodDeclaration */ && + (node.parent.kind === 179 /* ObjectLiteralExpression */ || + node.parent.kind === 200 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -7815,7 +8501,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 261 /* PropertyAssignment */) { + if (property.kind === 265 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); } @@ -7837,7 +8523,7 @@ var ts; return undefined; } switch (node.kind) { - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -7852,9 +8538,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 147 /* Decorator */: + case 148 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 147 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -7865,26 +8551,26 @@ var ts; node = node.parent; } break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 233 /* ModuleDeclaration */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 232 /* EnumDeclaration */: - case 265 /* SourceFile */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 234 /* ModuleDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 233 /* EnumDeclaration */: + case 269 /* SourceFile */: return node; } } @@ -7894,9 +8580,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return container; } } @@ -7918,27 +8604,27 @@ var ts; return node; } switch (node.kind) { - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: node = node.parent; break; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return node; - case 147 /* Decorator */: + case 148 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 147 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -7954,45 +8640,54 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */) { + if (func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 185 /* ParenthesizedExpression */) { + while (parent.kind === 186 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 181 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 182 /* CallExpression */ && parent.expression === prev) { return parent; } } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; /** - * Determines whether a node is a property or element access expression for super. + * Determines whether a node is a property or element access expression for `super`. */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 179 /* PropertyAccessExpression */ || kind === 180 /* ElementAccessExpression */) + return (kind === 180 /* PropertyAccessExpression */ || kind === 181 /* ElementAccessExpression */) && node.expression.kind === 97 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; + /** + * Determines whether a node is a property or element access expression for `this`. + */ + function isThisProperty(node) { + var kind = node.kind; + return (kind === 180 /* PropertyAccessExpression */ || kind === 181 /* ElementAccessExpression */) + && node.expression.kind === 99 /* ThisKeyword */; + } + ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return node.typeName; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71 /* Identifier */: - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { return node.tag; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -8002,105 +8697,106 @@ var ts; return node.expression; } ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { + function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: // classes are valid targets return true; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 229 /* ClassDeclaration */; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: + return parent.kind === 230 /* ClassDeclaration */; + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && node.parent.kind === 229 /* ClassDeclaration */; - case 146 /* Parameter */: + && parent.kind === 230 /* ClassDeclaration */; + case 147 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; - return node.parent.body !== undefined - && (node.parent.kind === 152 /* Constructor */ - || node.parent.kind === 151 /* MethodDeclaration */ - || node.parent.kind === 154 /* SetAccessor */) - && node.parent.parent.kind === 229 /* ClassDeclaration */; + return parent.body !== undefined + && (parent.kind === 153 /* Constructor */ + || parent.kind === 152 /* MethodDeclaration */ + || parent.kind === 155 /* SetAccessor */) + && grandparent.kind === 230 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { + function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node); + && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { + function childIsDecorated(node, parent) { switch (node.kind) { - case 229 /* ClassDeclaration */: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151 /* MethodDeclaration */: - case 154 /* SetAccessor */: - return ts.forEach(node.parameters, nodeIsDecorated); + case 230 /* ClassDeclaration */: + return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 152 /* MethodDeclaration */: + case 155 /* SetAccessor */: + return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 251 /* JsxOpeningElement */ || - parent.kind === 250 /* JsxSelfClosingElement */ || - parent.kind === 252 /* JsxClosingElement */) { + if (parent.kind === 252 /* JsxOpeningElement */ || + parent.kind === 251 /* JsxSelfClosingElement */ || + parent.kind === 253 /* JsxClosingElement */) { return parent.tagName === node; } return false; } ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { + function isExpressionNode(node) { switch (node.kind) { case 97 /* SuperKeyword */: case 95 /* NullKeyword */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 12 /* RegularExpressionLiteral */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 183 /* TaggedTemplateExpression */: - case 202 /* AsExpression */: - case 184 /* TypeAssertionExpression */: - case 203 /* NonNullExpression */: - case 185 /* ParenthesizedExpression */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: - case 187 /* ArrowFunction */: - case 190 /* VoidExpression */: - case 188 /* DeleteExpression */: - case 189 /* TypeOfExpression */: - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: - case 194 /* BinaryExpression */: - case 195 /* ConditionalExpression */: - case 198 /* SpreadElement */: - case 196 /* TemplateExpression */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 184 /* TaggedTemplateExpression */: + case 203 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 204 /* NonNullExpression */: + case 186 /* ParenthesizedExpression */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 195 /* BinaryExpression */: + case 196 /* ConditionalExpression */: + case 199 /* SpreadElement */: + case 197 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: - case 200 /* OmittedExpression */: - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 197 /* YieldExpression */: - case 191 /* AwaitExpression */: - case 204 /* MetaProperty */: + case 201 /* OmittedExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 198 /* YieldExpression */: + case 192 /* AwaitExpression */: + case 205 /* MetaProperty */: return true; - case 143 /* QualifiedName */: - while (node.parent.kind === 143 /* QualifiedName */) { + case 144 /* QualifiedName */: + while (node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 162 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 163 /* TypeQuery */ || isJSXTagName(node); case 71 /* Identifier */: - if (node.parent.kind === 162 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 163 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -8112,59 +8808,59 @@ var ts; return false; } } - ts.isPartOfExpression = isPartOfExpression; + ts.isExpressionNode = isExpressionNode; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 264 /* EnumMember */: - case 261 /* PropertyAssignment */: - case 176 /* BindingElement */: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 268 /* EnumMember */: + case 265 /* PropertyAssignment */: + case 177 /* BindingElement */: return parent.initializer === node; - case 210 /* ExpressionStatement */: - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 219 /* ReturnStatement */: - case 220 /* WithStatement */: - case 221 /* SwitchStatement */: - case 257 /* CaseClause */: - case 223 /* ThrowStatement */: + case 211 /* ExpressionStatement */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 220 /* ReturnStatement */: + case 221 /* WithStatement */: + case 222 /* SwitchStatement */: + case 261 /* CaseClause */: + case 224 /* ThrowStatement */: return parent.expression === node; - case 214 /* ForStatement */: + case 215 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 228 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 228 /* VariableDeclarationList */) || forInStatement.expression === node; - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return node === parent.expression; - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return node === parent.expression; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return node === parent.expression; - case 147 /* Decorator */: - case 256 /* JsxExpression */: - case 255 /* JsxSpreadAttribute */: - case 263 /* SpreadAssignment */: + case 148 /* Decorator */: + case 260 /* JsxExpression */: + case 259 /* JsxSpreadAttribute */: + case 267 /* SpreadAssignment */: return true; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: - return isPartOfExpression(parent); + return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */; + return node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 249 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -8173,7 +8869,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 248 /* ExternalModuleReference */; + return node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 249 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -8188,13 +8884,21 @@ var ts; return node && !!(node.flags & 1048576 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). * This function does not test if the node is in a JavaScript file or not. */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181 /* CallExpression */) { + if (callExpression.kind !== 182 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -8212,14 +8916,18 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; /** - * Returns true if the node is a variable declaration whose initializer is a function expression. + * Returns true if the node is a variable declaration whose initializer is a function or class expression. * This function does not test if the node is in a JavaScript file or not. */ function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226 /* VariableDeclaration */) { + if (s.valueDeclaration && s.valueDeclaration.kind === 227 /* VariableDeclaration */) { var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 /* FunctionExpression */ || declaration.initializer.kind === 199 /* ClassExpression */); + return declaration.initializer && (declaration.initializer.kind === 187 /* FunctionExpression */ || declaration.initializer.kind === 200 /* ClassExpression */); } return false; } @@ -8241,12 +8949,11 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { + function getSpecialPropertyAssignmentKind(expr) { + if (!isInJavaScriptFile(expr)) { return 0 /* None */; } - var expr = expression; - if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 179 /* PropertyAccessExpression */) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || expr.left.kind !== 180 /* PropertyAccessExpression */) { return 0 /* None */; } var lhs = expr.left; @@ -8268,7 +8975,7 @@ var ts; else if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } - else if (lhs.expression.kind === 179 /* PropertyAccessExpression */) { + else if (lhs.expression.kind === 180 /* PropertyAccessExpression */) { // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71 /* Identifier */) { @@ -8285,36 +8992,42 @@ var ts; return 0 /* None */; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isSpecialPropertyDeclaration(expr) { + return isInJavaScriptFile(expr) && + expr.parent && expr.parent.kind === 211 /* ExpressionStatement */ && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function getExternalModuleName(node) { - if (node.kind === 238 /* ImportDeclaration */) { + if (node.kind === 239 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 237 /* ImportEqualsDeclaration */) { + if (node.kind === 238 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 248 /* ExternalModuleReference */) { + if (reference.kind === 249 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 244 /* ExportDeclaration */) { + if (node.kind === 245 /* ExportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 233 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + if (isModuleWithStringLiteralName(node)) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 237 /* ImportEqualsDeclaration */) { + if (node.kind === 238 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 241 /* NamespaceImport */) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 238 /* ImportDeclaration */ + return node.kind === 239 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } @@ -8322,13 +9035,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 146 /* Parameter */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 262 /* ShorthandPropertyAssignment */: - case 261 /* PropertyAssignment */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 147 /* Parameter */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 266 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -8336,7 +9049,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 273 /* JSDocFunctionType */ && + return node.kind === 277 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; @@ -8349,45 +9062,62 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 58 /* EqualsToken */ && + node.expression.right; + } + ts.getSourceOfAssignment = getSourceOfAssignment; + function getSingleInitializerOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0].initializer === child) && + node.declarationList.declarations[0].initializer; + } + ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; + function getSingleVariableOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0] === child) && + node.declarationList.declarations[0]; + } + ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; + function getNestedModuleDeclaration(node) { + return node.kind === 234 /* ModuleDeclaration */ && + node.body && + node.body.kind === 234 /* ModuleDeclaration */ && + node.body; + } + ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; + if (parent && (parent.kind === 265 /* PropertyAssignment */ || getNestedModuleDeclaration(parent))) { + getJSDocCommentsAndTagsWorker(parent); + } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** // * @param {number} name // * @returns {number} // */ // var x = function(name) { return name.length; } - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208 /* VariableStatement */; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208 /* VariableStatement */; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocCommentsAndTagsWorker(variableStatementNode); - } - // Also recognize when the node is the RHS of an assignment expression - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 /* BinaryExpression */ && - parent.operatorToken.kind === 58 /* EqualsToken */ && - parent.parent.kind === 210 /* ExpressionStatement */; - if (isSourceOfAssignmentExpressionStatement) { + if (parent && parent.parent && + (getSingleVariableOfVariableStatement(parent.parent, node) || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - var isModuleDeclaration = node.kind === 233 /* ModuleDeclaration */ && - parent && parent.kind === 233 /* ModuleDeclaration */; - var isPropertyAssignmentExpression = parent && parent.kind === 261 /* PropertyAssignment */; - if (isModuleDeclaration || isPropertyAssignmentExpression) { + if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatement(parent.parent.parent, node)) { + getJSDocCommentsAndTagsWorker(parent.parent.parent); + } + if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || + node.kind === 180 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 211 /* ExpressionStatement */) { getJSDocCommentsAndTagsWorker(parent); } // Pull parameter comments from declaring function as well - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { @@ -8408,17 +9138,29 @@ var ts; return undefined; } var name = node.name.escapedText; - ts.Debug.assert(node.parent.kind === 275 /* JSDocComment */); - var func = node.parent.parent; - if (!ts.isFunctionLike(func)) { + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { return undefined; } - var parameter = ts.find(func.parameters, function (p) { - return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; - }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + var host = getJSDocHost(node); + var decl = getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatement(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getJSDocHost(node) { + ts.Debug.assert(node.parent.kind === 279 /* JSDocComment */); + return node.parent.parent; + } + ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { var name = node.name.escapedText; var typeParameters = node.parent.parent.parent.typeParameters; @@ -8426,27 +9168,14 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; var AssignmentKind; (function (AssignmentKind) { AssignmentKind[AssignmentKind["None"] = 0] = "None"; @@ -8457,30 +9186,30 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 185 /* ParenthesizedExpression */: - case 177 /* ArrayLiteralExpression */: - case 198 /* SpreadElement */: + case 186 /* ParenthesizedExpression */: + case 178 /* ArrayLiteralExpression */: + case 199 /* SpreadElement */: node = parent; break; - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -8501,16 +9230,27 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 169 /* ParenthesizedType */); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 186 /* ParenthesizedExpression */); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { + if (node.kind !== 180 /* PropertyAccessExpression */ && node.kind !== 181 /* ElementAccessExpression */) { return false; } - node = node.parent; - while (node && node.kind === 185 /* ParenthesizedExpression */) { - node = node.parent; - } - return node && node.kind === 188 /* DeleteExpression */; + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 189 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -8522,16 +9262,6 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2 /* Ambient */) || (node.kind === 265 /* SourceFile */ && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; // True if the given identifier, string literal, or number literal is the name of a declaration node function isDeclarationName(name) { switch (name.kind) { @@ -8544,7 +9274,6 @@ var ts; } } ts.isDeclarationName = isDeclarationName; - /* @internal */ // See GH#16030 function isAnyDeclarationName(name) { switch (name.kind) { @@ -8563,7 +9292,7 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 144 /* ComputedPropertyName */ && + node.parent.kind === 145 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -8571,32 +9300,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 264 /* EnumMember */: - case 261 /* PropertyAssignment */: - case 179 /* PropertyAccessExpression */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 268 /* EnumMember */: + case 265 /* PropertyAssignment */: + case 180 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 143 /* QualifiedName */) { + while (parent.kind === 144 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 162 /* TypeQuery */; + return parent.kind === 163 /* TypeQuery */; } return false; - case 176 /* BindingElement */: - case 242 /* ImportSpecifier */: + case 177 /* BindingElement */: + case 243 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 246 /* ExportSpecifier */: - case 253 /* JsxAttribute */: + case 247 /* ExportSpecifier */: + case 257 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -8612,13 +9341,13 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */ || - node.kind === 236 /* NamespaceExportDeclaration */ || - node.kind === 239 /* ImportClause */ && !!node.name || - node.kind === 240 /* NamespaceImport */ || - node.kind === 242 /* ImportSpecifier */ || - node.kind === 246 /* ExportSpecifier */ || - node.kind === 243 /* ExportAssignment */ && exportAssignmentIsAlias(node); + return node.kind === 238 /* ImportEqualsDeclaration */ || + node.kind === 237 /* NamespaceExportDeclaration */ || + node.kind === 240 /* ImportClause */ && !!node.name || + node.kind === 241 /* NamespaceImport */ || + node.kind === 243 /* ImportSpecifier */ || + node.kind === 247 /* ExportSpecifier */ || + node.kind === 244 /* ExportAssignment */ && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -8702,9 +9431,22 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 142 /* LastKeyword */; + return 72 /* FirstKeyword */ <= token && token <= 143 /* LastKeyword */; } ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 117 /* FirstContextualKeyword */ <= token && token <= 143 /* LastContextualKeyword */; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } @@ -8723,14 +9465,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -8744,10 +9486,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -8774,7 +9516,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 144 /* ComputedPropertyName */ && + return name.kind === 145 /* ComputedPropertyName */ && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -8795,11 +9537,10 @@ var ts; if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.escapedText; - return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(nameExpression.text); @@ -8811,7 +9552,7 @@ var ts; function getTextOfIdentifierOrLiteral(node) { if (node) { if (node.kind === 71 /* Identifier */) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { @@ -8851,11 +9592,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 146 /* Parameter */; + return root.kind === 147 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 176 /* BindingElement */) { + while (node.kind === 177 /* BindingElement */) { node = node.parent.parent; } return node; @@ -8863,15 +9604,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 152 /* Constructor */ - || kind === 186 /* FunctionExpression */ - || kind === 228 /* FunctionDeclaration */ - || kind === 187 /* ArrowFunction */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 233 /* ModuleDeclaration */ - || kind === 265 /* SourceFile */; + return kind === 153 /* Constructor */ + || kind === 187 /* FunctionExpression */ + || kind === 229 /* FunctionDeclaration */ + || kind === 188 /* ArrowFunction */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 234 /* ModuleDeclaration */ + || kind === 269 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -8890,23 +9631,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 182 /* NewExpression */: + case 183 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 192 /* PrefixUnaryExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 188 /* DeleteExpression */: - case 191 /* AwaitExpression */: - case 195 /* ConditionalExpression */: - case 197 /* YieldExpression */: + case 193 /* PrefixUnaryExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 192 /* AwaitExpression */: + case 196 /* ConditionalExpression */: + case 198 /* YieldExpression */: return 1 /* Right */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (operator) { case 40 /* AsteriskAsteriskToken */: case 58 /* EqualsToken */: @@ -8930,15 +9671,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 194 /* BinaryExpression */) { + if (expression.kind === 195 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 192 /* PrefixUnaryExpression */ || expression.kind === 193 /* PostfixUnaryExpression */) { + else if (expression.kind === 193 /* PrefixUnaryExpression */ || expression.kind === 194 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -8956,36 +9697,37 @@ var ts; case 86 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 199 /* ClassExpression */: - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 200 /* ClassExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: case 12 /* RegularExpressionLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 196 /* TemplateExpression */: - case 185 /* ParenthesizedExpression */: - case 200 /* OmittedExpression */: + case 197 /* TemplateExpression */: + case 186 /* ParenthesizedExpression */: + case 201 /* OmittedExpression */: return 19; - case 183 /* TaggedTemplateExpression */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 184 /* TaggedTemplateExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: return 18; - case 182 /* NewExpression */: + case 183 /* NewExpression */: return hasArguments ? 18 : 17; - case 181 /* CallExpression */: + case 182 /* CallExpression */: return 17; - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return 16; - case 192 /* PrefixUnaryExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 188 /* DeleteExpression */: - case 191 /* AwaitExpression */: + case 193 /* PrefixUnaryExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 189 /* DeleteExpression */: + case 192 /* AwaitExpression */: return 15; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (operatorKind) { case 51 /* ExclamationToken */: case 52 /* TildeToken */: @@ -9043,13 +9785,13 @@ var ts; default: return -1; } - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return 4; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return 2; - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return 1; - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return 0; default: return -1; @@ -9059,6 +9801,7 @@ var ts; function createDiagnosticCollection() { var nonFileDiagnostics = []; var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; var diagnosticsModified = false; var modificationCount = 0; return { @@ -9084,6 +9827,11 @@ var ts; } } else { + // If we've already read the non-file diagnostics, do not modify the existing array. + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); @@ -9092,6 +9840,7 @@ var ts; } function getGlobalDiagnostics() { sortAndDeduplicate(); + hasReadNonFileDiagnostics = true; return nonFileDiagnostics; } function getDiagnostics(fileName) { @@ -9165,10 +9914,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { - // An escaped identifier had a leading underscore prior to being escaped, which would return true - // The escape adds an extra underscore which does not change the result - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; + var ch = name.charCodeAt(0); + return (ch >= 97 /* a */ && ch <= 122 /* z */) || name.indexOf("-") > -1; } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -9367,7 +10114,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 152 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 153 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -9413,10 +10160,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 153 /* GetAccessor */) { + if (accessor.kind === 154 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 154 /* SetAccessor */) { + else if (accessor.kind === 155 /* SetAccessor */) { setAccessor = accessor; } else { @@ -9425,7 +10172,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 153 /* GetAccessor */ || member.kind === 154 /* SetAccessor */) + if ((member.kind === 154 /* GetAccessor */ || member.kind === 155 /* SetAccessor */) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -9436,10 +10183,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 153 /* GetAccessor */ && !getAccessor) { + if (member.kind === 154 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 154 /* SetAccessor */ && !setAccessor) { + if (member.kind === 155 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -9458,11 +10205,11 @@ var ts; * Gets the effective type annotation of a variable, parameter, or property. If the node was * parsed in a JavaScript file, gets the type annotation from JSDoc. */ - function getEffectiveTypeAnnotationNode(node) { + function getEffectiveTypeAnnotationNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocType(node); } } @@ -9471,11 +10218,11 @@ var ts; * Gets the effective return type annotation of a signature. If the node was parsed in a * JavaScript file, gets the return type annotation from JSDoc. */ - function getEffectiveReturnTypeNode(node) { + function getEffectiveReturnTypeNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocReturnType(node); } } @@ -9484,11 +10231,11 @@ var ts; * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ - function getEffectiveTypeParameterDeclarations(node) { + function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } @@ -9498,9 +10245,9 @@ var ts; * Gets the effective type annotation of the value parameter of a set accessor. If the node * was parsed in a JavaScript file, gets the type annotation from JSDoc. */ - function getEffectiveSetAccessorTypeAnnotationNode(node) { + function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter); + return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -9703,6 +10450,14 @@ var ts; return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32 /* Static */); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64 /* Readonly */); + } + ts.hasReadonlyModifier = hasReadonlyModifier; function getSelectedModifierFlags(node, flags) { return getModifierFlags(node) & flags; } @@ -9716,7 +10471,6 @@ var ts; return flags; } ts.getModifierFlags = getModifierFlags; - /* @internal */ function getModifierFlagsNoCache(node) { var flags = 0 /* None */; if (node.modifiers) { @@ -9760,7 +10514,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 /* ExpressionWithTypeArguments */ && + if (node.kind === 202 /* ExpressionWithTypeArguments */ && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -9778,8 +10532,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 178 /* ObjectLiteralExpression */ - || kind === 177 /* ArrayLiteralExpression */; + return kind === 179 /* ObjectLiteralExpression */ + || kind === 178 /* ArrayLiteralExpression */; } return false; } @@ -9789,7 +10543,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 /* ExpressionWithTypeArguments */ + return node.kind === 202 /* ExpressionWithTypeArguments */ && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 /* ImplementsKeyword */ @@ -9799,21 +10553,21 @@ var ts; ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || - node.kind === 179 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + node.kind === 180 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 178 /* ObjectLiteralExpression */ && + return expression.kind === 179 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 177 /* ArrayLiteralExpression */ && + return expression.kind === 178 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -9897,17 +10651,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options) { + function getNewLineCharacter(options, system) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; + return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -10085,8 +10836,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -10128,26 +10879,6 @@ var ts; return 0; } ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; - function levenshtein(s1, s2) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - for (var i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (var i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (var j = 1; j < s2.length + 1; j++) { - current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - // shift current back to previous, and then reuse previous' array - var tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; function skipAlias(symbol, checker) { return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; } @@ -10179,28 +10910,122 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 193 /* PostfixUnaryExpression */: - case 192 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 210 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && parent.parent.kind === 211 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } } + return true; } + ts.compareDataObjects = compareDataObjects; + /** + * clears already present map by calling onDeleteExistingValue callback before deleting that key/value + */ + function clearMap(map, onDeleteValue) { + // Remove all + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + /** + * Mutates the map with newMap such that keys in map will be same as newMap. + */ + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + // Needs update + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + // Not present any more in new map, remove it + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + // Add new values that are not already present + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + // New values + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + ts.mutateMap = mutateMap; + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + 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); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128 /* Abstract */); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 65536 /* Object */ ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 5 /* ESNext */: + case 6 /* ESNext */: return "lib.esnext.full.d.ts"; case 4 /* ES2017 */: return "lib.es2017.full.d.ts"; @@ -10419,9 +11244,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 145 /* TypeParameter */) { + if (d && d.kind === 146 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 231 /* InterfaceDeclaration */) { return current; } } @@ -10429,7 +11254,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 152 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 153 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -10447,7 +11272,7 @@ var ts; } ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 /* BindingElement */ || ts.isBindingPattern(node))) { + while (node && (node.kind === 177 /* BindingElement */ || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -10455,14 +11280,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 226 /* VariableDeclaration */) { + if (node.kind === 227 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 227 /* VariableDeclarationList */) { + if (node && node.kind === 228 /* VariableDeclarationList */) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 208 /* VariableStatement */) { + if (node && node.kind === 209 /* VariableStatement */) { flags |= ts.getModifierFlags(node); } return flags; @@ -10478,14 +11303,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 226 /* VariableDeclaration */) { + if (node.kind === 227 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 227 /* VariableDeclarationList */) { + if (node && node.kind === 228 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 208 /* VariableStatement */) { + if (node && node.kind === 209 /* VariableStatement */) { flags |= node.flags; } return flags; @@ -10510,6 +11335,8 @@ var ts; if (!trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } + // Set the UI locale for string collation + ts.setUILocale(locale); function trySetLanguageAndTerritory(language, territory, errors) { var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); @@ -10585,6 +11412,14 @@ var ts; return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; } ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; /** * Remove extra underscore from escaped identifier text content. * @deprecated Use `id.text` for the unescaped text. @@ -10611,18 +11446,18 @@ var ts; } // Covers remaining cases switch (hostNode.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return expr.name; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -10631,10 +11466,10 @@ var ts; return undefined; case 1 /* EndOfFileToken */: return undefined; - case 185 /* ParenthesizedExpression */: { + case 186 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 222 /* LabeledStatement */: { + case 223 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -10656,27 +11491,37 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { - return declaration.name.right; - } - if (declaration.kind === 194 /* BinaryExpression */) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - case 3 /* PrototypeProperty */: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 71 /* Identifier */: + return declaration; + case 289 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: { + var name = declaration.name; + if (name.kind === 144 /* QualifiedName */) { + return name.right; + } + break; + } + case 195 /* BinaryExpression */: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + case 288 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 244 /* ExportAssignment */: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283 /* JSDocTypedefTag */) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; /** @@ -10708,33 +11553,33 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, 284 /* JSDocParameterTag */); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, 282 /* JSDocAugmentsTag */); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278 /* JSDocClassTag */); + return getFirstJSDocTag(node, 283 /* JSDocClassTag */); } ts.getJSDocClassTag = getJSDocClassTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); + return getFirstJSDocTag(node, 285 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, 287 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; /** Gets the JSDoc type tag for the node if present and valid */ function getJSDocTypeTag(node) { // We should have already issued an error if there were multiple type jsdocs, so just use the first one. - var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -10753,8 +11598,8 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); - if (!tag && node.kind === 146 /* Parameter */) { + var tag = getFirstJSDocTag(node, 286 /* JSDocTypeTag */); + if (!tag && node.kind === 147 /* Parameter */) { var paramTags = getJSDocParameterTags(node); if (paramTags) { tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); @@ -10789,6 +11634,12 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -10832,592 +11683,608 @@ var ts; ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 143 /* QualifiedName */; + return node.kind === 144 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 144 /* ComputedPropertyName */; + return node.kind === 145 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 145 /* TypeParameter */; + return node.kind === 146 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 146 /* Parameter */; + return node.kind === 147 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 147 /* Decorator */; + return node.kind === 148 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 148 /* PropertySignature */; + return node.kind === 149 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 149 /* PropertyDeclaration */; + return node.kind === 150 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 150 /* MethodSignature */; + return node.kind === 151 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 151 /* MethodDeclaration */; + return node.kind === 152 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 152 /* Constructor */; + return node.kind === 153 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 153 /* GetAccessor */; + return node.kind === 154 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 154 /* SetAccessor */; + return node.kind === 155 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 155 /* CallSignature */; + return node.kind === 156 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 156 /* ConstructSignature */; + return node.kind === 157 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 157 /* IndexSignature */; + return node.kind === 158 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 158 /* TypePredicate */; + return node.kind === 159 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 159 /* TypeReference */; + return node.kind === 160 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 160 /* FunctionType */; + return node.kind === 161 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 161 /* ConstructorType */; + return node.kind === 162 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 162 /* TypeQuery */; + return node.kind === 163 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 163 /* TypeLiteral */; + return node.kind === 164 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 164 /* ArrayType */; + return node.kind === 165 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 165 /* TupleType */; + return node.kind === 166 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 166 /* UnionType */; + return node.kind === 167 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 167 /* IntersectionType */; + return node.kind === 168 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 168 /* ParenthesizedType */; + return node.kind === 169 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 169 /* ThisType */; + return node.kind === 170 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 170 /* TypeOperator */; + return node.kind === 171 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 171 /* IndexedAccessType */; + return node.kind === 172 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 172 /* MappedType */; + return node.kind === 173 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 173 /* LiteralType */; + return node.kind === 174 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 174 /* ObjectBindingPattern */; + return node.kind === 175 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 175 /* ArrayBindingPattern */; + return node.kind === 176 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 176 /* BindingElement */; + return node.kind === 177 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 177 /* ArrayLiteralExpression */; + return node.kind === 178 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 178 /* ObjectLiteralExpression */; + return node.kind === 179 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 179 /* PropertyAccessExpression */; + return node.kind === 180 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 180 /* ElementAccessExpression */; + return node.kind === 181 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 181 /* CallExpression */; + return node.kind === 182 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 182 /* NewExpression */; + return node.kind === 183 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 183 /* TaggedTemplateExpression */; + return node.kind === 184 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 184 /* TypeAssertionExpression */; + return node.kind === 185 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 185 /* ParenthesizedExpression */; + return node.kind === 186 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288 /* PartiallyEmittedExpression */) { + while (node.kind === 292 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 186 /* FunctionExpression */; + return node.kind === 187 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 187 /* ArrowFunction */; + return node.kind === 188 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 188 /* DeleteExpression */; + return node.kind === 189 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 191 /* AwaitExpression */; + return node.kind === 192 /* AwaitExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 190 /* VoidExpression */; + return node.kind === 191 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 191 /* AwaitExpression */; + return node.kind === 192 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 192 /* PrefixUnaryExpression */; + return node.kind === 193 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 193 /* PostfixUnaryExpression */; + return node.kind === 194 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 194 /* BinaryExpression */; + return node.kind === 195 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 195 /* ConditionalExpression */; + return node.kind === 196 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 196 /* TemplateExpression */; + return node.kind === 197 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 197 /* YieldExpression */; + return node.kind === 198 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 198 /* SpreadElement */; + return node.kind === 199 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 199 /* ClassExpression */; + return node.kind === 200 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 200 /* OmittedExpression */; + return node.kind === 201 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 201 /* ExpressionWithTypeArguments */; + return node.kind === 202 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 202 /* AsExpression */; + return node.kind === 203 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 203 /* NonNullExpression */; + return node.kind === 204 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 204 /* MetaProperty */; + return node.kind === 205 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 205 /* TemplateSpan */; + return node.kind === 206 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 206 /* SemicolonClassElement */; + return node.kind === 207 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 207 /* Block */; + return node.kind === 208 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 208 /* VariableStatement */; + return node.kind === 209 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 209 /* EmptyStatement */; + return node.kind === 210 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 210 /* ExpressionStatement */; + return node.kind === 211 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 211 /* IfStatement */; + return node.kind === 212 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 212 /* DoStatement */; + return node.kind === 213 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 213 /* WhileStatement */; + return node.kind === 214 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 214 /* ForStatement */; + return node.kind === 215 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 215 /* ForInStatement */; + return node.kind === 216 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 216 /* ForOfStatement */; + return node.kind === 217 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 217 /* ContinueStatement */; + return node.kind === 218 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 218 /* BreakStatement */; + return node.kind === 219 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 219 /* BreakStatement */ || node.kind === 218 /* ContinueStatement */; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 219 /* ReturnStatement */; + return node.kind === 220 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 220 /* WithStatement */; + return node.kind === 221 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 221 /* SwitchStatement */; + return node.kind === 222 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 222 /* LabeledStatement */; + return node.kind === 223 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 223 /* ThrowStatement */; + return node.kind === 224 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 224 /* TryStatement */; + return node.kind === 225 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 225 /* DebuggerStatement */; + return node.kind === 226 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 226 /* VariableDeclaration */; + return node.kind === 227 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 227 /* VariableDeclarationList */; + return node.kind === 228 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 228 /* FunctionDeclaration */; + return node.kind === 229 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 229 /* ClassDeclaration */; + return node.kind === 230 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 230 /* InterfaceDeclaration */; + return node.kind === 231 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 231 /* TypeAliasDeclaration */; + return node.kind === 232 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 232 /* EnumDeclaration */; + return node.kind === 233 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 233 /* ModuleDeclaration */; + return node.kind === 234 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 234 /* ModuleBlock */; + return node.kind === 235 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 235 /* CaseBlock */; + return node.kind === 236 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 236 /* NamespaceExportDeclaration */; + return node.kind === 237 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 237 /* ImportEqualsDeclaration */; + return node.kind === 238 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 238 /* ImportDeclaration */; + return node.kind === 239 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 239 /* ImportClause */; + return node.kind === 240 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 240 /* NamespaceImport */; + return node.kind === 241 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 241 /* NamedImports */; + return node.kind === 242 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 242 /* ImportSpecifier */; + return node.kind === 243 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 243 /* ExportAssignment */; + return node.kind === 244 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 244 /* ExportDeclaration */; + return node.kind === 245 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 245 /* NamedExports */; + return node.kind === 246 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 246 /* ExportSpecifier */; + return node.kind === 247 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 247 /* MissingDeclaration */; + return node.kind === 248 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 248 /* ExternalModuleReference */; + return node.kind === 249 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 249 /* JsxElement */; + return node.kind === 250 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 250 /* JsxSelfClosingElement */; + return node.kind === 251 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 251 /* JsxOpeningElement */; + return node.kind === 252 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 252 /* JsxClosingElement */; + return node.kind === 253 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 254 /* JsxFragment */; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 255 /* JsxOpeningFragment */; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 256 /* JsxClosingFragment */; + } + ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 253 /* JsxAttribute */; + return node.kind === 257 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 254 /* JsxAttributes */; + return node.kind === 258 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 255 /* JsxSpreadAttribute */; + return node.kind === 259 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 256 /* JsxExpression */; + return node.kind === 260 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 257 /* CaseClause */; + return node.kind === 261 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 258 /* DefaultClause */; + return node.kind === 262 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 259 /* HeritageClause */; + return node.kind === 263 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 260 /* CatchClause */; + return node.kind === 264 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 261 /* PropertyAssignment */; + return node.kind === 265 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 262 /* ShorthandPropertyAssignment */; + return node.kind === 266 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 263 /* SpreadAssignment */; + return node.kind === 267 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 264 /* EnumMember */; + return node.kind === 268 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 265 /* SourceFile */; + return node.kind === 269 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 266 /* Bundle */; + return node.kind === 270 /* Bundle */; } ts.isBundle = isBundle; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 267 /* JSDocTypeExpression */; + return node.kind === 271 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 268 /* JSDocAllType */; + return node.kind === 272 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 269 /* JSDocUnknownType */; + return node.kind === 273 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 270 /* JSDocNullableType */; + return node.kind === 274 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 271 /* JSDocNonNullableType */; + return node.kind === 275 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 272 /* JSDocOptionalType */; + return node.kind === 276 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 273 /* JSDocFunctionType */; + return node.kind === 277 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 274 /* JSDocVariadicType */; + return node.kind === 278 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 275 /* JSDocComment */; + return node.kind === 279 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 277 /* JSDocAugmentsTag */; + return node.kind === 282 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocParameterTag(node) { - return node.kind === 279 /* JSDocParameterTag */; + return node.kind === 284 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 280 /* JSDocReturnTag */; + return node.kind === 285 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 281 /* JSDocTypeTag */; + return node.kind === 286 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 282 /* JSDocTemplateTag */; + return node.kind === 287 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 283 /* JSDocTypedefTag */; + return node.kind === 288 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 284 /* JSDocPropertyTag */; + return node.kind === 289 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 284 /* JSDocPropertyTag */ || node.kind === 279 /* JSDocParameterTag */; + return node.kind === 289 /* JSDocPropertyTag */ || node.kind === 284 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 285 /* JSDocTypeLiteral */; + return node.kind === 280 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; })(ts || (ts = {})); @@ -11428,7 +12295,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 286 /* SyntaxList */; + return n.kind === 290 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -11438,7 +12305,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 143 /* FirstNode */; + return kind >= 144 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -11446,7 +12313,7 @@ var ts; * For example, this is true for an IfKeyword but not for an IfStatement. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 142 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 143 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -11478,16 +12345,7 @@ var ts; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isStringTextContainingNode(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 13 /* NoSubstitutionTemplateLiteral */: - return true; - default: - return false; - } + return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -11523,7 +12381,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 143 /* QualifiedName */ + return kind === 144 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isEntityName = isEntityName; @@ -11532,14 +12390,14 @@ var ts; return kind === 71 /* Identifier */ || kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 144 /* ComputedPropertyName */; + || kind === 145 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 174 /* ObjectBindingPattern */ - || kind === 175 /* ArrayBindingPattern */; + || kind === 175 /* ObjectBindingPattern */ + || kind === 176 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -11554,13 +12412,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return true; default: return false; @@ -11569,13 +12427,13 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 273 /* JSDocFunctionType */: - case 161 /* ConstructorType */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 161 /* FunctionType */: + case 277 /* JSDocFunctionType */: + case 162 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -11590,49 +12448,49 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 152 /* Constructor */ - || kind === 149 /* PropertyDeclaration */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 157 /* IndexSignature */ - || kind === 206 /* SemicolonClassElement */ - || kind === 247 /* MissingDeclaration */; + return kind === 153 /* Constructor */ + || kind === 150 /* PropertyDeclaration */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 158 /* IndexSignature */ + || kind === 207 /* SemicolonClassElement */ + || kind === 248 /* MissingDeclaration */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */); + return node && (node.kind === 230 /* ClassDeclaration */ || node.kind === 200 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */); + return node && (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */); } ts.isAccessor = isAccessor; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 156 /* ConstructSignature */ - || kind === 155 /* CallSignature */ - || kind === 148 /* PropertySignature */ - || kind === 150 /* MethodSignature */ - || kind === 157 /* IndexSignature */ - || kind === 247 /* MissingDeclaration */; + return kind === 157 /* ConstructSignature */ + || kind === 156 /* CallSignature */ + || kind === 149 /* PropertySignature */ + || kind === 151 /* MethodSignature */ + || kind === 158 /* IndexSignature */ + || kind === 248 /* MissingDeclaration */; } ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 261 /* PropertyAssignment */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 263 /* SpreadAssignment */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 247 /* MissingDeclaration */; + return kind === 265 /* PropertyAssignment */ + || kind === 266 /* ShorthandPropertyAssignment */ + || kind === 267 /* SpreadAssignment */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 248 /* MissingDeclaration */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) + return (kind >= 159 /* FirstTypeNode */ && kind <= 174 /* LastTypeNode */) || kind === 119 /* AnyKeyword */ || kind === 133 /* NumberKeyword */ || kind === 134 /* ObjectKeyword */ @@ -11644,7 +12502,14 @@ var ts; || kind === 139 /* UndefinedKeyword */ || kind === 95 /* NullKeyword */ || kind === 130 /* NeverKeyword */ - || kind === 201 /* ExpressionWithTypeArguments */; + || kind === 202 /* ExpressionWithTypeArguments */ + || kind === 272 /* JSDocAllType */ + || kind === 273 /* JSDocUnknownType */ + || kind === 274 /* JSDocNullableType */ + || kind === 275 /* JSDocNonNullableType */ + || kind === 276 /* JSDocOptionalType */ + || kind === 277 /* JSDocFunctionType */ + || kind === 278 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -11657,8 +12522,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return true; } return false; @@ -11669,8 +12534,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 175 /* ArrayBindingPattern */ - || kind === 174 /* ObjectBindingPattern */; + return kind === 176 /* ArrayBindingPattern */ + || kind === 175 /* ObjectBindingPattern */; } return false; } @@ -11678,15 +12543,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 177 /* ArrayLiteralExpression */ - || kind === 178 /* ObjectLiteralExpression */; + return kind === 178 /* ArrayLiteralExpression */ + || kind === 179 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 176 /* BindingElement */ - || kind === 200 /* OmittedExpression */; + return kind === 177 /* BindingElement */ + || kind === 201 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -11695,9 +12560,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 176 /* BindingElement */: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 177 /* BindingElement */: return true; } return false; @@ -11718,8 +12583,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 174 /* ObjectBindingPattern */: - case 178 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 179 /* ObjectLiteralExpression */: return true; } return false; @@ -11731,8 +12596,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: return true; } return false; @@ -11741,18 +12606,18 @@ var ts; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 179 /* PropertyAccessExpression */ - || kind === 143 /* QualifiedName */; + return kind === 180 /* PropertyAccessExpression */ + || kind === 144 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 183 /* TaggedTemplateExpression */: - case 147 /* Decorator */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 184 /* TaggedTemplateExpression */: + case 148 /* Decorator */: return true; default: return false; @@ -11760,12 +12625,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + return node.kind === 182 /* CallExpression */ || node.kind === 183 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 196 /* TemplateExpression */ + return kind === 197 /* TemplateExpression */ || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -11776,31 +12641,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - case 182 /* NewExpression */: - case 181 /* CallExpression */: - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 183 /* TaggedTemplateExpression */: - case 177 /* ArrayLiteralExpression */: - case 185 /* ParenthesizedExpression */: - case 178 /* ObjectLiteralExpression */: - case 199 /* ClassExpression */: - case 186 /* FunctionExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 183 /* NewExpression */: + case 182 /* CallExpression */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 254 /* JsxFragment */: + case 184 /* TaggedTemplateExpression */: + case 178 /* ArrayLiteralExpression */: + case 186 /* ParenthesizedExpression */: + case 179 /* ObjectLiteralExpression */: + case 200 /* ClassExpression */: + case 187 /* FunctionExpression */: case 71 /* Identifier */: case 12 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 99 /* ThisKeyword */: case 101 /* TrueKeyword */: case 97 /* SuperKeyword */: - case 203 /* NonNullExpression */: - case 204 /* MetaProperty */: + case 204 /* NonNullExpression */: + case 205 /* MetaProperty */: case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression return true; default: @@ -11814,13 +12680,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: - case 188 /* DeleteExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 191 /* AwaitExpression */: - case 184 /* TypeAssertionExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 192 /* AwaitExpression */: + case 185 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -11829,9 +12695,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return true; - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; default: @@ -11842,7 +12708,7 @@ var ts; /* @internal */ /** * Determines whether a node is an expression based only on its kind. - * Use `isPartOfExpression` if not in transforms. + * Use `isExpressionNode` if not in transforms. */ function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); @@ -11850,15 +12716,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 195 /* ConditionalExpression */: - case 197 /* YieldExpression */: - case 187 /* ArrowFunction */: - case 194 /* BinaryExpression */: - case 198 /* SpreadElement */: - case 202 /* AsExpression */: - case 200 /* OmittedExpression */: - case 289 /* CommaListExpression */: - case 288 /* PartiallyEmittedExpression */: + case 196 /* ConditionalExpression */: + case 198 /* YieldExpression */: + case 188 /* ArrowFunction */: + case 195 /* BinaryExpression */: + case 199 /* SpreadElement */: + case 203 /* AsExpression */: + case 201 /* OmittedExpression */: + case 293 /* CommaListExpression */: + case 292 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -11866,18 +12732,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 184 /* TypeAssertionExpression */ - || kind === 202 /* AsExpression */; + return kind === 185 /* TypeAssertionExpression */ + || kind === 203 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 288 /* PartiallyEmittedExpression */; + return node.kind === 292 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 287 /* NotEmittedStatement */; + return node.kind === 291 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -11889,13 +12755,13 @@ var ts; // Statement function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return true; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -11903,7 +12769,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 215 /* ForInStatement */ || node.kind === 216 /* ForOfStatement */; + return node.kind === 216 /* ForInStatement */ || node.kind === 217 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -11927,111 +12793,111 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */ + return kind === 235 /* ModuleBlock */ + || kind === 234 /* ModuleDeclaration */ || kind === 71 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */; + return kind === 235 /* ModuleBlock */ + || kind === 234 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 233 /* ModuleDeclaration */; + || kind === 234 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 241 /* NamedImports */ - || kind === 240 /* NamespaceImport */; + return kind === 242 /* NamedImports */ + || kind === 241 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; + return node.kind === 234 /* ModuleDeclaration */ || node.kind === 233 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 187 /* ArrowFunction */ - || kind === 176 /* BindingElement */ - || kind === 229 /* ClassDeclaration */ - || kind === 199 /* ClassExpression */ - || kind === 152 /* Constructor */ - || kind === 232 /* EnumDeclaration */ - || kind === 264 /* EnumMember */ - || kind === 246 /* ExportSpecifier */ - || kind === 228 /* FunctionDeclaration */ - || kind === 186 /* FunctionExpression */ - || kind === 153 /* GetAccessor */ - || kind === 239 /* ImportClause */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 242 /* ImportSpecifier */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 253 /* JsxAttribute */ - || kind === 151 /* MethodDeclaration */ - || kind === 150 /* MethodSignature */ - || kind === 233 /* ModuleDeclaration */ - || kind === 236 /* NamespaceExportDeclaration */ - || kind === 240 /* NamespaceImport */ - || kind === 146 /* Parameter */ - || kind === 261 /* PropertyAssignment */ - || kind === 149 /* PropertyDeclaration */ - || kind === 148 /* PropertySignature */ - || kind === 154 /* SetAccessor */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 145 /* TypeParameter */ - || kind === 226 /* VariableDeclaration */ - || kind === 283 /* JSDocTypedefTag */; + return kind === 188 /* ArrowFunction */ + || kind === 177 /* BindingElement */ + || kind === 230 /* ClassDeclaration */ + || kind === 200 /* ClassExpression */ + || kind === 153 /* Constructor */ + || kind === 233 /* EnumDeclaration */ + || kind === 268 /* EnumMember */ + || kind === 247 /* ExportSpecifier */ + || kind === 229 /* FunctionDeclaration */ + || kind === 187 /* FunctionExpression */ + || kind === 154 /* GetAccessor */ + || kind === 240 /* ImportClause */ + || kind === 238 /* ImportEqualsDeclaration */ + || kind === 243 /* ImportSpecifier */ + || kind === 231 /* InterfaceDeclaration */ + || kind === 257 /* JsxAttribute */ + || kind === 152 /* MethodDeclaration */ + || kind === 151 /* MethodSignature */ + || kind === 234 /* ModuleDeclaration */ + || kind === 237 /* NamespaceExportDeclaration */ + || kind === 241 /* NamespaceImport */ + || kind === 147 /* Parameter */ + || kind === 265 /* PropertyAssignment */ + || kind === 150 /* PropertyDeclaration */ + || kind === 149 /* PropertySignature */ + || kind === 155 /* SetAccessor */ + || kind === 266 /* ShorthandPropertyAssignment */ + || kind === 232 /* TypeAliasDeclaration */ + || kind === 146 /* TypeParameter */ + || kind === 227 /* VariableDeclaration */ + || kind === 288 /* JSDocTypedefTag */; } function isDeclarationStatementKind(kind) { - return kind === 228 /* FunctionDeclaration */ - || kind === 247 /* MissingDeclaration */ - || kind === 229 /* ClassDeclaration */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 232 /* EnumDeclaration */ - || kind === 233 /* ModuleDeclaration */ - || kind === 238 /* ImportDeclaration */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 244 /* ExportDeclaration */ - || kind === 243 /* ExportAssignment */ - || kind === 236 /* NamespaceExportDeclaration */; + return kind === 229 /* FunctionDeclaration */ + || kind === 248 /* MissingDeclaration */ + || kind === 230 /* ClassDeclaration */ + || kind === 231 /* InterfaceDeclaration */ + || kind === 232 /* TypeAliasDeclaration */ + || kind === 233 /* EnumDeclaration */ + || kind === 234 /* ModuleDeclaration */ + || kind === 239 /* ImportDeclaration */ + || kind === 238 /* ImportEqualsDeclaration */ + || kind === 245 /* ExportDeclaration */ + || kind === 244 /* ExportAssignment */ + || kind === 237 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 /* BreakStatement */ - || kind === 217 /* ContinueStatement */ - || kind === 225 /* DebuggerStatement */ - || kind === 212 /* DoStatement */ - || kind === 210 /* ExpressionStatement */ - || kind === 209 /* EmptyStatement */ - || kind === 215 /* ForInStatement */ - || kind === 216 /* ForOfStatement */ - || kind === 214 /* ForStatement */ - || kind === 211 /* IfStatement */ - || kind === 222 /* LabeledStatement */ - || kind === 219 /* ReturnStatement */ - || kind === 221 /* SwitchStatement */ - || kind === 223 /* ThrowStatement */ - || kind === 224 /* TryStatement */ - || kind === 208 /* VariableStatement */ - || kind === 213 /* WhileStatement */ - || kind === 220 /* WithStatement */ - || kind === 287 /* NotEmittedStatement */ - || kind === 291 /* EndOfDeclarationMarker */ - || kind === 290 /* MergeDeclarationMarker */; + return kind === 219 /* BreakStatement */ + || kind === 218 /* ContinueStatement */ + || kind === 226 /* DebuggerStatement */ + || kind === 213 /* DoStatement */ + || kind === 211 /* ExpressionStatement */ + || kind === 210 /* EmptyStatement */ + || kind === 216 /* ForInStatement */ + || kind === 217 /* ForOfStatement */ + || kind === 215 /* ForStatement */ + || kind === 212 /* IfStatement */ + || kind === 223 /* LabeledStatement */ + || kind === 220 /* ReturnStatement */ + || kind === 222 /* SwitchStatement */ + || kind === 224 /* ThrowStatement */ + || kind === 225 /* TryStatement */ + || kind === 209 /* VariableStatement */ + || kind === 214 /* WhileStatement */ + || kind === 221 /* WithStatement */ + || kind === 291 /* NotEmittedStatement */ + || kind === 295 /* EndOfDeclarationMarker */ + || kind === 294 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 145 /* TypeParameter */) { - return node.parent.kind !== 282 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 146 /* TypeParameter */) { + return node.parent.kind !== 287 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -12058,10 +12924,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 207 /* Block */) + if (node.kind !== 208 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 224 /* TryStatement */ || node.parent.kind === 260 /* CatchClause */) { + if (node.parent.kind === 225 /* TryStatement */ || node.parent.kind === 264 /* CatchClause */) { return false; } } @@ -12071,8 +12937,8 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 248 /* ExternalModuleReference */ - || kind === 143 /* QualifiedName */ + return kind === 249 /* ExternalModuleReference */ + || kind === 144 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -12082,63 +12948,72 @@ var ts; var kind = node.kind; return kind === 99 /* ThisKeyword */ || kind === 71 /* Identifier */ - || kind === 179 /* PropertyAccessExpression */; + || kind === 180 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 249 /* JsxElement */ - || kind === 256 /* JsxExpression */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */; + return kind === 250 /* JsxElement */ + || kind === 260 /* JsxExpression */ + || kind === 251 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */ + || kind === 254 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 253 /* JsxAttribute */ - || kind === 255 /* JsxSpreadAttribute */; + return kind === 257 /* JsxAttribute */ + || kind === 259 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 256 /* JsxExpression */; + || kind === 260 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 251 /* JsxOpeningElement */ - || kind === 250 /* JsxSelfClosingElement */; + return kind === 252 /* JsxOpeningElement */ + || kind === 251 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 257 /* CaseClause */ - || kind === 258 /* DefaultClause */; + return kind === 261 /* CaseClause */ + || kind === 262 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 267 /* FirstJSDocNode */ && node.kind <= 285 /* LastJSDocNode */; + return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 275 /* JSDocComment */ || isJSDocTag(node); + return node.kind === 279 /* JSDocComment */ || isJSDocTag(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + return node.kind >= 281 /* FirstJSDocTagNode */ && node.kind <= 289 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 155 /* SetAccessor */; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 154 /* GetAccessor */; + } + ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ function hasJSDocNodes(node) { @@ -12160,12 +13035,14 @@ var ts; SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; })(SignatureFlags || (SignatureFlags = {})); + // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; + // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 265 /* SourceFile */) { + if (kind === 269 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71 /* Identifier */) { @@ -12210,59 +13087,60 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 142 /* LastToken */) { + if (!node || node.kind <= 143 /* LastToken */) { return; } switch (node.kind) { - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -12273,287 +13151,291 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 165 /* TupleType */: + case 166 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 166 /* UnionType */: - case 167 /* IntersectionType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: + case 169 /* ParenthesizedType */: + case 171 /* TypeOperator */: return visitNode(cbNode, node.type); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 172 /* MappedType */: + case 173 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return visitNode(cbNode, node.literal); - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 202 /* AsExpression */: + case 203 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return visitNode(cbNode, node.name); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 207 /* Block */: - case 234 /* ModuleBlock */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 265 /* SourceFile */: + case 269 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: return visitNode(cbNode, node.label); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 257 /* CaseClause */: + case 261 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 147 /* Decorator */: + case 148 /* Decorator */: return visitNode(cbNode, node.expression); - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 264 /* EnumMember */: + case 268 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 247 /* MissingDeclaration */: + case 248 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 249 /* JsxElement */: + case 250 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: + case 254 /* JsxFragment */: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.attributes); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 267 /* JSDocTypeExpression */: + case 271 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 271 /* JSDocNonNullableType */: + case 275 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 270 /* JSDocNullableType */: + case 274 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 272 /* JSDocOptionalType */: + case 276 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 273 /* JSDocFunctionType */: + case 277 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 274 /* JSDocVariadicType */: + case 278 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 275 /* JSDocComment */: + case 279 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 279 /* JSDocParameterTag */: - case 284 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: + case 289 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -12562,17 +13444,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 280 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 281 /* JSDocTypeTag */: + case 285 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 277 /* JSDocAugmentsTag */: + case 286 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 282 /* JSDocTemplateTag */: + case 282 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.class); + case 287 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 267 /* JSDocTypeExpression */) { + node.typeExpression.kind === 271 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -12580,7 +13462,7 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 285 /* JSDocTypeLiteral */: + case 280 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -12588,7 +13470,7 @@ var ts; } } return; - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -12661,13 +13543,15 @@ var ts; (function (Parser) { // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks + // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; + // tslint:enable variable-name var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -12761,6 +13645,7 @@ var ts; } Parser.parseSourceFile = parseSourceFile; function parseIsolatedEntityName(content, languageVersion) { + // Choice of `isDeclarationFile` should be arbitrary initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); // Prime the scanner. nextToken(); @@ -12773,7 +13658,7 @@ var ts; function parseJsonText(fileName, sourceText) { initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); // Set source file so that errors will be reported with this file name - sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */); + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); var result = sourceFile; // Prime the scanner. nextToken(); @@ -12809,7 +13694,16 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ || scriptKind === 6 /* JSON */ ? 65536 /* JavaScriptFile */ : 0 /* None */; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); @@ -12829,7 +13723,11 @@ var ts; sourceText = undefined; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 2097152 /* Ambient */; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); @@ -12853,13 +13751,14 @@ var ts; for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; + if (jsDoc) { + if (!node.jsDoc) { + node.jsDoc = [jsDoc]; + } + else { + node.jsDoc.push(jsDoc); + } } - node.jsDoc.push(jsDoc); } } return node; @@ -12894,17 +13793,17 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(265 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(269 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + sourceFile.isDeclarationFile = isDeclarationFile; sourceFile.scriptKind = scriptKind; return sourceFile; } @@ -13172,15 +14071,19 @@ var ts; return parseExpected(25 /* SemicolonToken */); } } - // note: this function creates only node function createNode(kind, pos) { nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) : + kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind) { + var node = createNode(kind); + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + addJSDocComment(node); } - return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return node; } function createNodeArray(elements, pos, end) { // Since the element list of a node array is typically created by starting with an empty array and @@ -13213,7 +14116,7 @@ var ts; else { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); + var result = createNode(kind); if (kind === 71 /* Identifier */) { result.escapedText = ""; } @@ -13251,8 +14154,8 @@ var ts; function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || @@ -13277,7 +14180,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(144 /* ComputedPropertyName */); + var node = createNode(145 /* ComputedPropertyName */); parseExpected(21 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -13434,6 +14337,10 @@ var ts; nextToken(); return ts.tokenIsIdentifierOrKeyword(token()); } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } function isHeritageClauseExtendsOrImplementsKeyword() { if (token() === 108 /* ImplementsKeyword */ || token() === 85 /* ExtendsKeyword */) { @@ -13590,7 +14497,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 96256 /* ContextFlags */; + var nodeContextFlags = node.flags & 6387712 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -13672,14 +14579,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 152 /* Constructor */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 149 /* PropertyDeclaration */: - case 206 /* SemicolonClassElement */: + case 153 /* Constructor */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 207 /* SemicolonClassElement */: return true; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -13694,8 +14601,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 257 /* CaseClause */: - case 258 /* DefaultClause */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: return true; } } @@ -13704,58 +14611,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 208 /* VariableStatement */: - case 207 /* Block */: - case 211 /* IfStatement */: - case 210 /* ExpressionStatement */: - case 223 /* ThrowStatement */: - case 219 /* ReturnStatement */: - case 221 /* SwitchStatement */: - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 214 /* ForStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 209 /* EmptyStatement */: - case 224 /* TryStatement */: - case 222 /* LabeledStatement */: - case 212 /* DoStatement */: - case 225 /* DebuggerStatement */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 209 /* VariableStatement */: + case 208 /* Block */: + case 212 /* IfStatement */: + case 211 /* ExpressionStatement */: + case 224 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 222 /* SwitchStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 210 /* EmptyStatement */: + case 225 /* TryStatement */: + case 223 /* LabeledStatement */: + case 213 /* DoStatement */: + case 226 /* DebuggerStatement */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 232 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 264 /* EnumMember */; + return node.kind === 268 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 148 /* PropertySignature */: - case 155 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 149 /* PropertySignature */: + case 156 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 226 /* VariableDeclaration */) { + if (node.kind !== 227 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -13776,7 +14683,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 146 /* Parameter */) { + if (node.kind !== 147 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -13891,7 +14798,7 @@ var ts; return createMissingList(); } function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); while (parseOptional(23 /* DotToken */)) { if (token() === 27 /* LessThanToken */) { @@ -13905,7 +14812,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(143 /* QualifiedName */, entity.pos); + var node = createNode(144 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -13942,7 +14849,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(196 /* TemplateExpression */); + var template = createNode(197 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); var list = []; @@ -13954,7 +14861,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(205 /* TemplateSpan */); + var span = createNode(206 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18 /* CloseBraceToken */) { @@ -13997,7 +14904,7 @@ var ts; // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + node.numericLiteralFlags = scanner.getTokenFlags() & 496 /* NumericLiteralFlags */; } nextToken(); finishNode(node); @@ -14005,8 +14912,8 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(159 /* TypeReference */); - node.typeName = parseEntityName(/*allowReservedWords*/ !!(contextFlags & 1048576 /* JSDoc */), ts.Diagnostics.Type_expected); + var node = createNode(160 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } @@ -14014,18 +14921,18 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(158 /* TypePredicate */, lhs.pos); + var node = createNode(159 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(169 /* ThisType */); + var node = createNode(170 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType() { - var result = createNode(268 /* JSDocAllType */); + var result = createNode(272 /* JSDocAllType */); nextToken(); return finishNode(result); } @@ -14048,28 +14955,28 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(269 /* JSDocUnknownType */, pos); + var result = createNode(273 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(270 /* JSDocNullableType */, pos); + var result = createNode(274 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNode(273 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(277 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); - return addJSDocComment(finishNode(result)); + return finishNode(result); } - var node = createNode(159 /* TypeReference */); + var node = createNode(160 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(146 /* Parameter */); + var parameter = createNode(147 /* Parameter */); if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); @@ -14080,17 +14987,17 @@ var ts; function parseJSDocNodeWithType(kind) { var result = createNode(kind); nextToken(); - result.type = parseType(); + result.type = parseNonArrayType(); return finishNode(result); } function parseTypeQuery() { - var node = createNode(162 /* TypeQuery */); + var node = createNode(163 /* TypeQuery */); parseExpected(103 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(145 /* TypeParameter */); + var node = createNode(146 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(85 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -14134,8 +15041,8 @@ var ts; token() === 57 /* AtToken */ || isStartOfType(/*inStartOfParameter*/ true); } - function parseParameter(requireEqualsToken) { - var node = createNode(146 /* Parameter */); + function parseParameter() { + var node = createNodeWithJSDoc(147 /* Parameter */); if (token() === 99 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); @@ -14160,8 +15067,8 @@ var ts; } node.questionToken = parseOptionalToken(55 /* QuestionToken */); node.type = parseParameterType(); - node.initializer = parseInitializer(/*inParameter*/ true, requireEqualsToken); - return addJSDocComment(finishNode(node)); + node.initializer = parseInitializer(); + return finishNode(node); } function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { @@ -14208,7 +15115,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8 /* RequireCompleteParameterList */)); }); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { @@ -14233,19 +15140,16 @@ var ts; parseSemicolon(); } function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156 /* ConstructSignature */) { + var node = createNodeWithJSDoc(kind); + if (kind === 157 /* ConstructSignature */) { parseExpected(94 /* NewKeyword */); } fillSignature(56 /* ColonToken */, 4 /* Type */, node); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isIndexSignature() { - if (token() !== 21 /* OpenBracketToken */) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); + return token() === 21 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { // The only allowed sequence is: @@ -14297,44 +15201,34 @@ var ts; nextToken(); return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157 /* IndexSignature */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseIndexSignatureDeclaration(node) { + node.kind = 158 /* IndexSignature */; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55 /* QuestionToken */); + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - var method = createNode(150 /* MethodSignature */, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; + node.kind = 151 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, 4 /* Type */, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); + fillSignature(56 /* ColonToken */, 4 /* Type */, node); } else { - var property = createNode(148 /* PropertySignature */, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + node.kind = 149 /* PropertySignature */; + node.type = parseTypeAnnotation(); if (token() === 58 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. - property.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); } + parseTypeMemberSemicolon(); + return finishNode(node); } function isTypeMemberStart() { // Return true if we have the start of a signature member @@ -14370,24 +15264,24 @@ var ts; } function parseTypeMember() { if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(155 /* CallSignature */); + return parseSignatureMember(156 /* CallSignature */); } if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(156 /* ConstructSignature */); + return parseSignatureMember(157 /* ConstructSignature */); } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0 /* Unknown */); + node.modifiers = parseModifiers(); if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); + return parseIndexSignatureDeclaration(node); } - return parsePropertyOrMethodSignature(fullStart, modifiers); + return parsePropertyOrMethodSignature(node); } function nextTokenIsOpenParenOrLessThan() { nextToken(); return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(163 /* TypeLiteral */); + var node = createNode(164 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -14410,14 +15304,14 @@ var ts; return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(145 /* TypeParameter */); + var node = createNode(146 /* TypeParameter */); node.name = parseIdentifier(); parseExpected(92 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(172 /* MappedType */); + var node = createNode(173 /* MappedType */); parseExpected(17 /* OpenBraceToken */); node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); parseExpected(21 /* OpenBracketToken */); @@ -14430,34 +15324,34 @@ var ts; return finishNode(node); } function parseTupleType() { - var node = createNode(165 /* TupleType */); + var node = createNode(166 /* TupleType */); node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(168 /* ParenthesizedType */); + var node = createNode(169 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161 /* ConstructorType */) { + var node = createNodeWithJSDoc(kind); + if (kind === 162 /* ConstructorType */) { parseExpected(94 /* NewKeyword */); } fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); return token() === 23 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(173 /* LiteralType */); + var node = createNode(174 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(192 /* PrefixUnaryExpression */); + unaryMinusExpression = createNode(193 /* PrefixUnaryExpression */); unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } @@ -14480,8 +15374,8 @@ var ts; case 119 /* AnyKeyword */: case 136 /* StringKeyword */: case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: + case 122 /* BooleanKeyword */: case 139 /* UndefinedKeyword */: case 130 /* NeverKeyword */: case 134 /* ObjectKeyword */: @@ -14493,10 +15387,8 @@ var ts; return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); - case 24 /* DotDotDotToken */: - return parseJSDocNodeWithType(274 /* JSDocVariadicType */); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(271 /* JSDocNonNullableType */); + return parseJSDocNodeWithType(275 /* JSDocNonNullableType */); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -14536,6 +15428,7 @@ var ts; case 133 /* NumberKeyword */: case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: + case 140 /* UniqueKeyword */: case 105 /* VoidKeyword */: case 139 /* UndefinedKeyword */: case 95 /* NullKeyword */: @@ -14572,59 +15465,72 @@ var ts; nextToken(); return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } - function parseJSDocPostfixTypeOrHigher() { + function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); - var kind = getKind(token()); - if (!kind) - return type; - nextToken(); - var postfix = createNode(kind, type.pos); - postfix.type = type; - return finishNode(postfix); - function getKind(tokenKind) { - switch (tokenKind) { + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { case 58 /* EqualsToken */: // only parse postfix = inside jsdoc, because it's ambiguous elsewhere - return contextFlags & 1048576 /* JSDoc */ ? 272 /* JSDocOptionalType */ : undefined; + if (!(contextFlags & 1048576 /* JSDoc */)) { + return type; + } + type = createJSDocPostfixType(276 /* JSDocOptionalType */, type); + break; case 51 /* ExclamationToken */: - return 271 /* JSDocNonNullableType */; + type = createJSDocPostfixType(275 /* JSDocNonNullableType */, type); + break; case 55 /* QuestionToken */: - return 270 /* JSDocNullableType */; - } - } - } - function parseArrayTypeOrHigher() { - var type = parseJSDocPostfixTypeOrHigher(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21 /* OpenBracketToken */)) { - if (isStartOfType()) { - var node = createNode(171 /* IndexedAccessType */, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); - } - else { - var node = createNode(164 /* ArrayType */, type.pos); - node.elementType = type; - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); + type = createJSDocPostfixType(274 /* JSDocNullableType */, type); + break; + case 21 /* OpenBracketToken */: + parseExpected(21 /* OpenBracketToken */); + if (isStartOfType()) { + var node = createNode(172 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(165 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + break; + default: + return type; } } return type; } + function createJSDocPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } function parseTypeOperator(operator) { - var node = createNode(170 /* TypeOperator */); + var node = createNode(171 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseTypeOperatorOrHigher() { - switch (token()) { + var operator = token(); + switch (operator) { case 127 /* KeyOfKeyword */: - return parseTypeOperator(127 /* KeyOfKeyword */); + case 140 /* UniqueKeyword */: + return parseTypeOperator(operator); + case 24 /* DotDotDotToken */: { + var result = createNode(278 /* JSDocVariadicType */); + nextToken(); + result.type = parsePostfixTypeOrHigher(); + return finishNode(result); + } } - return parseArrayTypeOrHigher(); + return parsePostfixTypeOrHigher(); } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { parseOptional(operator); @@ -14641,10 +15547,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(168 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(167 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); } function isStartOfFunctionType() { if (token() === 27 /* LessThanToken */) { @@ -14701,7 +15607,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(158 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(159 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -14724,10 +15630,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160 /* FunctionType */); + return parseFunctionOrConstructorType(161 /* FunctionType */); } if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(161 /* ConstructorType */); + return parseFunctionOrConstructorType(162 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -14821,33 +15727,8 @@ var ts; } return expr; } - function parseInitializer(inParameter, requireEqualsToken) { - if (token() !== 58 /* EqualsToken */) { - // It's not uncommon during typing for the user to miss writing the '=' token. Check if - // there is no newline after the last token and if we're on an expression. If so, parse - // this as an equals-value clause with a missing equals. - // NOTE: There are two places where we allow equals-value clauses. The first is in a - // variable declarator. The second is with a parameter. For variable declarators - // it's more likely that a { would be a allowed (as an object literal). While this - // is also allowed for parameters, the risk is that we consume the { as an object - // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17 /* OpenBraceToken */) || !isStartOfExpression()) { - // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - - // do not try to parse initializer - return undefined; - } - if (inParameter && requireEqualsToken) { - // = is required when speculatively parsing arrow function parameters, - // so return a fake initializer as a signal that the equals token was missing - var result = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics._0_expected, "="); - result.escapedText = "= not found"; - return result; - } - } - // Initializer[In, Yield] : - // = AssignmentExpression[?In, ?Yield] - parseExpected(58 /* EqualsToken */); - return parseAssignmentExpressionOrHigher(); + function parseInitializer() { + return parseOptional(58 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { // AssignmentExpression[in,yield]: @@ -14937,7 +15818,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(197 /* YieldExpression */); + var node = createNode(198 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -14959,13 +15840,13 @@ var ts; ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(187 /* ArrowFunction */, asyncModifier.pos); + node = createNode(188 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(187 /* ArrowFunction */, identifier.pos); + node = createNode(188 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(146 /* Parameter */, identifier.pos); + var parameter = createNode(147 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -14998,7 +15879,7 @@ var ts; arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); + return finishNode(arrowFunction); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -15059,22 +15940,38 @@ var ts; if (second === 24 /* DotDotDotToken */) { return 1 /* True */; } + // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This + // isn't actually allowed, but we want to treat it as a lambda so we can provide + // a good error message. + if (ts.isModifierKind(second) && second !== 120 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + return 1 /* True */; + } // If we had "(" followed by something that's not an identifier, // then this definitely doesn't look like a lambda. - // Note: we could be a little more lenient and allow - // "(public" or "(private". These would not ever actually be allowed, - // but we could provide a good error message instead of bailing out. if (!isIdentifier()) { return 0 /* False */; } - // If we have something like "(a:", then we must have a - // type-annotated parameter in an arrow function expression. - if (nextToken() === 56 /* ColonToken */) { - return 1 /* True */; + switch (nextToken()) { + case 56 /* ColonToken */: + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + return 1 /* True */; + case 55 /* QuestionToken */: + nextToken(); + // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 58 /* EqualsToken */ || token() === 20 /* CloseParenToken */) { + return 1 /* True */; + } + // Otherwise it is definitely not a lambda. + return 0 /* False */; + case 26 /* CommaToken */: + case 58 /* EqualsToken */: + case 20 /* CloseParenToken */: + // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function + return 2 /* Unknown */; } - // This *could* be a parenthesized arrow function. - // Return Unknown to let the caller know. - return 2 /* Unknown */; + // It is definitely not an arrow function + return 0 /* False */; } else { ts.Debug.assert(first === 27 /* LessThanToken */); @@ -15145,7 +16042,7 @@ var ts; return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187 /* ArrowFunction */); + var node = createNodeWithJSDoc(188 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -15168,8 +16065,7 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && ((token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) || - ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { + if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } @@ -15212,7 +16108,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(195 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(196 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -15225,7 +16121,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 142 /* OfKeyword */; + return t === 92 /* InKeyword */ || t === 143 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -15333,39 +16229,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194 /* BinaryExpression */, left.pos); + var node = createNode(195 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(202 /* AsExpression */, left.pos); + var node = createNode(203 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(192 /* PrefixUnaryExpression */); + var node = createNode(193 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(188 /* DeleteExpression */); + var node = createNode(189 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(189 /* TypeOfExpression */); + var node = createNode(190 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(190 /* VoidExpression */); + var node = createNode(191 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -15381,7 +16277,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(191 /* AwaitExpression */); + var node = createNode(192 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -15424,7 +16320,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 185 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -15521,20 +16417,20 @@ var ts; */ function parseUpdateExpression() { if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(192 /* PrefixUnaryExpression */); + var node = createNode(193 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(194 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -15648,7 +16544,7 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(179 /* PropertyAccessExpression */, expression.pos); + var node = createNode(180 /* PropertyAccessExpression */, expression.pos); node.expression = expression; parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -15670,21 +16566,28 @@ var ts; return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 251 /* JsxOpeningElement */) { - var node = createNode(249 /* JsxElement */, opening.pos); + if (opening.kind === 252 /* JsxOpeningElement */) { + var node = createNode(250 /* JsxElement */, opening.pos); node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); + node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } + else if (opening.kind === 255 /* JsxOpeningFragment */) { + var node = createNode(254 /* JsxFragment */, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } else { - ts.Debug.assert(opening.kind === 250 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 251 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -15696,10 +16599,10 @@ var ts; // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. if (inExpressionContext && token() === 27 /* LessThanToken */) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194 /* BinaryExpression */, result.pos); + var badNode = createNode(195 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -15711,7 +16614,7 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10 /* JsxText */, scanner.getStartPos()); + var node = createNode(10 /* JsxText */); node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); @@ -15724,11 +16627,11 @@ var ts; case 17 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); } ts.Debug.fail("Unknown JSX child kind " + token()); } - function parseJsxChildren(openingTagName) { + function parseJsxChildren(openingTag) { var list = []; var listPos = getNodePos(); var saveParsingContext = parsingContext; @@ -15742,7 +16645,13 @@ var ts; else if (token() === 1 /* EndOfFileToken */) { // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + var openingTagName = openingTag.tagName; + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + } break; } else if (token() === 7 /* ConflictMarkerTrivia */) { @@ -15757,13 +16666,18 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(254 /* JsxAttributes */); + var jsxAttributes = createNode(258 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); parseExpected(27 /* LessThanToken */); + if (token() === 29 /* GreaterThanToken */) { + parseExpected(29 /* GreaterThanToken */); + var node_1 = createNode(255 /* JsxOpeningFragment */, fullStart); + return finishNode(node_1); + } var tagName = parseJsxElementName(); var attributes = parseJsxAttributes(); var node; @@ -15771,7 +16685,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(251 /* JsxOpeningElement */, fullStart); + node = createNode(252 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -15783,7 +16697,7 @@ var ts; parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(250 /* JsxSelfClosingElement */, fullStart); + node = createNode(251 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -15799,7 +16713,7 @@ var ts; var expression = token() === 99 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(180 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -15807,7 +16721,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(256 /* JsxExpression */); + var node = createNode(260 /* JsxExpression */); parseExpected(17 /* OpenBraceToken */); if (token() !== 18 /* CloseBraceToken */) { node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); @@ -15827,7 +16741,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(253 /* JsxAttribute */); + var node = createNode(257 /* JsxAttribute */); node.name = parseIdentifierName(); if (token() === 58 /* EqualsToken */) { switch (scanJsxAttributeValue()) { @@ -15842,7 +16756,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(255 /* JsxSpreadAttribute */); + var node = createNode(259 /* JsxSpreadAttribute */); parseExpected(17 /* OpenBraceToken */); parseExpected(24 /* DotDotDotToken */); node.expression = parseExpression(); @@ -15850,7 +16764,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252 /* JsxClosingElement */); + var node = createNode(253 /* JsxClosingElement */); parseExpected(28 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -15862,8 +16776,24 @@ var ts; } return finishNode(node); } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(256 /* JsxClosingFragment */); + parseExpected(28 /* LessThanSlashToken */); + if (ts.tokenIsIdentifierOrKeyword(token())) { + var unexpectedTagName = parseJsxElementName(); + parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } function parseTypeAssertion() { - var node = createNode(184 /* TypeAssertionExpression */); + var node = createNode(185 /* TypeAssertionExpression */); parseExpected(27 /* LessThanToken */); node.type = parseType(); parseExpected(29 /* GreaterThanToken */); @@ -15874,7 +16804,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(180 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -15882,14 +16812,14 @@ var ts; } if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(203 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(204 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(180 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(181 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. @@ -15905,7 +16835,7 @@ var ts; continue; } if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { - var tagExpression = createNode(183 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(184 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -15928,7 +16858,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(181 /* CallExpression */, expression.pos); + var callExpr = createNode(182 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -15936,7 +16866,7 @@ var ts; continue; } else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(181 /* CallExpression */, expression.pos); + var callExpr = createNode(182 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -16046,28 +16976,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(185 /* ParenthesizedExpression */); + var node = createNodeWithJSDoc(186 /* ParenthesizedExpression */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseSpreadElement() { - var node = createNode(198 /* SpreadElement */); + var node = createNode(199 /* SpreadElement */); parseExpected(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(200 /* OmittedExpression */) : + token() === 26 /* CommaToken */ ? createNode(201 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(177 /* ArrayLiteralExpression */); + var node = createNode(178 /* ArrayLiteralExpression */); parseExpected(21 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -16076,36 +17006,28 @@ var ts; parseExpected(22 /* CloseBracketToken */); return finishNode(node); } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(153 /* GetAccessor */, fullStart, decorators, modifiers); + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0 /* Unknown */); + if (parseOptionalToken(24 /* DotDotDotToken */)) { + node.kind = 267 /* SpreadAssignment */; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } - else if (parseContextualModifier(135 /* SetKeyword */)) { - return parseAccessorDeclaration(154 /* SetAccessor */, fullStart, decorators, modifiers); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 154 /* GetAccessor */); } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - if (dotDotDotToken) { - var spreadElement = createNode(263 /* SpreadAssignment */, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 155 /* SetAccessor */); } var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); + node.name = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + return parseMethodDeclaration(node, asteriskToken); } // check if it is short-hand property assignment or normal property assignment // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production @@ -16114,28 +17036,22 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262 /* ShorthandPropertyAssignment */, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; + node.kind = 266 /* ShorthandPropertyAssignment */; var equalsToken = parseOptionalToken(58 /* EqualsToken */); if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(261 /* PropertyAssignment */, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; + node.kind = 265 /* PropertyAssignment */; parseExpected(56 /* ColonToken */); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } + return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(178 /* ObjectLiteralExpression */); + var node = createNode(179 /* ObjectLiteralExpression */); parseExpected(17 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -16154,7 +17070,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNode(186 /* FunctionExpression */); + var node = createNodeWithJSDoc(187 /* FunctionExpression */); node.modifiers = parseModifiers(); parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); @@ -16170,7 +17086,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; @@ -16179,12 +17095,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(94 /* NewKeyword */); if (parseOptional(23 /* DotToken */)) { - var node_1 = createNode(204 /* MetaProperty */, fullStart); - node_1.keywordToken = 94 /* NewKeyword */; - node_1.name = parseIdentifierName(); - return finishNode(node_1); + var node_2 = createNode(205 /* MetaProperty */, fullStart); + node_2.keywordToken = 94 /* NewKeyword */; + node_2.name = parseIdentifierName(); + return finishNode(node_2); } - var node = createNode(182 /* NewExpression */, fullStart); + var node = createNode(183 /* NewExpression */, fullStart); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); if (node.typeArguments || token() === 19 /* OpenParenToken */) { @@ -16194,7 +17110,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207 /* Block */); + var node = createNode(208 /* Block */); if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -16227,12 +17143,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(209 /* EmptyStatement */); + var node = createNode(210 /* EmptyStatement */); parseExpected(25 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(211 /* IfStatement */); + var node = createNode(212 /* IfStatement */); parseExpected(90 /* IfKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -16242,7 +17158,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(212 /* DoStatement */); + var node = createNode(213 /* DoStatement */); parseExpected(81 /* DoKeyword */); node.statement = parseStatement(); parseExpected(106 /* WhileKeyword */); @@ -16257,7 +17173,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(213 /* WhileStatement */); + var node = createNode(214 /* WhileStatement */); parseExpected(106 /* WhileKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -16280,8 +17196,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142 /* OfKeyword */) : parseOptional(142 /* OfKeyword */)) { - var forOfStatement = createNode(216 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(143 /* OfKeyword */) : parseOptional(143 /* OfKeyword */)) { + var forOfStatement = createNode(217 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -16289,14 +17205,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(215 /* ForInStatement */, pos); + var forInStatement = createNode(216 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(214 /* ForStatement */, pos); + var forStatement = createNode(215 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(25 /* SemicolonToken */); if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { @@ -16314,7 +17230,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 218 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 219 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -16322,7 +17238,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(219 /* ReturnStatement */); + var node = createNode(220 /* ReturnStatement */); parseExpected(96 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -16331,16 +17247,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(220 /* WithStatement */); + var node = createNode(221 /* WithStatement */); parseExpected(107 /* WithKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - node.statement = parseStatement(); + node.statement = doInsideOfContext(4194304 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(257 /* CaseClause */); + var node = createNode(261 /* CaseClause */); parseExpected(73 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(56 /* ColonToken */); @@ -16348,7 +17264,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(258 /* DefaultClause */); + var node = createNode(262 /* DefaultClause */); parseExpected(79 /* DefaultKeyword */); parseExpected(56 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -16358,12 +17274,12 @@ var ts; return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(221 /* SwitchStatement */); + var node = createNode(222 /* SwitchStatement */); parseExpected(98 /* SwitchKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(235 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(236 /* CaseBlock */); parseExpected(17 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(18 /* CloseBraceToken */); @@ -16378,7 +17294,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(223 /* ThrowStatement */); + var node = createNode(224 /* ThrowStatement */); parseExpected(100 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -16386,7 +17302,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(224 /* TryStatement */); + var node = createNode(225 /* TryStatement */); parseExpected(102 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -16399,7 +17315,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(260 /* CatchClause */); + var result = createNode(264 /* CatchClause */); parseExpected(74 /* CatchKeyword */); if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -16413,7 +17329,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(225 /* DebuggerStatement */); + var node = createNode(226 /* DebuggerStatement */); parseExpected(78 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -16422,20 +17338,19 @@ var ts; // Avoiding having to do the lookahead for a labeled statement by just trying to parse // out an expression, seeing if it is identifier and then seeing if it is followed by // a colon. - var fullStart = scanner.getStartPos(); + var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - var labeledStatement = createNode(222 /* LabeledStatement */, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); + node.kind = 223 /* LabeledStatement */; + node.label = expression; + node.statement = parseStatement(); } else { - var expressionStatement = createNode(210 /* ExpressionStatement */, fullStart); - expressionStatement.expression = expression; + node.kind = 211 /* ExpressionStatement */; + node.expression = expression; parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); } + return finishNode(node); } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); @@ -16503,7 +17418,7 @@ var ts; return false; } continue; - case 141 /* GlobalKeyword */: + case 142 /* GlobalKeyword */: nextToken(); return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; case 91 /* ImportKeyword */: @@ -16567,7 +17482,7 @@ var ts; case 128 /* ModuleKeyword */: case 129 /* NamespaceKeyword */: case 138 /* TypeKeyword */: - case 141 /* GlobalKeyword */: + case 142 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 114 /* PublicKeyword */: @@ -16598,16 +17513,16 @@ var ts; case 17 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); case 104 /* VarKeyword */: - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseVariableStatement(createNodeWithJSDoc(227 /* VariableDeclaration */)); case 110 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseVariableStatement(createNodeWithJSDoc(227 /* VariableDeclaration */)); } break; case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseFunctionDeclaration(createNodeWithJSDoc(229 /* FunctionDeclaration */)); case 75 /* ClassKeyword */: - return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + return parseClassDeclaration(createNodeWithJSDoc(230 /* ClassDeclaration */)); case 90 /* IfKeyword */: return parseIfStatement(); case 81 /* DoKeyword */: @@ -16617,9 +17532,9 @@ var ts; case 88 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(217 /* ContinueStatement */); + return parseBreakOrContinueStatement(218 /* ContinueStatement */); case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(218 /* BreakStatement */); + return parseBreakOrContinueStatement(219 /* BreakStatement */); case 96 /* ReturnKeyword */: return parseReturnStatement(); case 107 /* WithKeyword */: @@ -16653,7 +17568,7 @@ var ts; case 117 /* AbstractKeyword */: case 115 /* StaticKeyword */: case 131 /* ReadonlyKeyword */: - case 141 /* GlobalKeyword */: + case 142 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -16661,51 +17576,66 @@ var ts; } return parseExpressionOrLabeledStatement(); } + function isDeclareModifier(modifier) { + return modifier.kind === 124 /* DeclareKeyword */; + } function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 2097152 /* Ambient */; + } + return doInsideOfContext(2097152 /* Ambient */, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { switch (token()) { case 104 /* VarKeyword */: case 110 /* LetKeyword */: case 76 /* ConstKeyword */: - return parseVariableStatement(fullStart, decorators, modifiers); + return parseVariableStatement(node); case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(fullStart, decorators, modifiers); + return parseFunctionDeclaration(node); case 75 /* ClassKeyword */: - return parseClassDeclaration(fullStart, decorators, modifiers); + return parseClassDeclaration(node); case 109 /* InterfaceKeyword */: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); + return parseInterfaceDeclaration(node); case 138 /* TypeKeyword */: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + return parseTypeAliasDeclaration(node); case 83 /* EnumKeyword */: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141 /* GlobalKeyword */: + return parseEnumDeclaration(node); + case 142 /* GlobalKeyword */: case 128 /* ModuleKeyword */: case 129 /* NamespaceKeyword */: - return parseModuleDeclaration(fullStart, decorators, modifiers); + return parseModuleDeclaration(node); case 91 /* ImportKeyword */: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + return parseImportDeclarationOrImportEqualsDeclaration(node); case 84 /* ExportKeyword */: nextToken(); switch (token()) { case 79 /* DefaultKeyword */: case 58 /* EqualsToken */: - return parseExportAssignment(fullStart, decorators, modifiers); + return parseExportAssignment(node); case 118 /* AsKeyword */: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + return parseNamespaceExportDeclaration(node); default: - return parseExportDeclaration(fullStart, decorators, modifiers); + return parseExportDeclaration(node); } default: - if (decorators || modifiers) { + if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(247 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); + var missing = createMissingNode(248 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); } } } @@ -16723,16 +17653,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token() === 26 /* CommaToken */) { - return createNode(200 /* OmittedExpression */); + return createNode(201 /* OmittedExpression */); } - var node = createNode(176 /* BindingElement */); + var node = createNode(177 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); - node.initializer = parseInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(176 /* BindingElement */); + var node = createNode(177 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -16744,18 +17674,18 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(174 /* ObjectBindingPattern */); + var node = createNode(175 /* ObjectBindingPattern */); parseExpected(17 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(175 /* ArrayBindingPattern */); + var node = createNode(176 /* ArrayBindingPattern */); parseExpected(21 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(22 /* CloseBracketToken */); @@ -16773,17 +17703,24 @@ var ts; } return parseIdentifier(); } - function parseVariableDeclaration() { - var node = createNode(226 /* VariableDeclaration */); + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(/*allowExclamation*/ true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(227 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 71 /* Identifier */ && + token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227 /* VariableDeclarationList */); + var node = createNode(228 /* VariableDeclarationList */); switch (token()) { case 104 /* VarKeyword */: break; @@ -16806,13 +17743,13 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 142 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 143 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -16820,18 +17757,14 @@ var ts; function canFollowContextualOfKeyword() { return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208 /* VariableStatement */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseVariableStatement(node) { + node.kind = 209 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228 /* FunctionDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseFunctionDeclaration(node) { + node.kind = 229 /* FunctionDeclaration */; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); @@ -16839,37 +17772,30 @@ var ts; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152 /* Constructor */, pos); - node.decorators = decorators; - node.modifiers = modifiers; + function parseConstructorDeclaration(node) { + node.kind = 153 /* Constructor */; parseExpected(123 /* ConstructorKeyword */); fillSignature(56 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151 /* MethodDeclaration */, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 152 /* MethodDeclaration */; + node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; - var isAsync = ts.hasModifier(method, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; - fillSignature(56 /* ColonToken */, isGenerator | isAsync, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149 /* PropertyDeclaration */, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 150 /* PropertyDeclaration */; + if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); // For instance properties specifically, since they are evaluated inside the constructor, // we do *not * want to parse yield expressions, so we specifically turn the yield context // off. The grammar would look something like this: @@ -16879,36 +17805,29 @@ var ts; // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = ts.hasModifier(property, 32 /* Static */) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); + node.initializer = ts.hasModifier(node, 32 /* Static */) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseInitializer); parseSemicolon(); - return addJSDocComment(finishNode(property)); + return finishNode(node); } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + function parsePropertyOrMethodDeclaration(node) { var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var name = parsePropertyName(); + node.name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } + return parsePropertyDeclaration(node); } - function parseNonParameterInitializer() { - return parseInitializer(/*inParameter*/ false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseAccessorDeclaration(node, kind) { + node.kind = kind; node.name = parsePropertyName(); fillSignature(56 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -16988,7 +17907,7 @@ var ts; if (!parseOptional(57 /* AtToken */)) { break; } - var decorator = createNode(147 /* Decorator */, decoratorStart); + var decorator = createNode(148 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -17038,22 +17957,24 @@ var ts; } function parseClassElement() { if (token() === 25 /* SemicolonToken */) { - var result = createNode(206 /* SemicolonClassElement */); + var result = createNode(207 /* SemicolonClassElement */); nextToken(); return finishNode(result); } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + var node = createNodeWithJSDoc(0 /* Unknown */); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(node, 154 /* GetAccessor */); + } + if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(node, 155 /* SetAccessor */); } if (token() === 123 /* ConstructorKeyword */) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); + return parseConstructorDeclaration(node); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + return parseIndexSignatureDeclaration(node); } // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name @@ -17062,29 +17983,24 @@ var ts; token() === 8 /* NumericLiteral */ || token() === 39 /* AsteriskToken */ || token() === 21 /* OpenBracketToken */) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + return parsePropertyOrMethodDeclaration(node); } - if (decorators || modifiers) { + if (node.decorators || node.modifiers) { // treat this as a property declaration with a missing name. - var name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); + node.name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression( - /*fullStart*/ scanner.getStartPos(), - /*decorators*/ undefined, - /*modifiers*/ undefined, 199 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 200 /* ClassExpression */); } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229 /* ClassDeclaration */); + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 230 /* ClassDeclaration */); } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; parseExpected(75 /* ClassKeyword */); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -17098,7 +18014,7 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseNameOfClassDeclarationOrExpression() { // implements is a future reserved word so @@ -17124,7 +18040,7 @@ var ts; function parseHeritageClause() { var tok = token(); if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(259 /* HeritageClause */); + var node = createNode(263 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -17133,56 +18049,53 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(201 /* ExpressionWithTypeArguments */); + var node = createNode(202 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } + node.typeArguments = tryParseTypeArguments(); return finishNode(node); } + function tryParseTypeArguments() { + return token() === 27 /* LessThanToken */ + ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + : undefined; + } function isHeritageClause() { return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230 /* InterfaceDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseInterfaceDeclaration(node) { + node.kind = 231 /* InterfaceDeclaration */; parseExpected(109 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231 /* TypeAliasDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseTypeAliasDeclaration(node) { + node.kind = 232 /* TypeAliasDeclaration */; parseExpected(138 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(58 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(264 /* EnumMember */, scanner.getStartPos()); + var node = createNodeWithJSDoc(268 /* EnumMember */); node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232 /* EnumDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseEnumDeclaration(node) { + node.kind = 233 /* EnumDeclaration */; parseExpected(83 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(17 /* OpenBraceToken */)) { @@ -17192,10 +18105,10 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseModuleBlock() { - var node = createNode(234 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(235 /* ModuleBlock */); if (parseExpected(17 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(18 /* CloseBraceToken */); @@ -17205,25 +18118,21 @@ var ts; } return finishNode(node); } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 234 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; - node.decorators = decorators; - node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(23 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141 /* GlobalKeyword */) { + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 234 /* ModuleDeclaration */; + if (token() === 142 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -17240,11 +18149,11 @@ var ts; } return finishNode(node); } - function parseModuleDeclaration(fullStart, decorators, modifiers) { + function parseModuleDeclaration(node) { var flags = 0; - if (token() === 141 /* GlobalKeyword */) { + if (token() === 142 /* GlobalKeyword */) { // global augmentation - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } else if (parseOptional(129 /* NamespaceKeyword */)) { flags |= 16 /* Namespace */; @@ -17252,10 +18161,10 @@ var ts; else { parseExpected(128 /* ModuleKeyword */); if (token() === 9 /* StringLiteral */) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { return token() === 132 /* RequireKeyword */ && @@ -17267,52 +18176,46 @@ var ts; function nextTokenIsSlash() { return nextToken() === 41 /* SlashToken */; } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236 /* NamespaceExportDeclaration */, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; + function parseNamespaceExportDeclaration(node) { + node.kind = 237 /* NamespaceExportDeclaration */; parseExpected(118 /* AsKeyword */); parseExpected(129 /* NamespaceKeyword */); - exportDeclaration.name = parseIdentifier(); + node.name = parseIdentifier(); parseSemicolon(); - return finishNode(exportDeclaration); + return finishNode(node); } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + function parseImportDeclarationOrImportEqualsDeclaration(node) { parseExpected(91 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 140 /* FromKeyword */) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + if (token() !== 26 /* CommaToken */ && token() !== 141 /* FromKeyword */) { + return parseImportEqualsDeclaration(node, identifier); } } // Import statement - var importDeclaration = createNode(238 /* ImportDeclaration */, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; + node.kind = 239 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || // import id token() === 39 /* AsteriskToken */ || // import * token() === 17 /* OpenBraceToken */) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140 /* FromKeyword */); + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(141 /* FromKeyword */); } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); + node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); - return finishNode(importDeclaration); + return finishNode(node); } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237 /* ImportEqualsDeclaration */, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 238 /* ImportEqualsDeclaration */; + node.name = identifier; parseExpected(58 /* EqualsToken */); - importEqualsDeclaration.moduleReference = parseModuleReference(); + node.moduleReference = parseModuleReference(); parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); + return finishNode(node); } function parseImportClause(identifier, fullStart) { // ImportClause: @@ -17321,7 +18224,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(239 /* ImportClause */, fullStart); + var importClause = createNode(240 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -17331,7 +18234,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(241 /* NamedImports */); + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(242 /* NamedImports */); } return finishNode(importClause); } @@ -17341,7 +18244,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(248 /* ExternalModuleReference */); + var node = createNode(249 /* ExternalModuleReference */); parseExpected(132 /* RequireKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -17364,7 +18267,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(240 /* NamespaceImport */); + var namespaceImport = createNode(241 /* NamespaceImport */); parseExpected(39 /* AsteriskToken */); parseExpected(118 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -17379,14 +18282,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 241 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 242 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(246 /* ExportSpecifier */); + return parseImportOrExportSpecifier(247 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(242 /* ImportSpecifier */); + return parseImportOrExportSpecifier(243 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -17411,37 +18314,33 @@ var ts; else { node.name = identifierName; } - if (kind === 242 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 243 /* ImportSpecifier */ && checkIdentifierIsKeyword) { // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244 /* ExportDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportDeclaration(node) { + node.kind = 245 /* ExportDeclaration */; if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(140 /* FromKeyword */); + parseExpected(141 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(245 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(246 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 140 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(140 /* FromKeyword */); + if (token() === 141 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(141 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } parseSemicolon(); return finishNode(node); } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243 /* ExportAssignment */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportAssignment(node) { + node.kind = 244 /* ExportAssignment */; if (parseOptional(58 /* EqualsToken */)) { node.isExportEquals = true; } @@ -17520,7 +18419,7 @@ var ts; var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment); if (checkJsDirectiveMatchResult) { checkJsDirective = { - enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", /*ignoreCase*/ true) === 0 /* EqualTo */, + enabled: ts.equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"), end: range.end, pos: range.pos }; @@ -17536,10 +18435,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */ - || node.kind === 238 /* ImportDeclaration */ - || node.kind === 243 /* ExportAssignment */ - || node.kind === 244 /* ExportDeclaration */ + || node.kind === 238 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 249 /* ExternalModuleReference */ + || node.kind === 239 /* ImportDeclaration */ + || node.kind === 244 /* ExportAssignment */ + || node.kind === 245 /* ExportDeclaration */ ? node : undefined; }); @@ -17580,8 +18479,8 @@ var ts; var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = createSourceFile("file.js", 5 /* Latest */, 1 /* JS */); + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -17590,19 +18489,20 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression(requireBraces) { - var result = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); - if (!parseExpected(17 /* OpenBraceToken */) && requireBraces) { - return undefined; - } + // Parses out a JSDoc type expression. + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(271 /* JSDocTypeExpression */, scanner.getTokenPos()); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); - parseExpected(18 /* CloseBraceToken */); + if (!mayOmitBraces || hasBrace) { + parseExpected(18 /* CloseBraceToken */); + } fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -17618,7 +18518,7 @@ var ts; if (comment) { comment.parent = parent; } - if (ts.isInJavaScriptFile(parent)) { + if (contextFlags & 65536 /* JavaScriptFile */) { if (!sourceFile.jsDocDiagnostics) { sourceFile.jsDocDiagnostics = []; } @@ -17775,7 +18675,7 @@ var ts; content.charCodeAt(start + 3) !== 42 /* asterisk */; } function createJSDocComment() { - var result = createNode(275 /* JSDocComment */, start); + var result = createNode(279 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -17799,6 +18699,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -17898,7 +18799,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(276 /* JSDocTag */, atToken.pos); + var result = createNode(281 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -17936,7 +18837,7 @@ var ts; switch (node.kind) { case 134 /* ObjectKeyword */: return true; - case 164 /* ArrayType */: + case 165 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; @@ -17952,8 +18853,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Parameter */ ? - createNode(279 /* JSDocParameterTag */, atToken.pos) : - createNode(284 /* JSDocPropertyTag */, atToken.pos); + createNode(284 /* JSDocParameterTag */, atToken.pos) : + createNode(289 /* JSDocPropertyTag */, atToken.pos); var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -17969,7 +18870,7 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(271 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); @@ -17981,9 +18882,9 @@ var ts; children.push(child); } if (children) { - jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 164 /* ArrayType */) { + if (typeExpression.type.kind === 165 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -17992,35 +18893,55 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 280 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 285 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(280 /* JSDocReturnTag */, atToken.pos); + var result = createNode(285 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 281 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 286 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(281 /* JSDocTypeTag */, atToken.pos); + var result = createNode(286 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); + result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); - var result = createNode(277 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(282 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = typeExpression; + result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(17 /* OpenBraceToken */); + var node = createNode(202 /* ExpressionWithTypeArguments */); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(/*createIfMissing*/ true); + while (parseOptional(23 /* DotToken */)) { + var prop = createNode(180 /* PropertyAccessExpression */, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } function parseClassTag(atToken, tagName) { - var tag = createNode(278 /* JSDocClassTag */, atToken.pos); + var tag = createNode(283 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); @@ -18028,7 +18949,7 @@ var ts; function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(283 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(288 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); @@ -18053,9 +18974,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 281 /* JSDocTypeTag */) { + if (child.kind === 286 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -18071,10 +18992,10 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 165 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -18084,7 +19005,7 @@ var ts; var pos = scanner.getTokenPos(); var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(233 /* ModuleDeclaration */, pos); + var jsDocNamespaceNode = createNode(234 /* ModuleDeclaration */, pos); jsDocNamespaceNode.flags |= flags; jsDocNamespaceNode.name = typeNameOrNamespaceName; jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); @@ -18117,7 +19038,7 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 279 /* JSDocParameterTag */ && + if (child && child.kind === 284 /* JSDocParameterTag */ && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -18145,7 +19066,7 @@ var ts; } function tryParseChildTag(target) { ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getStartPos()); + var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -18167,7 +19088,7 @@ var ts; return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocTemplateTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' @@ -18180,7 +19101,7 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145 /* TypeParameter */, name.pos); + var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -18192,7 +19113,7 @@ var ts; break; } } - var result = createNode(282 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(287 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -18716,6 +19637,9 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } })(ts || (ts = {})); /// /// @@ -18729,48 +19653,63 @@ var ts; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); function getModuleInstanceState(node) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 231 /* TypeAliasDeclaration */) { - return 0 /* NonInstantiated */; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2 /* ConstEnumOnly */; - } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { - return 0 /* NonInstantiated */; - } - else if (node.kind === 234 /* ModuleBlock */) { - var state_1 = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return false; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state_1 = 2 /* ConstEnumOnly */; - return false; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state_1 = 1 /* Instantiated */; - return true; + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 233 /* EnumDeclaration */: + if (ts.isConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 235 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 234 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 71 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; } - }); - return state_1; - } - else if (node.kind === 233 /* ModuleDeclaration */) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1 /* Instantiated */; - } - else if (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace) { - return 0 /* NonInstantiated */; - } - else { - return 1 /* Instantiated */; } + return 1 /* Instantiated */; } - ts.getModuleInstanceState = getModuleInstanceState; var ContainerFlags; (function (ContainerFlags) { // The current node is not a container, and no container manipulation should happen before @@ -18830,13 +19769,21 @@ var ts; // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; - var Symbol; + var Symbol; // tslint:disable-line variable-name var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; // state used to aggregate transform flags during bind. var subtreeTransformFlags = 0 /* None */; var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } function bindSourceFile(f, opts) { file = f; options = opts; @@ -18872,7 +19819,7 @@ var ts; } return bindSourceFile; function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { // bind in strict mode source files with alwaysStrict option return true; } @@ -18902,7 +19849,7 @@ var ts; if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233 /* ModuleDeclaration */)) { + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 234 /* ModuleDeclaration */)) { // other kinds of value declarations take precedence over modules symbol.valueDeclaration = node; } @@ -18911,58 +19858,59 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { + if (node.kind === 244 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } var name = ts.getNameOfDeclaration(node); if (name) { if (ts.isAmbientModule(node)) { var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } return ts.getEscapedTextOfIdentifierOrLiteral(name); } switch (node.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: return "__constructor" /* Constructor */; - case 160 /* FunctionType */: - case 155 /* CallSignature */: + case 161 /* FunctionType */: + case 156 /* CallSignature */: return "__call" /* Call */; - case 161 /* ConstructorType */: - case 156 /* ConstructSignature */: + case 162 /* ConstructorType */: + case 157 /* ConstructSignature */: return "__new" /* New */; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return "__index" /* Index */; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); - case 273 /* JSDocFunctionType */: + case 277 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 146 /* Parameter */: + case 147 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 273 /* JSDocFunctionType */); + ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } @@ -19012,7 +19960,7 @@ var ts; // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. symbol = symbolTable.get(name); - if (includes & 788448 /* Classifiable */) { + if (includes & 2885600 /* Classifiable */) { classifiableNames.set(name, true); } if (!symbol) { @@ -19052,15 +20000,15 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 /* ExportAssignment */ && !node.isExportEquals))) { + (isDefaultExport || (node.kind === 244 /* ExportAssignment */ && !node.isExportEquals))) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -19072,7 +20020,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 246 /* ExportSpecifier */ || (node.kind === 237 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 247 /* ExportSpecifier */ || (node.kind === 238 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -19094,9 +20042,9 @@ var ts; // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 283 /* JSDocTypedefTag */) + if (node.kind === 288 /* JSDocTypedefTag */) ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - var isJSDocTypedefInJSDocNamespace = node.kind === 283 /* JSDocTypedefTag */ && + var isJSDocTypedefInJSDocNamespace = node.kind === 288 /* JSDocTypedefTag */ && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; @@ -19159,16 +20107,15 @@ var ts; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); // A non-async 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) { - currentReturnTarget = createBranchLabel(); - } - else { + if (!isIIFE) { currentFlow = { flags: 2 /* Start */ }; if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } - currentReturnTarget = undefined; } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 153 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; @@ -19181,14 +20128,17 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { node.flags |= emitFlags; } - if (isIIFE) { + if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 153 /* Constructor */) { + node.returnFlowNode = currentFlow; + } } - else { + if (!isIIFE) { currentFlow = saveCurrentFlow; } currentBreakTarget = saveBreakTarget; @@ -19271,70 +20221,70 @@ var ts; return; } switch (node.kind) { - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: bindWhileStatement(node); break; - case 212 /* DoStatement */: + case 213 /* DoStatement */: bindDoStatement(node); break; - case 214 /* ForStatement */: + case 215 /* ForStatement */: bindForStatement(node); break; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 211 /* IfStatement */: + case 212 /* IfStatement */: bindIfStatement(node); break; - case 219 /* ReturnStatement */: - case 223 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 224 /* TryStatement */: + case 225 /* TryStatement */: bindTryStatement(node); break; - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: bindSwitchStatement(node); break; - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: bindCaseBlock(node); break; - case 257 /* CaseClause */: + case 261 /* CaseClause */: bindCaseClause(node); break; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: bindLabeledStatement(node); break; - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 181 /* CallExpression */: + case 182 /* CallExpression */: bindCallExpressionFlow(node); break; - case 275 /* JSDocComment */: + case 279 /* JSDocComment */: bindJSDocComment(node); break; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: bindJSDocTypedefTag(node); break; default: @@ -19346,15 +20296,15 @@ var ts; switch (expr.kind) { case 71 /* Identifier */: case 99 /* ThisKeyword */: - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return isNarrowableReference(expr); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return hasNarrowableArgument(expr); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); } return false; @@ -19363,7 +20313,7 @@ var ts; return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || - expr.kind === 179 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + expr.kind === 180 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -19374,14 +20324,14 @@ var ts; } } } - if (expr.expression.kind === 179 /* PropertyAccessExpression */ && + if (expr.expression.kind === 180 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -19402,9 +20352,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 58 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -19482,33 +20432,33 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 211 /* IfStatement */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: + case 212 /* IfStatement */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: return parent.expression === node; - case 214 /* ForStatement */: - case 195 /* ConditionalExpression */: + case 215 /* ForStatement */: + case 196 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 185 /* ParenthesizedExpression */) { + if (node.kind === 186 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 192 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 193 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 194 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + return node.kind === 195 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 54 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 /* ParenthesizedExpression */ || - node.parent.kind === 192 /* PrefixUnaryExpression */ && + while (node.parent.kind === 186 /* ParenthesizedExpression */ || + node.parent.kind === 193 /* PrefixUnaryExpression */ && node.parent.operator === 51 /* ExclamationToken */) { node = node.parent; } @@ -19550,7 +20500,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 223 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -19584,13 +20534,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 216 /* ForOfStatement */) { + if (node.kind === 217 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 227 /* VariableDeclarationList */) { + if (node.initializer.kind !== 228 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -19612,7 +20562,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 219 /* ReturnStatement */) { + if (node.kind === 220 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -19632,7 +20582,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 219 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -19728,7 +20678,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 262 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -19793,16 +20743,16 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); } - if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 213 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -19813,10 +20763,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 177 /* ArrayLiteralExpression */) { + else if (node.kind === 178 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 198 /* SpreadElement */) { + if (e.kind === 199 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -19824,16 +20774,16 @@ var ts; } } } - else if (node.kind === 178 /* ObjectLiteralExpression */) { + else if (node.kind === 179 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 261 /* PropertyAssignment */) { + if (p.kind === 265 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 262 /* ShorthandPropertyAssignment */) { + else if (p.kind === 266 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 263 /* SpreadAssignment */) { + else if (p.kind === 267 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -19889,7 +20839,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 180 /* ElementAccessExpression */) { + if (operator === 58 /* EqualsToken */ && node.left.kind === 181 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -19900,7 +20850,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 179 /* PropertyAccessExpression */) { + if (node.expression.kind === 180 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -19939,7 +20889,7 @@ var ts; } function bindJSDocComment(node) { ts.forEachChild(node, function (n) { - if (n.kind !== 283 /* JSDocTypedefTag */) { + if (n.kind !== 288 /* JSDocTypedefTag */) { bind(n); } }); @@ -19960,10 +20910,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 185 /* ParenthesizedExpression */) { + while (expr.kind === 186 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 186 /* FunctionExpression */ || expr.kind === 187 /* ArrowFunction */) { + if (expr.kind === 187 /* FunctionExpression */ || expr.kind === 188 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -19971,7 +20921,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 179 /* PropertyAccessExpression */) { + if (node.expression.kind === 180 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -19980,53 +20930,53 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 254 /* JsxAttributes */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 179 /* ObjectLiteralExpression */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 258 /* JsxAttributes */: return 1 /* IsContainer */; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 173 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 265 /* SourceFile */: + case 269 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 273 /* JSDocFunctionType */: - case 160 /* FunctionType */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 161 /* ConstructorType */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 156 /* CallSignature */: + case 277 /* JSDocFunctionType */: + case 161 /* FunctionType */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 162 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 260 /* CatchClause */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 235 /* CaseBlock */: + case 264 /* CatchClause */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 236 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 207 /* Block */: + case 208 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -20059,42 +21009,42 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265 /* SourceFile */: + case 269 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 178 /* ObjectLiteralExpression */: - case 230 /* InterfaceDeclaration */: - case 254 /* JsxAttributes */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 179 /* ObjectLiteralExpression */: + case 231 /* InterfaceDeclaration */: + case 258 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 273 /* JSDocFunctionType */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 277 /* JSDocFunctionType */: + case 232 /* TypeAliasDeclaration */: + case 173 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -20115,11 +21065,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 265 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 265 /* SourceFile */ || body.kind === 234 /* ModuleBlock */)) { + var body = node.kind === 269 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 269 /* SourceFile */ || body.kind === 235 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 244 /* ExportDeclaration */ || stat.kind === 243 /* ExportAssignment */) { + if (stat.kind === 245 /* ExportDeclaration */ || stat.kind === 244 /* ExportAssignment */) { return true; } } @@ -20129,7 +21079,7 @@ var ts; function setExportContextFlag(node) { // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + if (node.flags & 2097152 /* Ambient */ && !hasExportDeclarations(node)) { node.flags |= 32 /* ExportContext */; } else { @@ -20165,22 +21115,13 @@ var ts; else { var state = declareModuleSymbol(node); if (state !== 0 /* NonInstantiated */) { - if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; } } } @@ -20214,7 +21155,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 267 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { continue; } var identifier = prop.name; @@ -20226,7 +21167,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */ || prop.kind === 151 /* MethodDeclaration */ + var currentKind = prop.kind === 265 /* PropertyAssignment */ || prop.kind === 266 /* ShorthandPropertyAssignment */ || prop.kind === 152 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -20250,17 +21191,17 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & 8 /* EnumMember */) { + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { symbol.parent = container.symbol; } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -20284,10 +21225,10 @@ var ts; node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { + !(node.flags & 2097152 /* Ambient */)) { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); } } } @@ -20335,7 +21276,7 @@ var ts; // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); } } } @@ -20370,8 +21311,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 265 /* SourceFile */ && - blockScopeContainer.kind !== 233 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 269 /* SourceFile */ && + blockScopeContainer.kind !== 234 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -20381,8 +21322,8 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } function checkStrictModePostfixUnaryExpression(node) { @@ -20445,7 +21386,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 142 /* LastToken */) { + if (node.kind > 143 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -20473,7 +21414,7 @@ var ts; } for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { var tag = _c[_b]; - if (tag.kind === 283 /* JSDocTypedefTag */) { + if (tag.kind === 288 /* JSDocTypedefTag */) { var savedParent = parent; parent = jsDoc; bind(tag); @@ -20512,7 +21453,7 @@ var ts; // current "blockScopeContainer" needs to be set to its immediate namespace parent. if (node.isInJSDocNamespace) { var parentNode = node.parent; - while (parentNode && parentNode.kind !== 283 /* JSDocTypedefTag */) { + while (parentNode && parentNode.kind !== 288 /* JSDocTypedefTag */) { parentNode = parentNode.parent; } bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); @@ -20520,16 +21461,19 @@ var ts; } // falls through case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 266 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -20554,132 +21498,132 @@ var ts; ts.Debug.fail("Unknown special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return checkStrictModeCatchClause(node); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return checkStrictModeWithStatement(node); - case 169 /* ThisType */: + case 170 /* ThisType */: seenThisKeyword = true; return; - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return checkTypePredicate(node); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); - case 146 /* Parameter */: + case 147 /* Parameter */: return bindParameter(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return bindPropertyWorker(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 264 /* EnumMember */: + case 268 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 160 /* FunctionType */: - case 273 /* JSDocFunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 277 /* JSDocFunctionType */: + case 162 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 172 /* MappedType */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 173 /* MappedType */: return bindAnonymousTypeWorker(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return bindFunctionExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return bindJsxAttributes(node); - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return bindImportClause(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return bindExportDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return bindExportAssignment(node); - case 265 /* SourceFile */: + case 269 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 207 /* Block */: + case 208 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 279 /* JSDocParameterTag */: - if (node.parent.kind !== 285 /* JSDocTypeLiteral */) { + case 284 /* JSDocParameterTag */: + if (node.parent.kind !== 280 /* JSDocTypeLiteral */) { break; } // falls through - case 284 /* JSDocPropertyTag */: + case 289 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 276 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 283 /* JSDocTypedefTag */: { + case 288 /* JSDocTypedefTag */: { var fullName = node.fullName; if (!fullName || fullName.kind === 71 /* Identifier */) { return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); @@ -20699,7 +21643,7 @@ var ts; if (parameterName && parameterName.kind === 71 /* Identifier */) { checkStrictModeIdentifier(parameterName); } - if (parameterName && parameterName.kind === 169 /* ThisType */) { + if (parameterName && parameterName.kind === 170 /* ThisType */) { seenThisKeyword = true; } bind(type); @@ -20719,31 +21663,32 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - // An export default clause with an expression exports a value - // We want to exclude both class and function here, this is necessary to issue an error when there are both - // default export-assignment and default export function and class declaration. - var flags = node.kind === 243 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 244 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression exports all meanings of that identifier ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 2097152 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + if (node.parent.kind !== 269 /* SourceFile */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } else { var parent_1 = node.parent; if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } } @@ -20782,15 +21727,12 @@ var ts; function isExportsOrModuleExportsOrAlias(node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); } function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (ts.isIdentifier(node)) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - return false; + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } function isExportsOrModuleExportsOrAliasOrAssignment(node) { return isExportsOrModuleExportsOrAlias(node) || @@ -20815,18 +21757,18 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (container.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: // Declare a 'member' if the container is an ES5 class or ES6 constructor container.symbol.members = container.symbol.members || ts.createSymbolTable(); // It's acceptable for multiple 'this' assignments of the same identifier to occur declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); break; - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 153 /* Constructor */: + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = container.parent; @@ -20835,8 +21777,18 @@ var ts; break; } } + function bindSpecialPropertyDeclaration(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + if (node.expression.kind === 99 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if ((node.expression.kind === 71 /* Identifier */ || node.expression.kind === 180 /* PropertyAccessExpression */) && + node.parent.parent.kind === 269 /* SourceFile */) { + bindStaticPropertyAssignment(node); + } + } function bindPrototypePropertyAssignment(node) { - // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x is a function or class, or not declared. // Look up the function in the local scope, since prototype assignments should // follow the function declaration var leftSideOfAssignment = node.left; @@ -20848,34 +21800,67 @@ var ts; classPrototype.parent = leftSideOfAssignment; bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ true); } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function or class, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ function bindStaticPropertyAssignment(node) { - // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function. - // Look up the function in the local scope, since prototype assignments should + // Look up the function in the local scope, since static assignments should // follow the function declaration - var leftSideOfAssignment = node.left; + var leftSideOfAssignment = node.kind === 180 /* PropertyAccessExpression */ ? node : node.left; var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + if (ts.isIdentifier(target)) { + // Fix up parent pointers since we're going to use these nodes before we bind into them + target.parent = leftSideOfAssignment; + if (node.kind === 195 /* BinaryExpression */) { + leftSideOfAssignment.parent = node; + } + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } } } function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { + var symbol = lookupSymbolForName(functionName); + var targetSymbol = symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol) ? + symbol.valueDeclaration.initializer.symbol : + symbol; + ts.Debug.assert(propertyAccess.parent.kind === 195 /* BinaryExpression */ || propertyAccess.parent.kind === 211 /* ExpressionStatement */); + var isLegalPosition; + if (propertyAccess.parent.kind === 195 /* BinaryExpression */) { + var initializerKind = propertyAccess.parent.right.kind; + isLegalPosition = (initializerKind === 200 /* ClassExpression */ || initializerKind === 187 /* FunctionExpression */) && + propertyAccess.parent.parent.parent.kind === 269 /* SourceFile */; + } + else { + isLegalPosition = propertyAccess.parent.parent.kind === 269 /* SourceFile */; + } + if (!isPrototypeProperty && (!targetSymbol || !(targetSymbol.flags & 1920 /* Namespace */)) && isLegalPosition) { + ts.Debug.assert(ts.isIdentifier(propertyAccess.expression)); + var identifier = propertyAccess.expression; + var flags = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags = 106639 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + if (targetSymbol) { + addDeclarationToSymbol(symbol, identifier, flags); + } + else { + targetSymbol = declareSymbol(container.locals, /*parent*/ undefined, identifier, flags, excludeFlags); + } } - if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) { + if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */))) { return; } // Set up the members collection if it doesn't exist already @@ -20883,7 +21868,7 @@ var ts; (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */); + declareSymbol(symbolTable, targetSymbol, propertyAccess, 4 /* Property */, 0 /* PropertyExcludes */); } function bindCallExpression(node) { // We're only inspecting call expressions to detect CommonJS modules, so we can skip @@ -20893,7 +21878,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { @@ -20920,7 +21905,7 @@ var ts; if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); } symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -20956,7 +21941,7 @@ var ts; } } function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { + if (inStrictMode && !(node.flags & 2097152 /* Ambient */)) { // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) checkStrictModeEvalOrArguments(node, node.name); @@ -20975,7 +21960,7 @@ var ts; } } function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -20990,7 +21975,7 @@ var ts; } } function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { if (ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } @@ -21003,7 +21988,7 @@ var ts; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */) && ts.isAsyncFunction(node)) { emitFlags |= 1024 /* HasAsyncFunctions */; } if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { @@ -21025,13 +22010,13 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 209 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 210 /* EmptyStatement */) || // report error on class declarations - node.kind === 229 /* ClassDeclaration */ || + node.kind === 230 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 233 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 234 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 232 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (node.kind === 233 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; // unreachable code is reported if @@ -21044,8 +22029,8 @@ var ts; // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 /* VariableStatement */ || + !(node.flags & 2097152 /* Ambient */) && + (node.kind !== 209 /* VariableStatement */ || ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -21065,56 +22050,56 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 181 /* CallExpression */: + case 182 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); - case 146 /* Parameter */: + case 147 /* Parameter */: return computeParameter(node, subtreeFlags); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152 /* Constructor */: + case 153 /* Constructor */: return computeConstructor(node, subtreeFlags); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return computePropertyDeclaration(node, subtreeFlags); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return computeMethod(node, subtreeFlags); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -21136,6 +22121,11 @@ var ts; } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; @@ -21144,8 +22134,8 @@ var ts; switch (kind) { case 97 /* SuperKeyword */: return true; - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: var expression = node.expression; var expressionKind = expression.kind; return expressionKind === 97 /* SuperKeyword */; @@ -21169,12 +22159,12 @@ var ts; var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 179 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 177 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } @@ -21223,8 +22213,8 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (expressionKind === 202 /* AsExpression */ - || expressionKind === 184 /* TypeAssertionExpression */) { + if (expressionKind === 203 /* AsExpression */ + || expressionKind === 185 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -21342,6 +22332,7 @@ var ts; || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } @@ -21366,6 +22357,7 @@ var ts; if (node.decorators || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { transformFlags |= 3 /* AssertTypeScript */; } @@ -21587,7 +22579,7 @@ var ts; var excludeFlags = 536872257 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; @@ -21597,24 +22589,27 @@ var ts; case 117 /* AbstractKeyword */: case 124 /* DeclareKeyword */: case 76 /* ConstKeyword */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - case 203 /* NonNullExpression */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: + case 250 /* JsxElement */: + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: case 10 /* JsxText */: - case 252 /* JsxClosingElement */: - case 253 /* JsxAttribute */: - case 254 /* JsxAttributes */: - case 255 /* JsxSpreadAttribute */: - case 256 /* JsxExpression */: + case 253 /* JsxClosingElement */: + case 254 /* JsxFragment */: + case 255 /* JsxOpeningFragment */: + case 256 /* JsxClosingFragment */: + case 257 /* JsxAttribute */: + case 258 /* JsxAttributes */: + case 259 /* JsxSpreadAttribute */: + case 260 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; @@ -21622,11 +22617,11 @@ var ts; case 14 /* TemplateHead */: case 15 /* TemplateMiddle */: case 16 /* TemplateTail */: - case 196 /* TemplateExpression */: - case 183 /* TaggedTemplateExpression */: - case 262 /* ShorthandPropertyAssignment */: + case 197 /* TemplateExpression */: + case 184 /* TaggedTemplateExpression */: + case 266 /* ShorthandPropertyAssignment */: case 115 /* StaticKeyword */: - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; @@ -21636,18 +22631,18 @@ var ts; } break; case 8 /* NumericLiteral */: - if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; @@ -21660,36 +22655,36 @@ var ts; case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 158 /* TypePredicate */: - case 159 /* TypeReference */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 162 /* TypeQuery */: - case 163 /* TypeLiteral */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 169 /* ThisType */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 173 /* LiteralType */: - case 236 /* NamespaceExportDeclaration */: + case 146 /* TypeParameter */: + case 149 /* PropertySignature */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 159 /* TypePredicate */: + case 160 /* TypeReference */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 163 /* TypeQuery */: + case 164 /* TypeLiteral */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 170 /* ThisType */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 174 /* LiteralType */: + case 237 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; break; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. @@ -21706,10 +22701,10 @@ var ts; transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; break; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; break; case 97 /* SuperKeyword */: @@ -21720,28 +22715,28 @@ var ts; // Mark this node and its ancestors as containing a lexical `this` keyword. transformFlags |= 16384 /* ContainsLexicalThis */; break; - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; excludeFlags = 537396545 /* BindingPatternExcludes */; break; - case 176 /* BindingElement */: + case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { transformFlags |= 524288 /* ContainsRest */; } break; - case 147 /* Decorator */: + case 148 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: excludeFlags = 540087617 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it @@ -21759,8 +22754,8 @@ var ts; transformFlags |= 8 /* AssertESNext */; } break; - case 177 /* ArrayLiteralExpression */: - case 182 /* NewExpression */: + case 178 /* ArrayLiteralExpression */: + case 183 /* NewExpression */: excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 @@ -21768,23 +22763,23 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 219 /* ReturnStatement */: - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: + case 220 /* ReturnStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; break; } @@ -21800,33 +22795,33 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) { + if (kind >= 159 /* FirstTypeNode */ && kind <= 174 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 177 /* ArrayLiteralExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 178 /* ArrayLiteralExpression */: return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return 574674241 /* ModuleExcludes */; - case 146 /* Parameter */: + case 147 /* Parameter */: return 536872257 /* ParameterExcludes */; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return 601249089 /* ArrowFunctionExcludes */; - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: return 601281857 /* FunctionExcludes */; - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return 546309441 /* VariableDeclarationListExcludes */; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return 539358529 /* ClassExcludes */; - case 152 /* Constructor */: + case 153 /* Constructor */: return 601015617 /* ConstructorExcludes */; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return 601015617 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: @@ -21836,21 +22831,21 @@ var ts; case 122 /* BooleanKeyword */: case 137 /* SymbolKeyword */: case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 146 /* TypeParameter */: + case 149 /* PropertySignature */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return 540087617 /* ObjectLiteralExcludes */; - case 260 /* CatchClause */: + case 264 /* CatchClause */: return 537920833 /* CatchClauseExcludes */; - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return 537396545 /* BindingPatternExcludes */; default: return 536872257 /* NodeExcludes */; @@ -21911,7 +22906,7 @@ var ts; if (shouldBail) return; // Visit the type's related types, if any - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var objectType = type; var objectFlags = objectType.objectFlags; if (objectFlags & 4 /* Reference */) { @@ -21927,16 +22922,16 @@ var ts; visitObjectType(objectType); } } - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 32768 /* TypeParameter */) { visitTypeParameter(type); } - if (type.flags & 196608 /* UnionOrIntersection */) { + if (type.flags & 393216 /* UnionOrIntersection */) { visitUnionOrIntersectionType(type); } - if (type.flags & 262144 /* Index */) { + if (type.flags & 524288 /* Index */) { visitIndexType(type); } - if (type.flags & 524288 /* IndexedAccess */) { + if (type.flags & 1048576 /* IndexedAccess */) { visitIndexedAccessType(type); } } @@ -22024,7 +23019,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 162 /* TypeQuery */) { + if (d.type && d.type.kind === 163 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -22089,7 +23084,7 @@ var ts; return; } var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { + if (!ts.isString(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); } @@ -22138,7 +23133,7 @@ var ts; // And if it doesn't exist, tough. } var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -22574,8 +23569,8 @@ var ts; matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -22797,7 +23792,7 @@ var ts; var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; - return { packageJsonContent: packageJsonContent, packageId: packageId }; + return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { if (directoryExists && traceEnabled) { @@ -22805,7 +23800,7 @@ var ts; } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocations.push(packageJsonPath); - return { packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined }; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { @@ -22854,14 +23849,27 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); + if (packageInfo.found) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); + } + else { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. + packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + } + } var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); } + /* @internal */ function getPackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { @@ -22869,6 +23877,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } @@ -22878,7 +23887,7 @@ var ts; } function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); if (resolutionFromCache) { @@ -22915,24 +23924,32 @@ var ts; /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" } } - return moduleName; + return packageName; } /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -22963,7 +23980,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { // Climb up parent directories looking for a module. - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -23009,20 +24026,6 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } - /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ - 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 || (ts = {})); /// /// @@ -23070,9 +24073,11 @@ var ts; var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; + // tslint:disable variable-name var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); + // tslint:enable variable-name var typeCount = 0; var symbolCount = 0; var enumCount = 0; @@ -23083,10 +24088,12 @@ var ts; var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); @@ -23239,15 +24246,34 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, + getUnionType: getUnionType, + createAnonymousType: createAnonymousType, + createSignature: createSignature, + createSymbol: createSymbol, + createIndexInfo: createIndexInfo, + getAnyType: function () { return anyType; }, + getStringType: function () { return stringType; }, + getNumberType: function () { return numberType; }, + createPromiseType: createPromiseType, + createArrayType: createArrayType, + getBooleanType: function () { return booleanType; }, + getVoidType: function () { return voidType; }, + getUndefinedType: function () { return undefinedType; }, + getNullType: function () { return nullType; }, + getESSymbolType: function () { return esSymbolType; }, + getNeverType: function () { return neverType; }, + isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, - getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + getAccessibleSymbolChain: getAccessibleSymbolChain, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -23255,25 +24281,27 @@ var ts; var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; + var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); + var undefinedType = createIntrinsicType(4096 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 /* Undefined */ | 4194304 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(8192 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 /* Null */ | 4194304 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); var booleanType = createBooleanType([trueType, falseType]); var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(1024 /* Void */, "void"); - var neverType = createIntrinsicType(8192 /* Never */, "never"); - var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var voidType = createIntrinsicType(2048 /* Void */, "void"); + var neverType = createIntrinsicType(16384 /* Never */, "never"); + var silentNeverType = createIntrinsicType(16384 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(16384 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(33554432 /* NonPrimitive */, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); @@ -23283,9 +24311,14 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 16777216 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var markerSuperType = createType(32768 /* TypeParameter */); + var markerSubType = createType(32768 /* TypeParameter */); + markerSubType.constraint = markerSuperType; + var markerOtherType = createType(32768 /* TypeParameter */); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -23293,6 +24326,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -23420,29 +24454,29 @@ var ts; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ - "string": 1 /* TypeofEQString */, - "number": 2 /* TypeofEQNumber */, - "boolean": 4 /* TypeofEQBoolean */, - "symbol": 8 /* TypeofEQSymbol */, - "undefined": 16384 /* EQUndefined */, - "object": 16 /* TypeofEQObject */, - "function": 32 /* TypeofEQFunction */ + string: 1 /* TypeofEQString */, + number: 2 /* TypeofEQNumber */, + boolean: 4 /* TypeofEQBoolean */, + symbol: 8 /* TypeofEQSymbol */, + undefined: 16384 /* EQUndefined */, + object: 16 /* TypeofEQObject */, + function: 32 /* TypeofEQFunction */ }); var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128 /* TypeofNEString */, - "number": 256 /* TypeofNENumber */, - "boolean": 512 /* TypeofNEBoolean */, - "symbol": 1024 /* TypeofNESymbol */, - "undefined": 131072 /* NEUndefined */, - "object": 2048 /* TypeofNEObject */, - "function": 4096 /* TypeofNEFunction */ + string: 128 /* TypeofNEString */, + number: 256 /* TypeofNENumber */, + boolean: 512 /* TypeofNEBoolean */, + symbol: 1024 /* TypeofNESymbol */, + undefined: 131072 /* NEUndefined */, + object: 2048 /* TypeofNEObject */, + function: 4096 /* TypeofNEFunction */ }); var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType + string: stringType, + number: numberType, + boolean: booleanType, + symbol: esSymbolType, + undefined: undefinedType }); var typeofType = createTypeofType(); var _jsxNamespace; @@ -23453,16 +24487,6 @@ var ts; var _hasComputedJsxElementChildrenPropertyName = false; /** Things we lazy load from the JSX namespace */ var jsxTypes = ts.createUnderscoreEscapedMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); @@ -23483,6 +24507,29 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; })(CheckMode || (CheckMode = {})); + var CallbackCheck; + (function (CallbackCheck) { + CallbackCheck[CallbackCheck["None"] = 0] = "None"; + CallbackCheck[CallbackCheck["Bivariant"] = 1] = "Bivariant"; + CallbackCheck[CallbackCheck["Strict"] = 2] = "Strict"; + })(CallbackCheck || (CallbackCheck = {})); + var MappedTypeModifiers; + (function (MappedTypeModifiers) { + MappedTypeModifiers[MappedTypeModifiers["Readonly"] = 1] = "Readonly"; + MappedTypeModifiers[MappedTypeModifiers["Optional"] = 2] = "Optional"; + })(MappedTypeModifiers || (MappedTypeModifiers = {})); + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var MembersOrExportsResolutionKind; + (function (MembersOrExportsResolutionKind) { + MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; + MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; + })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); @@ -23509,16 +24556,16 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } - function error(location, message, arg0, arg1, arg2) { + function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); } - function createSymbol(flags, name) { + function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); - symbol.checkFlags = 0; + symbol.checkFlags = checkFlags || 0; return symbol; } function isTransientSymbol(symbol) { @@ -23583,7 +24630,9 @@ var ts; return result; } function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || + source.flags & 67108864 /* JSContainer */ || target.flags & 67108864 /* JSContainer */) { + // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums target.constEnumOnlyModule = false; @@ -23591,7 +24640,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 233 /* ModuleDeclaration */))) { + (target.valueDeclaration.kind === 234 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 234 /* ModuleDeclaration */))) { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } @@ -23622,6 +24671,16 @@ var ts; }); } } + function combineSymbolTables(first, second) { + if (!first || first.size === 0) + return second; + if (!second || second.size === 0) + return first; + var combined = ts.createSymbolTable(); + mergeSymbolTable(combined, first); + mergeSymbolTable(combined, second); + return combined; + } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { var targetSymbol = target.get(id); @@ -23652,7 +24711,7 @@ var ts; else { // find a module that about to be augmented // do not validate names of augmentations that are defined in ambient context - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152 /* Ambient */) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); @@ -23698,11 +24757,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } - function getObjectFlags(type) { - return type.flags & 32768 /* Object */ ? type.objectFlags : 0; - } function isGlobalSourceFile(node) { - return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 269 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -23733,7 +24789,7 @@ var ts; var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 107455 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -23746,7 +24802,7 @@ var ts; if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - ts.isInAmbientContext(declaration)) { + declaration.flags & 2097152 /* Ambient */) { // nodes are in different files and order cannot be determined return true; } @@ -23760,17 +24816,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 176 /* BindingElement */) { + if (declaration.kind === 177 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 176 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 177 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 227 /* VariableDeclaration */), usage); } - else if (declaration.kind === 226 /* VariableDeclaration */) { + else if (declaration.kind === 227 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -23784,12 +24840,12 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 246 /* ExportSpecifier */ || (usage.parent.kind === 243 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 247 /* ExportSpecifier */ || (usage.parent.kind === 244 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 243 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 244 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); @@ -23797,9 +24853,9 @@ var ts; function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 208 /* VariableStatement */: - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: + case 209 /* VariableStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -23819,16 +24875,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 149 /* PropertyDeclaration */ && + current.parent.kind === 150 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 151 /* MethodDeclaration */) { + if (declaration.kind === 152 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -23851,6 +24907,7 @@ var ts; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; + var lastNonBlockLocation; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; @@ -23867,11 +24924,13 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 275 /* JSDocComment */) { + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 279 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ + // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 146 /* Parameter */ || - lastLocation.kind === 145 /* TypeParameter */ + lastLocation.kind === 147 /* Parameter */ || + lastLocation.kind === 146 /* TypeParameter */ + // local types not visible outside the function body : false; } if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { @@ -23880,9 +24939,9 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 146 /* Parameter */ || + lastLocation.kind === 147 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 146 /* Parameter */); + result.valueDeclaration.kind === 147 /* Parameter */); } } if (useResult) { @@ -23894,14 +24953,14 @@ var ts; } } switch (location.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default")) { @@ -23925,7 +24984,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 246 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 247 /* ExportSpecifier */)) { break; } } @@ -23933,13 +24992,13 @@ var ts; break loop; } break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -23956,10 +25015,10 @@ var ts; } } break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 793064 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -23974,7 +25033,7 @@ var ts; } break loop; } - if (location.kind === 199 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 200 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -23982,7 +25041,7 @@ var ts; } } break; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -24002,9 +25061,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 231 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -24012,19 +25071,19 @@ var ts; } } break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -24037,7 +25096,7 @@ var ts; } } break; - case 147 /* Decorator */: + case 148 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -24046,7 +25105,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 146 /* Parameter */) { + if (location.parent && location.parent.kind === 147 /* Parameter */) { location = location.parent; } // @@ -24060,18 +25119,21 @@ var ts; } break; } + if (location.kind !== 208 /* Block */) { + lastNonBlockLocation = location; + } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 265 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 269 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -24090,7 +25152,7 @@ var ts; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); } } if (!suggestion) { @@ -24132,7 +25194,7 @@ var ts; // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236 /* NamespaceExportDeclaration */) { + if (decls && decls.length === 1 && decls[0].kind === 237 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -24140,12 +25202,12 @@ var ts; return result; } function diagnosticName(nameArg) { - return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 145 /* TypeParameter */ && decl.parent === container) { + if (decl.kind === 146 /* TypeParameter */ && decl.parent === container) { return true; } } @@ -24198,18 +25260,20 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201 /* ExpressionWithTypeArguments */: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; + case 202 /* ExpressionWithTypeArguments */: + if (ts.isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through default: return undefined; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~1920 /* Namespace */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -24250,7 +25314,7 @@ var ts; } } else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -24261,9 +25325,9 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 233 /* EnumDeclaration */) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + if (!(declaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } @@ -24284,13 +25348,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return node; - case 239 /* ImportClause */: + case 240 /* ImportClause */: return node.parent; - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return node.parent.parent; - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -24300,7 +25364,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -24430,19 +25494,19 @@ var ts; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246 /* ExportSpecifier */: + case 247 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); } } @@ -24497,11 +25561,11 @@ var ts; links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); ts.Debug.assert(!!node); - if (node.kind === 243 /* ExportAssignment */) { + if (node.kind === 244 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 246 /* ExportSpecifier */) { + else if (node.kind === 247 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -24523,13 +25587,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 143 /* QualifiedName */) { + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 144 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 237 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 238 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -24551,13 +25615,13 @@ var ts; return undefined; } } - else if (name.kind === 143 /* QualifiedName */ || name.kind === 179 /* PropertyAccessExpression */) { + else if (name.kind === 144 /* QualifiedName */ || name.kind === 180 /* PropertyAccessExpression */) { var left = void 0; - if (name.kind === 143 /* QualifiedName */) { + if (name.kind === 144 /* QualifiedName */) { left = name.left; } - else if (name.kind === 179 /* PropertyAccessExpression */ && - (name.expression.kind === 185 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { + else if (name.kind === 180 /* PropertyAccessExpression */ && + (name.expression.kind === 186 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { left = name.expression; } else { @@ -24567,7 +25631,7 @@ var ts; // i.e class C extends foo()./*do language service operation here*/B {} return undefined; } - var right = name.kind === 143 /* QualifiedName */ ? name.right : name.name; + var right = name.kind === 144 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -24575,6 +25639,9 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } + if (ts.isInJavaScriptFile(name) && ts.isDeclarationOfFunctionOrClassExpression(namespace)) { + namespace = getSymbolOfNode(namespace.valueDeclaration.initializer); + } symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { @@ -24583,7 +25650,7 @@ var ts; return undefined; } } - else if (name.kind === 185 /* ParenthesizedExpression */) { + else if (name.kind === 186 /* ParenthesizedExpression */) { // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. // This is the case when we are trying to do any language service operation in heritage clauses. // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. @@ -24712,16 +25779,20 @@ var ts; } function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); - if (!symbol) { - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); - } + if (symbol) { + return symbol; } - return symbol; + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return undefined; + } + var type = getTypeOfSymbol(exportEquals); + return type.flags & 16382 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : + symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : + symbol.exports || emptySymbols; } function getExportsOfModule(moduleSymbol) { var links = getSymbolLinks(moduleSymbol); @@ -24732,7 +25803,9 @@ var ts; * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables */ function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { + if (!source) + return; + source.forEach(function (sourceSymbol, id) { if (id === "default") return; var targetSymbol = target.get(id); @@ -24799,10 +25872,10 @@ var ts; return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; } function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); } function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 @@ -24816,7 +25889,7 @@ var ts; var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 152 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 153 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -24839,7 +25912,7 @@ var ts; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(32768 /* Object */); + var type = createType(65536 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; return type; @@ -24894,12 +25967,12 @@ var ts; } } switch (location.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -24952,7 +26025,6 @@ var ts; return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */) && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { @@ -24985,7 +26057,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 247 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -25000,10 +26072,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: continue; default: return false; @@ -25085,7 +26157,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -25119,12 +26191,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 162 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + if (entityName.parent.kind === 163 /* TypeQuery */ || + ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || + entityName.parent.kind === 145 /* ComputedPropertyName */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 143 /* QualifiedName */ || entityName.kind === 179 /* PropertyAccessExpression */ || - entityName.parent.kind === 237 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 144 /* QualifiedName */ || entityName.kind === 180 /* PropertyAccessExpression */ || + entityName.parent.kind === 238 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -25201,18 +26275,21 @@ var ts; function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); var context = createNodeBuilderContext(enclosingDeclaration, flags); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; @@ -25246,10 +26323,10 @@ var ts; if (type.flags & 8 /* Boolean */) { return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); - var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, getNameOfSymbol(type.symbol, context)); + var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 272 /* EnumLike */) { @@ -25265,25 +26342,28 @@ var ts; if (type.flags & 128 /* BooleanLiteral */) { return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 1024 /* Void */) { + if (type.flags & 1024 /* UniqueESSymbol */) { + return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); + } + if (type.flags & 2048 /* Void */) { return ts.createKeywordTypeNode(105 /* VoidKeyword */); } - if (type.flags & 2048 /* Undefined */) { + if (type.flags & 4096 /* Undefined */) { return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); } - if (type.flags & 4096 /* Null */) { + if (type.flags & 8192 /* Null */) { return ts.createKeywordTypeNode(95 /* NullKeyword */); } - if (type.flags & 8192 /* Never */) { + if (type.flags & 16384 /* Never */) { return ts.createKeywordTypeNode(130 /* NeverKeyword */); } if (type.flags & 512 /* ESSymbol */) { return ts.createKeywordTypeNode(137 /* SymbolKeyword */); } - if (type.flags & 16777216 /* NonPrimitive */) { + if (type.flags & 33554432 /* NonPrimitive */) { return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { context.encounteredError = true; @@ -25291,13 +26371,13 @@ var ts; } return ts.createThis(); } - var objectFlags = getObjectFlags(type); + var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 16384 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false); + if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + var name = type.symbol ? symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -25306,11 +26386,11 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); } - if (type.flags & (65536 /* Union */ | 131072 /* Intersection */)) { - var types = type.flags & 65536 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { + var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; var typeNodes = mapToTypeNodes(types, context); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 65536 /* Union */ ? 166 /* UnionType */ : 167 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 /* Union */ ? 167 /* UnionType */ : 168 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -25321,23 +26401,23 @@ var ts; } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 262144 /* Index */) { + if (type.flags & 524288 /* Index */) { var indexedType = type.type; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 524288 /* IndexedAccess */) { + if (type.flags & 1048576 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); @@ -25388,7 +26468,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -25407,12 +26487,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 162 /* ConstructorType */, context); return signatureNode; } } @@ -25526,11 +26606,11 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); @@ -25554,7 +26634,7 @@ var ts; var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 150 /* MethodSignature */, context); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 151 /* MethodSignature */, context); methodDeclaration.name = propertyName; methodDeclaration.questionToken = optionalToken; typeElements.push(methodDeclaration); @@ -25574,8 +26654,8 @@ var ts; function mapToTypeNodes(types, context) { if (ts.some(types)) { var result = []; - for (var i = 0; i < types.length; ++i) { - var type = types[i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -25636,28 +26716,23 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); - if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { - // special-case synthetic rest parameters in JS files - return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, parameterSymbol.isRestParameter ? ts.createToken(24 /* DotDotDotToken */) : undefined, "args", - /*questionToken*/ undefined, typeToTypeNodeHelper(anyArrayType, context), - /*initializer*/ undefined); - } - var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; - var name = parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : - ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); - var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 147 /* Parameter */); + ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); var parameterType = getTypeOfSymbol(parameterSymbol); - if (isRequiredInitializedParameter(parameterDeclaration)) { - parameterType = getNullableType(parameterType, 2048 /* Undefined */); + if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { + parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration + ? parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.symbolName(parameterSymbol) + : ts.symbolName(parameterSymbol); + var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); @@ -25667,7 +26742,7 @@ var ts; function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 176 /* BindingElement */) { + if (clone.kind === 177 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); @@ -25709,8 +26784,7 @@ var ts; } typeParameterNodes = mapToTypeNodes(typeParameters, context); } - var symbolName = getNameOfSymbol(symbol, context); - var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ @@ -25755,10 +26829,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 6144 /* Nullable */)) { + if (!(t.flags & 12288 /* Nullable */)) { if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 65536 /* Union */) { + if (baseType.flags & 131072 /* Union */) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -25770,9 +26844,9 @@ var ts; result.push(t); } } - if (flags & 4096 /* Null */) + if (flags & 8192 /* Null */) result.push(nullType); - if (flags & 2048 /* Undefined */) + if (flags & 4096 /* Undefined */) result.push(undefinedType); return result || types; } @@ -25787,8 +26861,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168 /* ParenthesizedType */; }); - if (node.kind === 231 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 169 /* ParenthesizedType */; }); + if (node.kind === 232 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -25796,30 +26870,37 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 234 /* ModuleBlock */ && + node.parent.kind === 235 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol, context) { + /** + * Gets a human-readable name for a symbol. + * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. + * + * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. + * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. + */ + function getNameOfSymbolAsWritten(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { context.encounteredError = true; } switch (declaration.kind) { - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -25829,7 +26910,7 @@ var ts; return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; } } - return ts.unescapeLeadingUnderscores(symbol.escapedName); + return ts.symbolName(symbol); } function getSymbolDisplayBuilder() { /** @@ -25837,7 +26918,7 @@ var ts; * for the name of the symbol if it is available to match how the user wrote the name. */ function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); + writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); } /** * Writes a property access or element access with the name of the symbol out to the writer. @@ -25845,18 +26926,22 @@ var ts; * ensuring that any names written with literals use element accesses. */ function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); + var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); var firstChar = symbolName.charCodeAt(0); var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); if (needsElementAccess) { - writePunctuation(writer, 21 /* OpenBracketToken */); + if (firstChar !== 91 /* openBracket */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + } if (ts.isSingleOrDoubleQuote(firstChar)) { writer.writeStringLiteral(symbolName); } else { writer.writeSymbol(symbolName, symbol); } - writePunctuation(writer, 22 /* CloseBracketToken */); + if (firstChar !== 91 /* openBracket */) { + writePunctuation(writer, 22 /* CloseBracketToken */); + } } else { writePunctuation(writer, 23 /* DotToken */); @@ -25942,22 +27027,22 @@ var ts; function writeType(type, flags) { var nextFlags = flags & ~1024 /* InTypeAlias */; // Write undefined/null type as any - if (type.flags & 16793231 /* Intrinsic */) { + if (type.flags & 33585807 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (getObjectFlags(type) & 4 /* Reference */) { + else if (ts.getObjectFlags(type) & 4 /* Reference */) { writeTypeReference(type, nextFlags); } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */)) { + else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { var parent = getParentOfSymbol(type.symbol); buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); // In a literal enum type with a single member E { A }, E and E.A denote the @@ -25967,7 +27052,7 @@ var ts; appendSymbolNameOnly(type.symbol, writer); } } - else if (getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 16384 /* TypeParameter */)) { + else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } @@ -25976,16 +27061,26 @@ var ts; var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); } - else if (type.flags & 196608 /* UnionOrIntersection */) { + else if (type.flags & 393216 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); } - else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { + else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { writeAnonymousType(type, nextFlags); } + else if (type.flags & 1024 /* UniqueESSymbol */) { + if (flags & 131072 /* AllowUniqueESSymbolType */) { + writeKeyword(writer, 140 /* UniqueKeyword */); + writeSpace(writer); + } + else { + writer.reportInaccessibleUniqueSymbolError(); + } + writeKeyword(writer, 137 /* SymbolKeyword */); + } else if (type.flags & 96 /* StringOrNumberLiteral */) { writer.writeStringLiteral(literalTypeToString(type)); } - else if (type.flags & 262144 /* Index */) { + else if (type.flags & 524288 /* Index */) { if (flags & 128 /* InElementType */) { writePunctuation(writer, 19 /* OpenParenToken */); } @@ -25996,7 +27091,7 @@ var ts; writePunctuation(writer, 20 /* CloseParenToken */); } } - else if (type.flags & 524288 /* IndexedAccess */) { + else if (type.flags & 1048576 /* IndexedAccess */) { writeType(type.objectType, 128 /* InElementType */); writePunctuation(writer, 21 /* OpenBracketToken */); writeType(type.indexType, 0 /* None */); @@ -26056,8 +27151,8 @@ var ts; } else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 199 /* ClassExpression */) { - writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + writeAnonymousType(type, flags); } else { // Write the type reference in the format f
.g.C where A and B are type arguments @@ -26090,7 +27185,7 @@ var ts; if (flags & 128 /* InElementType */) { writePunctuation(writer, 19 /* OpenParenToken */); } - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); } else { @@ -26106,12 +27201,12 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 199 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || + !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); + writeTypeOfSymbol(type.symbol, flags); } else if (ts.contains(symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name @@ -26155,7 +27250,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -26164,13 +27259,13 @@ var ts; } } } - function writeTypeOfSymbol(type, typeFormatFlags) { + function writeTypeOfSymbol(symbol, typeFormatFlags) { if (typeFormatFlags & 32768 /* InArrayType */) { writePunctuation(writer, 19 /* OpenParenToken */); } writeKeyword(writer, 103 /* TypeOfKeyword */); writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); if (typeFormatFlags & 32768 /* InArrayType */) { writePunctuation(writer, 20 /* CloseParenToken */); } @@ -26180,6 +27275,13 @@ var ts; writeKeyword(writer, 131 /* ReadonlyKeyword */); writeSpace(writer); } + if (ts.getCheckFlags(prop) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(prop.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name) { + writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); + } + } buildSymbolDisplay(prop, writer); if (prop.flags & 16777216 /* Optional */) { writePunctuation(writer, 55 /* QuestionToken */); @@ -26265,7 +27367,7 @@ var ts; continue; } if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); } } var t = getTypeOfSymbol(p); @@ -26357,18 +27459,18 @@ var ts; writeSpace(writer); var type = getTypeOfSymbol(p); if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048 /* Undefined */); + type = getOptionalType(type); } buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { writePunctuation(writer, 17 /* OpenBraceToken */); buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); writePunctuation(writer, 18 /* CloseBraceToken */); } - else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { writePunctuation(writer, 21 /* OpenBracketToken */); var elements = bindingPattern.elements; buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); @@ -26382,7 +27484,7 @@ var ts; if (ts.isOmittedExpression(bindingElement)) { return; } - ts.Debug.assert(bindingElement.kind === 176 /* BindingElement */); + ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); if (bindingElement.propertyName) { writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 56 /* ColonToken */); @@ -26542,22 +27644,22 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 176 /* BindingElement */: + case 177 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 228 /* FunctionDeclaration */: - case 232 /* EnumDeclaration */: - case 237 /* ImportEqualsDeclaration */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 233 /* EnumDeclaration */: + case 238 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -26565,77 +27667,82 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 237 /* ImportEqualsDeclaration */ && parent.kind !== 265 /* SourceFile */ && ts.isInAmbientContext(parent))) { + !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 152 /* Constructor */: - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 157 /* IndexSignature */: - case 146 /* Parameter */: - case 234 /* ModuleBlock */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 159 /* TypeReference */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: + case 153 /* Constructor */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: + case 147 /* Parameter */: + case 235 /* ModuleBlock */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 160 /* TypeReference */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: return false; // Type parameters are always visible - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: // Source file and namespace export are always visible - case 265 /* SourceFile */: - case 236 /* NamespaceExportDeclaration */: + case 269 /* SourceFile */: + case 237 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return false; default: return false; } } } - function collectLinkedAliases(node) { + function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node, /*isUse*/ false); + if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 246 /* ExportSpecifier */) { + else if (node.parent.kind === 247 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } - var result = []; + var result; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } return result; function buildVisibleNodeList(declarations) { ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - ts.pushIfUnique(result, resultNode); + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } + else { + result = result || []; + ts.pushIfUnique(result, resultNode); + } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; @@ -26710,12 +27817,12 @@ var ts; function getDeclarationContainer(node) { node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 226 /* VariableDeclaration */: - case 227 /* VariableDeclarationList */: - case 242 /* ImportSpecifier */: - case 241 /* NamedImports */: - case 240 /* NamespaceImport */: - case 239 /* ImportClause */: + case 227 /* VariableDeclaration */: + case 228 /* VariableDeclarationList */: + case 243 /* ImportSpecifier */: + case 242 /* NamedImports */: + case 241 /* NamespaceImport */: + case 240 /* ImportClause */: return false; default: return true; @@ -26746,14 +27853,14 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 144 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 145 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (source.flags & 8192 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 12288 /* Nullable */); }); + if (source.flags & 16384 /* Never */) { return emptyObjectType; } - if (source.flags & 65536 /* Union */) { + if (source.flags & 131072 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); @@ -26783,17 +27890,17 @@ var ts; if (parentType === unknownType) { return unknownType; } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } + // If no type was specified or inferred for parent, + // infer from the initializer of the binding element if one is present. + // Otherwise, go with the undefined type of the parent. + if (!parentType) { + return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; + } + if (isTypeAny(parentType)) { return parentType; } var type; - if (pattern.kind === 174 /* ObjectBindingPattern */) { + if (pattern.kind === 175 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (!isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -26815,12 +27922,13 @@ var ts; // computed properties with non-literal names are treated as 'any' return anyType; } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. var text = ts.getTextOfPropertyName(name); + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } var declaredType = getTypeOfPropertyOfType(parentType, text); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || @@ -26859,7 +27967,7 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer ? @@ -26879,20 +27987,21 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 178 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; + if (optional === void 0) { optional = true; } + return strictNullChecks && optional ? getOptionalType(type) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 215 /* ForInStatement */) { + if (declaration.parent.parent.kind === 216 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; + return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 216 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 217 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -26907,11 +28016,11 @@ var ts; var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); + return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 226 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { + declaration.kind === 227 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 2097152 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no // initializer or a 'null' or 'undefined' initializer. @@ -26924,11 +28033,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 146 /* Parameter */) { + if (declaration.kind === 147 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 154 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153 /* GetAccessor */); + if (func.kind === 155 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 154 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -26949,13 +28058,13 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. @@ -26963,7 +28072,7 @@ var ts; return trueType; } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 262 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 266 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -26980,14 +28089,14 @@ var ts; var jsDocType; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - var expression = declaration.kind === 194 /* BinaryExpression */ ? declaration : - declaration.kind === 179 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 194 /* BinaryExpression */) : + var expression = declaration.kind === 195 /* BinaryExpression */ ? declaration : + declaration.kind === 180 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 195 /* BinaryExpression */) : undefined; if (!expression) { return unknownType; } if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 152 /* Constructor */) { + if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 153 /* Constructor */) { definedInConstructor = true; } else { @@ -27001,9 +28110,10 @@ var ts; if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(jsDocType, declarationType)) { - var name = ts.getNameOfDeclaration(declaration); - error(name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(name), typeToString(jsDocType), typeToString(declarationType)); + else if (jsDocType !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(jsDocType, declarationType) && + !(symbol.flags & 67108864 /* JSContainer */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } else if (!jsDocType) { @@ -27085,7 +28195,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 /* ObjectBindingPattern */ + return pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -27104,10 +28214,14 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } + // always widen a 'unique symbol' type if the type was created for a different declaration. + if (type.flags & 1024 /* UniqueESSymbol */ && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + type = esSymbolType; + } // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. - if (declaration.kind === 261 /* PropertyAssignment */) { + if (declaration.kind === 265 /* PropertyAssignment */) { return type; } return getWidenedType(type); @@ -27124,7 +28238,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 147 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function getTypeOfVariableOrParameterOrProperty(symbol) { @@ -27140,7 +28254,7 @@ var ts; return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 243 /* ExportAssignment */) { + if (declaration.kind === 244 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { @@ -27156,8 +28270,8 @@ var ts; // * exports.p = expr // * this.p = expr // * className.prototype.method = expr - if (declaration.kind === 194 /* BinaryExpression */ || - declaration.kind === 179 /* PropertyAccessExpression */ && declaration.parent.kind === 194 /* BinaryExpression */) { + if (declaration.kind === 195 /* BinaryExpression */ || + declaration.kind === 180 /* PropertyAccessExpression */ && declaration.parent.kind === 195 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } else { @@ -27172,7 +28286,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 153 /* GetAccessor */) { + if (accessor.kind === 154 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -27193,8 +28307,8 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 154 /* SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 154 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 155 /* SetAccessor */); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { @@ -27238,7 +28352,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 154 /* GetAccessor */); error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -27248,7 +28362,7 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 1081344 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -27263,7 +28377,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; } } } @@ -27349,20 +28463,20 @@ var ts; function isReferenceToType(type, target) { return type !== undefined && target !== undefined - && (getObjectFlags(type) & 4 /* Reference */) !== 0 + && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target; } function getTargetType(type) { - return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); function check(type) { - if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); return target === checkBase || ts.forEach(getBaseTypes(target), check); } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { return ts.forEach(type.types, check); } } @@ -27386,29 +28500,29 @@ var ts; return undefined; } switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 273 /* JSDocFunctionType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 231 /* TypeAliasDeclaration */: - case 282 /* JSDocTemplateTag */: - case 172 /* MappedType */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 151 /* MethodSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 232 /* TypeAliasDeclaration */: + case 287 /* JSDocTemplateTag */: + case 173 /* MappedType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 172 /* MappedType */) { + if (node.kind === 173 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); var thisType = includeThisTypes && - (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || node.kind === 230 /* InterfaceDeclaration */) && + (node.kind === 230 /* ClassDeclaration */ || node.kind === 200 /* ClassExpression */ || node.kind === 231 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -27416,7 +28530,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, 230 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 231 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -27425,8 +28539,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 229 /* ClassDeclaration */ || - node.kind === 199 /* ClassExpression */ || node.kind === 231 /* TypeAliasDeclaration */) { + if (node.kind === 231 /* InterfaceDeclaration */ || node.kind === 230 /* ClassDeclaration */ || + node.kind === 200 /* ClassExpression */ || node.kind === 232 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -27454,14 +28568,22 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 540672 /* TypeVariable */) { + if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + var decl = type.symbol.valueDeclaration; + if (ts.isInJavaScriptFile(decl)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(decl); + if (tag) { + return tag.class; + } + } + return ts.getClassExtendsHeritageClauseElement(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -27483,6 +28605,8 @@ var ts; */ function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { + var decl = type.symbol.valueDeclaration; + var extended = ts.getClassExtendsHeritageClauseElement(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -27491,7 +28615,11 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) { + if (extended && baseTypeNode !== extended) { + ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -27530,7 +28658,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.emptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -27558,14 +28686,6 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag && augTag.typeExpression && augTag.typeExpression.type) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } if (baseType === unknownType) { return; } @@ -27574,7 +28694,7 @@ var ts; return; } if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); return; } type.resolvedBaseTypes = [baseType]; @@ -27584,23 +28704,23 @@ var ts; // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. var outerTypeParameters = type.outerTypeParameters; if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; + var last_1 = outerTypeParameters.length - 1; var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol; } return true; } // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return type.flags & (65536 /* Object */ | 33554432 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 231 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -27626,13 +28746,17 @@ var ts; } } } - // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is - // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, - // and if none of the base interfaces have a "this" type. - function isIndependentInterface(symbol) { + /** + * Returns true if the interface given by the symbol is free of "this" references. + * + * Specifically, the result is true if the interface itself contains no references + * to "this" in its body, if all base types are interfaces, + * and if none of the base interfaces have a "this" type. + */ + function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */) { + if (declaration.kind === 231 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -27664,7 +28788,7 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { type.objectFlags |= 4 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; @@ -27673,7 +28797,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); + type.thisType = createType(32768 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -27690,9 +28814,9 @@ var ts; return unknownType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; + return d.kind === 288 /* JSDocTypedefTag */ || d.kind === 232 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = declaration.kind === 288 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { @@ -27716,13 +28840,13 @@ var ts; function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !ts.isInAmbientContext(member); + return !(member.flags & 2097152 /* Ambient */); } switch (expr.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 71 /* Identifier */: @@ -27739,7 +28863,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { + if (declaration.kind === 233 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { @@ -27754,7 +28878,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ && !(type.flags & 65536 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -27766,7 +28890,7 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 232 /* EnumDeclaration */) { + if (declaration.kind === 233 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); @@ -27777,7 +28901,7 @@ var ts; } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 65536 /* Union */) { + if (enumType_1.flags & 131072 /* Union */) { enumType_1.flags |= 256 /* EnumLiteral */; enumType_1.symbol = symbol; } @@ -27801,7 +28925,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384 /* TypeParameter */); + var type = createType(32768 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -27815,6 +28939,9 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { return getDeclaredTypeOfClassOrInterface(symbol); } @@ -27833,24 +28960,14 @@ var ts; if (symbol.flags & 2097152 /* Alias */) { return getDeclaredTypeOfAlias(symbol); } - return unknownType; - } - // A type reference is considered independent if each type argument is considered independent. - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; + return undefined; } - // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string - // literal type, an array with an element type that is considered independent, or a type reference that is - // considered independent. - function isIndependentType(node) { + /** + * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string + * literal type, an array with an element type that is free of this references, or a type reference that is + * free of this references. + */ + function isThislessType(node) { switch (node.kind) { case 119 /* AnyKeyword */: case 136 /* StringKeyword */: @@ -27862,55 +28979,57 @@ var ts; case 139 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 130 /* NeverKeyword */: - case 173 /* LiteralType */: + case 174 /* LiteralType */: return true; - case 164 /* ArrayType */: - return isIndependentType(node.elementType); - case 159 /* TypeReference */: - return isIndependentTypeReference(node); + case 165 /* ArrayType */: + return isThislessType(node.elementType); + case 160 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; } - // A variable-like declaration is considered independent (free of this references) if it has a type annotation - // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). - function isIndependentVariableLikeDeclaration(node) { + /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + function isThislessTypeParameter(node) { + return !node.constraint || isThislessType(node.constraint); + } + /** + * A variable-like declaration is free of this references if it has a type annotation + * that is thisless, or if it has no type annotation and no initializer (and is thus of type any). + */ + function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isIndependentType(typeNode) : !node.initializer; - } - // A function-like declaration is considered independent (free of this references) if it has a return type - // annotation that is considered independent and if each parameter is considered independent. - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 /* Constructor */) { - var typeNode = ts.getEffectiveReturnTypeNode(node); - if (!typeNode || !isIndependentType(typeNode)) { - return false; - } - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; + return typeNode ? isThislessType(typeNode) : !node.initializer; } - // Returns true if the class or interface member given by the symbol is free of "this" references. The - // function may return false for symbols that are actually free of "this" references because it is not - // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are conservatively - // assumed not to be free of "this" references. - function isIndependentMember(symbol) { + /** + * A function-like declaration is considered free of `this` references if it has a return type + * annotation that is free of this references and if each parameter is thisless and if + * each type parameter (if present) is thisless. + */ + function isThislessFunctionLikeDeclaration(node) { + var returnType = ts.getEffectiveReturnTypeNode(node); + return (node.kind === 153 /* Constructor */ || (returnType && isThislessType(returnType))) && + node.parameters.every(isThislessVariableLikeDeclaration) && + (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); + } + /** + * Returns true if the class or interface member given by the symbol is free of "this" references. The + * function may return false for symbols that are actually free of "this" references because it is not + * feasible to perform a complete analysis in all cases. In particular, property members with types + * inferred from their initializers and function members with inferred return types are conservatively + * assumed not to be free of "this" references. + */ + function isThisless(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return isIndependentVariableLikeDeclaration(declaration); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - return isIndependentFunctionLikeDeclaration(declaration); + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + return isThislessFunctionLikeDeclaration(declaration); } } } @@ -27922,7 +29041,7 @@ var ts; var result = ts.createSymbolTable(); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; - result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; } @@ -27937,23 +29056,219 @@ var ts; function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call" /* Call */)); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new" /* New */)); + var members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); } return type; } + /** + * Indicates whether a type can be used as a late-bound name. + */ + function isTypeUsableAsLateBoundName(type) { + return !!(type.flags & 1120 /* StringOrNumberLiteralOrUnique */); + } + /** + * Indicates whether a declaration name is definitely late-bindable. + * A declaration name is only late-bindable if: + * - It is a `ComputedPropertyName`. + * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an + * `ElementAccessExpression` consisting only of these same three types of nodes. + * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type. + */ + function isLateBindableName(node) { + return ts.isComputedPropertyName(node) + && ts.isEntityNameExpression(node.expression) + && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); + } + /** + * Indicates whether a declaration has a late-bindable dynamic name. + */ + function hasLateBindableName(node) { + var name = ts.getNameOfDeclaration(node); + return name && isLateBindableName(name); + } + /** + * Indicates whether a declaration has a dynamic name that cannot be late-bound. + */ + function hasNonBindableDynamicName(node) { + return ts.hasDynamicName(node) && !hasLateBindableName(node); + } + /** + * Indicates whether a declaration name is a dynamic name that cannot be late-bound. + */ + function isNonBindableDynamicName(node) { + return ts.isDynamicName(node) && !isLateBindableName(node); + } + /** + * Gets the symbolic name for a late-bound member from its type. + */ + function getLateBoundNameFromType(type) { + if (type.flags & 1024 /* UniqueESSymbol */) { + return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + } + if (type.flags & 96 /* StringOrNumberLiteral */) { + return ts.escapeLeadingUnderscores("" + type.value); + } + } + /** + * Adds a declaration to a late-bound dynamic member. This performs the same function for + * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound + * members. + */ + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } + else { + symbol.declarations.push(member); + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + /** + * Performs late-binding of a dynamic member. This performs the same function for + * late-bound members that `declareSymbol` in binder.ts performs for early-bound + * members. + * + * If a symbol is a dynamic name from a computed property, we perform an additional "late" + * binding phase to attempt to resolve the name for the symbol from the type of the computed + * property's expression. If the type of the expression is a string-literal, numeric-literal, + * or unique symbol type, we can use that type as the name of the symbol. + * + * For example, given: + * + * const x = Symbol(); + * + * interface I { + * [x]: number; + * } + * + * The binder gives the property `[x]: number` a special symbol with the name "__computed". + * In the late-binding phase we can type-check the expression `x` and see that it has a + * unique symbol type which we can then use as the name of the member. This allows users + * to define custom symbols that can be used in the members of an object type. + * + * @param parent The containing symbol for the member. + * @param earlySymbols The early-bound symbols of the parent. + * @param lateSymbols The late-bound symbols of the parent. + * @param decl The member to bind. + */ + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + var links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + // In the event we attempt to resolve the late-bound name of this member recursively, + // fall back to the early-bound name of this member. + links.resolvedSymbol = decl.symbol; + var type = checkComputedPropertyName(decl.name); + if (isTypeUsableAsLateBoundName(type)) { + var memberName = getLateBoundNameFromType(type); + var symbolFlags = decl.symbol.flags; + // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. + var lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + // Report an error if a late-bound member has the same name as an early-bound member, + // or if we have another early-bound symbol declaration with the same name and + // conflicting flags. + var earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { + // If we have an existing early-bound member, combine its declarations so that we can + // report an error at each declaration. + var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + } + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + lateSymbol.parent = parent; + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + var links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */; + var earlySymbols = !isStatic ? symbol.members : + symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) : + symbol.exports; + // In the event we recursively resolve the members/exports of the symbol, we + // set the initial value of resolvedMembers/resolvedExports to the early-bound + // members/exports of the symbol. + links[resolutionKind] = earlySymbols || emptySymbols; + // fill in any as-yet-unresolved late-bound members. + var lateSymbols = ts.createSymbolTable(); + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var members = ts.getMembersOfDeclaration(decl); + if (members) { + for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { + var member = members_3[_b]; + if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols; + } + return links[resolutionKind]; + } + /** + * Gets a SymbolTable containing both the early- and late-bound members of a symbol. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getMembersOfSymbol(symbol) { + return symbol.flags & 6240 /* LateBindingContainer */ + ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) + : symbol.members || emptySymbols; + } + /** + * If a symbol is the dynamic name of the member of an object type, get the late-bound + * symbol of the member. + * + * For a description of late-binding, see `lateBindMember`. + */ + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + var links = getSymbolLinks(symbol); + if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) { + // force late binding of members/exports. This will set the late-bound symbol + if (ts.some(symbol.declarations, ts.hasStaticModifier)) { + getExportsOfSymbol(symbol.parent); + } + else { + getMembersOfSymbol(symbol.parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4 /* Reference */) { + if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); } } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); } return type; @@ -27967,7 +29282,7 @@ var ts; var numberIndexInfo; if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = identityMapper; - members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); callSignatures = source.declaredCallSignatures; constructSignatures = source.declaredConstructSignatures; stringIndexInfo = source.declaredStringIndexInfo; @@ -27983,7 +29298,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -28044,7 +29359,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -28122,8 +29437,8 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { - var type = types_1[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var type = types_2[_i]; var indexInfo = getIndexInfoOfType(type, kind); if (!indexInfo) { return undefined; @@ -28213,7 +29528,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { - var members = symbol.members; + var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -28230,7 +29545,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { + if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1081344 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -28272,13 +29587,15 @@ var ts; var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170 /* TypeOperator */) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 171 /* TypeOperator */ && + constraintDeclaration.operator === 127 /* KeyOfKeyword */) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var propertySymbol = _a[_i]; addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); } - if (getIndexInfoOfType(modifiersType, 0 /* String */)) { + if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); } } @@ -28286,8 +29603,8 @@ var ts; // First, if the constraint type is a type parameter, obtain the base constraint. Then, // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + var keyType = constraintType.flags & 1081344 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 524288 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -28311,8 +29628,8 @@ var ts; var propName = ts.escapeLeadingUnderscores(t.value); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216 /* Optional */); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + var checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, checkFlags); prop.type = propType; if (propertySymbol) { prop.syntheticOrigin = propertySymbol; @@ -28321,7 +29638,7 @@ var ts; prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } - else if (t.flags & 2 /* String */) { + else if (t.flags & (1 /* Any */ | 2 /* String */)) { stringIndexInfo = createIndexInfo(propType, templateReadonly); } } @@ -28343,7 +29660,8 @@ var ts; function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170 /* TypeOperator */) { + if (constraintDeclaration.kind === 171 /* TypeOperator */ && + constraintDeclaration.operator === 127 /* KeyOfKeyword */) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. @@ -28355,21 +29673,30 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; } + function getMappedTypeModifiers(type) { + return (type.declaration.readonlyToken ? 1 /* Readonly */ : 0) | + (type.declaration.questionToken ? 2 /* Optional */ : 0); + } + function getCombinedMappedTypeModifiers(type) { + var modifiersType = getModifiersTypeFromMappedType(type); + return getMappedTypeModifiers(type) | + (isGenericMappedType(modifiersType) ? getMappedTypeModifiers(modifiersType) : 0); + } function isPartialMappedType(type) { - return getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; + return ts.getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; } function isGenericMappedType(type) { - return getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -28383,10 +29710,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 65536 /* Union */) { + else if (type.flags & 131072 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -28394,7 +29721,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -28403,7 +29730,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -28427,7 +29754,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { break; } } @@ -28437,19 +29764,19 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 196608 /* UnionOrIntersection */ ? + return type.flags & 393216 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 65536 /* Union */)) { - return getPropertiesOfType(unionType); + if (!(unionType.flags & 131072 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var memberType = types_2[_i]; - for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var memberType = types_3[_i]; + for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); @@ -28459,8 +29786,8 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + return type.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 1048576 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { @@ -28476,13 +29803,13 @@ var ts; return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { - if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) { + if (type.flags & (1081344 /* TypeVariable */ | 393216 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); if (constraint !== noConstraintType && constraint !== circularConstraintType) { return constraint; } } - else if (type.flags & 262144 /* Index */) { + else if (type.flags & 524288 /* Index */) { return stringType; } return undefined; @@ -28515,29 +29842,29 @@ var ts; return result; } function computeBaseConstraint(t) { - if (t.flags & 16384 /* TypeParameter */) { + if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType ? constraint : constraint ? getBaseConstraint(constraint) : undefined; } - if (t.flags & 196608 /* UnionOrIntersection */) { + if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var type_2 = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type_2 = types_4[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 131072 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 262144 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 262144 /* Index */) { + if (t.flags & 524288 /* Index */) { return stringType; } - if (t.flags & 524288 /* IndexedAccess */) { + if (t.flags & 1048576 /* IndexedAccess */) { var transformed = getTransformedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); @@ -28556,27 +29883,48 @@ var ts; function getApparentTypeOfIntersectionType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); } - /** - * Gets the default type for a type parameter. - * - * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. - */ - function getDefaultFromTypeParameter(typeParameter) { + function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + var targetDefault = getResolvedTypeParameterDefault(typeParameter.target); typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { + // To block recursion, set the initial value to the resolvingDefaultType. + typeParameter.default = resolvingDefaultType; var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + // If we have not been called recursively, set the correct default type. + typeParameter.default = defaultType; + } } } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + else if (typeParameter.default === resolvingDefaultType) { + // If we are called recursively for this type parameter, mark the default as circular. + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type or the default is + * circular, `undefined` is returned. + */ + function getDefaultFromTypeParameter(typeParameter) { + var defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + /** + * Indicates whether the declaration of a typeParameter has a default type. + */ + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -28584,26 +29932,26 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 /* StringLike */ ? globalStringType : + var t = type.flags & 1081344 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 262144 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 524322 /* StringLike */ ? globalStringType : t.flags & 84 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : - t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1536 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 33554432 /* NonPrimitive */ ? emptyObjectType : t; } function createUnionOrIntersectionProperty(containingType, name) { var props; var types = containingType.types; - var isUnion = containingType.flags & 65536 /* Union */; + var isUnion = containingType.flags & 131072 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var current = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var current = types_5[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -28648,8 +29996,7 @@ var ts; } propTypes.push(type); } - var result = createSymbol(4 /* Property */ | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; + var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; result.declarations = declarations; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -28686,7 +30033,7 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -28700,13 +30047,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 196608 /* UnionOrIntersection */) { + if (type.flags & 393216 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { + if (type.flags & 458752 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -28720,7 +30067,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { + if (type.flags & 458752 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -28740,7 +30087,7 @@ var ts; return getIndexTypeOfStructuredType(getApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { + if (isObjectTypeWithInferableIndex(type)) { var propTypes = []; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; @@ -28775,7 +30122,7 @@ var ts; } function isJSDocOptionalParameter(node) { if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 272 /* JSDocOptionalType */) { + if (node.type && node.type.kind === 276 /* JSDocOptionalType */) { return true; } var paramTags = ts.getJSDocParameterTags(node); @@ -28786,7 +30133,7 @@ var ts; return true; } if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 272 /* JSDocOptionalType */; + return paramTag.typeExpression.type.kind === 276 /* JSDocOptionalType */; } } } @@ -28844,7 +30191,7 @@ var ts; var minTypeArgumentCount = 0; if (typeParameters) { for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { + if (!hasTypeParameterDefault(typeParameters[i])) { minTypeArgumentCount = i + 1; } } @@ -28859,11 +30206,11 @@ var ts; * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { if (!typeArguments) { typeArguments = []; } @@ -28871,13 +30218,17 @@ var ts; // If a type parameter does not have a default type, or if the default type // is a forward reference, the empty object type is used. for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); } for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + defaultType = anyType; + } + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); } + typeArguments.length = typeParameters.length; } } return typeArguments; @@ -28911,7 +30262,7 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 173 /* LiteralType */) { + if (param.type && param.type.kind === 174 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -28924,36 +30275,50 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 153 /* GetAccessor */ || declaration.kind === 154 /* SetAccessor */) && - !ts.hasDynamicName(declaration) && + if ((declaration.kind === 154 /* GetAccessor */ || declaration.kind === 155 /* SetAccessor */) && + !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + var otherKind = declaration.kind === 154 /* GetAccessor */ ? 155 /* SetAccessor */ : 154 /* GetAccessor */; + var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 152 /* Constructor */ ? + var classType = declaration.kind === 153 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 /* TypePredicate */ ? + var typePredicate = declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - // JS functions get a free rest parameter if they reference `arguments` - var hasRestLikeParameter = ts.hasRestParameter(declaration); - if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { - hasRestLikeParameter = true; - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - parameters.push(syntheticArgsSymbol); - } + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + // JS functions get a free rest parameter if: + // a) The last parameter has `...` preceding its type + // b) It references `arguments` somewhere + var lastParam = ts.lastOrUndefined(declaration.parameters); + var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); + var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; + }); + if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { + return false; + } + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + if (lastParamVariadicType) { + // Replace the last parameter with a rest parameter. + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { return getTypeFromTypeNode(declaration.parameters[0].type); @@ -28967,8 +30332,8 @@ var ts; } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 153 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154 /* SetAccessor */); + if (declaration.kind === 154 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 155 /* SetAccessor */); return getAnnotatedAccessorType(setter); } if (ts.nodeIsMissing(declaration.body)) { @@ -28991,12 +30356,12 @@ var ts; return false; switch (node.kind) { case 71 /* Identifier */: - return node.escapedText === "arguments" && ts.isPartOfExpression(node); - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return node.name.kind === 144 /* ComputedPropertyName */ + return node.escapedText === "arguments" && ts.isExpressionNode(node); + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return node.name.kind === 145 /* ComputedPropertyName */ && traverse(node.name); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); @@ -29010,20 +30375,20 @@ var ts; for (var i = 0; i < symbol.declarations.length; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 273 /* JSDocFunctionType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 277 /* JSDocFunctionType */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -29091,7 +30456,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { + if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -29133,13 +30498,22 @@ var ts; // that uses the original type identities for all unconstrained type parameters. return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } + function getBaseSignature(signature) { + var typeParameters = signature.typeParameters; + if (typeParameters) { + var typeEraser_1 = createTypeEraser(typeParameters); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || emptyObjectType; }); + return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + } + return signature; + } function getOrCreateTypeFromSignature(signature) { // There are two ways to declare a construct signature, one is by declaring a class constructor // using the constructor keyword, and the other is declaring a bare construct signature in an // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 /* Constructor */ || signature.declaration.kind === 156 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 153 /* Constructor */ || signature.declaration.kind === 157 /* ConstructSignature */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -29180,7 +30554,7 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145 /* TypeParameter */).constraint; + return type.symbol && ts.getDeclarationOfKind(type.symbol, 146 /* TypeParameter */).constraint; } function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { @@ -29196,7 +30570,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 146 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -29227,13 +30601,13 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } } - return result & 14680064 /* PropagatingFlags */; + return result & 29360128 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -29267,17 +30641,28 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJavascript = ts.isInJavaScriptFile(node); - if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); - return unknownType; + var isJs = ts.isInJavaScriptFile(node); + var isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var missingAugmentsTag = isJs && node.parent.kind !== 282 /* JSDocAugmentsTag */; + var diag = minTypeArgumentCount === typeParameters.length + ? missingAugmentsTag + ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : missingAugmentsTag + ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return unknownType; + } } // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -29322,21 +30707,11 @@ var ts; } return type; } - /** - * Get type from reference to named type that cannot be generic (enum or type parameter) - */ - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } function getTypeReferenceName(node) { switch (node.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return node.typeName; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -29361,22 +30736,31 @@ var ts; if (type) { return type; } - if (symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node)) { - // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If - // the symbol is a constructor function, return the inferred class type; otherwise, - // the type of this reference is just the type of the value we resolved to. - var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType)) { - var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType) { - return referenceType; - } + // Get type from reference to named type that cannot be generic (enum or type parameter) + var res = tryGetDeclaredTypeOfSymbol(symbol); + if (res !== undefined) { + if (typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return res; + } + if (!(symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node))) { + return unknownType; + } + // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + // the symbol is a constructor function, return the inferred class type; otherwise, + // the type of this reference is just the type of the value we resolved to. + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; } - // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); - return valueType; } - return getTypeFromNonGenericTypeReference(node, symbol); + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + return valueType; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -29392,18 +30776,16 @@ var ts; } } function isJSDocTypeReference(node) { - return node.flags & 1048576 /* JSDoc */ && node.kind === 159 /* TypeReference */; + return node.flags & 1048576 /* JSDoc */ && node.kind === 160 /* TypeReference */; } function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -29434,7 +30816,7 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; + return strictNullChecks ? getNullableType(type, 8192 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); @@ -29477,9 +30859,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: return declaration; } } @@ -29488,12 +30870,12 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768 /* Object */)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + if (!(type.flags & 65536 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } return type; @@ -29607,12 +30989,15 @@ var ts; var typeParameters = []; var properties = []; for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384 /* TypeParameter */); + var typeParameter = createType(32768 /* TypeParameter */); typeParameters.push(typeParameter); var property = createSymbol(4 /* Property */, "" + i); property.type = typeParameter; properties.push(property); } + var lengthSymbol = createSymbol(4 /* Property */, "length"); + lengthSymbol.type = getLiteralType(arity); + properties.push(lengthSymbol); var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; type.outerTypeParameters = undefined; @@ -29621,7 +31006,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); + type.thisType = createType(32768 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -29644,27 +31029,11 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; + function getTypeId(type) { + return type.id; } function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; + return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } // Return true if the given intersection type contains (a) more than one unit type or (b) an object // type and a nullable type (null or undefined). @@ -29672,11 +31041,11 @@ var ts; var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6368 /* Unit */ && combined & 6368 /* Unit */) { + if (t.flags & 13536 /* Unit */ && combined & 13536 /* Unit */) { return true; } combined |= t.flags; - if (combined & 6144 /* Nullable */ && combined & (32768 /* Object */ | 16777216 /* NonPrimitive */)) { + if (combined & 12288 /* Nullable */ && combined & (65536 /* Object */ | 33554432 /* NonPrimitive */)) { return true; } } @@ -29684,21 +31053,21 @@ var ts; } function addTypeToUnion(typeSet, type) { var flags = type.flags; - if (flags & 65536 /* Union */) { + if (flags & 131072 /* Union */) { addTypesToUnion(typeSet, type.types); } else if (flags & 1 /* Any */) { typeSet.containsAny = true; } - else if (!strictNullChecks && flags & 6144 /* Nullable */) { - if (flags & 2048 /* Undefined */) + else if (!strictNullChecks && flags & 12288 /* Nullable */) { + if (flags & 4096 /* Undefined */) typeSet.containsUndefined = true; - if (flags & 4096 /* Null */) + if (flags & 8192 /* Null */) typeSet.containsNull = true; - if (!(flags & 2097152 /* ContainsWideningType */)) + if (!(flags & 4194304 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 /* Never */ || flags & 131072 /* Intersection */ && isEmptyIntersectionType(type))) { + else if (!(flags & 16384 /* Never */ || flags & 262144 /* Intersection */ && isEmptyIntersectionType(type))) { // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn // intersections of unit types into 'never' upon construction, but deferring the reduction makes it @@ -29707,12 +31076,14 @@ var ts; typeSet.containsString = true; if (flags & 4 /* Number */) typeSet.containsNumber = true; - if (flags & 96 /* StringOrNumberLiteral */) - typeSet.containsStringOrNumberLiteral = true; + if (flags & 512 /* ESSymbol */) + typeSet.containsESSymbol = true; + if (flags & 1120 /* StringOrNumberLiteralOrUnique */) + typeSet.containsLiteralOrUniqueESSymbol = true; var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.splice(~index, 0, type); } @@ -29722,24 +31093,26 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; if (isTypeIdenticalTo(t, type)) { return true; } } return false; } - function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - if (candidate !== type && isTypeSubtypeOf(candidate, type)) { + function isSubtypeOfAny(source, targets) { + for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { + var target = targets_1[_i]; + if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { return true; } } @@ -29778,7 +31151,8 @@ var ts; var t = types[i]; var remove = t.flags & 32 /* StringLiteral */ && types.containsString || t.flags & 64 /* NumberLiteral */ && types.containsNumber || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 1024 /* UniqueESSymbol */ && types.containsESSymbol || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 2097152 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -29806,7 +31180,7 @@ var ts; if (subtypeReduction) { removeSubtypes(typeSet); } - else if (typeSet.containsStringOrNumberLiteral) { + else if (typeSet.containsLiteralOrUniqueESSymbol) { removeRedundantLiteralTypes(typeSet); } if (typeSet.length === 0) { @@ -29827,8 +31201,8 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(65536 /* Union */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); + type = createType(131072 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; /* @@ -29850,37 +31224,37 @@ var ts; return links.resolvedType; } function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072 /* Intersection */) { + if (type.flags & 262144 /* Intersection */) { addTypesToIntersection(typeSet, type.types); } else if (type.flags & 1 /* Any */) { typeSet.containsAny = true; } - else if (type.flags & 8192 /* Never */) { + else if (type.flags & 16384 /* Never */) { typeSet.containsNever = true; } - else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { + else if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { typeSet.containsEmptyObject = true; } - else if ((strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768 /* Object */) { + else if ((strictNullChecks || !(type.flags & 12288 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 65536 /* Object */) { typeSet.containsObjectType = true; } - if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { + if (type.flags & 131072 /* Union */ && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { typeSet.push(type); } } } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. + // Add the given types to the given type set. Order is preserved, freshness is removed from literal + // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { var type = types_9[_i]; - addTypeToIntersection(typeSet, type); + addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -29922,8 +31296,8 @@ var ts; var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(131072 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 12288 /* Nullable */); + type = createType(262144 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -29940,7 +31314,7 @@ var ts; } function getIndexTypeForGenericType(type) { if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144 /* Index */); + type.resolvedIndexType = createType(524288 /* Index */); type.resolvedIndexType.type = type; } return type.resolvedIndexType; @@ -29948,40 +31322,48 @@ var ts; function getLiteralTypeFromPropertyName(prop) { return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? neverType : - getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + getLiteralType(ts.symbolName(prop)); } function getLiteralTypeFromPropertyNames(type) { return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); } function getIndexType(type) { - return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + return maybeTypeOfKind(type, 1081344 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type); } function getIndexTypeOrString(type) { var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; + return indexType.flags & 16384 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + switch (node.operator) { + case 127 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 140 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 137 /* SymbolKeyword */ + ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) + : unknownType; + break; + } } return links.resolvedType; } function createIndexedAccessType(objectType, indexType) { - var type = createType(524288 /* IndexedAccess */); + var type = createType(1048576 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? - ts.escapeLeadingUnderscores("" + indexType.value) : + var accessExpression = accessNode && accessNode.kind === 181 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); @@ -29998,7 +31380,7 @@ var ts; return getTypeOfSymbol(prop); } } - if (!(indexType.flags & 6144 /* Nullable */) && isTypeAssignableToKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!(indexType.flags & 12288 /* Nullable */) && isTypeAssignableToKind(indexType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */)) { if (isTypeAny(objectType)) { return anyType; } @@ -30024,7 +31406,7 @@ var ts; } } if (accessNode) { - var indexNode = accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = accessNode.kind === 181 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } @@ -30039,20 +31421,20 @@ var ts; return anyType; } function isGenericObjectType(type) { - return type.flags & 540672 /* TypeVariable */ ? true : - getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : - type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : + return type.flags & 1081344 /* TypeVariable */ ? true : + ts.getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & 393216 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericObjectType) : false; } function isGenericIndexType(type) { - return type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) ? true : - type.flags & 196608 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : + return type.flags & (1081344 /* TypeVariable */ | 524288 /* Index */) ? true : + type.flags & 393216 /* UnionOrIntersection */ ? ts.forEach(type.types, isGenericIndexType) : false; } // Return true if the given type is a non-generic object type with a string index signature and no // other members. function isStringIndexOnlyType(type) { - if (type.flags & 32768 /* Object */ && !isGenericMappedType(type)) { + if (type.flags & 65536 /* Object */ && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && @@ -30068,7 +31450,7 @@ var ts; // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed // access types with default property values as expressed by D. - if (objectType.flags & 131072 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { + if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { @@ -30102,7 +31484,7 @@ var ts; // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 1 /* Any */) { return objectType; } @@ -30118,7 +31500,7 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { + if (indexType.flags & 131072 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -30158,7 +31540,7 @@ var ts; if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { + if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { links.resolvedType = emptyTypeLiteralType; } else { @@ -30174,7 +31556,7 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return node.parent.kind === 232 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; } function getAliasTypeArgumentsForTypeNode(node) { var symbol = getAliasSymbolForTypeNode(node); @@ -30185,26 +31567,26 @@ var ts; * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left, right) { + function getSpreadType(left, right, symbol, propagatedFlags) { if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } - if (left.flags & 8192 /* Never */) { + if (left.flags & 16384 /* Never */) { return right; } - if (right.flags & 8192 /* Never */) { + if (right.flags & 16384 /* Never */) { return left; } - if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); + if (left.flags & 131072 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right, symbol, propagatedFlags); }); } - if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); + if (right.flags & 131072 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 16777216 /* NonPrimitive */) { + if (right.flags & 33554432 /* NonPrimitive */) { return nonPrimitiveType; } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 262178 /* StringLike */ | 272 /* EnumLike */)) { + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */)) { return left; } var members = ts.createSymbolTable(); @@ -30256,7 +31638,11 @@ var ts; members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); + spread.flags |= propagatedFlags; + spread.flags |= 2097152 /* FreshLiteral */ | 8388608 /* ContainsObjectLiteral */; + spread.objectFlags |= (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); + return spread; } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { @@ -30269,6 +31655,12 @@ var ts; result.syntheticOrigin = prop; return result; } + function getNonReadonlyIndexSignature(index) { + if (index && index.isReadonly) { + return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); + } + return index; + } function isClassMethod(prop) { return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); } @@ -30279,9 +31671,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 1048576 /* FreshLiteral */)) { + if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 2097152 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 1048576 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 2097152 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -30290,7 +31682,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? type.regularType : type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -30313,20 +31705,25 @@ var ts; } return links.resolvedType; } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; + function createUniqueESSymbolType(symbol) { + var type = createType(1024 /* UniqueESSymbol */); + type.symbol = symbol; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (ts.isValidESSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + var links = getSymbolLinks(symbol); + return links.type || (links.type = createUniqueESSymbolType(symbol)); } - return links.resolvedType; + return esSymbolType; } function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 231 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 153 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -30343,8 +31740,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 268 /* JSDocAllType */: - case 269 /* JSDocUnknownType */: + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: return anyType; case 136 /* StringKeyword */: return stringType; @@ -30364,54 +31761,54 @@ var ts; return neverType; case 134 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 169 /* ThisType */: + case 170 /* ThisType */: case 99 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return getTypeFromTypeReference(node); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return booleanType; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 165 /* TupleType */: + case 166 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 166 /* UnionType */: + case 167 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 270 /* JSDocNullableType */: + case 274 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 168 /* ParenthesizedType */: - case 271 /* JSDocNonNullableType */: - case 272 /* JSDocOptionalType */: - case 267 /* JSDocTypeExpression */: + case 169 /* ParenthesizedType */: + case 275 /* JSDocNonNullableType */: + case 276 /* JSDocOptionalType */: + case 271 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 285 /* JSDocTypeLiteral */: - case 273 /* JSDocFunctionType */: + case 278 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 280 /* JSDocTypeLiteral */: + case 277 /* JSDocFunctionType */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 172 /* MappedType */: + case 173 /* MappedType */: return getTypeFromMappedTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 71 /* Identifier */: - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); - case 274 /* JSDocVariadicType */: - return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -30480,7 +31877,7 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { - var result = createType(16384 /* TypeParameter */); + var result = createType(32768 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -30535,8 +31932,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName); - result.checkFlags = 1 /* Instantiated */; + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -30558,11 +31954,11 @@ var ts; // The first time an anonymous type is instantiated we compute and store a list of the type // parameters that are in scope (and therefore potentially referenced). For type literals that // aren't the right hand side of a generic type alias declaration we optimize by reducing the - // set of type parameters to those that are actually referenced somewhere in the literal. + // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : outerTypeParameters; links.typeParameters = typeParameters; if (typeParameters.length) { @@ -30587,13 +31983,27 @@ var ts; } return type; } - function isTypeParameterReferencedWithin(tp, node) { - return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); - function checkThis(node) { - return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + function isTypeParameterPossiblyReferenced(tp, node) { + // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks + // between the node and the type parameter declaration, if the node contains actual references to the + // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + var container_1 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 208 /* Block */ ? "quit" : n === container_1; })) { + return ts.forEachChild(node, containsReference); + } } - function checkIdentifier(node) { - return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + return true; + function containsReference(node) { + switch (node.kind) { + case 170 /* ThisType */: + return tp.isThisType; + case 71 /* Identifier */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; + case 163 /* TypeQuery */: + return true; + } + return ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -30603,9 +32013,9 @@ var ts; // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a // union type A | undefined, we produce { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144 /* Index */) { + if (constraintType.flags & 524288 /* Index */) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384 /* TypeParameter */) { + if (typeVariable_1.flags & 32768 /* TypeParameter */) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -30620,7 +32030,7 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); + return type.flags & (1 /* Any */ | 32768 /* TypeParameter */ | 65536 /* Object */ | 262144 /* Intersection */ | 1048576 /* IndexedAccess */); } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); @@ -30635,10 +32045,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 32768 /* TypeParameter */) { return mapper(type); } - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { if (type.objectFlags & 16 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need @@ -30653,16 +32063,16 @@ var ts; return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } } - if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 131072 /* Intersection */) { + if (type.flags & 262144 /* Intersection */) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.flags & 262144 /* Index */) { + if (type.flags & 524288 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 524288 /* IndexedAccess */) { + if (type.flags & 1048576 /* IndexedAccess */) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } @@ -30674,32 +32084,32 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return node.operatorToken.kind === 54 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return ts.forEach(node.properties, isContextSensitive); - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. return node.initializer && isContextSensitive(node.initializer); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: // It is possible to that node.expression is undefined (e.g
) return node.expression && isContextSensitive(node.expression); } @@ -30714,7 +32124,7 @@ var ts; if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 187 /* ArrowFunction */) { + if (node.kind !== 188 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -30723,13 +32133,13 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 207 /* Block */ ? false : isContextSensitive(node.body); + return node.body.kind === 208 /* Block */ ? false : isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -30740,7 +32150,7 @@ var ts; return result; } } - else if (type.flags & 131072 /* Intersection */) { + else if (type.flags & 262144 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -30761,11 +32171,20 @@ var ts; function isTypeAssignableTo(source, target) { return isTypeRelatedTo(source, target, assignableRelation); } - // A type S is considered to be an instance of a type T if S and T are the same type or if S is a - // subtype of T but not structurally identical to T. This specifically means that two distinct but - // structurally identical types (such as two classes) are not considered instances of each other. - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + // An object type S is considered to be derived from an object type T if + // S is a union type and every constituent of S is derived from T, + // T is a union type and S is derived from at least one constituent of T, or + // S is a type variable with a base constraint that is derived from T, + // T is one of the global types Object and Function and S is a subtype of T, or + // T occurs directly or indirectly in an 'extends' clause of S. + // Note that this check ignores type parameters and only considers the + // inheritance hierarchy. + function isTypeDerivedFrom(source, target) { + return source.flags & 131072 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 131072 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 1081344 /* TypeVariable */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -30794,13 +32213,13 @@ var ts; return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; @@ -30812,13 +32231,16 @@ var ts; target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 152 /* MethodDeclaration */ && + kind !== 151 /* MethodSignature */ && kind !== 153 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { var targetThisType = getThisTypeOfSignature(target); if (targetThisType) { // void sources are assignable to anything. - var related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) || compareTypes(targetThisType, sourceThisType, reportErrors); if (!related) { if (reportErrors) { @@ -30837,24 +32259,24 @@ var ts; for (var i = 0; i < checkCount; i++) { var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have - // function types with a single call signature, we known we are relating two callback parameters. In + // function types with a single call signature, we know we are relating two callback parameters. In // that case it is sufficient to only relate the parameters of the signatures co-variantly because, // similar to return values, callback parameters are output positions. This means that a Promise, // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) // with respect to T. + var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); + (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); } return 0 /* False */; } @@ -30882,7 +32304,7 @@ var ts; // When relating callback signatures, we still need to relate return types bi-variantly as otherwise // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + result &= callbackCheck === 1 /* Bivariant */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || compareTypes(sourceReturnType, targetReturnType, reportErrors); } } @@ -30960,10 +32382,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 16777216 /* NonPrimitive */ ? true : - type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 33554432 /* NonPrimitive */ ? true : + type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -30986,7 +32408,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -30999,11 +32421,11 @@ var ts; function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 8192 /* Never */) - return false; - if (t & 1 /* Any */ || s & 8192 /* Never */) + if (t & 1 /* Any */ || s & 16384 /* Never */) return true; - if (s & 262178 /* StringLike */ && t & 2 /* String */) + if (t & 16384 /* Never */) + return false; + if (s & 524322 /* StringLike */ && t & 2 /* String */) return true; if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && @@ -31017,22 +32439,26 @@ var ts; return true; if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) return true; + if (s & 1536 /* ESSymbolLike */ && t & 512 /* ESSymbol */) + return true; if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { - if (s & 65536 /* Union */ && t & 65536 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 131072 /* Union */ && t & 131072 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 224 /* Literal */ && t & 224 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 2048 /* Undefined */ && (!strictNullChecks || t & (2048 /* Undefined */ | 1024 /* Void */))) + if (s & 4096 /* Undefined */ && (!strictNullChecks || t & (4096 /* Undefined */ | 2048 /* Void */))) return true; - if (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + if (s & 8192 /* Null */ && (!strictNullChecks || t & 8192 /* Null */)) return true; - if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) + if (s & 65536 /* Object */ && t & 33554432 /* NonPrimitive */) return true; + if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) + return false; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; @@ -31045,22 +32471,24 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 2097152 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 2097152 /* FreshLiteral */) { target = target.regularType; } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + if (source === target || + relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { + if (source.flags & 2064384 /* StructuredOrTypeVariable */ || target.flags & 2064384 /* StructuredOrTypeVariable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -31082,13 +32510,6 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var ExpandingFlags; - (function (ExpandingFlags) { - ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; - ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; - ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; - ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; - })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0 /* None */; var overflow = false; var isIntersectionConstituent = false; @@ -31139,7 +32560,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608 /* UnionOrIntersection */)) { + if (!(type.flags & 393216 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -31147,7 +32568,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 6144 /* Nullable */) { + if (t.flags & 12288 /* Nullable */) { continue; } if (seenNonNullable) { @@ -31164,10 +32585,10 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 2097152 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 2097152 /* FreshLiteral */) { target = target.regularType; } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases @@ -31176,9 +32597,10 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + if (relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (isObjectLiteralType(source) && source.flags & 2097152 /* FreshLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -31194,13 +32616,11 @@ var ts; } } if (relation !== comparableRelation && - !(source.flags & 196608 /* UnionOrIntersection */) && - !(target.flags & 65536 /* Union */) && + !(source.flags & 393216 /* UnionOrIntersection */) && + !(target.flags & 131072 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && - (getPropertiesOfType(source).length > 0 || - getSignaturesOfType(source, 0 /* Call */).length > 0 || - getSignaturesOfType(source, 1 /* Construct */).length > 0) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { @@ -31223,20 +32643,20 @@ var ts; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 65536 /* Union */) { + if (source.flags & 131072 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)); } else { - if (target.flags & 65536 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */)); + if (target.flags & 131072 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */) && !(target.flags & 16382 /* Primitive */)); } - else if (target.flags & 131072 /* Intersection */) { + else if (target.flags & 262144 /* Intersection */) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 131072 /* Intersection */) { + else if (source.flags & 262144 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -31252,7 +32672,7 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */)) { + if (!result && (source.flags & 2064384 /* StructuredOrTypeVariable */ || target.flags & 2064384 /* StructuredOrTypeVariable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } @@ -31260,10 +32680,10 @@ var ts; } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { + if (source.flags & 65536 /* Object */ && target.flags & 16382 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 65536 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } reportRelationError(headMessage, source, target); @@ -31272,11 +32692,11 @@ var ts; } function isIdenticalTo(source, target) { var result; - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || - source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ || + source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; @@ -31286,12 +32706,19 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { - var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + if (maybeTypeOfKind(target, 65536 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(source.flags & 67108864 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } + if (target.flags & 131072 /* Union */) { + var discriminantType = findMatchingDiscriminantType(source, target); + if (discriminantType) { + // check excess properties against discriminant type only, not the entire union + return hasExcessProperties(source, discriminantType, reportErrors); + } + } var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -31317,7 +32744,7 @@ var ts; } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); } else { reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); @@ -31351,7 +32778,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 131072 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -31367,23 +32794,32 @@ var ts; } return 0 /* False */; } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { + var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { + var sourceProperty = sourcePropertiesFiltered_1[_i]; var sourceType = getTypeOfSymbol(sourceProperty); for (var _a = 0, _b = target.types; _a < _b.length; _a++) { var type = _b[_a]; var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); if (targetType && isRelatedTo(sourceType, targetType)) { - return type; + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + if (match) { + return undefined; + } + match = type; } } } } } + return match; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -31400,7 +32836,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 131072 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -31425,7 +32861,7 @@ var ts; } return result; } - function typeArgumentsRelatedTo(source, target, reportErrors) { + function typeArgumentsRelatedTo(source, target, variances, reportErrors) { var sources = source.typeArguments || ts.emptyArray; var targets = target.typeArguments || ts.emptyArray; if (sources.length !== targets.length && relation === identityRelation) { @@ -31434,11 +32870,45 @@ var ts; var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0 /* False */; + // When variance information isn't available we default to covariance. This happens + // in the process of computing variance information for recursive types and when + // comparing 'this' type arguments. + var variance = i < variances.length ? variances[i] : 1 /* Covariant */; + // We ignore arguments for independent type parameters (because they're never witnessed). + if (variance !== 4 /* Independent */) { + var s = sources[i]; + var t = targets[i]; + var related = -1 /* True */; + if (variance === 1 /* Covariant */) { + related = isRelatedTo(s, t, reportErrors); + } + else if (variance === 2 /* Contravariant */) { + related = isRelatedTo(t, s, reportErrors); + } + else if (variance === 3 /* Bivariant */) { + // In the bivariant case we first compare contravariantly without reporting + // errors. Then, if that doesn't succeed, we compare covariantly with error + // reporting. Thus, error elaboration will be based on the the covariant check, + // which is generally easier to reason about. + related = isRelatedTo(t, s, /*reportErrors*/ false); + if (!related) { + related = isRelatedTo(s, t, reportErrors); + } + } + else { + // In the invariant case we first compare covariantly, and only when that + // succeeds do we proceed to compare contravariantly. Thus, error elaboration + // will typically be based on the covariant check. + related = isRelatedTo(s, t, reportErrors); + if (related) { + related &= isRelatedTo(t, s, reportErrors); + } + } + if (!related) { + return 0 /* False */; + } + result &= related; } - result &= related; } return result; } @@ -31513,10 +32983,11 @@ var ts; } function structuredTypeRelatedTo(source, target, reportErrors) { var result; + var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 16384 /* TypeParameter */) { + if (target.flags & 32768 /* TypeParameter */) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -31526,9 +32997,9 @@ var ts; } } } - else if (target.flags & 262144 /* Index */) { + else if (target.flags & 524288 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 262144 /* Index */) { + if (source.flags & 524288 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } @@ -31542,7 +33013,7 @@ var ts; } } } - else if (target.flags & 524288 /* IndexedAccess */) { + else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and // A is the apparent type of S. var constraint = getConstraintOfIndexedAccess(target); @@ -31553,35 +33024,31 @@ var ts; } } } - if (source.flags & 16384 /* TypeParameter */) { + else if (isGenericMappedType(target) && !isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + if (source.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(source); + // A type parameter with no constraint is not related to the non-primitive object type. + if (constraint || !(target.flags & 33554432 /* NonPrimitive */)) { + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; } } - else { - var constraint = getConstraintOfTypeParameter(source); - // A type parameter with no constraint is not related to the non-primitive object type. - if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) { - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; - } - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } } - else if (source.flags & 524288 /* IndexedAccess */) { + else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and // A is the apparent type of S. var constraint = getConstraintOfIndexedAccess(source); @@ -31591,31 +33058,59 @@ var ts; return result; } } - else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { + else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { // if we have indexed access types with identical index types, see if relationship holds for // the two object types. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } } else { - if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { - // We have type references to same target type, see if relationship holds for all type arguments - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && + !(source.flags & 134217728 /* MarkerType */ || target.flags & 134217728 /* MarkerType */)) { + // We have type references to the same generic type, and the type references are not marker + // type references (which are intended by be compared structurally). Obtain the variance + // information for the type parameters and relate the type arguments accordingly. + var variances = getVariances(source.target); + if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { return result; } + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */); + var sourceIsPrimitive = !!(source.flags & 16382 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { + if (source.flags & (65536 /* Object */ | 262144 /* Intersection */) && target.flags & 65536 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; // An empty object type is related to any mapped type that includes a '?' modifier. @@ -31641,8 +33136,11 @@ var ts; } } if (result) { - errorInfo = saveErrorInfo; - return result; + if (!originalErrorInfo) { + errorInfo = saveErrorInfo; + return result; + } + errorInfo = originalErrorInfo; } } } @@ -31652,18 +33150,14 @@ var ts; // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. function mappedTypeRelatedTo(source, target, reportErrors) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; + var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : + !(getCombinedMappedTypeModifiers(source) & 2 /* Optional */) || + getCombinedMappedTypeModifiers(target) & 2 /* Optional */); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_1; + if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -31672,7 +33166,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -31680,10 +33174,24 @@ var ts; } return 0 /* False */; } + if (isObjectLiteralType(target)) { + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var sourceProp = _a[_i]; + if (!getPropertyOfObjectType(target, sourceProp.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target)); + } + return 0 /* False */; + } + } + } + } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var targetProp = properties_3[_i]; + for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { + var targetProp = properties_3[_b]; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { @@ -31754,20 +33262,20 @@ var ts; * and no required properties, call/construct signatures or index signatures */ function isWeakType(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); } - if (type.flags & 131072 /* Intersection */) { + if (type.flags & 262144 /* Intersection */) { return ts.every(type.types, isWeakType); } return false; } function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + var isComparingJsxAttributes = !!(source.flags & 67108864 /* JsxAttributes */); for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { @@ -31777,7 +33285,7 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { + if (!(source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -31786,8 +33294,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return 0 /* False */; @@ -31810,7 +33318,7 @@ var ts; var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type // as it would otherwise be possible to new an abstract class. Note that the assignability // check we perform for an extends clause excludes construct signatures from the target, @@ -31826,7 +33334,7 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { // We have instantiations of the same anonymous type (which typically will be the type of a // method). Simply do a pairwise comparison of the signatures in the two signature lists instead // of the much more expensive N * M comparison matrix we explore below. We erase type parameters @@ -31875,8 +33383,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, - /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, 0 /* None */, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -31937,7 +33444,7 @@ var ts; // if T is related to U. return kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } - if (isObjectLiteralType(source)) { + if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; if (kind === 0 /* String */) { var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); @@ -31990,11 +33497,72 @@ var ts; return false; } } + // Return a type reference where the source type parameter is replaced with the target marker + // type, and flag the result as a marker type reference. + function getMarkerTypeReference(type, source, target) { + var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); + result.flags |= 134217728 /* MarkerType */; + return result; + } + // Return an array containing the variance of each type parameter. The variance is effectively + // a digest of the type comparisons that occur for each type argument when instantiations of the + // generic type are structurally compared. We infer the variance information by comparing + // instantiations of the generic type for type arguments with known relations. The function + // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function + // has been invoked recursively for the given generic type. + function getVariances(type) { + if (!strictFunctionTypes) { + return ts.emptyArray; + } + var typeParameters = type.typeParameters || ts.emptyArray; + var variances = type.variances; + if (!variances) { + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this + variances = [1 /* Covariant */]; + } + else { + // The emptyArray singleton is used to signal a recursive invocation. + type.variances = ts.emptyArray; + variances = []; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var tp = typeParameters_1[_i]; + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + var typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); + var typeWithSub = getMarkerTypeReference(type, tp, markerSubType); + var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + variances.push(variance); + } + } + type.variances = variances; + } + return variances; + } + // Return true if the given type reference has a 'void' type argument for a covariant type parameter. + // See comment at call in recursiveTypeRelatedTo for when this case matters. + function hasCovariantVoidArgument(type, variances) { + for (var i = 0; i < variances.length; i++) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 2048 /* Void */) { + return true; + } + } + return false; + } function isUnconstrainedTypeParameter(type) { - return type.flags & 16384 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -32077,19 +33645,6 @@ var ts; return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } - // Return true if the given type is the constructor type for an abstract class - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16 /* Anonymous */) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32 /* Class */) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.hasModifier(declaration, 128 /* Abstract */)) { - return true; - } - } - } - return false; - } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely @@ -32097,13 +33652,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 32768 /* Object */) { + if (depth >= 5 && type.flags & 65536 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 32768 /* Object */ && t.symbol === symbol) { + if (t.flags & 65536 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -32243,29 +33798,37 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : getUnionType(types, /*subtypeReduction*/ true); } + // Return the leftmost type for which no type to the right is a subtype. + function getCommonSubtype(types) { + return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); + } function isArrayType(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 12288 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isEmptyArrayLiteralType(type) { + var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; + return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return !!(type.flags & 6368 /* Unit */); + return !!(type.flags & 13536 /* Unit */); } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : - type.flags & 65536 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + type.flags & 131072 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { @@ -32273,23 +33836,34 @@ var ts; type.flags & 32 /* StringLiteral */ ? stringType : type.flags & 64 /* NumberLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 /* StringLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? numberType : + type.flags & 32 /* StringLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? stringType : + type.flags & 64 /* NumberLiteral */ && type.flags & 2097152 /* FreshLiteral */ ? numberType : type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 65536 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 1024 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return type; + } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } function getFalsyFlagsOfTypes(types) { var result = 0; @@ -32303,15 +33877,15 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 65536 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + return type.flags & 131072 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : - type.flags & 7406 /* PossiblyFalsy */; + type.flags & 14574 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 14560 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { @@ -32321,7 +33895,7 @@ var ts; return type.flags & 2 /* String */ ? emptyStringType : type.flags & 4 /* Number */ ? zeroType : type.flags & 8 /* Boolean */ || type === falseType ? falseType : - type.flags & (1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */) || + type.flags & (2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */) || type.flags & 32 /* StringLiteral */ && type.value === "" || type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : neverType; @@ -32332,23 +33906,26 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (2048 /* Undefined */ | 4096 /* Null */); + var missing = (flags & ~type.flags) & (4096 /* Undefined */ | 8192 /* Null */); return missing === 0 ? type : - missing === 2048 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 4096 /* Null */ ? getUnionType([type, nullType]) : + missing === 4096 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 8192 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } + function getOptionalType(type) { + ts.Debug.assert(strictNullChecks); + return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); + } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; } /** - * Return true if type was inferred from an object literal or written as an object type literal + * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module * with no call or construct signatures. */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && - getSignaturesOfType(type, 0 /* Call */).length === 0 && - getSignaturesOfType(type, 1 /* Construct */).length === 0; + function isObjectTypeWithInferableIndex(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 512 /* ValueModule */)) !== 0 && + !typeHasCallOrConstructSignatures(type); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName); @@ -32377,7 +33954,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && type.flags & 2097152 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -32387,41 +33964,102 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; + regularNew.flags = resolved.flags & ~2097152 /* FreshLiteral */; regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } - function getWidenedProperty(prop) { + function createWideningContext(parent, propertyName, siblings) { + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + var siblings_1 = []; + for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) { + var type = _a[_i]; + if (isObjectLiteralType(type)) { + var prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), function (t) { + siblings_1.push(t); + }); + } + } + } + context.siblings = siblings_1; + } + return context.siblings; + } + function getPropertyNamesOfContext(context) { + if (!context.resolvedPropertyNames) { + var names = ts.createMap(); + for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { + var t = _a[_i]; + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { + var prop = _c[_b]; + names.set(prop.escapedName, true); + } + } + } + context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + } + return context.resolvedPropertyNames; + } + function getWidenedProperty(prop, context) { var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); + var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); + var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getWidenedTypeOfObjectLiteral(type) { + function getUndefinedProperty(name) { + var cached = undefinedProperties.get(name); + if (cached) { + return cached; + } + var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); + result.type = undefinedType; + undefinedProperties.set(name, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; // Since get accessors already widen their return value there is no need to // widen accessor based properties here. - members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop); + members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop, context) : prop); + } + if (context) { + for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { + var name = _c[_b]; + if (!members.has(name)) { + members.set(name, getUndefinedProperty(name)); + } + } } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } - function getWidenedConstituentType(type) { - return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); - } function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { - if (type.flags & 6144 /* Nullable */) { + return getWidenedTypeWithContext(type, /*context*/ undefined); + } + function getWidenedTypeWithContext(type, context) { + if (type.flags & 12582912 /* RequiresWidening */) { + if (type.flags & 12288 /* Nullable */) { return anyType; } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - return getWidenedTypeOfObjectLiteral(type); + if (isObjectLiteralType(type)) { + return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 65536 /* Union */) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + if (type.flags & 131072 /* Union */) { + var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + // Widening an empty object literal transitions from a highly restrictive type to + // a highly inclusive one. For that reason we perform subtype reduction here if the + // union includes empty object types (e.g. reducing {} | string to just {}). + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -32442,31 +34080,38 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 65536 /* Union */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { + if (type.flags & 4194304 /* ContainsWideningType */) { + if (type.flags & 131072 /* Union */) { + if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } + else { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } } } - } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152 /* ContainsWideningType */) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + if (isObjectLiteralType(type)) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 4194304 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.symbolName(p), typeToString(getWidenedType(t))); + } + errorReported = true; } - errorReported = true; } } } @@ -32476,25 +34121,25 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 146 /* Parameter */: + case 147 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 176 /* BindingElement */: + case 177 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -32507,7 +34152,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && type.flags & 4194304 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -32576,12 +34221,12 @@ var ts; // we perform type inference (i.e. a type parameter of a generic function). We cache // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) || + var objectFlags = ts.getObjectFlags(type); + return !!(type.flags & (1081344 /* TypeVariable */ | 524288 /* Index */) || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 393216 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { @@ -32590,13 +34235,34 @@ var ts; return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + /** Create an object with properties named in the string literal type. Every property has type `{}` */ + function createEmptyObjectTypeFromStringLiteral(type) { + var members = ts.createSymbolTable(); + forEachType(type, function (t) { + if (!(t.flags & 32 /* StringLiteral */)) { + return; + } + var name = ts.escapeLeadingUnderscores(t.value); + var literalProp = createSymbol(4 /* Property */, name); + literalProp.type = emptyObjectType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + var indexInfo = type.flags & 2 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } - // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct - // an object type with the same set of properties as the source type, where the type of each - // property is computed by inferring from the source property type to X for the type - // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). - function inferTypeForHomomorphicMappedType(source, target) { + /** + * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + * an object type with the same set of properties as the source type, where the type of each + * property is computed by inferring from the source property type to X for the type + * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + */ + function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { var properties = getPropertiesOfType(source); var indexInfo = getIndexInfoOfType(source, 0 /* String */); if (properties.length === 0 && !indexInfo) { @@ -32611,32 +34277,30 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); - if (!inferredPropType) { + var propType = getTypeOfSymbol(prop); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. + if (propType.flags & 16777216 /* ContainsAnyFunctionType */) { return undefined; } - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; + inferredProp.type = inferTargetType(propType); members.set(prop.escapedName, inferredProp); } if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); } return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); function inferTargetType(sourceType) { inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType); - return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); + inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); + return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; } } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = getPropertiesOfObjectType(target); + var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { @@ -32648,7 +34312,7 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; @@ -32667,8 +34331,8 @@ var ts; } return; } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || - source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || + source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -32706,51 +34370,69 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 540672 /* TypeVariable */) { + if (target.flags & 1081344 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType which is used as a wildcard - // when constructing types from type parameters that had no inference candidates. - if (source.flags & 8388608 /* ContainsAnyFunctionType */ || source === silentNeverType) { + // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard + // when constructing types from type parameters that had no inference candidates). + if (source.flags & 16777216 /* ContainsAnyFunctionType */ || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - if (!inference.candidates || priority < inference.priority) { + // We give lowest priority to inferences of implicitNeverType (which is used as the + // element type for empty array literals). Thus, inferences from empty array literals + // only matter when no other inferences are made. + var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); + if (!inference.candidates || p < inference.priority) { inference.candidates = [source]; - inference.priority = priority; + inference.priority = p; } - else if (priority === inference.priority) { + else if (p === inference.priority) { inference.candidates.push(source); } - if (!(priority & 4 /* ReturnType */) && target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + else if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + var variances = getVariances(source.target); for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); + if (i < variances.length && variances[i] === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } + else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } } } - else if (source.flags & 262144 /* Index */ && target.flags & 262144 /* Index */) { + else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { + priority ^= 1 /* Contravariant */; inferFromTypes(source.type, target.type); + priority ^= 1 /* Contravariant */; } - else if (source.flags & 524288 /* IndexedAccess */ && target.flags & 524288 /* IndexedAccess */) { + else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { + var empty = createEmptyObjectTypeFromStringLiteral(source); + priority ^= 1 /* Contravariant */; + inferFromTypes(empty, target.type); + priority ^= 1 /* Contravariant */; + } + else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (target.flags & 196608 /* UnionOrIntersection */) { + else if (target.flags & 393216 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -32770,12 +34452,12 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; + priority |= 2 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } } - else if (source.flags & 65536 /* Union */) { + else if (source.flags & 131072 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -32785,7 +34467,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & (32768 /* Object */ | 131072 /* Intersection */)) { + if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -32795,8 +34477,8 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 32768 /* Object */ && - !(getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); + var isNonConstructorObject = target.flags & 65536 /* Object */ && + !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (ts.contains(symbolStack, symbol)) { @@ -32812,8 +34494,18 @@ var ts; } } } + function inferFromContravariantTypes(source, target) { + if (strictFunctionTypes) { + priority ^= 1 /* Contravariant */; + inferFromTypes(source, target); + priority ^= 1 /* Contravariant */; + } + else { + inferFromTypes(source, target); + } + } function getInferenceInfoForType(type) { - if (type.flags & 540672 /* TypeVariable */) { + if (type.flags & 1081344 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -32830,26 +34522,32 @@ var ts; inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); } - if (getObjectFlags(target) & 32 /* Mapped */) { + if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144 /* Index */) { + if (constraintType.flags & 524288 /* Index */) { // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference // such that direct inferences to T get priority over inferences to Partial, for example. var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); + var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); + if (ts.contains(mappedTypeStack, key)) { + return; + } + (mappedTypeStack || (mappedTypeStack = [])).push(key); + var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); + mappedTypeStack.pop(); if (inferredType) { var savePriority = priority; - priority |= 2 /* MappedType */; + priority |= 4 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } } return; } - if (constraintType.flags & 16384 /* TypeParameter */) { + if (constraintType.flags & 32768 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. inferFromTypes(getIndexType(source), constraintType); @@ -32883,11 +34581,11 @@ var ts; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); } } function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromContravariantTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); } @@ -32936,17 +34634,32 @@ var ts; reducedTypes.push(t); } } - return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 131072 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); + return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + } + function isObjectLiteralType(type) { + return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function widenObjectLiteralCandidates(candidates) { + if (candidates.length > 1) { + var objectLiterals = ts.filter(candidates, isObjectLiteralType); + if (objectLiterals.length) { + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); + } + } + return candidates; } function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; if (!inferredType) { if (inference.candidates) { + // Extract all object literal types and replace them with a single widened and normalized type. + var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if // all inferences were made to top-level ocurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and @@ -32955,12 +34668,14 @@ var ts; var widenLiteralTypes = inference.topLevel && !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; - // Infer widened union or supertype, or the unknown type for no common supertype. We infer union types - // for inferences coming from return types in order to avoid common supertype failures. - var unionOrSuperType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? - getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates); - inferredType = getWidenedType(unionOrSuperType); + var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if + // union types were requested or if all inferences were made from the return type position, infer a + // union type. Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : + context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : + getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unwidenedType); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -32982,12 +34697,13 @@ var ts; inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); } } + inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); } } } @@ -33016,7 +34732,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 162 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 143 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 163 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 144 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -33032,13 +34748,13 @@ var ts; if (node.kind === 99 /* ThisKeyword */) { return "0"; } - if (node.kind === 179 /* PropertyAccessExpression */) { + if (node.kind === 180 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + return key && key + "." + ts.idText(node.name); } - if (node.kind === 176 /* BindingElement */) { + if (node.kind === 177 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 176 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 177 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -33046,12 +34762,12 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 174 /* ObjectBindingPattern */) { + if (element.parent.kind === 175 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: - return ts.unescapeLeadingUnderscores(name.escapedText); - case 144 /* ComputedPropertyName */: + return ts.idText(name); + case 145 /* ComputedPropertyName */: return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -33069,26 +34785,26 @@ var ts; switch (source.kind) { case 71 /* Identifier */: return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 /* VariableDeclaration */ || target.kind === 176 /* BindingElement */) && + (target.kind === 227 /* VariableDeclaration */ || target.kind === 177 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99 /* ThisKeyword */: return target.kind === 99 /* ThisKeyword */; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; - case 179 /* PropertyAccessExpression */: - return target.kind === 179 /* PropertyAccessExpression */ && + case 180 /* PropertyAccessExpression */: + return target.kind === 180 /* PropertyAccessExpression */ && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 176 /* BindingElement */: - if (target.kind !== 179 /* PropertyAccessExpression */) + case 177 /* BindingElement */: + if (target.kind !== 180 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 176 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 177 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 226 /* VariableDeclaration */) { + if (source.parent.parent.kind === 227 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return maybeId && isMatchingReference(maybeId, t.expression); } @@ -33096,7 +34812,7 @@ var ts; return false; } function containsMatchingReference(source, target) { - while (source.kind === 179 /* PropertyAccessExpression */) { + while (source.kind === 180 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -33109,7 +34825,7 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 /* PropertyAccessExpression */ && + return target.kind === 180 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -33117,14 +34833,14 @@ var ts; if (expr.kind === 71 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 179 /* PropertyAccessExpression */) { + if (expr.kind === 180 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536 /* Union */) { + if (type && type.flags & 131072 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { @@ -33135,6 +34851,20 @@ var ts; } return false; } + function findDiscriminantProperties(sourceProperties, target) { + var result; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProperty = sourceProperties_2[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -33147,7 +34877,7 @@ var ts; } } } - if (callExpression.expression.kind === 179 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 180 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -33161,7 +34891,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536 /* Union */)) { + if (!(source.flags & 131072 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -33177,11 +34907,11 @@ var ts; // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 8192 /* Never */) { + if (assignedType.flags & 16384 /* Never */) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192 /* Never */)) { + if (!(reducedType.flags & 16384 /* Never */)) { return reducedType; } } @@ -33230,32 +34960,42 @@ var ts; type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 32768 /* Object */) { + if (flags & 65536 /* Object */) { return isFunctionObjectType(type) ? strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; } - if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { + if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 4096 /* Null */) { + if (flags & 8192 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 512 /* ESSymbol */) { + if (flags & 1536 /* ESSymbolLike */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 16777216 /* NonPrimitive */) { + if (flags & 33554432 /* NonPrimitive */) { return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; } - if (flags & 540672 /* TypeVariable */) { + if (flags & 1081344 /* TypeVariable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 196608 /* UnionOrIntersection */) { + if (flags & 393216 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } return 8388607 /* All */; } function getTypeWithFacts(type, include) { + if (type.flags & 1048576 /* IndexedAccess */) { + // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to + // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -33281,15 +35021,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 178 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 265 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 216 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 195 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); @@ -33306,21 +35046,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return stringType; - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return undefinedType; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return unknownType; @@ -33328,7 +35068,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 /* ObjectBindingPattern */ ? + var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : @@ -33346,35 +35086,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 215 /* ForInStatement */) { + if (node.parent.parent.kind === 216 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 216 /* ForOfStatement */) { + if (node.parent.parent.kind === 217 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; } return unknownType; } function getInitialType(node) { - return node.kind === 226 /* VariableDeclaration */ ? + return node.kind === 227 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */ ? + return node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 226 /* VariableDeclaration */ && node.initializer && + return node.kind === 227 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 /* BindingElement */ && node.parent.kind === 194 /* BinaryExpression */ && + node.kind !== 177 /* BindingElement */ && node.parent.kind === 195 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: return getReferenceCandidate(node.left); @@ -33386,13 +35126,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 185 /* ParenthesizedExpression */ || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 186 /* ParenthesizedExpression */ || + parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 257 /* CaseClause */) { + if (clause.kind === 261 /* CaseClause */) { var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } @@ -33416,13 +35156,13 @@ var ts; return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 131072 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 131072 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536 /* Union */) { + if (source.flags & 131072 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -33437,10 +35177,10 @@ var ts; return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 131072 /* Union */ ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered); @@ -33451,7 +35191,7 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union // of the resulting types is returned. function mapType(type, mapper) { - if (!(type.flags & 65536 /* Union */)) { + if (!(type.flags & 131072 /* Union */)) { return mapper(type); } var types = type.types; @@ -33520,9 +35260,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 8192 /* Never */ ? + return elementType.flags & 16384 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 65536 /* Union */ ? + createArrayType(elementType.flags & 131072 /* Union */ ? getUnionType(elementType.types, /*subtypeReduction*/ true) : elementType); } @@ -33531,17 +35271,17 @@ var ts; return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); } function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; } function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var t = types_15[_i]; - if (!(t.flags & 8192 /* Never */)) { - if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + if (!(t.flags & 16384 /* Never */)) { + if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } hasEvolvingArrayType = true; @@ -33562,11 +35302,11 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 181 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 180 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 182 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 181 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 194 /* BinaryExpression */ && + parent.parent.kind === 195 /* BinaryExpression */ && parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -33606,7 +35346,7 @@ var ts; if (flowAnalysisDisabled) { return unknownType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 35620607 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -33616,8 +35356,8 @@ var ts; // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { + var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent && reference.parent.kind === 204 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 16384 /* Never */) { return declaredType; } return resultType; @@ -33688,7 +35428,7 @@ var ts; else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && reference.kind !== 180 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -33726,7 +35466,7 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 65536 /* Union */) { + if (declaredType.flags & 131072 /* Union */) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; @@ -33744,15 +35484,15 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 181 /* CallExpression */ ? + var expr = node.kind === 182 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256 /* EvolvingArray */) { + if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 181 /* CallExpression */) { + if (node.kind === 182 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -33774,7 +35514,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 8192 /* Never */) { + if (type.flags & 16384 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -33791,7 +35531,7 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 16384 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -33917,8 +35657,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 179 /* PropertyAccessExpression */ && - computedType.flags & 65536 /* Union */ && + return expr.kind === 180 /* PropertyAccessExpression */ && + computedType.flags & 131072 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -33951,10 +35691,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 189 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -33988,7 +35728,7 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144 /* Nullable */) { + if (valueType.flags & 12288 /* Nullable */) { if (!strictNullChecks) { return type; } @@ -34000,12 +35740,12 @@ var ts; assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 16810497 /* NotUnionOrUnit */) { + if (type.flags & 33620481 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 16384 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -34027,7 +35767,7 @@ var ts; if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 65536 /* Union */)) { + if (assumeTrue && !(type.flags & 131072 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. @@ -34036,7 +35776,7 @@ var ts; if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 540672 /* TypeVariable */) { + if (type.flags & 1081344 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -34058,13 +35798,13 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 16384 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); @@ -34097,10 +35837,10 @@ var ts; if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2 /* Interface */) { + if (ts.getObjectFlags(rightType) & 2 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (getObjectFlags(rightType) & 16 /* Anonymous */) { + else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -34108,7 +35848,7 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } return type; } @@ -34118,9 +35858,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192 /* Never */)) { + if (!(assignableType.flags & 16384 /* Never */)) { return assignableType; } } @@ -34160,7 +35900,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 /* ElementAccessExpression */ || invokedExpression.kind === 179 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 181 /* ElementAccessExpression */ || invokedExpression.kind === 180 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -34180,15 +35920,15 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: if (expr.operator === 51 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -34207,7 +35947,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -34224,9 +35964,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 /* ModuleBlock */ || - node.kind === 265 /* SourceFile */ || - node.kind === 149 /* PropertyDeclaration */; + node.kind === 235 /* ModuleBlock */ || + node.kind === 269 /* SourceFile */ || + node.kind === 150 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. @@ -34248,7 +35988,7 @@ var ts; if (node.kind === 71 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 147 /* Parameter */) { symbol.isAssigned = true; } } @@ -34263,20 +36003,20 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 /* Parameter */ && + declaration.kind === 147 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 2048 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); + getFalsyFlags(declaredType) & 4096 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } function isApparentTypePosition(node) { var parent = node.parent; - return parent.kind === 179 /* PropertyAccessExpression */ || - parent.kind === 181 /* CallExpression */ && parent.expression === node || - parent.kind === 180 /* ElementAccessExpression */ && parent.expression === node; + return parent.kind === 180 /* PropertyAccessExpression */ || + parent.kind === 182 /* CallExpression */ && parent.expression === node || + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; } function typeHasNullableConstraint(type) { - return type.flags & 540672 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 6144 /* Nullable */); + return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } function getDeclaredOrApparentType(symbol, node) { // When a node is the left hand expression of a property access, element access, or call expression, @@ -34303,7 +36043,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 187 /* ArrowFunction */) { + if (container.kind === 188 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -34324,7 +36064,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 229 /* ClassDeclaration */ + if (declaration.kind === 230 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -34336,14 +36076,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 199 /* ClassExpression */) { + else if (declaration.kind === 200 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); while (container !== undefined) { if (container.parent === declaration) { - if (container.kind === 149 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + if (container.kind === 150 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } @@ -34389,15 +36129,15 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 146 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 147 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 /* FunctionExpression */ || - flowContainer.kind === 187 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 187 /* FunctionExpression */ || + flowContainer.kind === 188 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -34405,12 +36145,14 @@ var ts; // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 246 /* ExportSpecifier */) || - node.parent.kind === 203 /* NonNullExpression */ || - ts.isInAmbientContext(declaration); + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || + node.parent.kind === 204 /* NonNullExpression */ || + declaration.kind === 227 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 2097152 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048 /* Undefined */); + getOptionalType(type); var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -34424,7 +36166,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -34437,7 +36179,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 260 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 264 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -34462,8 +36204,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 214 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 227 /* VariableDeclarationList */).parent === container && + if (container.kind === 215 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 228 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -34477,7 +36219,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 185 /* ParenthesizedExpression */) { + while (current.parent.kind === 186 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -34485,7 +36227,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 192 /* PrefixUnaryExpression */ || current.parent.kind === 193 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 193 /* PrefixUnaryExpression */ || current.parent.kind === 194 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; } @@ -34498,7 +36240,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 149 /* PropertyDeclaration */ || container.kind === 152 /* Constructor */) { + if (container.kind === 150 /* PropertyDeclaration */ || container.kind === 153 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -34566,38 +36308,38 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 152 /* Constructor */) { + if (container.kind === 153 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 187 /* ArrowFunction */) { + if (container.kind === 188 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 152 /* Constructor */: + case 153 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: if (ts.hasModifier(container, 32 /* Static */)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -34609,8 +36351,8 @@ var ts; // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } - if (container.kind === 186 /* FunctionExpression */ && - container.parent.kind === 194 /* BinaryExpression */ && + if (container.kind === 187 /* FunctionExpression */ && + container.parent.kind === 195 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') var className = container.parent // x.prototype.y = f @@ -34646,7 +36388,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 273 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 277 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -34656,15 +36398,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 147 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 182 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 187 /* ArrowFunction */) { + while (container && container.kind === 188 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -34677,14 +36419,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144 /* ComputedPropertyName */; }); - if (current && current.kind === 144 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 145 /* ComputedPropertyName */; }); + if (current && current.kind === 145 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 179 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -34692,7 +36434,7 @@ var ts; } return unknownType; } - if (!isCallExpression && container.kind === 152 /* Constructor */) { + if (!isCallExpression && container.kind === 153 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -34758,7 +36500,7 @@ var ts; // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === 151 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (container.kind === 152 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -34772,7 +36514,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (container.parent.kind === 179 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; @@ -34784,15 +36526,16 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return unknownType; + } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } return unknownType; } - if (container.kind === 152 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 153 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -34807,7 +36550,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 152 /* Constructor */; + return container.kind === 153 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -34815,21 +36558,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 179 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */; + return container.kind === 152 /* MethodDeclaration */ || + container.kind === 151 /* MethodSignature */ || + container.kind === 154 /* GetAccessor */ || + container.kind === 155 /* SetAccessor */; } else { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */ || - container.kind === 149 /* PropertyDeclaration */ || - container.kind === 148 /* PropertySignature */ || - container.kind === 152 /* Constructor */; + return container.kind === 152 /* MethodDeclaration */ || + container.kind === 151 /* MethodSignature */ || + container.kind === 154 /* GetAccessor */ || + container.kind === 155 /* SetAccessor */ || + container.kind === 150 /* PropertyDeclaration */ || + container.kind === 149 /* PropertySignature */ || + container.kind === 153 /* Constructor */; } } } @@ -34837,22 +36580,22 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 151 /* MethodDeclaration */ || - func.kind === 153 /* GetAccessor */ || - func.kind === 154 /* SetAccessor */) && func.parent.kind === 178 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 186 /* FunctionExpression */ && func.parent.kind === 261 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 152 /* MethodDeclaration */ || + func.kind === 154 /* GetAccessor */ || + func.kind === 155 /* SetAccessor */) && func.parent.kind === 179 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 187 /* FunctionExpression */ && func.parent.kind === 265 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 262144 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 187 /* ArrowFunction */) { + if (func.kind === 188 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -34879,7 +36622,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 261 /* PropertyAssignment */) { + if (literal.parent.kind !== 265 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -34893,9 +36636,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 195 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { var target = parent.left; - if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { + if (target.kind === 180 /* PropertyAccessExpression */ || target.kind === 181 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -34938,6 +36681,10 @@ var ts; var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. + indexOfParameter -= 1; + } if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -34961,12 +36708,12 @@ var ts; // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer) { + if (node === declaration.initializer || node.kind === 58 /* EqualsToken */) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 146 /* Parameter */) { + if (declaration.kind === 147 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -34978,7 +36725,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 /* BindingElement */) { + if (parentDeclaration.kind !== 177 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -35019,10 +36766,14 @@ var ts; return undefined; } function isInParameterInitializerBeforeContainingFunction(node) { + var inBindingInitializer = false; while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 /* Parameter */ && node.parent.initializer === node) { + if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { return true; } + if (ts.isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } node = node.parent; } return false; @@ -35030,7 +36781,7 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 152 /* Constructor */ || + if (functionDecl.kind === 153 /* Constructor */ || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); @@ -35056,43 +36807,58 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183 /* TaggedTemplateExpression */) { + if (template.parent.kind === 184 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (ts.isAssignmentOperator(operator)) { - // Don't do this for special property assignments to avoid circularity - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { + var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; + switch (operatorToken.kind) { + case 58 /* EqualsToken */: + return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + case 54 /* BarBarToken */: + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand. + var type = getContextualType(binaryExpression); + return !type && node === right ? getTypeOfExpression(left, /*cache*/ true) : type; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + return node === right ? getContextualType(binaryExpression) : undefined; + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + // For completions after `x === ` + return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; + default: return undefined; - } - // In an assignment expression, the right operand is contextually typed by the type of the left operand. - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } } - else if (operator === 54 /* BarBarToken */) { - // When an || expression has a contextual type, the operands are contextually typed by that type. When an || - // expression has no contextual type, the right operand is contextually typed by the type of the left operand. - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left, /*cache*/ true); - } - return type; - } - else if (operator === 53 /* AmpersandAmpersandToken */ || operator === 26 /* CommaToken */) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + // Don't do this for special property assignments to avoid circularity. + function isContextSensitiveAssignment(binaryExpression) { + var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + switch (kind) { + case 0 /* None */: + return true; + case 5 /* Property */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + return !binaryExpression.left.symbol; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + return false; + default: + ts.Debug.assertNever(kind); } - return undefined; } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -35101,14 +36867,14 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 131072 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -35118,12 +36884,12 @@ var ts; var objectLiteral = element.parent; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { - if (!ts.hasDynamicName(element)) { + if (!hasNonBindableDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + var symbolName_1 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); if (propertyType) { return propertyType; } @@ -35151,7 +36917,12 @@ var ts; // JSX expression can appear in two position : JSX Element's children or JSX attribute var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? node.parent.parent : - node.parent.openingElement.attributes; // node.parent is JsxElement + ts.isJsxElement(node.parent) ? + node.parent.openingElement.attributes : + undefined; // node.parent is JsxFragment with no attributes + if (!jsxAttributes) { + return undefined; // don't check children of a fragment + } // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName @@ -35163,7 +36934,7 @@ var ts; // JSX expression is in JSX attribute return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); } - else if (node.parent.kind === 249 /* JsxElement */) { + else if (node.parent.kind === 250 /* JsxElement */) { // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; @@ -35191,8 +36962,37 @@ var ts; // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); + var contextualType = getContextualType(node); + contextualType = contextualType && mapType(contextualType, getApparentType); + if (!(contextualType && contextualType.flags & 131072 /* Union */ && ts.isObjectLiteralExpression(node))) { + return contextualType; + } + // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` + var match; + propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (!prop.symbol) + continue; + if (prop.kind !== 265 /* PropertyAssignment */) + continue; + if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = getTypeOfNode(prop.initializer); + for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); + if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + match = undefined; + break propLoop; + } + match = type; + } + } + } + } + return match || contextualType; } /** * Woah! Do you really want to use this function? @@ -35212,7 +37012,7 @@ var ts; * @returns the contextual type of an expression. */ function getContextualType(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -35221,53 +37021,63 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 176 /* BindingElement */: + case 227 /* VariableDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 177 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 187 /* ArrowFunction */: - case 219 /* ReturnStatement */: + case 188 /* ArrowFunction */: + case 220 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 183 /* NewExpression */: + if (node.kind === 94 /* NewKeyword */) { + return getContextualType(parent); + } + // falls through + case 182 /* CallExpression */: return getContextualTypeForArgument(parent, node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 177 /* ArrayLiteralExpression */: { + case 178 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 205 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); + case 206 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 197 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185 /* ParenthesizedExpression */: { + case 186 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: return getAttributesTypeFromJsxOpeningLikeElement(parent); + case 261 /* CaseClause */: { + if (node.kind === 73 /* CaseKeyword */) { + var switchStatement = parent.parent.parent; + return getTypeOfExpression(switchStatement.expression); + } + } } return undefined; } @@ -35302,7 +37112,7 @@ var ts; return sourceLength < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */; + return node.kind === 187 /* FunctionExpression */ || node.kind === 188 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -35321,12 +37131,12 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } - if (!(type.flags & 65536 /* Union */)) { + if (!(type.flags & 131072 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; @@ -35367,8 +37177,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 176 /* BindingElement */ && !!node.initializer) || - (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 177 /* BindingElement */ && !!node.initializer) || + (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; @@ -35378,7 +37188,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); for (var index = 0; index < elements.length; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 199 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -35403,7 +37213,7 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; + hasSpreadElement = hasSpreadElement || e.kind === 199 /* SpreadElement */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -35413,20 +37223,19 @@ var ts; type.pattern = node; return type; } - var contextualType_1 = getApparentTypeOfContextualType(node); - if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { - var pattern = contextualType_1.pattern; + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 176 /* ArrayBindingPattern */ || pattern.kind === 178 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType_1.typeArguments[i]); + elementTypes.push(contextualType.typeArguments[i]); } else { - if (patternElement.kind !== 200 /* OmittedExpression */) { + if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -35440,11 +37249,11 @@ var ts; } return createArrayType(elementTypes.length ? getUnionType(elementTypes, /*subtypeReduction*/ true) : - strictNullChecks ? neverType : undefinedWideningType); + strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return isNumericComputedName(name); case 71 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -35493,8 +37302,8 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & 6144 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */) && + if (links.resolvedType.flags & 12288 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -35524,7 +37333,7 @@ var ts; var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 /* ObjectBindingPattern */ || contextualType.pattern.kind === 178 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 175 /* ObjectBindingPattern */ || contextualType.pattern.kind === 179 /* ObjectLiteralExpression */); var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); var typeFlags = 0; var patternWithComputedProperties = false; @@ -35534,18 +37343,18 @@ var ts; var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; - var member = memberDecl.symbol; + var member = getSymbolOfNode(memberDecl); var literalName = void 0; - if (memberDecl.kind === 261 /* PropertyAssignment */ || - memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 265 /* PropertyAssignment */ || + memberDecl.kind === 266 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var jsdocType = void 0; if (isInJSFile) { jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); } var type = void 0; - if (memberDecl.kind === 261 /* PropertyAssignment */) { - if (memberDecl.name.kind === 144 /* ComputedPropertyName */) { + if (memberDecl.kind === 265 /* PropertyAssignment */) { + if (memberDecl.name.kind === 145 /* ComputedPropertyName */) { var t = checkComputedPropertyName(memberDecl.name); if (t.flags & 224 /* Literal */) { literalName = ts.escapeLeadingUnderscores("" + t.value); @@ -35553,11 +37362,11 @@ var ts; } type = checkPropertyAssignment(memberDecl, checkMode); } - else if (memberDecl.kind === 151 /* MethodDeclaration */) { + else if (memberDecl.kind === 152 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, checkMode); } else { - ts.Debug.assert(memberDecl.kind === 262 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 266 /* ShorthandPropertyAssignment */); type = checkExpressionForMutableLocation(memberDecl.name, checkMode); } if (jsdocType) { @@ -35565,12 +37374,15 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); + var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; + var prop = nameType && isTypeUsableAsLateBoundName(nameType) + ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) + : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 261 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 265 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 266 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -35578,7 +37390,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.escapedName); @@ -35598,12 +37410,12 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 263 /* SpreadAssignment */) { + else if (memberDecl.kind === 267 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; @@ -35615,7 +37427,7 @@ var ts; error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; } - spread = getSpreadType(spread, type); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags); offset = i + 1; continue; } @@ -35625,10 +37437,10 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 154 /* GetAccessor */ || memberDecl.kind === 155 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (!literalName && ts.hasDynamicName(memberDecl)) { + if (!literalName && hasNonBindableDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -35646,7 +37458,7 @@ var ts; if (contextualTypeHasPattern) { for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; - if (!propertiesTable.get(prop.escapedName)) { + if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { if (!(prop.flags & 16777216 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -35657,14 +37469,7 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags); } return spread; } @@ -35673,8 +37478,8 @@ var ts; var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 2097152 /* FreshLiteral */; + result.flags |= 8388608 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 29360128 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -35682,25 +37487,25 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 6144 /* Nullable */)) { - propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); + if (!(result.flags & 12288 /* Nullable */)) { + propagatedFlags |= (result.flags & 29360128 /* PropagatingFlags */); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 16777216 /* NonPrimitive */) || - getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 32768 /* Object */ && !isGenericMappedType(type) || - type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (1 /* Any */ | 33554432 /* NonPrimitive */) || + getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 65536 /* Object */ && !isGenericMappedType(type) || + type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); + checkJsxOpeningLikeElementOrOpeningFragment(node); return getJsxGlobalElementType() || anyType; } function checkJsxElement(node) { // Check attributes - checkJsxOpeningLikeElement(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -35710,12 +37515,19 @@ var ts; } return getJsxGlobalElementType() || anyType; } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { + error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); + } + return getJsxGlobalElementType() || anyType; + } /** * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers */ function isUnhyphenatedJsxName(name) { // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; + return !ts.stringContains(name, "-"); } /** * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name @@ -35723,7 +37535,7 @@ var ts; function isJsxIntrinsicIdentifier(tagName) { // TODO (yuisu): comment switch (tagName.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: case 99 /* ThisKeyword */: return false; case 71 /* Identifier */: @@ -35772,9 +37584,9 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 259 /* JsxSpreadAttribute */); if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); attributesArray = []; attributesTable = ts.createSymbolTable(); } @@ -35783,7 +37595,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -35793,7 +37605,7 @@ var ts; if (!hasSpreadAnyType) { if (spread !== emptyObjectType) { if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); } attributesArray = getPropertiesOfType(spread); } @@ -35806,23 +37618,10 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 250 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { - var childrenTypes = []; - for (var _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that - // because then type of children property will have constituent of string type. - if (child.kind === 10 /* JsxText */) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } + var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { // Error if there is a attribute named "children" explicitly specified and children element. // This is because children element will overwrite the value from attributes. @@ -35851,11 +37650,28 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; + result.flags |= 67108864 /* JsxAttributes */ | 8388608 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } } + function checkJsxChildren(node, checkMode) { + var childrenTypes = []; + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that + // because then type of children property will have constituent of string type. + if (child.kind === 10 /* JsxText */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + return childrenTypes; + } /** * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) @@ -35897,7 +37713,7 @@ var ts; return links.resolvedSymbol = intrinsicElementsType.symbol; } // Wasn't found - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { @@ -35915,7 +37731,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); + ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -35999,7 +37815,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 131072 /* Intersection */) { + if (propsType.flags & 262144 /* Intersection */) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -36020,7 +37836,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxGlobalStatelessElementType(); if (jsxStatelessElementType) { @@ -36054,7 +37870,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type var jsxStatelessElementType = getJsxGlobalStatelessElementType(); @@ -36119,7 +37935,7 @@ var ts; */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } - if (elementType.flags & 65536 /* Union */) { + if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); @@ -36136,8 +37952,8 @@ var ts; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + var stringLiteralTypeName = elementType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); } @@ -36145,7 +37961,7 @@ var ts; if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); } // If we need to report an error, we already done so here. So just return any to prevent any more error downstream return anyType; @@ -36323,14 +38139,18 @@ var ts; } } } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } checkJsxPreconditions(node); // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; + var reactSym = resolveName(reactLocation, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -36340,7 +38160,12 @@ var ts; markAliasSymbolAsReferenced(reactSym); } } - checkJsxAttributesAssignableToTagNameAttributes(node); + if (isNodeOpeningLikeElement) { + checkJsxAttributesAssignableToTagNameAttributes(node); + } + else { + checkJsxChildren(node.parent); + } } /** * Check if a property with the given name is known anywhere in the given type. In an object type, a property @@ -36356,7 +38181,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 32768 /* Object */) { + if (targetType.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -36366,7 +38191,7 @@ var ts; return true; } } - else if (targetType.flags & 196608 /* UnionOrIntersection */) { + else if (targetType.flags & 393216 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -36412,7 +38237,7 @@ var ts; for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -36424,7 +38249,7 @@ var ts; if (node.expression) { var type = checkExpression(node.expression, checkMode); if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type); } return type; } @@ -36435,7 +38260,7 @@ var ts; // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 150 /* PropertyDeclaration */; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; @@ -36453,7 +38278,7 @@ var ts; */ function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? + var errorNode = node.kind === 180 /* PropertyAccessExpression */ || node.kind === 227 /* VariableDeclaration */ ? node.name : node.right; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { @@ -36470,11 +38295,7 @@ var ts; // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 /* MethodDeclaration */ && propKind !== 150 /* MethodSignature */; - }); - if (hasNonMethodDeclaration) { + if (symbolHasNonMethodDeclaration(prop)) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -36488,6 +38309,14 @@ var ts; return false; } } + // Referencing abstract properties within their own constructors is not allowed + if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + return false; + } + } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { return true; @@ -36495,7 +38324,7 @@ var ts; // Property is known to be private or protected at this point // Private property is accessible if the property is within the declaring class if (flags & 8 /* Private */) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; @@ -36522,29 +38351,34 @@ var ts; if (flags & 32 /* Static */) { return true; } - // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (type.flags & 32768 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = getConstraintOfTypeParameter(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } - if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { + if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; } + function symbolHasNonMethodDeclaration(symbol) { + return forEachProperty(symbol, function (prop) { + var propKind = getDeclarationKindFromSymbol(prop); + return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; + }); + } function checkNonNullExpression(node) { return checkNonNullType(checkExpression(node), node); } function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */; + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? + error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); var t = getNonNullableType(type); - return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t; + return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } return type; } @@ -36555,50 +38389,76 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { - // handle cases when type is Type parameter with invalid or any constraint + var propType; + var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; + var leftType = checkNonNullExpression(left); + var apparentType = getApparentType(getWidenedType(leftType)); + if (isTypeAny(apparentType) || apparentType === silentNeverType) { return apparentType; } + var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); - if (indexInfo && indexInfo.type) { - if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { - error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + if (!(indexInfo && indexInfo.type)) { + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, leftType.flags & 32768 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } - return indexInfo.type; + return unknownType; } - if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); + if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { + error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); } - return unknownType; + propType = indexInfo.type; } - checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); - return unknownType; + else { + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); + // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module + leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; + if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && + !(isNonLocalAlias(leftSymbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { + getSymbolLinks(leftSymbol).referenced = undefined; + } + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); + return unknownType; + } } + propType = getDeclaredOrApparentType(prop, node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { + if (node.kind !== 180 /* PropertyAccessExpression */ || + assignmentKind === 1 /* Definite */ || + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 131072 /* Union */)) { + return propType; + } + // If strict null checks and strict property initialization checks are enabled, if we have + // a this.xxx property access, if the property is an instance property without an initializer, + // and if we are in a constructor of the same class as the property declaration, assume that + // the property is uninitialized at the top of the control flow. + var assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && left.kind === 99 /* ThisKeyword */) { + var declaration = prop && prop.valueDeclaration; + if (declaration && isInstancePropertyWithoutInitializer(declaration)) { + var flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 153 /* Constructor */ && flowContainer.parent === declaration.parent) { + assumeUninitialized = true; + } + } + } + var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + // Return the declared type to reduce follow-on errors return propType; } - var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { @@ -36609,25 +38469,25 @@ var ts; if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); } - else if (valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(valueDeclaration) && + else if (valueDeclaration.kind === 230 /* ClassDeclaration */ && + node.parent.kind !== 160 /* TypeReference */ && + !(valueDeclaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return true; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: - return ts.isPartOfExpression(node) ? false : "quit"; + return ts.isExpressionNode(node) ? false : "quit"; } }); } @@ -36658,7 +38518,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { + if (containingType.flags & 131072 /* Union */ && !(containingType.flags & 16382 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -36669,7 +38529,7 @@ var ts; } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -36677,23 +38537,20 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); } function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455 /* Value */); - return suggestion && suggestion.escapedName; + var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 107455 /* Value */); + return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ false, function (symbols, name, meaning) { + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + ts.Debug.assert(outerName !== undefined, "outername should always be defined"); + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); - if (symbol) { - // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function - // So the table *contains* `x` but `x` isn't actually in scope. - // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol; - } - return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function + // So the table *contains* `x` but `x` isn't actually in scope. + // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. + return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - if (result) { - return result.escapedName; - } + return result && ts.symbolName(result); } /** * Given a name and a list of symbols whose names are *not* equal to the name, return a spelling suggestion if there is one that is close enough. @@ -36705,67 +38562,103 @@ var ts; * except for candidates: * * With no name * * Whose meaning doesn't match the `meaning` parameter. - * * Whose length differs from the target name by more than 0.3 of the length of the name. + * * Whose length differs from the target name by more than 0.34 of the length of the name. * * Whose levenshtein distance is more than 0.4 of the length of the name * (0.4 allows 1 substitution/transposition for every 5 characters, * and 1 insertion/deletion at 3 characters) - * Names longer than 30 characters don't get suggestions because Levenshtein distance is an n**2 algorithm. */ function getSpellingSuggestionForName(name, symbols, meaning) { - var worstDistance = name.length * 0.4; - var maximumLengthDifference = Math.min(3, name.length * 0.34); - var bestDistance = Number.MAX_VALUE; - var bestCandidate = undefined; + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; var justCheckExactMatches = false; - if (name.length > 30) { - return undefined; - } - name = name.toLowerCase(); + var nameLowerCase = name.toLowerCase(); for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { var candidate = symbols_3[_i]; - var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); - if (candidate.flags & meaning && - candidateName && - Math.abs(candidateName.length - name.length) < maximumLengthDifference) { - candidateName = candidateName.toLowerCase(); - if (candidateName === name) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3 || - name.length < 3 || - candidateName === "eval" || - candidateName === "intl" || - candidateName === "undefined" || - candidateName === "map" || - candidateName === "nan" || - candidateName === "set") { - continue; - } - var distance = ts.levenshtein(name, candidateName); - if (distance > worstDistance) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else if (distance < bestDistance) { - bestDistance = distance; - bestCandidate = candidate; - } + var candidateName = ts.symbolName(candidate); + if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { + continue; + } + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; } } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -36775,7 +38668,7 @@ var ts; } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 179 /* PropertyAccessExpression */ + var left = node.kind === 180 /* PropertyAccessExpression */ ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); @@ -36787,7 +38680,7 @@ var ts; return checkPropertyAccessibility(node, left, type, prop); } // In js files properties of unions are allowed in completion - if (ts.isInJavaScriptFile(left) && (type.flags & 65536 /* Union */)) { + if (ts.isInJavaScriptFile(left) && (type.flags & 131072 /* Union */)) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var elementType = _a[_i]; if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { @@ -36804,7 +38697,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 227 /* VariableDeclarationList */) { + if (initializer.kind === 228 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -36833,7 +38726,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 215 /* ForInStatement */ && + if (node.kind === 216 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -36851,7 +38744,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 183 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -36882,7 +38775,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 512 /* ESSymbol */) === 0) { + if ((expressionType.flags & 1536 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -36918,10 +38811,10 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 147 /* Decorator */) { + else if (node.kind !== 148 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -36987,7 +38880,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 198 /* SpreadElement */) { + if (arg && arg.kind === 199 /* SpreadElement */) { return i; } } @@ -37003,13 +38896,13 @@ var ts; // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 196 /* TemplateExpression */) { + if (tagExpression.template.kind === 197 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; @@ -37026,7 +38919,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 147 /* Decorator */) { + else if (node.kind === 148 /* Decorator */) { typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } @@ -37034,7 +38927,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 182 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 183 /* NewExpression */); return signature.minArgumentCount === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; @@ -37052,10 +38945,10 @@ var ts; if (!hasRightNumberOfTypeArgs) { return false; } - // If spread arguments are present, check that they correspond to a rest parameter. If so, no - // further checking is necessary. + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + return isRestParameterIndex(signature, spreadArgIndex) || + signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; } // Too many arguments implies incorrect arity. if (!signature.hasRestParameter && argCount > signature.parameters.length) { @@ -37067,7 +38960,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 32768 /* Object */) { + if (type.flags & 65536 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -37084,7 +38977,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -37104,7 +38997,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 147 /* Decorator */) { + if (node.kind !== 148 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -37124,7 +39017,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -37139,7 +39032,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 201 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type @@ -37170,29 +39063,27 @@ var ts; } return getInferredTypes(context); } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { + var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; + var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } + ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (!constraint) + continue; + var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return false; } } - return typeArgumentsAreAssignable; + return typeArgumentTypes; } /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. @@ -37231,7 +39122,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 183 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // 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. @@ -37248,7 +39139,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 201 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); // If the effective argument type is undefined, there is no synthetic type for the argument. @@ -37272,12 +39163,12 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 181 /* CallExpression */) { + if (node.kind === 182 /* CallExpression */) { var callee = node.expression; - if (callee.kind === 179 /* PropertyAccessExpression */) { + if (callee.kind === 180 /* PropertyAccessExpression */) { return callee.expression; } - else if (callee.kind === 180 /* ElementAccessExpression */) { + else if (callee.kind === 181 /* ElementAccessExpression */) { return callee.expression; } } @@ -37292,17 +39183,17 @@ var ts; * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 183 /* TaggedTemplateExpression */) { + if (node.kind === 184 /* TaggedTemplateExpression */) { var template = node.template; var args_4 = [undefined]; - if (template.kind === 196 /* TemplateExpression */) { + if (template.kind === 197 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 147 /* Decorator */) { + else if (node.kind === 148 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -37329,19 +39220,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147 /* Decorator */) { + if (node.kind === 148 /* Decorator */) { switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -37351,7 +39242,7 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 146 /* Parameter */: + case 147 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -37375,25 +39266,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 152 /* Constructor */) { + if (node.kind === 153 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -37420,23 +39311,23 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { node = node.parent; - if (node.kind === 152 /* Constructor */) { + if (node.kind === 153 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } // For a non-constructor parameter decorator, the `propertyKey` will be either // a string or a symbol, based on the name of the parameter's containing method. } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will @@ -37444,13 +39335,13 @@ var ts; var element = node; switch (element.name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + return getLiteralType(ts.idText(element.name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return getLiteralType(element.name.text); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 512 /* ESSymbol */)) { + if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { return nameType; } else { @@ -37474,21 +39365,21 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 229 /* ClassDeclaration */) { + if (node.kind === 230 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 149 /* PropertyDeclaration */) { + if (node.kind === 150 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 152 /* MethodDeclaration */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -37520,10 +39411,10 @@ var ts; // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 147 /* Decorator */) { + if (node.kind === 148 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -37535,8 +39426,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 147 /* Decorator */ || - (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */)) { + if (node.kind === 148 /* Decorator */ || + (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -37545,11 +39436,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147 /* Decorator */) { + if (node.kind === 148 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 184 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -37558,8 +39449,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 147 /* Decorator */; + var isTaggedTemplate = node.kind === 184 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 148 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { @@ -37633,7 +39524,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 182 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -37670,8 +39561,7 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - var typeArguments_1 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -37697,10 +39587,13 @@ var ts; var paramCount = hasRestParameter_1 ? min : min < max ? min + "-" + max : min; - var argCount = args.length - (hasSpreadArgument ? 1 : 0); - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_a_minimum_of_1 : + var argCount = args.length; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_a_minimum_of_1 : + hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1; diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); } @@ -37721,14 +39614,14 @@ var ts; var candidate = candidates[bestIndex]; var typeParameters = candidate.typeParameters; if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_2 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_2.length > typeParameters.length) { - typeArguments_2.pop(); + var typeArguments_1 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_1.length > typeParameters.length) { + typeArguments_1.pop(); } - while (typeArguments_2.length < typeParameters.length) { - typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + while (typeArguments_1.length < typeParameters.length) { + typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); } - var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + var instantiated = createSignatureInstantiation(candidate, typeArguments_1); candidates[bestIndex] = instantiated; return instantiated; } @@ -37763,10 +39656,12 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); - if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (typeArgumentResult) { + typeArgumentTypes = typeArgumentResult; + } + else { candidateForTypeArgumentError = originalCandidate; break; } @@ -37774,6 +39669,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -37871,21 +39767,9 @@ var ts; * but is a subtype of the Function interface, the call is an untyped function call. */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (funcType.flags & 65536 /* Union */) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; + // We exclude union types because we may have a union of function types that happen to have no common signatures. + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 /* Union */ | 16384 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -37930,9 +39814,9 @@ var ts; // Note, only class declarations can be declared abstract. // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } return resolveCall(node, constructSignatures, candidatesOutArray); @@ -37965,7 +39849,7 @@ var ts; if (!modifiers) { return true; } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { @@ -38015,16 +39899,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146 /* Parameter */: + case 147 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -38042,6 +39926,11 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { return resolveUntypedCall(node); } + if (isPotentiallyUncalledDecorator(node, callSignatures)) { + var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false); + error(node, ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { var errorInfo = void 0; @@ -38052,6 +39941,18 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } + /** + * Sometimes, we have a decorator that could accept zero arguments, + * but is receiving too many arguments as part of the decorator invocation. + * In those cases, a user may have meant to *call* the expression before using it as a decorator. + */ + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && ts.every(signatures, function (signature) { + return signature.minArgumentCount === 0 && + !signature.hasRestParameter && + signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + }); + } /** * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName @@ -38063,9 +39964,8 @@ var ts; * the function will fill it up with appropriate candidate signatures */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; + ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); } /** * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. @@ -38078,7 +39978,7 @@ var ts; */ function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 65536 /* Union */) { + if (elementType.flags & 131072 /* Union */) { var types = elementType.types; var result = void 0; for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { @@ -38095,18 +39995,18 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 181 /* CallExpression */: + case 182 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147 /* Decorator */: + case 148 /* Decorator */: return resolveDecorator(node, candidatesOutArray); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; } ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -38169,13 +40069,13 @@ var ts; function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + links.inferredClassType = createAnonymousType(symbol, getMembersOfSymbol(symbol) || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } function isInferredClassType(type) { return type.symbol - && getObjectFlags(type) & 16 /* Anonymous */ + && ts.getObjectFlags(type) & 16 /* Anonymous */ && getSymbolLinks(type.symbol).inferredClassType === type; } /** @@ -38184,27 +40084,28 @@ var ts; * @returns On success, the expression's signature's return type. On failure, anyType. */ function checkCallExpression(node) { - // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments); + if (!checkGrammarTypeArguments(node, node.typeArguments)) + checkGrammarArguments(node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; } - if (node.kind === 182 /* NewExpression */) { + if (node.kind === 183 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 152 /* Constructor */ && - declaration.kind !== 156 /* ConstructSignature */ && - declaration.kind !== 161 /* ConstructorType */ && + declaration.kind !== 153 /* Constructor */ && + declaration.kind !== 157 /* ConstructSignature */ && + declaration.kind !== 162 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations // in a JS file // Note:JS inferred classes might come from a variable declaration instead of a function declaration. // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. - var funcSymbol = node.expression.kind === 71 /* Identifier */ ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; + var funcSymbol = checkExpression(node.expression).symbol; + if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { + funcSymbol = getResolvedSymbol(node.expression); + } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { return type; @@ -38219,11 +40120,35 @@ var ts; if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } - return getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property + // as a fresh unique symbol literal type. + if (returnType.flags & 1536 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); + } + return returnType; + } + function isSymbolOrSymbolForCall(node) { + if (!ts.isCallExpression(node)) + return false; + var left = node.expression; + if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + // make sure `Symbol` is the global symbol + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName(left, "Symbol", 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import - checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node); + if (!checkGrammarArguments(node.arguments)) + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -38233,7 +40158,7 @@ var ts; for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 2048 /* Undefined */ || specifierType.flags & 4096 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 4096 /* Undefined */ || specifierType.flags & 8192 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -38285,18 +40210,21 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 228 /* FunctionDeclaration */ + ? 229 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 226 /* VariableDeclaration */ + ? 227 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); // function/variable declaration should be ambient - return ts.isInAmbientContext(decl); + return !!decl && !!(decl.flags & 2097152 /* Ambient */); } return false; } function checkTaggedTemplateExpression(node) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); + } return getReturnTypeOfSignature(getResolvedSignature(node)); } function checkAssertion(node) { @@ -38324,7 +40252,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return unknownType; } - else if (container.kind === 152 /* Constructor */) { + else if (container.kind === 153 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -38338,7 +40266,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return getNullableType(type, 2048 /* Undefined */); + return getOptionalType(type); } } return type; @@ -38452,7 +40380,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 207 /* Block */) { + if (func.body.kind !== 208 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -38493,27 +40421,43 @@ var ts; } // Return a union of the return expression types. type = getUnionType(types, /*subtypeReduction*/ true); - if (functionFlags & 1 /* Generator */) { - type = functionFlags & 2 /* Async */ - ? createAsyncIterableIteratorType(type) // AsyncGenerator function - : createIterableIteratorType(type); // Generator function - } } if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); + if (isUnitType(type)) { + var contextualType = !contextualSignature ? undefined : + contextualSignature === getSignatureFromDeclaration(func) ? type : + getReturnTypeOfSignature(contextualSignature); + if (contextualType) { + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ true); + break; + case 1 /* Generator */: + contextualType = getIteratedTypeOfGenerator(contextualType, /*isAsyncGenerator*/ false); + break; + case 2 /* Async */: + contextualType = getPromisedTypeOfPromise(contextualType); + break; + } + } + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); } var widenedType = getWidenedType(type); - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ - ? createPromiseReturnType(func, widenedType) // Async function - : widenedType; // Generator function, AsyncGenerator function, or normal function + switch (functionFlags & 3 /* AsyncGenerator */) { + case 3 /* AsyncGenerator */: + return createAsyncIterableIteratorType(widenedType); + case 1 /* Generator */: + return createIterableIteratorType(widenedType); + case 2 /* Async */: + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return createPromiseType(widenedType); + default: + return widenedType; + } } function checkAndAggregateYieldOperandTypes(func, checkMode) { var aggregatedTypes = []; @@ -38554,8 +40498,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 222 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -38576,7 +40519,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 8192 /* Never */) { + if (type.flags & 16384 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -38586,7 +40529,7 @@ var ts; } }); if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */)) { + func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */)) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -38608,16 +40551,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 2048 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 /* Block */ || !functionHasImplicitReturn(func)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 208 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 8192 /* Never */) { + if (returnType && returnType.flags & 16384 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -38646,7 +40589,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { checkNodeDeferred(node); @@ -38654,7 +40597,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 187 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -38689,7 +40632,7 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 151 /* MethodDeclaration */) { + if (produceDiagnostics && node.kind !== 152 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -38697,12 +40640,12 @@ var ts; return type; } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 152 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnOrPromisedType = returnTypeNode && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : + checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { // return is not necessary in the body of generators @@ -38717,7 +40660,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 207 /* Block */) { + if (node.body.kind === 208 /* Block */) { checkSourceElement(node.body); } else { @@ -38764,11 +40707,11 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) && + (expr.kind === 180 /* PropertyAccessExpression */ || expr.kind === 181 /* ElementAccessExpression */) && expr.expression.kind === 99 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152 /* Constructor */)) { + if (!(func && func.kind === 153 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -38781,13 +40724,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) { + if (expr.kind === 180 /* PropertyAccessExpression */ || expr.kind === 181 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240 /* NamespaceImport */; + return declaration && declaration.kind === 241 /* NamespaceImport */; } } } @@ -38796,7 +40739,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { + if (node.kind !== 71 /* Identifier */ && node.kind !== 180 /* PropertyAccessExpression */ && node.kind !== 181 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -38805,7 +40748,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 /* PropertyAccessExpression */ && expr.kind !== 180 /* ElementAccessExpression */) { + if (expr.kind !== 180 /* PropertyAccessExpression */ && expr.kind !== 181 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -38855,7 +40798,7 @@ var ts; case 38 /* MinusToken */: case 52 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 1536 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -38893,7 +40836,7 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 196608 /* UnionOrIntersection */) { + if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { var t = types_18[_i]; @@ -38908,21 +40851,26 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 /* Any */ | 1024 /* Void */ | 2048 /* Undefined */ | 4096 /* Null */)) { + if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { return false; } return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 262178 /* StringLike */ && isTypeAssignableTo(source, stringType)) || + (kind & 524322 /* StringLike */ && isTypeAssignableTo(source, stringType)) || (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 1024 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 8192 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 4096 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 2048 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || + (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || + (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || + (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || + (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 16777216 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + (kind & 33554432 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 131072 /* Union */ ? + ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : + isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -38936,14 +40884,12 @@ var ts; // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (!isTypeAny(leftType) && isTypeAssignableToKind(leftType, 8190 /* Primitive */)) { + if (!isTypeAny(leftType) && + allTypesAssignableToKind(leftType, 16382 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0 /* Call */).length || - getSignaturesOfType(rightType, 1 /* Construct */).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); } return booleanType; @@ -38958,10 +40904,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 512 /* ESSymbol */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { + if (!isTypeAssignableToKind(rightType, 33554432 /* NonPrimitive */ | 1081344 /* TypeVariable */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -38976,9 +40922,9 @@ var ts; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 /* PropertyAssignment */ || property.kind === 262 /* ShorthandPropertyAssignment */) { + if (property.kind === 265 /* PropertyAssignment */ || property.kind === 266 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -38991,7 +40937,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 262 /* ShorthandPropertyAssignment */) { + if (property.kind === 266 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { @@ -39003,8 +40949,8 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 263 /* SpreadAssignment */) { - if (languageVersion < 5 /* ESNext */) { + else if (property.kind === 267 /* SpreadAssignment */) { + if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } var nonRestNames = []; @@ -39037,8 +40983,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 200 /* OmittedExpression */) { - if (element.kind !== 198 /* SpreadElement */) { + if (element.kind !== 201 /* OmittedExpression */) { + if (element.kind !== 199 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType @@ -39066,7 +41012,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 194 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 195 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -39079,13 +41025,13 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 262 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 266 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -39095,21 +41041,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 194 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 195 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 178 /* ObjectLiteralExpression */) { + if (target.kind === 179 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 177 /* ArrayLiteralExpression */) { + if (target.kind === 178 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 /* SpreadAssignment */ ? + var error = target.parent.kind === 267 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { @@ -39131,35 +41077,35 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 12 /* RegularExpressionLiteral */: - case 183 /* TaggedTemplateExpression */: - case 196 /* TemplateExpression */: + case 184 /* TaggedTemplateExpression */: + case 197 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 139 /* UndefinedKeyword */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: - case 187 /* ArrowFunction */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 189 /* TypeOfExpression */: - case 203 /* NonNullExpression */: - case 250 /* JsxSelfClosingElement */: - case 249 /* JsxElement */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 178 /* ArrayLiteralExpression */: + case 179 /* ObjectLiteralExpression */: + case 190 /* TypeOfExpression */: + case 204 /* NonNullExpression */: + case 251 /* JsxSelfClosingElement */: + case 250 /* JsxElement */: return true; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -39171,29 +41117,22 @@ var ts; } return false; // Some forms listed here for clarity - case 190 /* VoidExpression */: // Explicit opt-out - case 184 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 202 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 191 /* VoidExpression */: // Explicit opt-out + case 185 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 203 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], /*subtypeReduction*/ true); + return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 178 /* ObjectLiteralExpression */ || left.kind === 177 /* ArrayLiteralExpression */)) { + if (operator === 58 /* EqualsToken */ && (left.kind === 179 /* ObjectLiteralExpression */ || left.kind === 178 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); @@ -39248,7 +41187,7 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 262178 /* StringLike */) && !isTypeAssignableToKind(rightType, 262178 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 524322 /* StringLike */) && !isTypeAssignableToKind(rightType, 524322 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } @@ -39258,7 +41197,7 @@ var ts; // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } - else if (isTypeAssignableToKind(leftType, 262178 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 262178 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 524322 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 524322 /* StringLike */, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -39315,7 +41254,7 @@ var ts; leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : leftType; case 58 /* EqualsToken */: checkAssignmentOperator(rightType); @@ -39331,8 +41270,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 1536 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -39407,7 +41346,7 @@ var ts; // Async generator functions prior to ESNext require the __await, __asyncDelegator, // and __asyncValues helpers if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && - languageVersion < 5 /* ESNext */) { + languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } // Generator functions prior to ES2015 require the __values helper @@ -39451,7 +41390,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2], /*subtypeReduction*/ true); } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -39491,27 +41430,42 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 184 /* TypeAssertionExpression */ || node.kind === 202 /* AsExpression */; + return node.kind === 185 /* TypeAssertionExpression */ || node.kind === 203 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || + (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } - function isLiteralContextualType(contextualType) { + function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { - return true; - } - contextualType = constraint; + if (contextualType.flags & 131072 /* Union */ && !(contextualType.flags & 8 /* Boolean */)) { + // If the contextual type is a union containing both of the 'true' and 'false' types we + // don't consider it a literal context for boolean literals. + var types_19 = contextualType.types; + return ts.some(types_19, function (t) { + return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_19, trueType) && containsType(types_19, falseType)) && + isLiteralOfContextualType(candidateType, t); + }); } - return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); + if (contextualType.flags & 1081344 /* TypeVariable */) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + return constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || + constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || + contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || + contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || + contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); } return false; } @@ -39520,14 +41474,14 @@ var ts; contextualType = getContextualType(node); } var type = checkExpression(node, checkMode); - var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); - return shouldWiden ? type : getWidenedLiteralType(type); + return isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, contextualType); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -39538,7 +41492,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -39568,7 +41522,7 @@ var ts; function getTypeOfExpression(node, cache) { // 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 (node.kind === 181 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (node.kind === 182 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -39603,7 +41557,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, checkMode) { var type; - if (node.kind === 143 /* QualifiedName */) { + if (node.kind === 144 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -39615,9 +41569,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); } @@ -39651,72 +41605,74 @@ var ts; return trueType; case 86 /* FalseKeyword */: return falseType; - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: return globalRegExpType; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: if (node.expression.kind === 91 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 182 /* NewExpression */: + case 183 /* NewExpression */: return checkCallExpression(node); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return checkClassExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: return checkAssertion(node); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return checkNonNullAssertion(node); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return checkMetaProperty(node); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return checkDeleteExpression(node); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return checkVoidExpression(node); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return checkAwaitExpression(node); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 200 /* OmittedExpression */: + case 201 /* OmittedExpression */: return undefinedWideningType; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return checkYieldExpression(node); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 249 /* JsxElement */: + case 250 /* JsxElement */: return checkJsxElement(node); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 254 /* JsxAttributes */: + case 254 /* JsxFragment */: + return checkJsxFragment(node); + case 258 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 251 /* JsxOpeningElement */: + case 252 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -39733,6 +41689,9 @@ var ts; if (!hasNonCircularBaseConstraint(typeParameter)) { error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } var constraintType = getConstraintOfTypeParameter(typeParameter); var defaultType = getDefaultFromTypeParameter(typeParameter); if (constraintType && defaultType) { @@ -39747,13 +41706,11 @@ var ts; // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code // or if its FunctionBody is strict code(11.1.5). - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 153 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -39764,7 +41721,7 @@ var ts; if (ts.indexOf(func.parameters, node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 152 /* Constructor */ || func.kind === 156 /* ConstructSignature */ || func.kind === 161 /* ConstructorType */) { + if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } @@ -39830,13 +41787,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 187 /* ArrowFunction */: - case 155 /* CallSignature */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 160 /* FunctionType */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 188 /* ArrowFunction */: + case 156 /* CallSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 161 /* FunctionType */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -39854,7 +41811,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 175 /* ArrayBindingPattern */ || name.kind === 174 /* ObjectBindingPattern */) { + else if (name.kind === 176 /* ArrayBindingPattern */ || name.kind === 175 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -39863,18 +41820,18 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 160 /* FunctionType */ || node.kind === 228 /* FunctionDeclaration */ || node.kind === 161 /* ConstructorType */ || - node.kind === 155 /* CallSignature */ || node.kind === 152 /* Constructor */ || - node.kind === 156 /* ConstructSignature */) { + else if (node.kind === 161 /* FunctionType */ || node.kind === 229 /* FunctionDeclaration */ || node.kind === 162 /* ConstructorType */ || + node.kind === 156 /* CallSignature */ || node.kind === 153 /* Constructor */ || + node.kind === 157 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); if (!(functionFlags & 4 /* Invalid */)) { // Async generators prior to ESNext require the __await and __asyncGenerator helpers - if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } // Async functions prior to ES2017 require the __awaiter helper @@ -39898,10 +41855,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 155 /* CallSignature */: + case 156 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -39948,7 +41905,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152 /* Constructor */) { + if (member.kind === 153 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -39962,16 +41919,16 @@ var ts; var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); if (memberName) { switch (member.kind) { - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: addName(names, member.name, memberName, 1 /* Getter */); break; - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: addName(names, member.name, memberName, 2 /* Setter */); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: addName(names, member.name, memberName, 3 /* Property */); break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: addName(names, member.name, memberName, 4 /* Method */); break; } @@ -40023,7 +41980,7 @@ var ts; case "arguments": case "prototype": var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); + var className = getNameOfSymbolAsWritten(getSymbolOfNode(node)); error(memberNameNode, message, memberName, className); break; } @@ -40034,7 +41991,7 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 148 /* PropertySignature */) { + if (member.kind === 149 /* PropertySignature */) { var memberName = void 0; switch (member.name.kind) { case 9 /* StringLiteral */: @@ -40042,7 +41999,7 @@ var ts; memberName = member.name.text; break; case 71 /* Identifier */: - memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + memberName = ts.idText(member.name); break; default: continue; @@ -40058,7 +42015,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230 /* InterfaceDeclaration */) { + if (node.kind === 231 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -40101,12 +42058,14 @@ var ts; } function checkPropertyDeclaration(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) + checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); } function checkMethodDeclaration(node) { // Grammar checking - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarMethod(node)) + checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. @@ -40119,7 +42078,8 @@ var ts; // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); // Grammar check for checking only related to constructorDeclaration - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + if (!checkGrammarConstructorTypeParameters(node)) + checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); @@ -40152,7 +42112,7 @@ var ts; return ts.forEachChild(n, containsSuperCall); } function isInstancePropertyWithInitializer(n) { - return n.kind === 149 /* PropertyDeclaration */ && + return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -40182,7 +42142,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -40203,11 +42163,12 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { // Grammar checking accessors - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) + checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 153 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (node.kind === 154 /* GetAccessor */) { + if (!(node.flags & 2097152 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } @@ -40216,14 +42177,14 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + var otherKind = node.kind === 154 /* GetAccessor */ ? 155 /* SetAccessor */ : 154 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); var otherFlags = ts.getModifierFlags(otherAccessor); @@ -40240,7 +42201,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153 /* GetAccessor */) { + if (node.kind === 154 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -40270,14 +42231,14 @@ var ts; mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, instantiateType(constraint, mapper), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 159 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 160 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -40291,11 +42252,14 @@ var ts; // There is no resolved symbol cached if the type resolved to a builtin // via JSDoc type reference resolution (eg, Boolean became boolean), none // of which are generic when they have no associated symbol - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + // (additionally, JSDoc's index signature syntax, Object actually uses generic syntax without being generic) + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; - if (!typeParameters && getObjectFlags(type) & 4 /* Reference */) { + if (!typeParameters && ts.getObjectFlags(type) & 4 /* Reference */) { typeParameters = type.target.localTypeParameters; } checkTypeArgumentConstraints(typeParameters, node.typeArguments); @@ -40333,15 +42297,15 @@ var ts; ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288 /* IndexedAccess */)) { + if (!(type.flags & 1048576 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { + if (accessNode.kind === 181 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + ts.getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; @@ -40366,17 +42330,21 @@ var ts; var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8 /* Private */) && ts.isInAmbientContext(node); + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 2097152 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 230 /* InterfaceDeclaration */ && - n.parent.kind !== 229 /* ClassDeclaration */ && - n.parent.kind !== 199 /* ClassExpression */ && - ts.isInAmbientContext(n)) { + if (n.parent.kind !== 231 /* InterfaceDeclaration */ && + n.parent.kind !== 230 /* ClassDeclaration */ && + n.parent.kind !== 200 /* ClassExpression */ && + n.flags & 2097152 /* Ambient */) { if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; @@ -40466,7 +42434,7 @@ var ts; if (node.name && subsequentName && (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && + var reportError = (node.kind === 152 /* MethodDeclaration */ || node.kind === 151 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -40504,8 +42472,8 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; + var inAmbientContext = node.flags & 2097152 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 231 /* InterfaceDeclaration */ || node.parent.kind === 164 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -40516,7 +42484,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 228 /* FunctionDeclaration */ || node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */ || node.kind === 152 /* Constructor */) { + if (node.kind === 229 /* FunctionDeclaration */ || node.kind === 152 /* MethodDeclaration */ || node.kind === 151 /* MethodSignature */ || node.kind === 153 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -40644,30 +42612,30 @@ var ts; })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(d) { switch (d.kind) { - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: // A jsdoc typedef is, by definition, a type alias - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return 2 /* ExportType */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 239 /* ImportClause */: - var result_3 = 0 /* None */; + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 240 /* ImportClause */: + var result_2 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - case 228 /* FunctionDeclaration */: - case 242 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 229 /* FunctionDeclaration */: + case 243 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: ts.Debug.fail(ts.SyntaxKind[d.kind]); @@ -40745,7 +42713,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -40754,7 +42722,7 @@ var ts; if (!types) { return undefined; } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true); + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { @@ -40919,7 +42887,7 @@ var ts; var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455 /* Value */); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return unknownType; } } @@ -40937,22 +42905,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 146 /* Parameter */: + case 147 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -40996,11 +42964,20 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 167 /* IntersectionType */: - case 166 /* UnionType */: + case 168 /* IntersectionType */: + case 167 /* UnionType */: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); if (!individualEntityName) { // Individual is something like string number @@ -41024,9 +43001,9 @@ var ts; } } return commonEntityName; - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return node.typeName; } } @@ -41042,7 +43019,7 @@ var ts; } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { @@ -41050,14 +43027,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 146 /* Parameter */) { + if (node.kind === 147 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -41066,20 +43043,25 @@ var ts; } } break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 146 /* Parameter */: + case 147 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + var containingSignature = node.parent; + for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { + var parameter = _e[_d]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } break; } } @@ -41102,6 +43084,42 @@ var ts; error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + if (!ts.getParameterSymbolFromJSDoc(node)) { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 144 /* QualifiedName */ ? node.name.right : node.name)); + } + } + function checkJSDocAugmentsTag(node) { + var classLike = ts.getJSDocHost(node); + if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + return; + } + var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 282 /* JSDocAugmentsTag */); + ts.Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + var name = getIdentifierFromEntityNameExpression(node.class.expression); + var extend = ts.getClassExtendsHeritageClauseElement(classLike); + if (extend) { + var className = getIdentifierFromEntityNameExpression(extend.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className)); + } + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 71 /* Identifier */: + return node; + case 180 /* PropertyAccessExpression */: + return node.name; + default: + return undefined; + } + } function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); @@ -41109,12 +43127,12 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 145 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!ts.hasDynamicName(node)) { + if (!hasNonBindableDynamicName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -41171,68 +43189,67 @@ var ts; for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { var node = deferredUnusedIdentifierNodes_1[_i]; switch (node.kind) { - case 265 /* SourceFile */: - case 233 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 234 /* ModuleDeclaration */: checkUnusedModuleMembers(node); break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: checkUnusedClassMembers(node); checkUnusedTypeParameters(node); break; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: checkUnusedTypeParameters(node); break; - case 207 /* Block */: - case 235 /* CaseBlock */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 208 /* Block */: + case 236 /* CaseBlock */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: checkUnusedLocalsAndParameters(node); break; - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: if (node.body) { checkUnusedLocalsAndParameters(node); } checkUnusedTypeParameters(node); break; - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - checkUnusedTypeParameters(node); - break; - case 231 /* TypeAliasDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 232 /* TypeAliasDeclaration */: checkUnusedTypeParameters(node); break; + default: + ts.Debug.fail("Node should not have been registered for unused identifiers check"); } } } } function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + if (noUnusedIdentifiers && !(node.flags & 2097152 /* Ambient */)) { node.locals.forEach(function (local) { if (!local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { + if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 147 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); } } }); @@ -41249,8 +43266,8 @@ var ts; var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 145 /* TypeParameter */) { + if ((declaration_2.kind === 227 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 146 /* TypeParameter */) { return; } } @@ -41262,23 +43279,23 @@ var ts; return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); } function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95 /* _ */; + return node.kind === 71 /* Identifier */ && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { if (node.members) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { + if (member.kind === 152 /* MethodDeclaration */ || member.kind === 150 /* PropertyDeclaration */) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); } } - else if (member.kind === 152 /* Constructor */) { + else if (member.kind === 153 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } } @@ -41287,7 +43304,7 @@ var ts; } } function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { if (node.typeParameters) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. @@ -41299,20 +43316,20 @@ var ts; for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); } } } } } function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { node.locals.forEach(function (local) { if (!local.isReferenced && !local.exportSymbol) { for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.symbolName(local)); } } } @@ -41321,7 +43338,7 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 207 /* Block */) { + if (node.kind === 208 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -41338,7 +43355,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -41351,21 +43368,21 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 148 /* PropertySignature */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 150 /* MethodSignature */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { + if (node.kind === 150 /* PropertyDeclaration */ || + node.kind === 149 /* PropertySignature */ || + node.kind === 152 /* MethodDeclaration */ || + node.kind === 151 /* MethodSignature */ || + node.kind === 154 /* GetAccessor */ || + node.kind === 155 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152 /* Ambient */) { // ambient context - no codegen impact return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 146 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 147 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -41417,7 +43434,7 @@ var ts; // bubble up and find containing type var enclosingClass = ts.getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + if (!enclosingClass || enclosingClass.flags & 2097152 /* Ambient */) { return; } if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { @@ -41439,12 +43456,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -41454,12 +43471,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 269 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -41494,7 +43511,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 226 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 227 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -41506,17 +43523,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 208 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 228 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 209 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 207 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 234 /* ModuleBlock */ || - container.kind === 233 /* ModuleDeclaration */ || - container.kind === 265 /* SourceFile */); + (container.kind === 208 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 235 /* ModuleBlock */ || + container.kind === 234 /* ModuleDeclaration */ || + container.kind === 269 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -41531,7 +43548,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 147 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -41542,7 +43559,7 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 179 /* PropertyAccessExpression */) { + if (n.kind === 180 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } @@ -41561,8 +43578,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 /* Parameter */ || - symbol.valueDeclaration.kind === 176 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 147 /* Parameter */ || + symbol.valueDeclaration.kind === 177 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -41576,7 +43593,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 149 /* PropertyDeclaration */ && + (current.parent.kind === 150 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -41607,18 +43624,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 176 /* BindingElement */) { - if (node.parent.kind === 174 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { + if (node.kind === 177 /* BindingElement */) { + if (node.parent.kind === 175 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 144 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 145 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -41626,27 +43643,27 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 176 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 146 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 147 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -41657,7 +43674,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -41666,8 +43683,10 @@ var ts; // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); + if (type !== unknownType && declarationType !== unknownType && + !isTypeIdenticalTo(type, declarationType) && + !(symbol.flags & 67108864 /* JSContainer */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); @@ -41677,10 +43696,10 @@ var ts; error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */) { + if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */) { + if (node.kind === 227 /* VariableDeclaration */ || node.kind === 177 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -41690,9 +43709,16 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { + var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); + var message = nextDeclaration.kind === 150 /* PropertyDeclaration */ || nextDeclaration.kind === 149 /* PropertySignature */ + ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 + : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); + } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 /* Parameter */ && right.kind === 226 /* VariableDeclaration */) || - (left.kind === 226 /* VariableDeclaration */ && right.kind === 146 /* Parameter */)) { + if ((left.kind === 147 /* Parameter */ && right.kind === 227 /* VariableDeclaration */) || + (left.kind === 227 /* VariableDeclaration */ && right.kind === 147 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -41717,12 +43743,13 @@ var ts; } function checkVariableStatement(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) + checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 179 /* ObjectLiteralExpression */) { if (ts.getFunctionFlags(node) & 2 /* Async */) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -41743,7 +43770,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209 /* EmptyStatement */) { + if (node.thenStatement.kind === 210 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -41763,12 +43790,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 228 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -41786,10 +43813,10 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 216 /* ForOfStatement */) { + if (node.kind === 217 /* ForOfStatement */) { if (node.awaitModifier) { var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } @@ -41804,14 +43831,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + if (varExpr.kind === 178 /* ArrayLiteralExpression */ || varExpr.kind === 179 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -41843,7 +43870,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { + if (node.initializer.kind === 228 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -41857,7 +43884,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + if (varExpr.kind === 178 /* ArrayLiteralExpression */ || varExpr.kind === 179 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -41870,7 +43897,7 @@ var ts; } // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 540672 /* TypeVariable */)) { + if (!isTypeAssignableToKind(rightType, 33554432 /* NonPrimitive */ | 1081344 /* TypeVariable */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -41921,16 +43948,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 65536 /* Union */) { + if (arrayType.flags & 131072 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); } } - else if (arrayType.flags & 262178 /* StringLike */) { + else if (arrayType.flags & 524322 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -41943,7 +43970,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 8192 /* Never */) { + if (arrayType.flags & 16384 /* Never */) { return stringType; } } @@ -41969,7 +43996,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 262178 /* StringLike */) { + if (arrayElementType.flags & 524322 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); @@ -42166,18 +44193,19 @@ var ts; } function checkBreakOrContinueStatement(node) { // Grammar checking - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) + checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 153 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */)) !== undefined; + return node.kind === 154 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 155 /* SetAccessor */)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -42191,22 +44219,22 @@ var ts; if (func) { var signature = getSignatureFromDeclaration(func); var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return expressions of generators when return type tracking is added + // for generators. + return; + } + if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { - // A generator does not need its return expressions checked against its return type. - // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added - // for generators. - return; - } - if (func.kind === 154 /* SetAccessor */) { + if (func.kind === 155 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 152 /* Constructor */) { + else if (func.kind === 153 /* Constructor */) { if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -42227,7 +44255,7 @@ var ts; } } } - else if (func.kind !== 152 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -42257,7 +44285,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 258 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 262 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -42269,7 +44297,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 257 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 261 /* CaseClause */) { var caseClause = clause; // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable @@ -42299,7 +44327,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 222 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 223 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); return true; @@ -42363,17 +44391,18 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasModifier(member, 32 /* Static */) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + var symbol = getSymbolOfNode(member); + var propType = getTypeOfSymbol(symbol); + checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); } } } @@ -42382,7 +44411,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { + if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -42403,15 +44432,15 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && - (propDeclaration.kind === 194 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + (propDeclaration.kind === 195 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 145 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (getObjectFlags(containingType) & 2 /* Interface */) { + else if (ts.getObjectFlags(containingType) & 2 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -42561,7 +44590,7 @@ var ts; checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!ts.isInAmbientContext(node)) { + if (!(node.flags & 2097152 /* Ambient */)) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); @@ -42587,10 +44616,10 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 1081344 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked @@ -42627,6 +44656,7 @@ var ts; if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); } } function checkBaseTypeAccessibility(type, node) { @@ -42634,7 +44664,7 @@ var ts; if (signatures.length) { var declaration = signatures[0].declaration; if (declaration && ts.hasModifier(declaration, 8 /* Private */)) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); } @@ -42646,12 +44676,9 @@ var ts; // so we'll need to get back original 'target' symbol to work with correct set of flags return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); - } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 /* ClassDeclaration */ || d.kind === 230 /* InterfaceDeclaration */; + return d.kind === 230 /* ClassDeclaration */ || d.kind === 231 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -42685,12 +44712,12 @@ var ts; // type declaration, derived and base resolve to the same symbol even in the case of generic classes. if (derived === base) { // derived class inherits base without override/redeclaration - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 199 /* ClassExpression */) { + if (derivedClassDecl.kind === 200 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -42761,9 +44788,42 @@ var ts; } return ok; } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152 /* Ambient */) { + return; + } + var constructor = findConstructorDeclaration(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (isInstancePropertyWithoutInitializer(member)) { + var propName = member.name; + if (ts.isIdentifier(propName)) { + var type = getTypeOfSymbol(getSymbolOfNode(member)); + if (!(type.flags & 1 /* Any */ || getFalsyFlags(type) & 4096 /* Undefined */)) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); + } + } + } + } + } + } + function isInstancePropertyWithoutInitializer(node) { + return node.kind === 150 /* PropertyDeclaration */ && + !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && + !node.exclamationToken && + !node.initializer; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !(getFalsyFlags(flowType) & 4096 /* Undefined */); + } function checkInterfaceDeclaration(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + if (!checkGrammarDecoratorsAndModifiers(node)) + checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); @@ -42771,7 +44831,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 231 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -42800,7 +44860,7 @@ var ts; } function checkTypeAliasDeclaration(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); checkTypeParameters(node.typeParameters); checkSourceElement(node.type); @@ -42834,7 +44894,7 @@ var ts; } // In ambient enum declarations that specify no const modifier, enum member declarations that omit // a value are considered computed members (as opposed to having auto-incremented values). - if (ts.isInAmbientContext(member.parent) && !ts.isConst(member.parent)) { + if (member.parent.flags & 2097152 /* Ambient */ && !ts.isConst(member.parent)) { return undefined; } // If the member declaration specifies no value, the member is considered a constant enum member. @@ -42866,7 +44926,7 @@ var ts; else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (ts.isInAmbientContext(member.parent)) { + else if (member.parent.flags & 2097152 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { @@ -42876,7 +44936,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: var value_1 = evaluate(expr.operand); if (typeof value_1 === "number") { switch (expr.operator) { @@ -42886,7 +44946,7 @@ var ts; } } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -42910,18 +44970,18 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 179 /* PropertyAccessExpression */) { + if (ex.kind === 180 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -42942,7 +45002,7 @@ var ts; var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { - return getNodeLinks(declaration).enumMemberValue; + return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; @@ -42953,8 +45013,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 /* Identifier */ || - node.kind === 179 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 180 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 180 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 181 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9 /* StringLiteral */; } function checkEnumDeclaration(node) { @@ -42962,7 +45022,7 @@ var ts; return; } // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithCapturedNewTargetVariable(node, node.name); @@ -42971,7 +45031,7 @@ var ts; checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152 /* Ambient */) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } // Spec 2014 - Section 9.3: @@ -42994,7 +45054,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 232 /* EnumDeclaration */) { + if (declaration.kind !== 233 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -43017,9 +45077,9 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { var declaration = declarations_7[_i]; - if ((declaration.kind === 229 /* ClassDeclaration */ || - (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 230 /* ClassDeclaration */ || + (declaration.kind === 229 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 2097152 /* Ambient */)) { return declaration; } } @@ -43042,7 +45102,7 @@ var ts; if (produceDiagnostics) { // Grammar checking var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContext = node.flags & 2097152 /* Ambient */; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -43054,7 +45114,7 @@ var ts; // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node)) { if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -43082,7 +45142,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 229 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 230 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -43133,23 +45193,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 237 /* ImportEqualsDeclaration */: - case 238 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 239 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 176 /* BindingElement */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 227 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -43160,12 +45220,12 @@ var ts; break; } // falls through - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 228 /* FunctionDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 229 /* FunctionDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 232 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -43188,12 +45248,12 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: do { node = node.left; } while (node.kind !== 71 /* Identifier */); return node; - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 71 /* Identifier */); @@ -43206,9 +45266,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 235 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 269 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 245 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -43241,16 +45301,16 @@ var ts; (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 246 /* ExportSpecifier */ ? + var message = node.kind === 247 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 246 /* ExportSpecifier */ + && node.kind === 247 /* ExportSpecifier */ && !(target.flags & 107455 /* Value */) - && !ts.isInAmbientContext(node)) { + && !(node.flags & 2097152 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } @@ -43266,7 +45326,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -43276,7 +45336,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 241 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -43291,13 +45351,13 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkGrammarDecoratorsAndModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.moduleReference.kind !== 249 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 107455 /* Value */) { @@ -43313,7 +45373,7 @@ var ts; } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152 /* Ambient */)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -43325,7 +45385,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -43333,10 +45393,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 /* ModuleBlock */ && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 235 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 235 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 2097152 /* Ambient */; + if (node.parent.kind !== 269 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -43353,7 +45413,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 /* SourceFile */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 233 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 269 /* SourceFile */ || node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 234 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -43361,13 +45421,16 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { markExportAsReferenced(node); @@ -43379,8 +45442,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 234 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -43390,20 +45453,23 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.hasModifiers(node)) { + if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); + if (compilerOptions.declaration) { + collectLinkedAliases(node.expression, /*setVisibility*/ true); + } } else { checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 2097152 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (node.isExportEquals && !(node.flags & 2097152 /* Ambient */)) { if (modulekind >= ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); @@ -43430,31 +45496,33 @@ var ts; } // Checks for export * conflicts var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. - // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); - if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { - // it is legal to merge type alias with other values - // so count should be either 1 (just type alias) or 2 (type alias + merged value) - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (exports) { + exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } - } - }); + }); + } links.exportsChecked = true; } } @@ -43463,7 +45531,7 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || + return (declaration.kind !== 229 /* FunctionDeclaration */ && declaration.kind !== 152 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { @@ -43481,144 +45549,200 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return checkTypeParameter(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return checkParameter(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return checkPropertyDeclaration(node); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return checkSignatureDeclaration(node); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return checkMethodDeclaration(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return checkConstructorDeclaration(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return checkAccessorDeclaration(node); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return checkTypeReferenceNode(node); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return checkTypePredicate(node); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return checkTypeQuery(node); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return checkTypeLiteral(node); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return checkArrayType(node); - case 165 /* TupleType */: + case 166 /* TupleType */: return checkTupleType(node); - case 166 /* UnionType */: - case 167 /* IntersectionType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: + case 169 /* ParenthesizedType */: return checkSourceElement(node.type); - case 283 /* JSDocTypedefTag */: + case 171 /* TypeOperator */: + return checkTypeOperator(node); + case 282 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 288 /* JSDocTypedefTag */: return checkJSDocTypedefTag(node); - case 279 /* JSDocParameterTag */: - return checkSourceElement(node.typeExpression); - case 273 /* JSDocFunctionType */: + case 284 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 277 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 274 /* JSDocVariadicType */: - case 271 /* JSDocNonNullableType */: - case 270 /* JSDocNullableType */: - case 268 /* JSDocAllType */: - case 269 /* JSDocUnknownType */: - if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { - grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); - } + case 275 /* JSDocNonNullableType */: + case 274 /* JSDocNullableType */: + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: + checkJSDocTypeIsInJsFile(node); + ts.forEachChild(node, checkSourceElement); return; - case 267 /* JSDocTypeExpression */: + case 278 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 271 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 172 /* MappedType */: + case 173 /* MappedType */: return checkMappedType(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 207 /* Block */: - case 234 /* ModuleBlock */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return checkBlock(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return checkVariableStatement(node); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return checkExpressionStatement(node); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return checkIfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return checkDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return checkWhileStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return checkForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return checkForInStatement(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return checkForOfStatement(node); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return checkReturnStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return checkWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return checkSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return checkLabeledStatement(node); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return checkThrowStatement(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return checkTryStatement(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return checkBindingElement(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return checkClassDeclaration(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return checkImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return checkExportDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return checkExportAssignment(node); - case 209 /* EmptyStatement */: + case 210 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 225 /* DebuggerStatement */: + case 226 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 247 /* MissingDeclaration */: + case 248 /* MissingDeclaration */: return checkMissingDeclaration(node); } } + function checkJSDocTypeIsInJsFile(node) { + if (!ts.isInJavaScriptFile(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + // Only legal location is in the *last* parameter tag. + var parent = node.parent; + if (!ts.isJSDocTypeExpression(parent)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + var paramTag = parent.parent; + if (!ts.isJSDocParameterTag(paramTag)) { + error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (!param) { + // We will error in `checkJSDocParameterTag`. + return; + } + var host = ts.getHostSignatureFromJSDoc(paramTag); + if (!host || ts.last(host.parameters).symbol !== param) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + var type = getTypeFromTypeNode(node.type); + var parent = node.parent; + var paramTag = parent.parent; + if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + // Else we will add a diagnostic, see `checkJSDocVariadicType`. + var param = ts.getParameterSymbolFromJSDoc(paramTag); + if (param) { + var host_1 = ts.getHostSignatureFromJSDoc(paramTag); + /* + Only return an array type if the corresponding parameter is marked as a rest parameter. + So in the following situation we will not create an array type: + /** @param {...number} a * / + function f(a) {} + Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. + */ + var lastParamDeclaration = host_1 && ts.last(host_1.parameters); + if (lastParamDeclaration.symbol === param && ts.isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + return addOptionality(type); + } // Function and class expression bodies are checked after all statements in the enclosing body. This is // to ensure constructs like the following are permitted: // const foo = function () { @@ -43637,17 +45761,17 @@ var ts; for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { var node = deferredNodes_1[_i]; switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: checkClassExpressionDeferred(node); break; } @@ -43678,7 +45802,7 @@ var ts; flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); - if (ts.isExternalModule(node)) { + if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile) { @@ -43751,19 +45875,8 @@ var ts; } } // Language service support - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 /* WithStatement */ && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { + if (location.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return []; } @@ -43777,13 +45890,13 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -43791,17 +45904,17 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 793064 /* Type */); } break; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -43849,28 +45962,28 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 145 /* TypeParameter */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: + case 146 /* TypeParameter */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: return true; } } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 143 /* QualifiedName */) { + while (node.parent && node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 159 /* TypeReference */; + return node.parent && node.parent.kind === 160 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 179 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 180 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 201 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 202 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -43883,17 +45996,28 @@ var ts; } return result; } + function isNodeWithinConstructorOfClass(node, classDeclaration) { + return ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + return true; + } + else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } function isNodeWithinClass(node, classDeclaration) { return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 144 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 237 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 238 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 243 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 244 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -43918,7 +46042,7 @@ var ts; return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 /* PropertyAccessExpression */ && + entityName.parent.kind === 180 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -43926,13 +46050,13 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 243 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 244 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } - if (entityName.kind !== 179 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + if (entityName.kind !== 180 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 237 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 238 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -43942,7 +46066,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 201 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 202 /* ExpressionWithTypeArguments */) { meaning = 793064 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -43958,15 +46082,15 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 279 /* JSDocParameterTag */) { + if (entityName.parent.kind === 284 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 145 /* TypeParameter */ && entityName.parent.parent.kind === 282 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 146 /* TypeParameter */ && entityName.parent.parent.kind === 287 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } - if (ts.isPartOfExpression(entityName)) { + if (ts.isExpressionNode(entityName)) { if (ts.nodeIsMissing(entityName)) { // Missing entity name. return undefined; @@ -43977,12 +46101,12 @@ var ts; } return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 179 /* PropertyAccessExpression */ || entityName.kind === 143 /* QualifiedName */) { + else if (entityName.kind === 180 /* PropertyAccessExpression */ || entityName.kind === 144 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 179 /* PropertyAccessExpression */) { + if (entityName.kind === 180 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -43992,23 +46116,23 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 159 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 160 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 253 /* JsxAttribute */) { + else if (entityName.parent.kind === 257 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 158 /* TypePredicate */) { + if (entityName.parent.kind === 159 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -44023,8 +46147,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 176 /* BindingElement */ && - node.parent.parent.kind === 174 /* ObjectBindingPattern */ && + else if (node.parent.kind === 177 /* BindingElement */ && + node.parent.parent.kind === 175 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); @@ -44035,8 +46159,8 @@ var ts; } switch (node.kind) { case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -44050,14 +46174,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 169 /* ThisType */: + case 170 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 97 /* SuperKeyword */: return checkExpression(node).symbol; case 123 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 153 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -44066,7 +46190,7 @@ var ts; // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } @@ -44080,6 +46204,8 @@ var ts; : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: + case 89 /* FunctionKeyword */: + case 36 /* EqualsGreaterThanToken */: return getSymbolOfNode(node.parent); default: return undefined; @@ -44089,7 +46215,7 @@ var ts; // The function returns a value symbol of an identifier in the short-hand property assignment. // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. - if (location && location.kind === 262 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 266 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -44101,7 +46227,7 @@ var ts; resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { + if (node.flags & 4194304 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } @@ -44114,7 +46240,7 @@ var ts; } return typeFromTypeNode; } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { @@ -44160,28 +46286,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 /* ObjectLiteralExpression */ || expr.kind === 177 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 179 /* ObjectLiteralExpression */ || expr.kind === 178 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 216 /* ForOfStatement */) { + if (expr.parent.kind === 217 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 194 /* BinaryExpression */) { + if (expr.parent.kind === 195 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || unknownType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 261 /* PropertyAssignment */) { + if (expr.parent.kind === 265 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 177 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 178 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; @@ -44219,7 +46345,7 @@ var ts; function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { + if (typeHasCallOrConstructSignatures(type)) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); @@ -44228,12 +46354,15 @@ var ts; } return getNamedMembers(propsByName); } + function typeHasCallOrConstructSignatures(type) { + return ts.typeHasCallOrConstructSignatures(type, checker); + } function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { var symbols_4 = []; - var name_3 = symbol.escapedName; + var name_4 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_3); + var symbol = getPropertyOfType(t, name_4); if (symbol) { symbols_4.push(symbol); } @@ -44264,7 +46393,7 @@ var ts; if (!ts.isGeneratedIdentifier(node)) { node = ts.getParseTreeNode(node, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -44321,7 +46450,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 265 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 269 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -44376,7 +46505,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 207 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 208 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -44417,16 +46546,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -44436,7 +46565,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(node) { node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 269 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -44462,6 +46591,11 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } + var target = getSymbolLinks(symbol).target; + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 107455 /* Value */) { + // An `export import ... =` of a value symbol is always considered referenced + return true; + } } if (checkChildren) { return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); @@ -44509,15 +46643,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 264 /* EnumMember */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 268 /* EnumMember */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 264 /* EnumMember */) { + if (node.kind === 268 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -44530,7 +46664,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { // ensure both `typeName` and `location` are parse tree nodes. @@ -44567,7 +46701,7 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + else if (isTypeAssignableToKind(type, 2048 /* Void */ | 12288 /* Nullable */ | 16384 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { @@ -44576,13 +46710,13 @@ var ts; else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 262178 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 524322 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 512 /* ESSymbol */)) { + else if (isTypeAssignableToKind(type, 1536 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -44601,8 +46735,12 @@ var ts; var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (type.flags & 1024 /* UniqueESSymbol */ && + type.symbol === symbol) { + flags |= 131072 /* AllowUniqueESSymbolType */; + } if (flags & 8192 /* AddUndefined */) { - type = getNullableType(type, 2048 /* Undefined */); + type = getOptionalType(type); } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -44648,7 +46786,7 @@ var ts; function isLiteralConstDeclaration(node) { if (ts.isConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 2097152 /* FreshLiteral */); } return false; } @@ -44716,6 +46854,11 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, + isLateBound: function (node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + var symbol = node && getSymbolOfNode(node); + return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + }, writeLiteralConstValue: writeLiteralConstValue, getJsxFactoryEntity: function () { return _jsxFactoryEntity; } }; @@ -44728,7 +46871,7 @@ var ts; // property access can only be used as values // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 179 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) + var meaning = (node.kind === 180 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ : 793064 /* Type */ | 1920 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -44779,7 +46922,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 269 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -44799,7 +46942,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 265 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 269 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -44856,6 +46999,10 @@ var ts; globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); @@ -44863,11 +47010,11 @@ var ts; function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152 /* Ambient */)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 32768 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455 /* Value */); @@ -44899,6 +47046,7 @@ var ts; case 8192 /* AsyncDelegator */: return "__asyncDelegator"; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; + case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; default: ts.Debug.fail("Unrecognized helper"); } } @@ -44909,19 +47057,22 @@ var ts; return externalHelpersModule; } // GRAMMAR CHECKING + function checkGrammarDecoratorsAndModifiers(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node); + } function checkGrammarDecorators(node) { if (!node.decorators) { return false; } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (node.kind === 152 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */) { + else if (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -44939,16 +47090,16 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 131 /* ReadonlyKeyword */) { - if (node.kind === 148 /* PropertySignature */ || node.kind === 150 /* MethodSignature */) { + if (node.kind === 149 /* PropertySignature */ || node.kind === 151 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 76 /* ConstKeyword */: - if (node.kind !== 232 /* EnumDeclaration */ && node.parent.kind === 229 /* ClassDeclaration */) { + if (node.kind !== 233 /* EnumDeclaration */ && node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); } break; @@ -44968,7 +47119,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + else if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -44991,10 +47142,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + else if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -45007,7 +47158,7 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */ && node.kind !== 157 /* IndexSignature */ && node.kind !== 146 /* Parameter */) { + else if (node.kind !== 150 /* PropertyDeclaration */ && node.kind !== 149 /* PropertySignature */ && node.kind !== 158 /* IndexSignature */ && node.kind !== 147 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } @@ -45027,17 +47178,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 79 /* DefaultKeyword */: - var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 269 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 234 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -45049,13 +47200,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234 /* ModuleBlock */) { + else if ((node.parent.flags & 2097152 /* Ambient */) && node.parent.kind === 235 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -45065,14 +47216,14 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 229 /* ClassDeclaration */) { - if (node.kind !== 151 /* MethodDeclaration */ && - node.kind !== 149 /* PropertyDeclaration */ && - node.kind !== 153 /* GetAccessor */ && - node.kind !== 154 /* SetAccessor */) { + if (node.kind !== 230 /* ClassDeclaration */) { + if (node.kind !== 152 /* MethodDeclaration */ && + node.kind !== 150 /* PropertyDeclaration */ && + node.kind !== 154 /* GetAccessor */ && + node.kind !== 155 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 230 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -45088,10 +47239,10 @@ var ts; if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 /* Ambient */ || node.parent.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 146 /* Parameter */) { + else if (node.kind === 147 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -45099,7 +47250,7 @@ var ts; break; } } - if (node.kind === 152 /* Constructor */) { + if (node.kind === 153 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -45114,13 +47265,13 @@ var ts; } return; } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 239 /* ImportDeclaration */ || node.kind === 238 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 147 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 147 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -45140,37 +47291,37 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 233 /* ModuleDeclaration */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 146 /* Parameter */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 158 /* IndexSignature */: + case 234 /* ModuleDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: + case 244 /* ExportAssignment */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 147 /* Parameter */: return false; default: - if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + if (node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { return false; } switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 230 /* InterfaceDeclaration */: - case 208 /* VariableStatement */: - case 231 /* TypeAliasDeclaration */: + case 231 /* InterfaceDeclaration */: + case 209 /* VariableStatement */: + case 232 /* TypeAliasDeclaration */: return true; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); default: ts.Debug.fail(); @@ -45183,10 +47334,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 151 /* MethodDeclaration */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -45241,7 +47392,7 @@ var ts; function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarClassLikeDeclaration(node) { @@ -45249,7 +47400,7 @@ var ts; return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 187 /* ArrowFunction */) { + if (node.kind === 188 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -45293,7 +47444,7 @@ var ts; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -45311,7 +47462,7 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 200 /* OmittedExpression */) { + if (arg.kind === 201 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -45337,7 +47488,7 @@ var ts; function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) { for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { var heritageClause = _a[_i]; if (heritageClause.token === 85 /* ExtendsKeyword */) { @@ -45387,20 +47538,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 144 /* ComputedPropertyName */) { + if (node.kind !== 145 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 195 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 /* FunctionDeclaration */ || - node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */); - if (ts.isInAmbientContext(node)) { + ts.Debug.assert(node.kind === 229 /* FunctionDeclaration */ || + node.kind === 187 /* FunctionExpression */ || + node.kind === 152 /* MethodDeclaration */); + if (node.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -45414,22 +47565,25 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var Flags; + (function (Flags) { + Flags[Flags["Property"] = 1] = "Property"; + Flags[Flags["GetAccessor"] = 2] = "GetAccessor"; + Flags[Flags["SetAccessor"] = 4] = "SetAccessor"; + Flags[Flags["GetOrSetAccessor"] = 6] = "GetOrSetAccessor"; + })(Flags || (Flags = {})); var seen = ts.createUnderscoreEscapedMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */) { + if (prop.kind === 267 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 262 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 266 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -45438,7 +47592,7 @@ var ts; if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 151 /* MethodDeclaration */) { + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 152 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -45452,25 +47606,26 @@ var ts; // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */) { - // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151 /* MethodDeclaration */) { - currentKind = Property; - } - else if (prop.kind === 153 /* GetAccessor */) { - currentKind = GetAccessor; - } - else if (prop.kind === 154 /* SetAccessor */) { - currentKind = SetAccessor; - } - else { - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + switch (prop.kind) { + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + // falls through + case 152 /* MethodDeclaration */: + currentKind = 1 /* Property */; + break; + case 154 /* GetAccessor */: + currentKind = 2 /* GetAccessor */; + break; + case 155 /* SetAccessor */: + currentKind = 4 /* SetAccessor */; + break; + default: + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -45481,11 +47636,11 @@ var ts; seen.set(effectiveName, currentKind); } else { - if (currentKind === Property && existingKind === Property) { + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + else if ((currentKind & 6 /* GetOrSetAccessor */) && (existingKind & 6 /* GetOrSetAccessor */)) { + if (existingKind !== 6 /* GetOrSetAccessor */ && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); } else { @@ -45502,7 +47657,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 255 /* JsxSpreadAttribute */) { + if (attr.kind === 259 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; @@ -45514,7 +47669,7 @@ var ts; return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 260 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -45523,12 +47678,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 216 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 217 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 228 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -45543,20 +47698,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 216 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -45570,7 +47725,7 @@ var ts; if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (ts.isInAmbientContext(accessor)) { + else if (accessor.flags & 2097152 /* Ambient */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { @@ -45583,11 +47738,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 154 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 154 /* SetAccessor */) { + else if (kind === 155 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -45610,15 +47765,50 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 154 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 154 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 140 /* UniqueKeyword */) { + if (node.type.kind !== 137 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(137 /* SymbolKeyword */)); + } + var parent = ts.walkUpParenthesizedTypes(node.parent); + switch (parent.kind) { + case 227 /* VariableDeclaration */: + var decl = parent; + if (decl.name.kind !== 71 /* Identifier */) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!ts.isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 150 /* PropertyDeclaration */: + if (!ts.hasModifier(parent, 32 /* Static */) || + !ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 149 /* PropertySignature */: + if (!ts.hasModifier(parent, 64 /* Readonly */)) { + return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -45628,7 +47818,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (node.parent.kind === 179 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } @@ -45642,18 +47832,18 @@ var ts; // However, property declarations disallow computed names in general, // and accessors are not allowed in ambient contexts in general, // so this error only really matters for methods. - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + if (node.flags & 2097152 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 231 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 163 /* TypeLiteral */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + else if (node.parent.kind === 164 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } function checkGrammarBreakOrContinueStatement(node) { @@ -45663,11 +47853,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 217 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 218 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -45675,8 +47865,8 @@ var ts; return false; } break; - case 221 /* SwitchStatement */: - if (node.kind === 218 /* BreakStatement */ && !node.label) { + case 222 /* SwitchStatement */: + if (node.kind === 219 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -45691,13 +47881,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 218 /* BreakStatement */ + var message = node.kind === 219 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 218 /* BreakStatement */ + var message = node.kind === 219 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -45709,7 +47899,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 175 /* ArrayBindingPattern */ || node.name.kind === 174 /* ObjectBindingPattern */) { + if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -45720,12 +47910,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.kind === 193 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 /* ForInStatement */ && node.parent.parent.kind !== 216 /* ForOfStatement */) { - if (ts.isInAmbientContext(node)) { + if (node.parent.parent.kind !== 216 /* ForInStatement */ && node.parent.parent.kind !== 217 /* ForOfStatement */) { + if (node.flags & 2097152 /* Ambient */) { if (node.initializer) { if (ts.isConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { @@ -45753,8 +47943,11 @@ var ts; } } } + if (node.exclamationToken && (node.parent.parent.kind !== 209 /* VariableStatement */ || !node.type || node.initializer || node.flags & 2097152 /* Ambient */)) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + !(node.parent.parent.flags & 2097152 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); @@ -45768,7 +47961,7 @@ var ts; } function checkESModuleMarker(name) { if (name.kind === 71 /* Identifier */) { - if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + if (ts.idText(name) === "__esModule") { return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } } @@ -45809,15 +48002,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 212 /* IfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: return false; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -45865,40 +48058,47 @@ var ts; } } function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(node, node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + var type = ts.getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } } function checkGrammarProperty(node) { if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 231 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 163 /* TypeLiteral */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + else if (node.parent.kind === 164 /* TypeLiteral */) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (ts.isInAmbientContext(node) && node.initializer) { + if (node.flags & 2097152 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } + if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace @@ -45913,13 +48113,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 230 /* InterfaceDeclaration */ || - node.kind === 231 /* TypeAliasDeclaration */ || - node.kind === 238 /* ImportDeclaration */ || - node.kind === 237 /* ImportEqualsDeclaration */ || - node.kind === 244 /* ExportDeclaration */ || - node.kind === 243 /* ExportAssignment */ || - node.kind === 236 /* NamespaceExportDeclaration */ || + if (node.kind === 231 /* InterfaceDeclaration */ || + node.kind === 232 /* TypeAliasDeclaration */ || + node.kind === 239 /* ImportDeclaration */ || + node.kind === 238 /* ImportEqualsDeclaration */ || + node.kind === 245 /* ExportDeclaration */ || + node.kind === 244 /* ExportAssignment */ || + node.kind === 237 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -45928,7 +48128,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 209 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -45936,10 +48136,10 @@ var ts; } } function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 2097152 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { + if (node.flags & 2097152 /* Ambient */) { // An accessors is already reported about the ambient context if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; @@ -45954,7 +48154,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 207 /* Block */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + if (node.parent.kind === 208 /* Block */ || node.parent.kind === 235 /* ModuleBlock */ || node.parent.kind === 269 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -45970,15 +48170,15 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.numericLiteralFlags & 4 /* Octal */) { + if (node.numericLiteralFlags & 32 /* Octal */) { var diagnosticMessage = void 0; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 173 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 174 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 264 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 268 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -45997,13 +48197,16 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -46027,8 +48230,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: return true; default: return ts.isDeclarationName(name); @@ -46036,18 +48239,31 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 239 /* ImportClause */: // For default import - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */:// For rename import `x as y` + case 240 /* ImportClause */: // For default import + case 238 /* ImportEqualsDeclaration */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */:// For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 242 /* ImportSpecifier */; + return decl.parent.kind === 243 /* ImportSpecifier */; default: return false; } } + var JsxNames; + (function (JsxNames) { + // tslint:disable variable-name + JsxNames.JSX = "JSX"; + JsxNames.IntrinsicElements = "IntrinsicElements"; + JsxNames.ElementClass = "ElementClass"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames.Element = "Element"; + JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + // tslint:enable variable-name + })(JsxNames || (JsxNames = {})); })(ts || (ts = {})); /// /// @@ -46063,9 +48279,6 @@ var ts; if (updated !== original) { setOriginalNode(updated, original); setTextRange(updated, original); - if (original.startsOnNewLine) { - updated.startsOnNewLine = true; - } ts.aggregateTransformFlags(updated); } return updated; @@ -46098,6 +48311,9 @@ var ts; // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). + if (node === undefined) { + return undefined; + } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; setOriginalNode(clone, node); @@ -46117,7 +48333,7 @@ var ts; if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } - if (typeof value === "string") { + if (ts.isString(value)) { return createStringLiteral(value); } return createLiteralFromNode(value); @@ -46154,7 +48370,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) + ? updateNode(createIdentifier(ts.idText(node), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -46189,12 +48405,12 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - /** Create a unique name generated for a node. */ - function getGeneratedNameForNode(node) { + function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); name.autoGenerateKind = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; + name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; nextAutoGenerateId++; return name; } @@ -46227,7 +48443,7 @@ var ts; ts.createFalse = createFalse; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(143 /* QualifiedName */); + var node = createSynthesizedNode(144 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -46241,7 +48457,7 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function createComputedPropertyName(expression) { - var node = createSynthesizedNode(144 /* ComputedPropertyName */); + var node = createSynthesizedNode(145 /* ComputedPropertyName */); node.expression = expression; return node; } @@ -46254,7 +48470,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(145 /* TypeParameter */); + var node = createSynthesizedNode(146 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -46270,7 +48486,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(146 /* Parameter */); + var node = createSynthesizedNode(147 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -46294,7 +48510,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(147 /* Decorator */); + var node = createSynthesizedNode(148 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -46307,7 +48523,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148 /* PropertySignature */); + var node = createSynthesizedNode(149 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -46327,7 +48543,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(149 /* PropertyDeclaration */); + var node = createSynthesizedNode(150 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -46349,7 +48565,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(150 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(151 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -46366,7 +48582,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(151 /* MethodDeclaration */); + var node = createSynthesizedNode(152 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -46394,7 +48610,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(152 /* Constructor */); + var node = createSynthesizedNode(153 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -46414,7 +48630,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(153 /* GetAccessor */); + var node = createSynthesizedNode(154 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -46437,7 +48653,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(154 /* SetAccessor */); + var node = createSynthesizedNode(155 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -46458,7 +48674,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(155 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(156 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -46466,7 +48682,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(156 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(157 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -46474,7 +48690,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(157 /* IndexSignature */); + var node = createSynthesizedNode(158 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -46513,7 +48729,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(158 /* TypePredicate */); + var node = createSynthesizedNode(159 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -46527,7 +48743,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(159 /* TypeReference */); + var node = createSynthesizedNode(160 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -46541,7 +48757,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(160 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(161 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -46549,7 +48765,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(161 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(162 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -46557,7 +48773,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(162 /* TypeQuery */); + var node = createSynthesizedNode(163 /* TypeQuery */); node.exprName = exprName; return node; } @@ -46569,7 +48785,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(163 /* TypeLiteral */); + var node = createSynthesizedNode(164 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -46581,7 +48797,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(164 /* ArrayType */); + var node = createSynthesizedNode(165 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -46593,7 +48809,7 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(165 /* TupleType */); + var node = createSynthesizedNode(166 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } @@ -46605,7 +48821,7 @@ var ts; } ts.updateTypleTypeNode = updateTypleTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(166 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(167 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -46613,7 +48829,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(167 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(168 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -46632,7 +48848,7 @@ var ts; : node; } function createParenthesizedType(type) { - var node = createSynthesizedNode(168 /* ParenthesizedType */); + var node = createSynthesizedNode(169 /* ParenthesizedType */); node.type = type; return node; } @@ -46644,22 +48860,22 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(169 /* ThisType */); + return createSynthesizedNode(170 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; - function createTypeOperatorNode(type) { - var node = createSynthesizedNode(170 /* TypeOperator */); - node.operator = 127 /* KeyOfKeyword */; - node.type = ts.parenthesizeElementTypeMember(type); + function createTypeOperatorNode(operatorOrType, type) { + var node = createSynthesizedNode(171 /* TypeOperator */); + node.operator = typeof operatorOrType === "number" ? operatorOrType : 127 /* KeyOfKeyword */; + node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; } ts.createTypeOperatorNode = createTypeOperatorNode; function updateTypeOperatorNode(node, type) { - return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node; + return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(171 /* IndexedAccessType */); + var node = createSynthesizedNode(172 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -46673,7 +48889,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(172 /* MappedType */); + var node = createSynthesizedNode(173 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -46691,7 +48907,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(173 /* LiteralType */); + var node = createSynthesizedNode(174 /* LiteralType */); node.literal = literal; return node; } @@ -46704,7 +48920,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(174 /* ObjectBindingPattern */); + var node = createSynthesizedNode(175 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -46716,7 +48932,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(175 /* ArrayBindingPattern */); + var node = createSynthesizedNode(176 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -46728,7 +48944,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(176 /* BindingElement */); + var node = createSynthesizedNode(177 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -46747,7 +48963,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(177 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(178 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -46761,7 +48977,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(178 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(179 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -46775,7 +48991,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(179 /* PropertyAccessExpression */); + var node = createSynthesizedNode(180 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); setEmitFlags(node, 131072 /* NoIndentation */); @@ -46792,7 +49008,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(180 /* ElementAccessExpression */); + var node = createSynthesizedNode(181 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -46806,7 +49022,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(181 /* CallExpression */); + var node = createSynthesizedNode(182 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -46822,7 +49038,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(182 /* NewExpression */); + var node = createSynthesizedNode(183 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -46838,7 +49054,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(183 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(184 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); node.template = template; return node; @@ -46852,7 +49068,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(184 /* TypeAssertionExpression */); + var node = createSynthesizedNode(185 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -46866,7 +49082,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(185 /* ParenthesizedExpression */); + var node = createSynthesizedNode(186 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -46878,7 +49094,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(186 /* FunctionExpression */); + var node = createSynthesizedNode(187 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -46902,7 +49118,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(187 /* ArrowFunction */); + var node = createSynthesizedNode(188 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -46936,7 +49152,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(188 /* DeleteExpression */); + var node = createSynthesizedNode(189 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46948,7 +49164,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(189 /* TypeOfExpression */); + var node = createSynthesizedNode(190 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46960,7 +49176,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(190 /* VoidExpression */); + var node = createSynthesizedNode(191 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46972,7 +49188,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(191 /* AwaitExpression */); + var node = createSynthesizedNode(192 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -46984,7 +49200,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(192 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(193 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -46997,7 +49213,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(193 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(194 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -47010,7 +49226,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(194 /* BinaryExpression */); + var node = createSynthesizedNode(195 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -47027,7 +49243,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(195 /* ConditionalExpression */); + var node = createSynthesizedNode(196 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -47057,7 +49273,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(196 /* TemplateExpression */); + var node = createSynthesizedNode(197 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -47095,7 +49311,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(197 /* YieldExpression */); + var node = createSynthesizedNode(198 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; @@ -47109,7 +49325,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(198 /* SpreadElement */); + var node = createSynthesizedNode(199 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -47121,7 +49337,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(199 /* ClassExpression */); + var node = createSynthesizedNode(200 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47142,11 +49358,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(200 /* OmittedExpression */); + return createSynthesizedNode(201 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(201 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(202 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -47160,7 +49376,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(202 /* AsExpression */); + var node = createSynthesizedNode(203 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -47174,7 +49390,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(203 /* NonNullExpression */); + var node = createSynthesizedNode(204 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -47186,7 +49402,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(204 /* MetaProperty */); + var node = createSynthesizedNode(205 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -47200,7 +49416,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(205 /* TemplateSpan */); + var node = createSynthesizedNode(206 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -47214,12 +49430,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(206 /* SemicolonClassElement */); + return createSynthesizedNode(207 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(207 /* Block */); + var block = createSynthesizedNode(208 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -47233,7 +49449,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(208 /* VariableStatement */); + var node = createSynthesizedNode(209 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -47248,11 +49464,11 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(209 /* EmptyStatement */); + return createSynthesizedNode(210 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; function createStatement(expression) { - var node = createSynthesizedNode(210 /* ExpressionStatement */); + var node = createSynthesizedNode(211 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } @@ -47264,7 +49480,7 @@ var ts; } ts.updateStatement = updateStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(211 /* IfStatement */); + var node = createSynthesizedNode(212 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -47280,7 +49496,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(212 /* DoStatement */); + var node = createSynthesizedNode(213 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -47294,7 +49510,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(213 /* WhileStatement */); + var node = createSynthesizedNode(214 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -47308,7 +49524,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(214 /* ForStatement */); + var node = createSynthesizedNode(215 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -47326,7 +49542,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(215 /* ForInStatement */); + var node = createSynthesizedNode(216 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -47342,7 +49558,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(216 /* ForOfStatement */); + var node = createSynthesizedNode(217 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -47360,7 +49576,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(217 /* ContinueStatement */); + var node = createSynthesizedNode(218 /* ContinueStatement */); node.label = asName(label); return node; } @@ -47372,7 +49588,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(218 /* BreakStatement */); + var node = createSynthesizedNode(219 /* BreakStatement */); node.label = asName(label); return node; } @@ -47384,7 +49600,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(219 /* ReturnStatement */); + var node = createSynthesizedNode(220 /* ReturnStatement */); node.expression = expression; return node; } @@ -47396,7 +49612,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(220 /* WithStatement */); + var node = createSynthesizedNode(221 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -47410,7 +49626,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(221 /* SwitchStatement */); + var node = createSynthesizedNode(222 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -47424,7 +49640,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(222 /* LabeledStatement */); + var node = createSynthesizedNode(223 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -47438,7 +49654,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(223 /* ThrowStatement */); + var node = createSynthesizedNode(224 /* ThrowStatement */); node.expression = expression; return node; } @@ -47450,7 +49666,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(224 /* TryStatement */); + var node = createSynthesizedNode(225 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -47466,11 +49682,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(225 /* DebuggerStatement */); + return createSynthesizedNode(226 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(226 /* VariableDeclaration */); + var node = createSynthesizedNode(227 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -47486,7 +49702,7 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(227 /* VariableDeclarationList */); + var node = createSynthesizedNode(228 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -47499,7 +49715,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(228 /* FunctionDeclaration */); + var node = createSynthesizedNode(229 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -47525,7 +49741,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(229 /* ClassDeclaration */); + var node = createSynthesizedNode(230 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47547,7 +49763,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(230 /* InterfaceDeclaration */); + var node = createSynthesizedNode(231 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47569,7 +49785,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(231 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(232 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47589,7 +49805,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(232 /* EnumDeclaration */); + var node = createSynthesizedNode(233 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47607,7 +49823,7 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(233 /* ModuleDeclaration */); + var node = createSynthesizedNode(234 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -47626,7 +49842,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(234 /* ModuleBlock */); + var node = createSynthesizedNode(235 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -47638,7 +49854,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(235 /* CaseBlock */); + var node = createSynthesizedNode(236 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -47650,7 +49866,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(236 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(237 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -47662,7 +49878,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(237 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(238 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -47680,7 +49896,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(238 /* ImportDeclaration */); + var node = createSynthesizedNode(239 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -47698,7 +49914,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(239 /* ImportClause */); + var node = createSynthesizedNode(240 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -47712,7 +49928,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(240 /* NamespaceImport */); + var node = createSynthesizedNode(241 /* NamespaceImport */); node.name = name; return node; } @@ -47724,7 +49940,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(241 /* NamedImports */); + var node = createSynthesizedNode(242 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -47736,7 +49952,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(242 /* ImportSpecifier */); + var node = createSynthesizedNode(243 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -47750,11 +49966,11 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(243 /* ExportAssignment */); + var node = createSynthesizedNode(244 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = expression; + node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(58 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression); return node; } ts.createExportAssignment = createExportAssignment; @@ -47767,7 +49983,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(244 /* ExportDeclaration */); + var node = createSynthesizedNode(245 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -47785,7 +50001,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(245 /* NamedExports */); + var node = createSynthesizedNode(246 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -47797,7 +50013,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246 /* ExportSpecifier */); + var node = createSynthesizedNode(247 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -47812,7 +50028,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(248 /* ExternalModuleReference */); + var node = createSynthesizedNode(249 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -47825,7 +50041,7 @@ var ts; ts.updateExternalModuleReference = updateExternalModuleReference; // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(249 /* JsxElement */); + var node = createSynthesizedNode(250 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -47841,7 +50057,7 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(250 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(251 /* JsxSelfClosingElement */); node.tagName = tagName; node.attributes = attributes; return node; @@ -47855,7 +50071,7 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(251 /* JsxOpeningElement */); + var node = createSynthesizedNode(252 /* JsxOpeningElement */); node.tagName = tagName; node.attributes = attributes; return node; @@ -47869,7 +50085,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(252 /* JsxClosingElement */); + var node = createSynthesizedNode(253 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -47880,8 +50096,24 @@ var ts; : node; } ts.updateJsxClosingElement = updateJsxClosingElement; + function createJsxFragment(openingFragment, children, closingFragment) { + var node = createSynthesizedNode(254 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + return node; + } + ts.createJsxFragment = createJsxFragment; + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment + || node.children !== children + || node.closingFragment !== closingFragment + ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node) + : node; + } + ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(253 /* JsxAttribute */); + var node = createSynthesizedNode(257 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -47895,7 +50127,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(254 /* JsxAttributes */); + var node = createSynthesizedNode(258 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -47907,7 +50139,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(255 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(259 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -47919,7 +50151,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(256 /* JsxExpression */); + var node = createSynthesizedNode(260 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -47933,7 +50165,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(257 /* CaseClause */); + var node = createSynthesizedNode(261 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -47947,7 +50179,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(258 /* DefaultClause */); + var node = createSynthesizedNode(262 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -47959,7 +50191,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(259 /* HeritageClause */); + var node = createSynthesizedNode(263 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -47972,8 +50204,8 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(260 /* CatchClause */); - node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration; + var node = createSynthesizedNode(264 /* CatchClause */); + node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; } @@ -47987,7 +50219,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(261 /* PropertyAssignment */); + var node = createSynthesizedNode(265 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -48002,7 +50234,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(262 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(266 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -48016,7 +50248,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(263 /* SpreadAssignment */); + var node = createSynthesizedNode(267 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; return node; } @@ -48029,7 +50261,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(264 /* EnumMember */); + var node = createSynthesizedNode(268 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -48045,7 +50277,7 @@ var ts; // Top-level nodes function updateSourceFileNode(node, statements) { if (node.statements !== statements) { - var updated = createSynthesizedNode(265 /* SourceFile */); + var updated = createSynthesizedNode(269 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -48124,7 +50356,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(287 /* NotEmittedStatement */); + var node = createSynthesizedNode(291 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -48136,7 +50368,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(291 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(295 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -48148,7 +50380,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(290 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(294 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -48163,7 +50395,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(288 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(292 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -48179,7 +50411,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 289 /* CommaListExpression */) { + if (node.kind === 293 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -48189,7 +50421,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(289 /* CommaListExpression */); + var node = createSynthesizedNode(293 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -48201,7 +50433,7 @@ var ts; } ts.updateCommaList = updateCommaList; function createBundle(sourceFiles) { - var node = ts.createNode(266 /* Bundle */); + var node = ts.createNode(270 /* Bundle */); node.sourceFiles = sourceFiles; return node; } @@ -48293,10 +50525,10 @@ var ts; } ts.createExternalModuleExport = createExternalModuleExport; function asName(name) { - return typeof name === "string" ? createIdentifier(name) : name; + return ts.isString(name) ? createIdentifier(name) : name; } function asExpression(value) { - return typeof value === "string" || typeof value === "number" ? createLiteral(value) : value; + return ts.isString(value) || typeof value === "number" ? createLiteral(value) : value; } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -48337,7 +50569,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -48364,6 +50596,16 @@ var ts; return node; } ts.setEmitFlags = setEmitFlags; + /** + * Sets flags that control emit behavior of a node. + */ + /* @internal */ + function addEmitFlags(node, emitFlags) { + var emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; + } + ts.addEmitFlags = addEmitFlags; /** * Gets a custom text range to use when emitting source maps. */ @@ -48380,6 +50622,7 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -48407,6 +50650,24 @@ var ts; return node; } ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Gets a custom text range to use when emitting comments. + */ + /*@internal*/ + function getStartsOnNewLine(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.startsOnNewLine; + } + ts.getStartsOnNewLine = getStartsOnNewLine; + /** + * Sets a custom text range to use when emitting comments. + */ + /*@internal*/ + function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; + } + ts.setStartsOnNewLine = setStartsOnNewLine; /** * Gets a custom text range to use when emitting comments. */ @@ -48562,7 +50823,7 @@ var ts; } ts.setOriginalNode = setOriginalNode; function mergeEmitNode(sourceEmitNode, destEmitNode) { - var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; + var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers, startsOnNewLine = sourceEmitNode.startsOnNewLine; if (!destEmitNode) destEmitNode = {}; // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. @@ -48582,6 +50843,8 @@ var ts; destEmitNode.constantValue = constantValue; if (helpers) destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers); + if (startsOnNewLine !== undefined) + destEmitNode.startsOnNewLine = startsOnNewLine; return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { @@ -48680,12 +50943,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + var right = ts.createIdentifier(ts.idText(jsxFactory.right)); right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); + return createReactNamespace(ts.idText(jsxFactory), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -48705,7 +50968,7 @@ var ts; if (children.length > 1) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; - child.startsOnNewLine = true; + startOnNewLine(child); argumentsList.push(child); } } @@ -48717,6 +50980,26 @@ var ts; /*typeArguments*/ undefined, argumentsList), location); } ts.createExpressionForJsxElement = createExpressionForJsxElement; + function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) { + var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment"); + var argumentsList = [tagName]; + argumentsList.push(ts.createNull()); + if (children && children.length > 0) { + if (children.length > 1) { + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + startOnNewLine(child); + argumentsList.push(child); + } + } + else { + argumentsList.push(children[0]); + } + } + return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ undefined, argumentsList), location); + } + ts.createExpressionForJsxFragment = createExpressionForJsxFragment; // Helpers function getHelperName(name) { return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); @@ -48787,7 +51070,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 222 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 223 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -48805,13 +51088,13 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -48837,7 +51120,7 @@ var ts; } else { switch (callee.kind) { - case 179 /* PropertyAccessExpression */: { + case 180 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -48850,7 +51133,7 @@ var ts; } break; } - case 180 /* ElementAccessExpression */: { + case 181 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -48907,14 +51190,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -49115,8 +51398,8 @@ var ts; var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); - if (node.startsOnNewLine) { - updated.startsOnNewLine = true; + if (ts.getStartsOnNewLine(node)) { + ts.setStartsOnNewLine(updated, /*newLine*/ true); } ts.aggregateTransformFlags(updated); return updated; @@ -49182,7 +51465,7 @@ var ts; while (statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { - target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); + ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { break; @@ -49238,7 +51521,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 185 /* ParenthesizedExpression */) { + if (skipped.kind === 186 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -49272,8 +51555,8 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(194 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(195 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(195 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { @@ -49282,7 +51565,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 197 /* YieldExpression */) { + && operand.kind === 198 /* YieldExpression */) { return false; } return true; @@ -49370,7 +51653,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 195 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -49385,7 +51668,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(196 /* ConditionalExpression */, 55 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -49398,11 +51681,32 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 194 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ ? ts.createParen(e) : e; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; + /** + * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but + * has a lookahead restriction for `function`, `async function`, and `class`. + * + * Basically, that means we need to parenthesize in the following cases: + * + * - BinaryExpression of CommaToken + * - CommaList (synthetic list of multiple comma expressions) + * - FunctionExpression + * - ClassExpression + */ + function parenthesizeDefaultExpression(e) { + var check = ts.skipPartiallyEmittedExpressions(e); + return (check.kind === 200 /* ClassExpression */ || + check.kind === 187 /* FunctionExpression */ || + check.kind === 293 /* CommaListExpression */ || + ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) + ? ts.createParen(e) + : e; + } + ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** * Wraps an expression in parentheses if it is needed in order to use the expression * as the expression of a NewExpression node. @@ -49410,14 +51714,14 @@ var ts; * @param expression The Expression node. */ function parenthesizeForNew(expression) { - var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); - switch (emittedExpression.kind) { - case 181 /* CallExpression */: + var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + switch (leftmostExpr.kind) { + case 182 /* CallExpression */: return ts.createParen(expression); - case 182 /* NewExpression */: - return emittedExpression.arguments - ? expression - : ts.createParen(expression); + case 183 /* NewExpression */: + return !leftmostExpr.arguments + ? ts.createParen(expression) + : expression; } return parenthesizeForAccess(expression); } @@ -49437,7 +51741,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 182 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 183 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -49475,7 +51779,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(195 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -49486,14 +51790,14 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 186 /* FunctionExpression */ || kind === 187 /* ArrowFunction */) { + if (kind === 187 /* FunctionExpression */ || kind === 188 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 /* ObjectLiteralExpression */ || leftmostExpressionKind === 186 /* FunctionExpression */) { + var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; + if (leftmostExpressionKind === 179 /* ObjectLiteralExpression */ || leftmostExpressionKind === 187 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; @@ -49501,10 +51805,10 @@ var ts; ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return ts.createParenthesizedType(member); } return member; @@ -49512,8 +51816,8 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 162 /* TypeQuery */: - case 170 /* TypeOperator */: + case 163 /* TypeQuery */: + case 171 /* TypeOperator */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -49536,24 +51840,28 @@ var ts; } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function getLeftmostExpression(node) { + function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: node = node.operand; continue; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: node = node.left; continue; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: node = node.condition; continue; - case 181 /* CallExpression */: - case 180 /* ElementAccessExpression */: - case 179 /* PropertyAccessExpression */: + case 182 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 181 /* ElementAccessExpression */: + case 180 /* PropertyAccessExpression */: node = node.expression; continue; - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -49561,7 +51869,7 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body).kind === 178 /* ObjectLiteralExpression */) { + if (!ts.isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 179 /* ObjectLiteralExpression */) { return ts.setTextRange(ts.createParen(body), body); } return body; @@ -49577,13 +51885,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - case 203 /* NonNullExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 204 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -49608,14 +51916,14 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipParentheses(node) { - while (node.kind === 185 /* ParenthesizedExpression */) { + while (node.kind === 186 /* ParenthesizedExpression */) { node = node.expression; } return node; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 203 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 204 /* NonNullExpression */) { node = node.expression; } return node; @@ -49623,11 +51931,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 185 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 184 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 202 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 203 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 186 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 185 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 203 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 204 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 292 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -49645,7 +51953,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 185 /* ParenthesizedExpression */ + return node.kind === 186 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -49661,8 +51969,7 @@ var ts; } ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { - node.startsOnNewLine = true; - return node; + return ts.setStartsOnNewLine(node, /*newLine*/ true); } ts.startOnNewLine = startOnNewLine; function getExternalHelpersModuleName(node) { @@ -49709,12 +52016,12 @@ var ts; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { var name = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 238 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 239 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 244 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 245 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -49832,7 +52139,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -49844,11 +52151,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -49880,12 +52187,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 146 /* Parameter */: - case 176 /* BindingElement */: + case 147 /* Parameter */: + case 177 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 198 /* SpreadElement */: - case 263 /* SpreadAssignment */: + case 199 /* SpreadElement */: + case 267 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -49897,7 +52204,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 176 /* BindingElement */: + case 177 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -49909,7 +52216,7 @@ var ts; : propertyName; } break; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -49921,7 +52228,7 @@ var ts; : propertyName; } break; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -49939,13 +52246,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -49985,11 +52292,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 178 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 174 /* ObjectBindingPattern */: - case 178 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 179 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -50152,264 +52459,266 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */) || kind === 169 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 143 /* LastToken */) || kind === 170 /* ThisType */) { return node; } switch (kind) { // Names case 71 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 146 /* Parameter */: + case 147 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 147 /* Decorator */: + case 148 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 148 /* PropertySignature */: + case 149 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 150 /* MethodSignature */: + case 151 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 152 /* Constructor */: + case 153 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 155 /* CallSignature */: + case 156 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 160 /* FunctionType */: + case 161 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* ConstructorType */: + case 162 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 165 /* TupleType */: + case 166 /* TupleType */: return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 166 /* UnionType */: + case 167 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 172 /* MappedType */: + case 173 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 202 /* AsExpression */: + case 203 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 207 /* Block */: + case 208 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 241 /* NamedImports */: + case 242 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 245 /* NamedExports */: + case 246 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 246 /* ExportSpecifier */: + case 247 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 249 /* JsxElement */: + case 250 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 251 /* JsxOpeningElement */: + case 252 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 253 /* JsxAttribute */: + case 254 /* JsxFragment */: + return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); + case 257 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 257 /* CaseClause */: + case 261 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 264 /* EnumMember */: + case 268 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 265 /* SourceFile */: + case 269 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -50451,58 +52760,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 142 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 143 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 158 /* TypePredicate */ && kind <= 173 /* LiteralType */)) { + if ((kind >= 159 /* TypePredicate */ && kind <= 174 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 206 /* SemicolonClassElement */: - case 209 /* EmptyStatement */: - case 200 /* OmittedExpression */: - case 225 /* DebuggerStatement */: - case 287 /* NotEmittedStatement */: + case 207 /* SemicolonClassElement */: + case 210 /* EmptyStatement */: + case 201 /* OmittedExpression */: + case 226 /* DebuggerStatement */: + case 291 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 146 /* Parameter */: + case 147 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 147 /* Decorator */: + case 148 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 148 /* PropertySignature */: + case 149 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50511,12 +52820,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 152 /* Constructor */: + case 153 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50524,7 +52833,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50532,49 +52841,49 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 176 /* BindingElement */: + case 177 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 181 /* CallExpression */: + case 182 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 182 /* NewExpression */: + case 183 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -50582,123 +52891,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 185 /* ParenthesizedExpression */: - case 188 /* DeleteExpression */: - case 189 /* TypeOfExpression */: - case 190 /* VoidExpression */: - case 191 /* AwaitExpression */: - case 197 /* YieldExpression */: - case 198 /* SpreadElement */: - case 203 /* NonNullExpression */: + case 186 /* ParenthesizedExpression */: + case 189 /* DeleteExpression */: + case 190 /* TypeOfExpression */: + case 191 /* VoidExpression */: + case 192 /* AwaitExpression */: + case 198 /* YieldExpression */: + case 199 /* SpreadElement */: + case 204 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 202 /* AsExpression */: + case 203 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 207 /* Block */: + case 208 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 211 /* IfStatement */: + case 212 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 212 /* DoStatement */: + case 213 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 213 /* WhileStatement */: - case 220 /* WithStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 214 /* ForStatement */: + case 215 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219 /* ReturnStatement */: - case 223 /* ThrowStatement */: + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 224 /* TryStatement */: + case 225 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50707,7 +53016,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -50715,134 +53024,139 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 239 /* ImportClause */: + case 240 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 247 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 249 /* JsxElement */: + case 250 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: + case 254 /* JsxFragment */: + result = reduceNode(node.openingFragment, cbNode, result); + result = ts.reduceLeft(node.children, cbNode, result); + result = reduceNode(node.closingFragment, cbNode, result); + break; + case 251 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 257 /* CaseClause */: + case 261 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 260 /* CatchClause */: + case 264 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 264 /* EnumMember */: + case 268 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 265 /* SourceFile */: + case 269 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -50915,7 +53229,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 201 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 202 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -50960,12 +53274,12 @@ var ts; return; // Add additional properties in debug mode to assist with debugging. Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + __debugFlags: { get: function () { return ts.formatSymbolFlags(this.flags); } } }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { - "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, - "__debugObjectFlags": { get: function () { return this.flags & 32768 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, - "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, + __debugObjectFlags: { get: function () { return this.flags & 65536 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ ts.objectAllocator.getNodeConstructor(), @@ -50977,11 +53291,11 @@ var ts; var ctor = nodeConstructors_1[_i]; if (!ctor.prototype.hasOwnProperty("__debugKind")) { Object.defineProperties(ctor.prototype, { - "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, - "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, - "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, - "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, - "__debugGetText": { + __debugKind: { get: function () { return ts.formatSyntaxKind(this.kind); } }, + __debugModifierFlags: { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + __debugTransformFlags: { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + __debugEmitFlags: { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + __debugGetText: { value: function (includeTrivia) { if (ts.nodeIsSynthesized(this)) return ""; @@ -51018,20 +53332,20 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); break; - case 237 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + case 238 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -51047,27 +53361,27 @@ var ts; // export { x, y } for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + if (!uniqueExports.get(ts.idText(specifier.name))) { var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + exportSpecifiers.add(ts.idText(name), specifier); var decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + uniqueExports.set(ts.idText(specifier.name), true); exportedNames = ts.append(exportedNames, specifier.name); } } } break; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -51075,7 +53389,7 @@ var ts; } } break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -51087,15 +53401,15 @@ var ts; else { // export function x() { } var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (!uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } } break; - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -51107,9 +53421,9 @@ var ts; else { // export class x { } var name = node.name; - if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.idText(name))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + uniqueExports.set(ts.idText(name), true); exportedNames = ts.append(exportedNames, name); } } @@ -51137,8 +53451,9 @@ var ts; } } else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { - uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + var text = ts.idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); exportedNames = ts.append(exportedNames, decl.name); } } @@ -51155,6 +53470,19 @@ var ts; } return values; } + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable + * - this is mostly subjective beyond the requirement that the expression not be sideeffecting + */ + function isSimpleCopiableExpression(expression) { + return expression.kind === 9 /* StringLiteral */ || + expression.kind === 8 /* NumericLiteral */ || + expression.kind === 13 /* NoSubstitutionTemplateLiteral */ || + ts.isKeyword(expression.kind) || + ts.isIdentifier(expression); + } + ts.isSimpleCopiableExpression = isSimpleCopiableExpression; })(ts || (ts = {})); /// /// @@ -51514,7 +53842,7 @@ var ts; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); + var name = ts.createIdentifier(ts.idText(propertyName)); return ts.createPropertyAccess(value, name); } } @@ -51626,7 +53954,7 @@ var ts; ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; - ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; @@ -51637,6 +53965,7 @@ var ts; var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); // Save the previous transformation hooks. @@ -51646,8 +53975,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(180 /* ElementAccessExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -51669,6 +53998,11 @@ var ts; * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; + /** + * Tracks what computed name expressions originating from elided names must be inlined + * at the next execution site, in document order + */ + var pendingExpressions; return transformSourceFile; /** * Transform TypeScript-specific syntax in a SourceFile. @@ -51711,15 +54045,15 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 265 /* SourceFile */: - case 235 /* CaseBlock */: - case 234 /* ModuleBlock */: - case 207 /* Block */: + case 269 /* SourceFile */: + case 236 /* CaseBlock */: + case 235 /* ModuleBlock */: + case 208 /* Block */: currentScope = node; currentScopeFirstDeclarationsOfName = undefined; break; - case 229 /* ClassDeclaration */: - case 228 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + case 229 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -51731,7 +54065,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 229 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 230 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); } break; } @@ -51775,10 +54109,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -51789,16 +54123,23 @@ var ts; if (parsed !== node) { // If the node has been transformed by a `before` transformer, perform no ellision on it // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, + // and will trigger debug failures when debug verbosity is turned up + if (node.transformFlags & 2 /* ContainsTypeScript */) { + // This node contains TypeScript, so we should visit its children. + return ts.visitEachChild(node, visitor, context); + } + // Otherwise, we can just return the node return node; } switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -51818,11 +54159,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 244 /* ExportDeclaration */ || - node.kind === 238 /* ImportDeclaration */ || - node.kind === 239 /* ImportClause */ || - (node.kind === 237 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 248 /* ExternalModuleReference */)) { + if (node.kind === 245 /* ExportDeclaration */ || + node.kind === 239 /* ImportDeclaration */ || + node.kind === 240 /* ImportClause */ || + (node.kind === 238 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 249 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -51852,19 +54193,19 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 149 /* PropertyDeclaration */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 158 /* IndexSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 206 /* SemicolonClassElement */: + case 207 /* SemicolonClassElement */: return node; default: ts.Debug.failBadSyntaxKind(node); @@ -51904,11 +54245,11 @@ var ts; case 124 /* DeclareKeyword */: case 131 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 163 /* TypeLiteral */: - case 158 /* TypePredicate */: - case 145 /* TypeParameter */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 164 /* TypeLiteral */: + case 159 /* TypePredicate */: + case 146 /* TypeParameter */: case 119 /* AnyKeyword */: case 122 /* BooleanKeyword */: case 136 /* StringKeyword */: @@ -51916,37 +54257,39 @@ var ts; case 130 /* NeverKeyword */: case 105 /* VoidKeyword */: case 137 /* SymbolKeyword */: - case 161 /* ConstructorType */: - case 160 /* FunctionType */: - case 162 /* TypeQuery */: - case 159 /* TypeReference */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - case 169 /* ThisType */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 173 /* LiteralType */: + case 162 /* ConstructorType */: + case 161 /* FunctionType */: + case 163 /* TypeQuery */: + case 160 /* TypeReference */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + case 170 /* ThisType */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 174 /* LiteralType */: // TypeScript type nodes are elided. - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: // TypeScript index signatures are elided. - case 147 /* Decorator */: + case 148 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 231 /* TypeAliasDeclaration */: - // TypeScript type-only declarations are elided. - case 149 /* PropertyDeclaration */: - // TypeScript property declarations are elided. - case 236 /* NamespaceExportDeclaration */: + case 232 /* TypeAliasDeclaration */: + // TypeScript type-only declarations are elided. + return undefined; + case 150 /* PropertyDeclaration */: + // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects + return visitPropertyDeclaration(node); + case 237 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 152 /* Constructor */: + case 153 /* Constructor */: return visitConstructor(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -51957,7 +54300,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -51968,35 +54311,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 146 /* Parameter */: + case 147 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -52006,33 +54349,33 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return visitNewExpression(node); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -52041,7 +54384,7 @@ var ts; } } function visitSourceFile(node) { - var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && + var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } @@ -52068,8 +54411,9 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - if (ts.getClassExtendsHeritageClauseElement(node)) - facts |= 64 /* HasExtendsClause */; + var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) + facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) facts |= 2 /* HasConstructorDecorators */; if (ts.childIsDecorated(node)) @@ -52096,6 +54440,8 @@ var ts; * @param node The node to transform. */ function visitClassDeclaration(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { @@ -52106,6 +54452,11 @@ var ts; ? createClassDeclarationHeadWithDecorators(node, name, facts) : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; + // Write any pending expressions from elided or moved computed property names + if (ts.some(pendingExpressions)) { + statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + } + pendingExpressions = savedPendingExpressions; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: @@ -52193,7 +54544,7 @@ var ts; : undefined; var classDeclaration = ts.createClassDeclaration( /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); @@ -52302,7 +54653,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); + var members = transformClassMembers(node, (facts & 64 /* IsDerivedClass */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -52328,6 +54679,8 @@ var ts; * @param node The node to transform. */ function visitClassExpression(node) { + var savedPendingExpressions = pendingExpressions; + pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 85 /* ExtendsKeyword */; })); @@ -52336,7 +54689,7 @@ var ts; /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, node); - if (staticProperties.length > 0) { + if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; var temp = ts.createTempVariable(hoistVariableDeclaration); if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { @@ -52348,21 +54701,25 @@ var ts; // the body of a class with static initializers. ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); + // Add any pending expressions leftover from elided or relocated computed property names + ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine)); + pendingExpressions = savedPendingExpressions; ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); return ts.inlineExpressions(expressions); } + pendingExpressions = savedPendingExpressions; return classExpression; } /** * Transforms the members of a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformClassMembers(node, hasExtendsClause) { + function transformClassMembers(node, isDerivedClass) { var members = []; - var constructor = transformConstructor(node, hasExtendsClause); + var constructor = transformConstructor(node, isDerivedClass); if (constructor) { members.push(constructor); } @@ -52373,9 +54730,9 @@ var ts; * Transforms (or creates) a constructor for a class. * * @param node The current class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructor(node, hasExtendsClause) { + function transformConstructor(node, isDerivedClass) { // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it @@ -52388,7 +54745,7 @@ var ts; return ts.visitEachChild(constructor, visitor, context); } var parameters = transformConstructorParameters(constructor); - var body = transformConstructorBody(node, constructor, hasExtendsClause); + var body = transformConstructorBody(node, constructor, isDerivedClass); // constructor(${parameters}) { // ${body} // } @@ -52401,7 +54758,6 @@ var ts; * parameter property assignments or instance property initializers. * * @param constructor The constructor declaration. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ function transformConstructorParameters(constructor) { // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: @@ -52428,9 +54784,9 @@ var ts; * * @param node The current class. * @param constructor The current class constructor. - * @param hasExtendsClause A value indicating whether the class has an extends clause. + * @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'. */ - function transformConstructorBody(node, constructor, hasExtendsClause) { + function transformConstructorBody(node, constructor, isDerivedClass) { var statements = []; var indexOfFirstStatement = 0; resumeLexicalEnvironment(); @@ -52451,7 +54807,7 @@ var ts; var propertyAssignments = getParametersWithPropertyAssignments(constructor); ts.addRange(statements, ts.map(propertyAssignments, transformParameterWithPropertyAssignment)); } - else if (hasExtendsClause) { + else if (isDerivedClass) { // Add a synthetic `super` call: // // super(...arguments); @@ -52498,7 +54854,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -52569,7 +54925,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 149 /* PropertyDeclaration */ + return member.kind === 150 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -52599,7 +54955,7 @@ var ts; for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { var property = properties_11[_i]; var expression = transformInitializedProperty(property, receiver); - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); expressions.push(expression); @@ -52613,7 +54969,10 @@ var ts; * @param receiver The object receiving the property assignment. */ function transformInitializedProperty(property, receiver) { - var propertyName = visitPropertyNameOfClassElement(property); + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); return ts.createAssignment(memberAccess, initializer); @@ -52627,7 +54986,7 @@ var ts; * the class. */ function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? isStaticDecoratedClassElement : isInstanceDecoratedClassElement); + return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); } /** * Determines whether a class member is a static member of a class that is decorated, or @@ -52635,8 +54994,8 @@ var ts; * * @param member The class member. */ - function isStaticDecoratedClassElement(member) { - return isDecoratedClassElement(member, /*isStatic*/ true); + function isStaticDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ true, parent); } /** * Determines whether a class member is an instance member of a class that is decorated, @@ -52644,8 +55003,8 @@ var ts; * * @param member The class member. */ - function isInstanceDecoratedClassElement(member) { - return isDecoratedClassElement(member, /*isStatic*/ false); + function isInstanceDecoratedClassElement(member, parent) { + return isDecoratedClassElement(member, /*isStatic*/ false, parent); } /** * Determines whether a class member is either a static or an instance member of a class @@ -52653,8 +55012,8 @@ var ts; * * @param member The class member. */ - function isDecoratedClassElement(member, isStatic) { - return ts.nodeOrChildIsDecorated(member) + function isDecoratedClassElement(member, isStatic, parent) { + return ts.nodeOrChildIsDecorated(member, parent) && isStatic === ts.hasModifier(member, 32 /* Static */); } /** @@ -52704,12 +55063,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -52803,8 +55162,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { - var member = members_3[_i]; + for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { + var member = members_4[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -52862,8 +55221,12 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 149 /* PropertyDeclaration */ + ? member.kind === 150 /* PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. : ts.createNull() : undefined; var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); @@ -52981,10 +55344,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 149 /* PropertyDeclaration */; + return kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */ + || kind === 150 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -52994,7 +55357,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 151 /* MethodDeclaration */; + return node.kind === 152 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -53005,12 +55368,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return true; } return false; @@ -53022,15 +55385,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 149 /* PropertyDeclaration */: - case 146 /* Parameter */: - case 153 /* GetAccessor */: + case 150 /* PropertyDeclaration */: + case 147 /* Parameter */: + case 154 /* GetAccessor */: return serializeTypeNode(node.type); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 151 /* MethodDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 152 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -53067,7 +55430,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 153 /* GetAccessor */) { + if (container && node.kind === 154 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -53117,22 +55480,22 @@ var ts; case 95 /* NullKeyword */: case 130 /* NeverKeyword */: return ts.createVoidZero(); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return ts.createIdentifier("Function"); - case 164 /* ArrayType */: - case 165 /* TupleType */: + case 165 /* ArrayType */: + case 166 /* TupleType */: return ts.createIdentifier("Array"); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: case 122 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); case 136 /* StringKeyword */: return ts.createIdentifier("String"); case 134 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 173 /* LiteralType */: + case 174 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); @@ -53152,18 +55515,18 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return serializeTypeReferenceNode(node); - case 167 /* IntersectionType */: - case 166 /* UnionType */: + case 168 /* IntersectionType */: + case 167 /* UnionType */: return serializeUnionOrIntersectionType(node); - case 162 /* TypeQuery */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 163 /* TypeLiteral */: + case 163 /* TypeQuery */: + case 171 /* TypeOperator */: + case 172 /* IndexedAccessType */: + case 173 /* MappedType */: + case 164 /* TypeLiteral */: case 119 /* AnyKeyword */: - case 169 /* ThisType */: + case 170 /* ThisType */: break; default: ts.Debug.failBadSyntaxKind(node); @@ -53177,6 +55540,15 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; + while (typeNode.kind === 169 /* ParenthesizedType */) { + typeNode = typeNode.type; // Skip parens if need be + } + if (typeNode.kind === 130 /* NeverKeyword */) { + continue; // Always elide `never` from the union/intersection if possible + } + if (!strictNullChecks && (typeNode.kind === 95 /* NullKeyword */ || typeNode.kind === 139 /* UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } var serializedIndividual = serializeTypeNode(typeNode); if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately @@ -53196,7 +55568,7 @@ var ts; } } // If we were able to find common type, use it - return serializedUnion; + return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never } /** * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with @@ -53255,7 +55627,7 @@ var ts; return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } return name; - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -53287,6 +55659,15 @@ var ts; function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); } + /** + * A simple inlinable expression is an expression which can be copied into multiple locations + * without risk of repeating any sideeffects and whose value could not possibly change between + * any such locations + */ + function isSimpleInlineableExpression(expression) { + return !ts.isIdentifier(expression) && ts.isSimpleCopiableExpression(expression) || + ts.isWellKnownSymbolSyntactically(expression); + } /** * Gets an expression that represents a property name. For a computed property, a * name is generated for the node. @@ -53296,17 +55677,36 @@ var ts; function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; if (ts.isComputedPropertyName(name)) { - return generateNameForComputedPropertyName + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? ts.getGeneratedNameForNode(name) : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.getSynthesizedClone(name); } } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist, omitSimple) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = isSimpleInlineableExpression(innerExpression); + if (!inlinable && shouldHoist) { + var generatedName = ts.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return ts.createAssignment(generatedName, expression); + } + return (omitSimple && (inlinable || ts.isIdentifier(innerExpression))) ? undefined : expression; + } + } /** * Visits the property name of a class element, for use when emitting property * initializers. For a computed property on a node with decorators, a temporary @@ -53316,14 +55716,14 @@ var ts; */ function visitPropertyNameOfClassElement(member) { var name = member.name; - if (ts.isComputedPropertyName(name)) { - var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - if (member.decorators) { - var generatedName = ts.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); - expression = ts.createAssignment(generatedName, expression); + var expr = getPropertyNameExpressionIfNeeded(name, ts.some(member.decorators), /*omitSimple*/ false); + if (expr) { + // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order + if (ts.some(pendingExpressions)) { + expr = ts.inlineExpressions(pendingExpressions.concat([expr])); + pendingExpressions.length = 0; } - return ts.updateComputedPropertyName(name, expression); + return ts.updateComputedPropertyName(name, expr); } else { return name; @@ -53366,6 +55766,13 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } + function visitPropertyDeclaration(node) { + var expr = getPropertyNameExpressionIfNeeded(node.name, ts.some(node.decorators) || !!node.initializer, /*omitSimple*/ true); + if (expr && !isSimpleInlineableExpression(expr)) { + (pendingExpressions || (pendingExpressions = [])).push(expr); + } + return undefined; + } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -53378,7 +55785,7 @@ var ts; * This function will be called when one of the following conditions are met: * - The node is an overload * - The node is marked as abstract, public, private, protected, or readonly - * - The node has both a decorator and a computed property name + * - The node has a computed property name * * @param node The method node. */ @@ -53413,7 +55820,7 @@ var ts; * * This function will be called when one of the following conditions are met: * - The node is marked as abstract, public, private, or protected - * - The node has both a decorator and a computed property name + * - The node has a computed property name * * @param node The get accessor node. */ @@ -53437,7 +55844,7 @@ var ts; * * This function will be called when one of the following conditions are met: * - The node is marked as abstract, public, private, or protected - * - The node has both a decorator and a computed property name + * - The node has a computed property name * * @param node The set accessor node. */ @@ -53795,12 +56202,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentScope.kind === 265 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentScope.kind === 269 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 232 /* EnumDeclaration */) { + if (node.kind === 233 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -53919,7 +56326,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 234 /* ModuleBlock */) { + if (body.kind === 235 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -53965,13 +56372,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 234 /* ModuleBlock */) { + if (body.kind !== 235 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 233 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 234 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -54012,7 +56419,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 240 /* NamespaceImport */) { + if (node.kind === 241 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -54208,7 +56615,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -54244,16 +56651,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(262 /* ShorthandPropertyAssignment */); + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(233 /* ModuleDeclaration */); + context.enableEmitNotification(234 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 233 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 234 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 232 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 233 /* EnumDeclaration */; } /** * Hook for node emit. @@ -54314,9 +56721,9 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -54354,9 +56761,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 265 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 233 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 232 /* EnumDeclaration */); + if (container && container.kind !== 269 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 234 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 233 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -54494,15 +56901,15 @@ var ts; case 120 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return visitAwaitExpression(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -54587,7 +56994,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 187 /* ArrowFunction */; + var isArrowFunction = node.kind === 188 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -54652,15 +57059,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(181 /* CallExpression */); - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(180 /* ElementAccessExpression */); + context.enableSubstitution(182 /* CallExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(229 /* ClassDeclaration */); - context.enableEmitNotification(151 /* MethodDeclaration */); - context.enableEmitNotification(153 /* GetAccessor */); - context.enableEmitNotification(154 /* SetAccessor */); - context.enableEmitNotification(152 /* Constructor */); + context.enableEmitNotification(230 /* ClassDeclaration */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(153 /* Constructor */); } } /** @@ -54700,18 +57107,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -54736,11 +57143,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 /* ClassDeclaration */ - || kind === 152 /* Constructor */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */; + return kind === 230 /* ClassDeclaration */ + || kind === 153 /* Constructor */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -54769,7 +57176,7 @@ var ts; /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getHelperName("__awaiter"), /*typeArguments*/ undefined, [ ts.createThis(), @@ -54838,45 +57245,45 @@ var ts; return node; } switch (node.kind) { - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return visitAwaitExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return visitVoidExpression(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return visitConstructorDeclaration(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return visitArrowFunction(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return visitParameter(node); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return visitExpressionStatement(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -54899,7 +57306,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 216 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); @@ -54911,7 +57318,7 @@ var ts; var objects = []; for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { var e = elements_3[_i]; - if (e.kind === 263 /* SpreadAssignment */) { + if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -54923,7 +57330,7 @@ var ts; if (!chunkObject) { chunkObject = []; } - if (e.kind === 261 /* PropertyAssignment */) { + if (e.kind === 265 /* PropertyAssignment */) { var p = e; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } @@ -54945,7 +57352,7 @@ var ts; // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 178 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 179 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -55253,15 +57660,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(181 /* CallExpression */); - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(180 /* ElementAccessExpression */); + context.enableSubstitution(182 /* CallExpression */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(181 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(229 /* ClassDeclaration */); - context.enableEmitNotification(151 /* MethodDeclaration */); - context.enableEmitNotification(153 /* GetAccessor */); - context.enableEmitNotification(154 /* SetAccessor */); - context.enableEmitNotification(152 /* Constructor */); + context.enableEmitNotification(230 /* ClassDeclaration */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(153 /* Constructor */); } } /** @@ -55301,18 +57708,18 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return substituteCallExpression(node); } return node; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); } return node; } @@ -55337,11 +57744,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 229 /* ClassDeclaration */ - || kind === 152 /* Constructor */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */; + return kind === 230 /* ClassDeclaration */ + || kind === 153 /* Constructor */ + || kind === 152 /* MethodDeclaration */ + || kind === 154 /* GetAccessor */ + || kind === 155 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -55427,6 +57834,7 @@ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); + var currentSourceFile; return transformSourceFile; /** * Transform JSX-specific syntax in a SourceFile. @@ -55437,6 +57845,7 @@ var ts; if (node.isDeclarationFile) { return node; } + currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); return visited; @@ -55451,11 +57860,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 249 /* JsxElement */: + case 250 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 256 /* JsxExpression */: + case 254 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ false); + case 260 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -55465,12 +57876,14 @@ var ts; switch (node.kind) { case 10 /* JsxText */: return visitJsxText(node); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return visitJsxExpression(node); - case 249 /* JsxElement */: + case 250 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); + case 254 /* JsxFragment */: + return visitJsxFragment(node, /*isChild*/ true); default: ts.Debug.failBadSyntaxKind(node); return undefined; @@ -55482,6 +57895,9 @@ var ts; function visitJsxSelfClosingElement(node, isChild) { return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node); } + function visitJsxFragment(node, isChild) { + return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); + } function visitJsxOpeningLikeElement(node, children, isChild, location) { var tagName = getTagName(node); var objectProperties; @@ -55514,6 +57930,13 @@ var ts; } return element; } + function visitJsxOpeningFragment(node, children, isChild, location) { + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + if (isChild) { + ts.startOnNewLine(element); + } + return element; + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -55527,10 +57950,13 @@ var ts; return ts.createTrue(); } else if (node.kind === 9 /* StringLiteral */) { - var decoded = tryDecodeEntities(node.text); - return decoded ? ts.setTextRange(ts.createLiteral(decoded), node) : node; + // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which + // Need to be escaped to be handled correctly in a normal string + var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); + return ts.setTextRange(literal, node); } - else if (node.kind === 256 /* JsxExpression */) { + else if (node.kind === 260 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -55588,7 +58014,9 @@ var ts; } } return firstNonWhitespace !== -1 + // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace. ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) + // Last line was all whitespace, so ignore it : acc; } function addLineOfJsxText(acc, trimmedLine) { @@ -55622,13 +58050,13 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 249 /* JsxElement */) { + if (node.kind === 250 /* JsxElement */) { return getTagName(node.openingElement); } else { var name = node.tagName; if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(ts.idText(name)); } else { return ts.createExpressionFromEntityName(name); @@ -55642,11 +58070,12 @@ var ts; */ function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { + var text = ts.idText(name); + if (/^[A-Za-z_]\w*$/.test(text)) { return name; } else { - return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); + return ts.createLiteral(text); } } function visitJsxExpression(node) { @@ -55655,259 +58084,259 @@ var ts; } ts.transformJsx = transformJsx; var entities = ts.createMapFromTemplate({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 + quot: 0x0022, + amp: 0x0026, + apos: 0x0027, + lt: 0x003C, + gt: 0x003E, + nbsp: 0x00A0, + iexcl: 0x00A1, + cent: 0x00A2, + pound: 0x00A3, + curren: 0x00A4, + yen: 0x00A5, + brvbar: 0x00A6, + sect: 0x00A7, + uml: 0x00A8, + copy: 0x00A9, + ordf: 0x00AA, + laquo: 0x00AB, + not: 0x00AC, + shy: 0x00AD, + reg: 0x00AE, + macr: 0x00AF, + deg: 0x00B0, + plusmn: 0x00B1, + sup2: 0x00B2, + sup3: 0x00B3, + acute: 0x00B4, + micro: 0x00B5, + para: 0x00B6, + middot: 0x00B7, + cedil: 0x00B8, + sup1: 0x00B9, + ordm: 0x00BA, + raquo: 0x00BB, + frac14: 0x00BC, + frac12: 0x00BD, + frac34: 0x00BE, + iquest: 0x00BF, + Agrave: 0x00C0, + Aacute: 0x00C1, + Acirc: 0x00C2, + Atilde: 0x00C3, + Auml: 0x00C4, + Aring: 0x00C5, + AElig: 0x00C6, + Ccedil: 0x00C7, + Egrave: 0x00C8, + Eacute: 0x00C9, + Ecirc: 0x00CA, + Euml: 0x00CB, + Igrave: 0x00CC, + Iacute: 0x00CD, + Icirc: 0x00CE, + Iuml: 0x00CF, + ETH: 0x00D0, + Ntilde: 0x00D1, + Ograve: 0x00D2, + Oacute: 0x00D3, + Ocirc: 0x00D4, + Otilde: 0x00D5, + Ouml: 0x00D6, + times: 0x00D7, + Oslash: 0x00D8, + Ugrave: 0x00D9, + Uacute: 0x00DA, + Ucirc: 0x00DB, + Uuml: 0x00DC, + Yacute: 0x00DD, + THORN: 0x00DE, + szlig: 0x00DF, + agrave: 0x00E0, + aacute: 0x00E1, + acirc: 0x00E2, + atilde: 0x00E3, + auml: 0x00E4, + aring: 0x00E5, + aelig: 0x00E6, + ccedil: 0x00E7, + egrave: 0x00E8, + eacute: 0x00E9, + ecirc: 0x00EA, + euml: 0x00EB, + igrave: 0x00EC, + iacute: 0x00ED, + icirc: 0x00EE, + iuml: 0x00EF, + eth: 0x00F0, + ntilde: 0x00F1, + ograve: 0x00F2, + oacute: 0x00F3, + ocirc: 0x00F4, + otilde: 0x00F5, + ouml: 0x00F6, + divide: 0x00F7, + oslash: 0x00F8, + ugrave: 0x00F9, + uacute: 0x00FA, + ucirc: 0x00FB, + uuml: 0x00FC, + yacute: 0x00FD, + thorn: 0x00FE, + yuml: 0x00FF, + OElig: 0x0152, + oelig: 0x0153, + Scaron: 0x0160, + scaron: 0x0161, + Yuml: 0x0178, + fnof: 0x0192, + circ: 0x02C6, + tilde: 0x02DC, + Alpha: 0x0391, + Beta: 0x0392, + Gamma: 0x0393, + Delta: 0x0394, + Epsilon: 0x0395, + Zeta: 0x0396, + Eta: 0x0397, + Theta: 0x0398, + Iota: 0x0399, + Kappa: 0x039A, + Lambda: 0x039B, + Mu: 0x039C, + Nu: 0x039D, + Xi: 0x039E, + Omicron: 0x039F, + Pi: 0x03A0, + Rho: 0x03A1, + Sigma: 0x03A3, + Tau: 0x03A4, + Upsilon: 0x03A5, + Phi: 0x03A6, + Chi: 0x03A7, + Psi: 0x03A8, + Omega: 0x03A9, + alpha: 0x03B1, + beta: 0x03B2, + gamma: 0x03B3, + delta: 0x03B4, + epsilon: 0x03B5, + zeta: 0x03B6, + eta: 0x03B7, + theta: 0x03B8, + iota: 0x03B9, + kappa: 0x03BA, + lambda: 0x03BB, + mu: 0x03BC, + nu: 0x03BD, + xi: 0x03BE, + omicron: 0x03BF, + pi: 0x03C0, + rho: 0x03C1, + sigmaf: 0x03C2, + sigma: 0x03C3, + tau: 0x03C4, + upsilon: 0x03C5, + phi: 0x03C6, + chi: 0x03C7, + psi: 0x03C8, + omega: 0x03C9, + thetasym: 0x03D1, + upsih: 0x03D2, + piv: 0x03D6, + ensp: 0x2002, + emsp: 0x2003, + thinsp: 0x2009, + zwnj: 0x200C, + zwj: 0x200D, + lrm: 0x200E, + rlm: 0x200F, + ndash: 0x2013, + mdash: 0x2014, + lsquo: 0x2018, + rsquo: 0x2019, + sbquo: 0x201A, + ldquo: 0x201C, + rdquo: 0x201D, + bdquo: 0x201E, + dagger: 0x2020, + Dagger: 0x2021, + bull: 0x2022, + hellip: 0x2026, + permil: 0x2030, + prime: 0x2032, + Prime: 0x2033, + lsaquo: 0x2039, + rsaquo: 0x203A, + oline: 0x203E, + frasl: 0x2044, + euro: 0x20AC, + image: 0x2111, + weierp: 0x2118, + real: 0x211C, + trade: 0x2122, + alefsym: 0x2135, + larr: 0x2190, + uarr: 0x2191, + rarr: 0x2192, + darr: 0x2193, + harr: 0x2194, + crarr: 0x21B5, + lArr: 0x21D0, + uArr: 0x21D1, + rArr: 0x21D2, + dArr: 0x21D3, + hArr: 0x21D4, + forall: 0x2200, + part: 0x2202, + exist: 0x2203, + empty: 0x2205, + nabla: 0x2207, + isin: 0x2208, + notin: 0x2209, + ni: 0x220B, + prod: 0x220F, + sum: 0x2211, + minus: 0x2212, + lowast: 0x2217, + radic: 0x221A, + prop: 0x221D, + infin: 0x221E, + ang: 0x2220, + and: 0x2227, + or: 0x2228, + cap: 0x2229, + cup: 0x222A, + int: 0x222B, + there4: 0x2234, + sim: 0x223C, + cong: 0x2245, + asymp: 0x2248, + ne: 0x2260, + equiv: 0x2261, + le: 0x2264, + ge: 0x2265, + sub: 0x2282, + sup: 0x2283, + nsub: 0x2284, + sube: 0x2286, + supe: 0x2287, + oplus: 0x2295, + otimes: 0x2297, + perp: 0x22A5, + sdot: 0x22C5, + lceil: 0x2308, + rceil: 0x2309, + lfloor: 0x230A, + rfloor: 0x230B, + lang: 0x2329, + rang: 0x232A, + loz: 0x25CA, + spades: 0x2660, + clubs: 0x2663, + hearts: 0x2665, + diams: 0x2666 }); })(ts || (ts = {})); /// @@ -55929,7 +58358,7 @@ var ts; return node; } switch (node.kind) { - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -56114,6 +58543,10 @@ var ts; var currentSourceFile; var currentText; var hierarchyFacts; + var taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } /** * Used to track if we are emitting body of the converted loop */ @@ -56135,6 +58568,7 @@ var ts; ts.addEmitHelpers(visited, context.readEmitHelpers()); currentSourceFile = undefined; currentText = undefined; + taggedTemplateStringDeclarations = undefined; hierarchyFacts = 0 /* None */; return visited; } @@ -56160,13 +58594,13 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ - && node.kind === 219 /* ReturnStatement */ + && node.kind === 220 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 207 /* Block */))) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 208 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } @@ -56194,63 +58628,63 @@ var ts; switch (node.kind) { case 115 /* StaticKeyword */: return undefined; // elide static keyword - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return visitClassExpression(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return visitParameter(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return visitArrowFunction(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return visitVariableDeclaration(node); case 71 /* Identifier */: return visitIdentifier(node); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return visitCaseBlock(node); - case 207 /* Block */: + case 208 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return visitExpressionStatement(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitCatchClause(node); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return visitNewExpression(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); case 13 /* NoSubstitutionTemplateLiteral */: case 14 /* TemplateHead */: @@ -56261,28 +58695,28 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return visitTemplateExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return visitSpreadElement(node); case 97 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 99 /* ThisKeyword */: return visitThisKeyword(node); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return visitMetaProperty(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return visitAccessorDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -56296,6 +58730,9 @@ var ts; addCaptureThisForNodeIfNeeded(statements, node); statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); + } ts.addRange(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); @@ -56366,13 +58803,13 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 218 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || + var jump = node.kind === 219 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; if (!node.label) { - if (node.kind === 218 /* BreakStatement */) { + if (node.kind === 219 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -56383,13 +58820,13 @@ var ts; } } else { - if (node.kind === 218 /* BreakStatement */) { + if (node.kind === 219 /* BreakStatement */) { labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); } else { labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -56510,9 +58947,7 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (ts.getEmitFlags(node) & 65536 /* Indented */) { - ts.setEmitFlags(classFunction, 65536 /* Indented */); - } + ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */); // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); @@ -56685,17 +59120,17 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 219 /* ReturnStatement */) { + if (statement.kind === 220 /* ReturnStatement */) { return true; } - else if (statement.kind === 211 /* IfStatement */) { + else if (statement.kind === 212 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 207 /* Block */) { + else if (statement.kind === 208 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -56753,7 +59188,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -56763,8 +59198,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 194 /* BinaryExpression */ - || superCallExpression.left.kind !== 181 /* CallExpression */) { + if (superCallExpression.kind !== 195 /* BinaryExpression */ + || superCallExpression.left.kind !== 182 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -56895,7 +59330,7 @@ var ts; var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter)) ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); - statement.startsOnNewLine = true; + ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); statements.push(statement); @@ -56961,7 +59396,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 187 /* ArrowFunction */) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 188 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -56981,22 +59416,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return statements; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 152 /* Constructor */: + case 153 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); @@ -57028,20 +59463,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 206 /* SemicolonClassElement */: + case 207 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 152 /* Constructor */: + case 153 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -57140,7 +59575,7 @@ var ts; ts.createObjectLiteral(properties, /*multiLine*/ true) ]); if (startsOnNewLine) { - call.startsOnNewLine = true; + ts.startOnNewLine(call); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; @@ -57233,7 +59668,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 229 /* FunctionDeclaration */ || node.kind === 187 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -57281,7 +59716,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 187 /* ArrowFunction */); + ts.Debug.assert(node.kind === 188 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -57348,9 +59783,9 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); @@ -57369,9 +59804,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -57557,10 +59992,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); + convertedLoopState.labels.set(ts.idText(node.label), true); } function resetLabel(node) { - convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); + convertedLoopState.labels.set(ts.idText(node.label), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -57573,14 +60008,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -57768,7 +60203,7 @@ var ts; && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 144 /* ComputedPropertyName */) { + if (property.name.kind === 145 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -57784,7 +60219,7 @@ var ts; var expressions = []; var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); if (node.multiLine) { - assignment.startsOnNewLine = true; + ts.startOnNewLine(assignment); } expressions.push(assignment); addObjectLiteralMembers(expressions, node, temp, numInitialProperties); @@ -57840,11 +60275,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 227 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 228 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -58104,7 +60539,7 @@ var ts; else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); + var outParamName = ts.createUniqueName("out_" + ts.idText(name)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -58124,20 +60559,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); } break; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -58157,7 +60592,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -58172,7 +60607,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name)); ts.setTextRange(expression, property); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } return expression; } @@ -58188,7 +60623,7 @@ var ts; var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { - expression.startsOnNewLine = true; + ts.startOnNewLine(expression); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; @@ -58247,7 +60682,7 @@ var ts; if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 153 /* GetAccessor */) { + if (node.kind === 154 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -58522,7 +60957,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 178 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -58577,7 +61012,7 @@ var ts; * @param node A string literal. */ function visitNumericLiteral(node) { - if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { return ts.setTextRange(ts.createNumericLiteral(node.text), node); } return node; @@ -58590,10 +61025,10 @@ var ts; function visitTaggedTemplateExpression(node) { // Visit the tag expression var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - // Allocate storage for the template site object - var temp = ts.createTempVariable(hoistVariableDeclaration); // Build up the template arguments and the raw and cooked strings for the template. - var templateArguments = [temp]; + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; var cookedStrings = []; var rawStrings = []; var template = node.template; @@ -58611,14 +61046,19 @@ var ts; templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); } } - // NOTE: The parentheses here is entirely optional as we are now able to auto- - // parenthesize when rebuilding the tree. This should be removed in a - // future version. It is here for now to match our existing emit. - return ts.createParen(ts.inlineExpressions([ - ts.createAssignment(temp, ts.createArrayLiteral(cookedStrings)), - ts.createAssignment(ts.createPropertyAccess(temp, "raw"), ts.createArrayLiteral(rawStrings)), - ts.createCall(tag, /*typeArguments*/ undefined, templateArguments) - ])); + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); } /** * Creates an ES5 compatible literal from an ES6 template literal. @@ -58780,13 +61220,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(152 /* Constructor */); - context.enableEmitNotification(151 /* MethodDeclaration */); - context.enableEmitNotification(153 /* GetAccessor */); - context.enableEmitNotification(154 /* SetAccessor */); - context.enableEmitNotification(187 /* ArrowFunction */); - context.enableEmitNotification(186 /* FunctionExpression */); - context.enableEmitNotification(228 /* FunctionDeclaration */); + context.enableEmitNotification(153 /* Constructor */); + context.enableEmitNotification(152 /* MethodDeclaration */); + context.enableEmitNotification(154 /* GetAccessor */); + context.enableEmitNotification(155 /* SetAccessor */); + context.enableEmitNotification(188 /* ArrowFunction */); + context.enableEmitNotification(187 /* FunctionExpression */); + context.enableEmitNotification(229 /* FunctionDeclaration */); } } /** @@ -58828,10 +61268,10 @@ var ts; function isNameOfDeclarationWithCollidingName(node) { var parent = node.parent; switch (parent.kind) { - case 176 /* BindingElement */: - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 227 /* VariableDeclaration */: return parent.name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -58913,11 +61353,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 210 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 211 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 181 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 182 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -58925,7 +61365,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 198 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 199 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -58941,12 +61381,26 @@ var ts; ts.createIdentifier("_super") ]); } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return ts.createCall(ts.getHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } var extendsHelper = { name: "typescript:extends", scoped: false, priority: 0, text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; + var templateObjectHelper = { + name: "typescript:makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; })(ts || (ts = {})); /// /// @@ -58966,15 +61420,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(251 /* JsxOpeningElement */); - context.enableEmitNotification(252 /* JsxClosingElement */); - context.enableEmitNotification(250 /* JsxSelfClosingElement */); + context.enableEmitNotification(252 /* JsxOpeningElement */); + context.enableEmitNotification(253 /* JsxClosingElement */); + context.enableEmitNotification(251 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(179 /* PropertyAccessExpression */); - context.enableSubstitution(261 /* PropertyAssignment */); + context.enableSubstitution(180 /* PropertyAccessExpression */); + context.enableSubstitution(265 /* PropertyAssignment */); return transformSourceFile; /** * Transforms an ES5 source file to ES3. @@ -58993,9 +61447,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 251 /* JsxOpeningElement */: - case 252 /* JsxClosingElement */: - case 250 /* JsxSelfClosingElement */: + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -59051,7 +61505,7 @@ var ts; * @param name An Identifier */ function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -59328,13 +61782,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 212 /* DoStatement */: + case 213 /* DoStatement */: return visitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return visitWhileStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -59347,24 +61801,24 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return visitAccessorDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return visitBreakStatement(node); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return visitContinueStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return visitReturnStatement(node); default: if (node.transformFlags & 16777216 /* ContainsYield */) { @@ -59385,21 +61839,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return visitBinaryExpression(node); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return visitConditionalExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return visitYieldExpression(node); - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return visitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -59412,9 +61866,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return visitFunctionExpression(node); default: ts.Debug.failBadSyntaxKind(node); @@ -59642,7 +62096,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -59654,7 +62108,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -59938,7 +62392,7 @@ var ts; var visited = ts.visitNode(expression, visitor, ts.isExpression); if (visited) { if (multiLine) { - visited.startsOnNewLine = true; + ts.startOnNewLine(visited); } expressions.push(visited); } @@ -59969,7 +62423,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (ts.forEach(node.arguments, containsYield)) { + if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) { // [source] // a.b(1, yield, 2); // @@ -60030,35 +62484,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 207 /* Block */: + case 208 /* Block */: return transformAndEmitBlock(node); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return transformAndEmitIfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return transformAndEmitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return transformAndEmitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return transformAndEmitWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -60381,7 +62835,7 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, /*location*/ node); } @@ -60392,7 +62846,7 @@ var ts; } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findContinueTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -60400,7 +62854,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); + var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined); if (label > 0) { emitBreak(label, /*location*/ node); } @@ -60411,7 +62865,7 @@ var ts; } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); + var label = findBreakTarget(node.label && ts.idText(node.label)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -60488,7 +62942,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 258 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 262 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -60501,7 +62955,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 257 /* CaseClause */) { + if (clause.kind === 261 /* CaseClause */) { var caseClause = clause; if (containsYield(caseClause.expression) && pendingClauses.length > 0) { break; @@ -60562,7 +63016,7 @@ var ts; // /*body*/ // .endlabeled // .mark endLabel - beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginLabeledBlock(ts.idText(node.label)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -60572,7 +63026,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); + beginScriptLabeledBlock(ts.idText(node.label)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -60657,7 +63111,7 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); @@ -60808,7 +63262,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); + var text = ts.idText(variable.name); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -61282,8 +63736,7 @@ var ts; if (clauses) { var labelExpression = ts.createPropertyAccess(state, "label"); var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses)); - switchStatement.startsOnNewLine = true; - return [switchStatement]; + return [ts.startOnNewLine(switchStatement)]; } if (statements) { return statements; @@ -61722,7 +64175,7 @@ var ts; default: return transformCommonJSModule; } } - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -61733,11 +64186,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(194 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(192 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(193 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(262 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(265 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(269 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -61751,7 +64204,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } currentSourceFile = node; @@ -61779,7 +64232,7 @@ var ts; function transformCommonJSModule(node) { startLexicalEnvironment(); var statements = []; - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); @@ -62041,23 +64494,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return visitExportDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 290 /* MergeDeclarationMarker */: + case 294 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 291 /* EndOfDeclarationMarker */: + case 295 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, importCallExpressionVisitor, context); @@ -62077,17 +64530,19 @@ var ts; } } function visitImportCallExpression(node) { + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: - return transformImportCallExpressionAMD(node); + return createImportCallExpressionAMD(argument, containsLexicalThis); case ts.ModuleKind.UMD: - return transformImportCallExpressionUMD(node); + return createImportCallExpressionUMD(argument, containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return transformImportCallExpressionCommonJS(node); + return createImportCallExpressionCommonJS(argument, containsLexicalThis); } } - function transformImportCallExpressionUMD(node) { + function createImportCallExpressionUMD(arg, containsLexicalThis) { // (function (factory) { // ... (regular UMD) // } @@ -62102,12 +64557,22 @@ var ts; // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ // }); needUMDDynamicImportHelper = true; - return ts.createConditional( - /*condition*/ ts.createIdentifier("__syncRequire"), - /*whenTrue*/ transformImportCallExpressionCommonJS(node), - /*whenFalse*/ transformImportCallExpressionAMD(node)); + if (ts.isSimpleCopiableExpression(arg)) { + var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */); + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); + } + else { + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); + } } - function transformImportCallExpressionAMD(node) { + function createImportCallExpressionAMD(arg, containsLexicalThis) { // improt("./blah") // emit as // define(["require", "exports", "blah"], function (require, exports) { @@ -62116,30 +64581,71 @@ var ts; // }); var resolve = ts.createUniqueName("resolve"); var reject = ts.createUniqueName("reject"); - return ts.createNew(ts.createIdentifier("Promise"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var parameters = [ + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + ]; + var body = ts.createBlock([ + ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) + ]); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, body); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], - /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), - /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + /*typeParameters*/ undefined, parameters, + /*type*/ undefined, body); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); } - function transformImportCallExpressionCommonJS(node) { + function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") // emit as // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), - /*typeArguments*/ undefined, [ts.createFunctionExpression( + var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); + var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + var func; + if (languageVersion >= 2 /* ES2015 */) { + func = ts.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, requireCall); + } + else { + func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - /*parameters*/ undefined, - /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)])); + // if there is a lexical 'this' in the import call arguments, ensure we indicate + // that this new function expression indicates it captures 'this' so that the + // es2015 transformer will properly substitute 'this' with '_this'. + if (containsLexicalThis) { + ts.setEmitFlags(func, 8 /* CapturesThis */); + } + } + return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } /** * Visits an ImportDeclaration node. @@ -62295,10 +64801,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -62430,7 +64936,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -62485,10 +64991,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241 /* NamedImports */: + case 242 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -62590,7 +65096,7 @@ var ts; */ function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -62687,7 +65193,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -62751,10 +65257,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return substituteBinaryExpression(node); - case 193 /* PostfixUnaryExpression */: - case 192 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -62775,7 +65281,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 265 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 269 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -62850,7 +65356,7 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 /* PostfixUnaryExpression */ + var expression = node.kind === 194 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; @@ -62917,10 +65423,10 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(194 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(192 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(193 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(265 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(269 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -63010,8 +65516,8 @@ var ts; function collectDependencyGroups(externalImports) { var groupIndices = ts.createMap(); var dependencyGroups = []; - for (var i = 0; i < externalImports.length; i++) { - var externalImport = externalImports[i]; + for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) { + var externalImport = externalImports_1[_i]; var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions); if (externalModuleName) { var text = externalModuleName.text; @@ -63084,7 +65590,7 @@ var ts; // only in the outer module body and not in the inner one. startLexicalEnvironment(); // Add any prologue directives. - var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); + var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile)); var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor); // var __moduleName = context_1 && context_1.id; statements.push(ts.createVariableStatement( @@ -63141,7 +65647,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 244 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 245 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -63166,7 +65672,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 244 /* ExportDeclaration */) { + if (externalImport.kind !== 245 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -63177,7 +65683,7 @@ var ts; for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; // write name of indirectly exported entry, i.e. 'export {x} from ...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -63245,19 +65751,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -63271,7 +65777,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); @@ -63307,15 +65813,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return visitImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -63491,7 +65997,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 265 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 269 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -63505,7 +66011,7 @@ var ts; return ts.isBindingPattern(node.name) ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, /*needsValue*/ false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); + : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name; } /** * Creates an assignment expression for an exported variable declaration. @@ -63555,7 +66061,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 208 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 209 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -63611,10 +66117,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 241 /* NamedImports */: + case 242 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -63688,7 +66194,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); + excludeName = ts.idText(decl.name); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -63732,7 +66238,7 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; @@ -63794,43 +66300,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return visitVariableStatement(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return visitClassDeclaration(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return visitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return visitForInStatement(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return visitForOfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return visitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return visitWhileStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return visitLabeledStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return visitWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return visitSwitchStatement(node); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return visitCaseBlock(node); - case 257 /* CaseClause */: + case 261 /* CaseClause */: return visitCaseClause(node); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return visitDefaultClause(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return visitTryStatement(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return visitCatchClause(node); - case 207 /* Block */: + case 208 /* Block */: return visitBlock(node); - case 290 /* MergeDeclarationMarker */: + case 294 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 291 /* EndOfDeclarationMarker */: + case 295 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -63896,6 +66402,9 @@ var ts; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var variable = _a[_i]; expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false)); + if (!variable.initializer) { + hoistBindingElement(variable); + } } return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression(); } @@ -64013,7 +66522,7 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 194 /* BinaryExpression */) { + && node.kind === 195 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -64038,7 +66547,7 @@ var ts; // }; // }); return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), - /*typeArguments*/ undefined, node.arguments); + /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []); } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. @@ -64078,7 +66587,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 265 /* SourceFile */; + return container !== undefined && container.kind === 269 /* SourceFile */; } else { return false; @@ -64111,7 +66620,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -64158,10 +66667,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return substituteBinaryExpression(node); - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -64254,14 +66763,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 193 /* PostfixUnaryExpression */ + var expression = node.kind === 194 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 193 /* PostfixUnaryExpression */) { + if (node.kind === 194 /* PostfixUnaryExpression */) { expression = node.operator === 43 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -64283,7 +66792,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 265 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 269 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -64324,7 +66833,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(265 /* SourceFile */); + context.enableEmitNotification(269 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; return transformSourceFile; @@ -64351,10 +66860,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -64460,7 +66969,7 @@ var ts; if (jsx === 2 /* React */) { transformers.push(ts.transformJsx); } - if (languageVersion < 5 /* ESNext */) { + if (languageVersion < 6 /* ESNext */) { transformers.push(ts.transformESNext); } if (languageVersion < 4 /* ES2017 */) { @@ -64494,7 +67003,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(292 /* Count */); + var enabledSyntaxKindFeatures = new Array(296 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -64834,7 +67343,7 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 265 /* SourceFile */) { + if (sourceFileOrBundle.kind === 269 /* SourceFile */) { // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); @@ -64979,7 +67488,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 287 /* NotEmittedStatement */ + if (node.kind !== 291 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -64996,7 +67505,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 287 /* NotEmittedStatement */ + if (node.kind !== 291 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -65173,7 +67682,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 291 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -65194,7 +67703,7 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 227 /* VariableDeclarationList */) { + if (node.kind === 228 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -65341,7 +67850,7 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } - function emitLeadingComment(commentPos, commentEnd, _kind, hasTrailingNewLine, rangePos) { + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -65355,7 +67864,7 @@ var ts; if (hasTrailingNewLine) { writer.writeLine(); } - else { + else if (kind === 3 /* MultiLineCommentTrivia */) { writer.write(" "); } } @@ -65498,8 +68007,8 @@ var ts; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 266 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 266 /* Bundle */; + var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var isBundledEmit = sourceFileOrBundle.kind === 270 /* Bundle */; var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -65573,7 +68082,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 238 /* ImportDeclaration */); + ts.Debug.assert(aliasEmitInfo.node.kind === 239 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); for (var i = 0; i < aliasEmitInfo.indent; i++) { @@ -65611,7 +68120,7 @@ var ts; }; function hasInternalAnnotation(range) { var comment = currentText.substring(range.pos, range.end); - return comment.indexOf("@internal") >= 0; + return ts.stringContains(comment, "@internal"); } function stripInternal(node) { if (node) { @@ -65626,6 +68135,7 @@ var ts; var writer = ts.createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; + writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; @@ -65649,10 +68159,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 226 /* VariableDeclaration */) { + if (declaration.kind === 227 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 241 /* NamedImports */ || declaration.kind === 242 /* ImportSpecifier */ || declaration.kind === 239 /* ImportClause */) { + else if (declaration.kind === 242 /* NamedImports */ || declaration.kind === 243 /* ImportSpecifier */ || declaration.kind === 240 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -65670,7 +68180,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 238 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 239 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -65680,12 +68190,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 233 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 234 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 233 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 234 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -65740,10 +68250,16 @@ var ts; emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } function reportInaccessibleThisError() { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -65753,7 +68269,7 @@ var ts; // for optional parameter properties // and also for non-optional initialized parameters that aren't a parameter property // these types may need to add `undefined`. - var shouldUseResolverType = declaration.kind === 146 /* Parameter */ && + var shouldUseResolverType = declaration.kind === 147 /* Parameter */ && (resolver.isRequiredInitializedParameter(declaration) || resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { @@ -65828,41 +68344,41 @@ var ts; case 139 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 130 /* NeverKeyword */: - case 169 /* ThisType */: - case 173 /* LiteralType */: + case 170 /* ThisType */: + case 174 /* LiteralType */: return writeTextOfNode(currentText, type); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return emitTypeReference(type); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return emitTypeQuery(type); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return emitArrayType(type); - case 165 /* TupleType */: + case 166 /* TupleType */: return emitTupleType(type); - case 166 /* UnionType */: + case 167 /* UnionType */: return emitUnionType(type); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return emitIntersectionType(type); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return emitParenType(type); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return emitTypeOperator(type); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return emitIndexedAccessType(type); - case 172 /* MappedType */: + case 173 /* MappedType */: return emitMappedType(type); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return emitTypeLiteral(type); case 71 /* Identifier */: return emitEntityName(type); - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return emitEntityName(type); - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { @@ -65870,8 +68386,8 @@ var ts; writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 143 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 143 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 144 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 144 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentText, right); @@ -65880,14 +68396,14 @@ var ts; function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 237 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 238 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 179 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 180 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -66050,10 +68566,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 237 /* ImportEqualsDeclaration */ || - (node.parent.kind === 265 /* SourceFile */ && isCurrentFileExternalModule)) { + else if (node.kind === 238 /* ImportEqualsDeclaration */ || + (node.parent.kind === 269 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 265 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 269 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -66063,7 +68579,7 @@ var ts; }); } else { - if (node.kind === 238 /* ImportDeclaration */) { + if (node.kind === 239 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -66081,23 +68597,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return writeVariableStatement(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return writeClassDeclaration(node); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -66105,7 +68621,7 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 265 /* SourceFile */) { + if (node.parent.kind === 269 /* SourceFile */) { var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { @@ -66114,7 +68630,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { + else if (node.kind !== 231 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -66166,7 +68682,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings.kind === 241 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -66190,7 +68706,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 241 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -66211,13 +68727,13 @@ var ts; // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 233 /* ModuleDeclaration */; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 234 /* ModuleDeclaration */; var moduleSpecifier; - if (parent.kind === 237 /* ImportEqualsDeclaration */) { + if (parent.kind === 238 /* ImportEqualsDeclaration */) { var node = parent; moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); } - else if (parent.kind === 233 /* ModuleDeclaration */) { + else if (parent.kind === 234 /* ModuleDeclaration */) { moduleSpecifier = parent.name; } else { @@ -66287,7 +68803,7 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body && node.body.kind !== 234 /* ModuleBlock */) { + while (node.body && node.body.kind !== 235 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -66357,7 +68873,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 151 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + return node.parent.kind === 152 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -66368,15 +68884,15 @@ var ts; // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 163 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 151 /* MethodDeclaration */ || - node.parent.kind === 150 /* MethodSignature */ || - node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - node.parent.kind === 155 /* CallSignature */ || - node.parent.kind === 156 /* ConstructSignature */); + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 164 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 152 /* MethodDeclaration */ || + node.parent.kind === 151 /* MethodSignature */ || + node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.kind === 156 /* CallSignature */ || + node.parent.kind === 157 /* ConstructSignature */); emitType(node.constraint); } else { @@ -66385,15 +68901,15 @@ var ts; } if (node.default && !isPrivateMethodTypeParameter(node)) { write(" = "); - if (node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 163 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 151 /* MethodDeclaration */ || - node.parent.kind === 150 /* MethodSignature */ || - node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - node.parent.kind === 155 /* CallSignature */ || - node.parent.kind === 156 /* ConstructSignature */); + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 164 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 152 /* MethodDeclaration */ || + node.parent.kind === 151 /* MethodSignature */ || + node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.kind === 156 /* CallSignature */ || + node.parent.kind === 157 /* ConstructSignature */); emitType(node.default); } else { @@ -66404,34 +68920,34 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 155 /* CallSignature */: + case 156 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 230 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -66465,7 +68981,7 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 229 /* ClassDeclaration */) { + if (node.parent.parent.kind === 230 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -66504,7 +69020,7 @@ var ts; diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + }, !ts.findAncestor(node, function (n) { return n.kind === 234 /* ModuleDeclaration */; })); } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -66561,7 +69077,7 @@ var ts; enclosingDeclaration = prevEnclosingDeclaration; } function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } emitJsDocComments(node); @@ -66570,25 +69086,28 @@ var ts; write(";"); writeLine(); } + function bindingNameContainsVisibleBindingElement(node) { + return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); + } + function isVariableDeclarationVisible(node) { + return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); + } function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 226 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 227 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - // If this node is a computed name, it can only be a symbol, because we've already skipped - // it if it's not a well known symbol. In that case, the text of the name will be exactly - // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor // we don't want to emit property declaration with "?" - if ((node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || - (node.kind === 146 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */ || + (node.kind === 147 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */) && node.parent.kind === 163 /* TypeLiteral */) { + if ((node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */) && node.parent.kind === 164 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (resolver.isLiteralConstDeclaration(node)) { @@ -66601,15 +69120,15 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 226 /* VariableDeclaration */) { + if (node.kind === 227 /* VariableDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 149 /* PropertyDeclaration */ || node.kind === 148 /* PropertySignature */ || - (node.kind === 146 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 150 /* PropertyDeclaration */ || node.kind === 149 /* PropertySignature */ || + (node.kind === 147 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -66618,7 +69137,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 229 /* ClassDeclaration */ || node.kind === 146 /* Parameter */) { + else if (node.parent.kind === 230 /* ClassDeclaration */ || node.kind === 147 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -66642,7 +69161,7 @@ var ts; } : undefined; } function emitBindingPattern(bindingPattern) { - // Only select non-omitted expression from the bindingPattern's elements. + // Only select visible, non-omitted expression from the bindingPattern's elements. // We have to do this to avoid emitting trailing commas. // For example: // original: var [, c,,] = [ 2,3,4] @@ -66650,7 +69169,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 200 /* OmittedExpression */) { + if (element.kind !== 201 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { elements.push(element); } } @@ -66686,7 +69205,7 @@ var ts; } } function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(varDeclaration); }); } function writeVariableStatement(node) { // If binding pattern doesn't have name, then there is nothing to be emitted for declaration file i.e. const [,] = [1,2]. @@ -66704,12 +69223,12 @@ var ts; else { write("var "); } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, resolver.isDeclarationVisible); + emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); write(";"); writeLine(); } function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -66718,13 +69237,13 @@ var ts; emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getAccessorNameVisibilityError); if (!ts.hasModifier(node, 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 153 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 154 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -66737,86 +69256,161 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 153 /* GetAccessor */ + return accessor.kind === 154 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type : undefined; } } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 154 /* SetAccessor */) { - // Setters have to have type named and cannot infer it so, the type should always be named - if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) { + if (accessorWithTypeAnnotation.kind === 155 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - // TODO(jfreeman): Investigate why we are passing node.name instead of node.parameters[0].name - typeName: accessorWithTypeAnnotation.name - }; } else { if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: accessorWithTypeAnnotation.name + }; } } function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node)) { + if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { return; } // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 228 /* FunctionDeclaration */) { + if (node.kind === 229 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 151 /* MethodDeclaration */ || node.kind === 152 /* Constructor */) { + else if (node.kind === 152 /* MethodDeclaration */ || node.kind === 153 /* Constructor */) { emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); } - if (node.kind === 228 /* FunctionDeclaration */) { + if (node.kind === 229 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } - else if (node.kind === 152 /* Constructor */) { + else if (node.kind === 153 /* Constructor */) { write("constructor"); } else { - writeTextOfNode(currentText, node.name); + writeNameOfDeclaration(node, getMethodNameVisibilityError); if (ts.hasQuestionToken(node)) { write("?"); } } emitSignatureDeclaration(node); } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 230 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + if (ts.hasDynamicName(node)) { + // If this node has a dynamic name, it can only be an identifier or property access because + // we've already skipped it otherwise. + ts.Debug.assert(resolver.isLateBound(node)); + writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); + } + else { + // If this node is a computed name, it can only be a symbol, because we've already skipped + // it if it's not a well known symbol. In that case, the text of the name will be exactly + // what we want, namely the name expression enclosed in brackets. + writeTextOfNode(currentText, node.name); + } + } + function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + var entityName = node.name.expression; + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + writeTextOfNode(currentText, node.name); } function emitSignatureDeclarationWithJsDocComments(node) { emitJsDocComments(node); @@ -66826,22 +69420,22 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; var closeParenthesizedFunctionType = false; - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { // Index signature can have readonly modifier emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); write("["); } else { - if (node.kind === 152 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { + if (node.kind === 153 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { write("();"); writeLine(); return; } // Construct signature or constructor type write new Signature - if (node.kind === 156 /* ConstructSignature */ || node.kind === 161 /* ConstructorType */) { + if (node.kind === 157 /* ConstructSignature */ || node.kind === 162 /* ConstructorType */) { write("new "); } - else if (node.kind === 160 /* FunctionType */) { + else if (node.kind === 161 /* FunctionType */) { var currentOutput = writer.getText(); // Do not generate incorrect type when function type with type parameters is type argument // This could happen if user used space between two '<' making it error free @@ -66856,22 +69450,22 @@ var ts; } // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 157 /* IndexSignature */) { + if (node.kind === 158 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 160 /* FunctionType */ || node.kind === 161 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 163 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 161 /* FunctionType */ || node.kind === 162 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 164 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 152 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { + else if (node.kind !== 153 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -66885,26 +69479,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 155 /* CallSignature */: + case 156 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -66912,7 +69506,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.kind === 230 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -66926,7 +69520,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -66961,9 +69555,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 160 /* FunctionType */ || - node.parent.kind === 161 /* ConstructorType */ || - node.parent.parent.kind === 163 /* TypeLiteral */) { + if (node.parent.kind === 161 /* FunctionType */ || + node.parent.kind === 162 /* ConstructorType */ || + node.parent.parent.kind === 164 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!ts.hasModifier(node.parent, 8 /* Private */)) { @@ -66979,29 +69573,29 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 155 /* CallSignature */: + case 156 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.hasModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -67009,7 +69603,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 229 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 230 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -67022,7 +69616,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -67034,12 +69628,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -67050,7 +69644,7 @@ var ts; } } function emitBindingElement(bindingElement) { - if (bindingElement.kind === 200 /* OmittedExpression */) { + if (bindingElement.kind === 201 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -67059,7 +69653,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 176 /* BindingElement */) { + else if (bindingElement.kind === 177 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -67098,40 +69692,40 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 233 /* ModuleDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 230 /* InterfaceDeclaration */: - case 229 /* ClassDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: + case 229 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 231 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return emitExportDeclaration(node); - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return writeFunctionDeclaration(node); - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 157 /* IndexSignature */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return emitAccessorDeclaration(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return emitPropertyDeclaration(node); - case 264 /* EnumMember */: + case 268 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return emitExportAssignment(node); - case 265 /* SourceFile */: + case 269 /* SourceFile */: return emitSourceFile(node); } } @@ -67159,7 +69753,7 @@ var ts; return addedBundledEmitReference; function getDeclFileName(emitFileNames, sourceFileOrBundle) { // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path - var isBundledEmit = sourceFileOrBundle.kind === 266 /* Bundle */; + var isBundledEmit = sourceFileOrBundle.kind === 270 /* Bundle */; if (isBundledEmit && !addBundledFileReference) { return; } @@ -67174,7 +69768,7 @@ var ts; var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { - var sourceFiles = sourceFileOrBundle.kind === 266 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; + var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); @@ -67259,7 +69853,7 @@ var ts; return ".js" /* Js */; } function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266 /* Bundle */) { + if (sourceFileOrBundle.kind === 270 /* Bundle */) { return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); } return ts.getOriginalSourceFile(sourceFileOrBundle); @@ -67336,8 +69930,8 @@ var ts; } } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 266 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 265 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 269 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); if (bundle) { @@ -67377,7 +69971,7 @@ var ts; } function emitHelpers(node, writeLines) { var helpersEmitted = false; - var bundle = node.kind === 266 /* Bundle */ ? node : undefined; + var bundle = node.kind === 270 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -67458,8 +70052,8 @@ var ts; break; } switch (node.kind) { - case 265 /* SourceFile */: return printFile(node); - case 266 /* Bundle */: return printBundle(node); + case 269 /* SourceFile */: return printFile(node); + case 270 /* Bundle */: return printBundle(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -67618,204 +70212,222 @@ var ts; return emitIdentifier(node); // Parse tree nodes // Names - case 143 /* QualifiedName */: + case 144 /* QualifiedName */: return emitQualifiedName(node); - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: return emitTypeParameter(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return emitParameter(node); - case 147 /* Decorator */: + case 148 /* Decorator */: return emitDecorator(node); // Type members - case 148 /* PropertySignature */: + case 149 /* PropertySignature */: return emitPropertySignature(node); - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 150 /* MethodSignature */: + case 151 /* MethodSignature */: return emitMethodSignature(node); - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return emitConstructor(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return emitAccessorDeclaration(node); - case 155 /* CallSignature */: + case 156 /* CallSignature */: return emitCallSignature(node); - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: return emitConstructSignature(node); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return emitIndexSignature(node); // Types - case 158 /* TypePredicate */: + case 159 /* TypePredicate */: return emitTypePredicate(node); - case 159 /* TypeReference */: + case 160 /* TypeReference */: return emitTypeReference(node); - case 160 /* FunctionType */: + case 161 /* FunctionType */: return emitFunctionType(node); - case 161 /* ConstructorType */: + case 277 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 162 /* ConstructorType */: return emitConstructorType(node); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return emitTypeQuery(node); - case 163 /* TypeLiteral */: + case 164 /* TypeLiteral */: return emitTypeLiteral(node); - case 164 /* ArrayType */: + case 165 /* ArrayType */: return emitArrayType(node); - case 165 /* TupleType */: + case 166 /* TupleType */: return emitTupleType(node); - case 166 /* UnionType */: + case 167 /* UnionType */: return emitUnionType(node); - case 167 /* IntersectionType */: + case 168 /* IntersectionType */: return emitIntersectionType(node); - case 168 /* ParenthesizedType */: + case 169 /* ParenthesizedType */: return emitParenthesizedType(node); - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 169 /* ThisType */: + case 170 /* ThisType */: return emitThisType(); - case 170 /* TypeOperator */: + case 171 /* TypeOperator */: return emitTypeOperator(node); - case 171 /* IndexedAccessType */: + case 172 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 172 /* MappedType */: + case 173 /* MappedType */: return emitMappedType(node); - case 173 /* LiteralType */: + case 174 /* LiteralType */: return emitLiteralType(node); + case 272 /* JSDocAllType */: + write("*"); + return; + case 273 /* JSDocUnknownType */: + write("?"); + return; + case 274 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 275 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 276 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 278 /* JSDocVariadicType */: + return emitJSDocVariadicType(node); // Binding patterns - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return emitBindingElement(node); // Misc - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return emitTemplateSpan(node); - case 206 /* SemicolonClassElement */: + case 207 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 207 /* Block */: + case 208 /* Block */: return emitBlock(node); - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: return emitVariableStatement(node); - case 209 /* EmptyStatement */: + case 210 /* EmptyStatement */: return emitEmptyStatement(); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return emitExpressionStatement(node); - case 211 /* IfStatement */: + case 212 /* IfStatement */: return emitIfStatement(node); - case 212 /* DoStatement */: + case 213 /* DoStatement */: return emitDoStatement(node); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: return emitWhileStatement(node); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return emitForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: return emitForInStatement(node); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: return emitForOfStatement(node); - case 217 /* ContinueStatement */: + case 218 /* ContinueStatement */: return emitContinueStatement(node); - case 218 /* BreakStatement */: + case 219 /* BreakStatement */: return emitBreakStatement(node); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: return emitReturnStatement(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: return emitWithStatement(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return emitSwitchStatement(node); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: return emitLabeledStatement(node); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: return emitThrowStatement(node); - case 224 /* TryStatement */: + case 225 /* TryStatement */: return emitTryStatement(node); - case 225 /* DebuggerStatement */: + case 226 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return emitClassDeclaration(node); - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return emitModuleBlock(node); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return emitCaseBlock(node); - case 236 /* NamespaceExportDeclaration */: + case 237 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: return emitImportDeclaration(node); - case 239 /* ImportClause */: + case 240 /* ImportClause */: return emitImportClause(node); - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return emitNamespaceImport(node); - case 241 /* NamedImports */: + case 242 /* NamedImports */: return emitNamedImports(node); - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: return emitImportSpecifier(node); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: return emitExportAssignment(node); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: return emitExportDeclaration(node); - case 245 /* NamedExports */: + case 246 /* NamedExports */: return emitNamedExports(node); - case 246 /* ExportSpecifier */: + case 247 /* ExportSpecifier */: return emitExportSpecifier(node); - case 247 /* MissingDeclaration */: + case 248 /* MissingDeclaration */: return; // Module references - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 10 /* JsxText */: return emitJsxText(node); - case 251 /* JsxOpeningElement */: - return emitJsxOpeningElement(node); - case 252 /* JsxClosingElement */: - return emitJsxClosingElement(node); - case 253 /* JsxAttribute */: + case 252 /* JsxOpeningElement */: + case 255 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 253 /* JsxClosingElement */: + case 256 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 257 /* JsxAttribute */: return emitJsxAttribute(node); - case 254 /* JsxAttributes */: + case 258 /* JsxAttributes */: return emitJsxAttributes(node); - case 255 /* JsxSpreadAttribute */: + case 259 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 256 /* JsxExpression */: + case 260 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 257 /* CaseClause */: + case 261 /* CaseClause */: return emitCaseClause(node); - case 258 /* DefaultClause */: + case 262 /* DefaultClause */: return emitDefaultClause(node); - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: return emitHeritageClause(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 261 /* PropertyAssignment */: + case 265 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 262 /* ShorthandPropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 263 /* SpreadAssignment */: + case 267 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 264 /* EnumMember */: + case 268 /* EnumMember */: return emitEnumMember(node); } // If the node is an expression, try to emit it as an expression with @@ -67851,69 +70463,71 @@ var ts; writeTokenNode(node); return; // Expressions - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 179 /* PropertyAccessExpression */: + case 180 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 181 /* CallExpression */: + case 182 /* CallExpression */: return emitCallExpression(node); - case 182 /* NewExpression */: + case 183 /* NewExpression */: return emitNewExpression(node); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return emitFunctionExpression(node); - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return emitArrowFunction(node); - case 188 /* DeleteExpression */: + case 189 /* DeleteExpression */: return emitDeleteExpression(node); - case 189 /* TypeOfExpression */: + case 190 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 190 /* VoidExpression */: + case 191 /* VoidExpression */: return emitVoidExpression(node); - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: return emitAwaitExpression(node); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 193 /* PostfixUnaryExpression */: + case 194 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return emitBinaryExpression(node); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return emitConditionalExpression(node); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: return emitTemplateExpression(node); - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: return emitYieldExpression(node); - case 198 /* SpreadElement */: + case 199 /* SpreadElement */: return emitSpreadExpression(node); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return emitClassExpression(node); - case 200 /* OmittedExpression */: + case 201 /* OmittedExpression */: return; - case 202 /* AsExpression */: + case 203 /* AsExpression */: return emitAsExpression(node); - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: return emitNonNullExpression(node); - case 204 /* MetaProperty */: + case 205 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 249 /* JsxElement */: + case 250 /* JsxElement */: return emitJsxElement(node); - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); + case 254 /* JsxFragment */: + return emitJsxFragment(node); // Transformation nodes - case 288 /* PartiallyEmittedExpression */: + case 292 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 289 /* CommaListExpression */: + case 293 /* CommaListExpression */: return emitCommaList(node); } } @@ -67988,9 +70602,16 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); - emit(node.name); + if (node.name) { + emit(node.name); + } emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); + if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } + else { + emitWithPrefix(": ", node.type); + } emitExpressionWithPrefix(" = ", node.initializer); } function emitDecorator(decorator) { @@ -68043,7 +70664,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 153 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -68092,6 +70713,24 @@ var ts; write(" => "); emit(node.type); } + function emitJSDocFunctionType(node) { + write("function"); + emitParameters(node, node.parameters); + write(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + write("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + write("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + write("="); + } function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); @@ -68113,6 +70752,10 @@ var ts; emit(node.elementType); write("[]"); } + function emitJSDocVariadicType(node) { + write("..."); + emit(node.type); + } function emitTupleType(node) { write("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); @@ -68255,7 +70898,7 @@ var ts; // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression); return !expression.numericLiteralFlags - && text.indexOf(ts.tokenToString(23 /* DotToken */)) < 0; + && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -68351,7 +70994,7 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 192 /* PrefixUnaryExpression */ + return operand.kind === 193 /* PrefixUnaryExpression */ && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); } @@ -68470,7 +71113,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); - if (node.elseStatement.kind === 211 /* IfStatement */) { + if (node.elseStatement.kind === 212 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -68533,7 +71176,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 227 /* VariableDeclarationList */) { + if (node.kind === 228 /* VariableDeclarationList */) { emit(node); } else { @@ -68644,26 +71287,15 @@ var ts; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + pushNameGenerationScope(node); + emitSignatureHead(node); + if (onEmitNode) { + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { - pushNameGenerationScope(); - emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } - popNameGenerationScope(); + emitBlockFunctionBody(body); } + popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); } @@ -68760,11 +71392,9 @@ var ts; } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 65 /* ClassMembers */); write("}"); - popNameGenerationScope(); if (indentedFlag) { decreaseIndent(); } @@ -68794,11 +71424,9 @@ var ts; emitModifiers(node, node.modifiers); write("enum "); emit(node.name); - pushNameGenerationScope(); write(" {"); emitList(node, node.members, 81 /* EnumMembers */); write("}"); - popNameGenerationScope(); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); @@ -68807,7 +71435,7 @@ var ts; } emit(node.name); var body = node.body; - while (body.kind === 233 /* ModuleDeclaration */) { + while (body.kind === 234 /* ModuleDeclaration */) { write("."); emit(body.name); body = body.body; @@ -68816,11 +71444,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - pushNameGenerationScope(); + pushNameGenerationScope(node); write("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); write("}"); - popNameGenerationScope(); + popNameGenerationScope(node); } function emitCaseBlock(node) { writeToken(17 /* OpenBraceToken */, node.pos); @@ -68925,7 +71553,7 @@ var ts; // function emitJsxElement(node) { emit(node.openingElement); - emitList(node, node.children, 131072 /* JsxElementChildren */); + emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); emit(node.closingElement); } function emitJsxSelfClosingElement(node) { @@ -68938,22 +71566,31 @@ var ts; } write("/>"); } - function emitJsxOpeningElement(node) { + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 131072 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { write("<"); - emitJsxTagName(node.tagName); - writeIfAny(node.attributes.properties, " "); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); + if (ts.isJsxOpeningElement(node)) { + emitJsxTagName(node.tagName); + // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap + if (node.attributes.properties && node.attributes.properties.length > 0) { + write(" "); + emit(node.attributes); + } } write(">"); } function emitJsxText(node) { writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } - function emitJsxClosingElement(node) { + function emitJsxClosingElementOrFragment(node) { write(""); } function emitJsxAttributes(node) { @@ -69104,11 +71741,11 @@ var ts; } function emitSourceFileWorker(node) { var statements = node.statements; - pushNameGenerationScope(); + pushNameGenerationScope(node); emitHelpersIndirect(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); - popNameGenerationScope(); + popNameGenerationScope(node); } // Transformation nodes function emitPartiallyEmittedExpression(node) { @@ -69402,11 +72039,6 @@ var ts; function decreaseIndent() { writer.decreaseIndent(); } - function writeIfAny(nodes, text) { - if (ts.some(nodes)) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -69437,8 +72069,9 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = guessIndentation(lines); - for (var i = 0; i < lines.length; i++) { - var line = indentation ? lines[i].slice(indentation) : lines[i]; + for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { + var lineText = lines_1[_a]; + var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); write(line); @@ -69448,8 +72081,8 @@ var ts; } function guessIndentation(lines) { var indentation; - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var line = lines_1[_a]; + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { if (indentation === undefined || i < indentation) { @@ -69521,7 +72154,7 @@ var ts; } } else { - return nextNode.startsOnNewLine; + return ts.getStartsOnNewLine(nextNode); } } function shouldWriteClosingLineTerminator(parentNode, children, format) { @@ -69549,7 +72182,7 @@ var ts; } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { - var startsOnNewLine = node.startsOnNewLine; + var startsOnNewLine = ts.getStartsOnNewLine(node); if (startsOnNewLine === undefined) { return (format & 32768 /* PreferNewLine */) !== 0; } @@ -69562,7 +72195,7 @@ var ts; node1 = skipSynthesizedParentheses(node1); node2 = skipSynthesizedParentheses(node2); // Always use a newline for synthesized code if the synthesizer desires it. - if (node2.startsOnNewLine) { + if (ts.getStartsOnNewLine(node2)) { return true; } return !ts.nodeIsSynthesized(parent) @@ -69575,7 +72208,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 185 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 186 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -69585,7 +72218,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -69612,14 +72245,20 @@ var ts; /** * Push a new name generation scope. */ - function pushNameGenerationScope() { + function pushNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } tempFlagsStack.push(tempFlags); tempFlags = 0; } /** * Pop the current name generation scope. */ - function popNameGenerationScope() { + function popNameGenerationScope(node) { + if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + return; + } tempFlags = tempFlagsStack.pop(); } /** @@ -69629,8 +72268,17 @@ var ts; if (name.autoGenerateKind === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - var node = getNodeForGeneratedName(name); - return generateNameCached(node); + if (name.skipNameGenerationScope) { + var savedTempFlags = tempFlags; + popNameGenerationScope(/*node*/ undefined); + var result = generateNameCached(getNodeForGeneratedName(name)); + pushNameGenerationScope(/*node*/ undefined); + tempFlags = savedTempFlags; + return result; + } + else { + return generateNameCached(getNodeForGeneratedName(name)); + } } else { // Auto, Loop, and Unique names are cached based on their unique @@ -69757,21 +72405,21 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return makeUniqueName(getTextOfNode(node)); - case 233 /* ModuleDeclaration */: - case 232 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 238 /* ImportDeclaration */: - case 244 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: - case 243 /* ExportAssignment */: + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + case 244 /* ExportAssignment */: return generateNameForExportDefault(); - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: return generateNameForClassExpression(); - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -69787,7 +72435,7 @@ var ts; case 2 /* Loop */: return makeTempVariableName(268435456 /* _i */); case 3 /* Unique */: - return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); + return makeUniqueName(ts.idText(name)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -69907,7 +72555,7 @@ var ts; ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementChildren"] = 131072] = "JsxElementChildren"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; @@ -69919,26 +72567,410 @@ var ts; ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; + function createBuilder(options) { + var isModuleEmit; + var fileInfos = ts.createMap(); + var semanticDiagnosticsPerFile = ts.createMap(); + /** The map has key by source file's path that has been changed */ + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; + var emitHandler; + return { + updateProgram: updateProgram, + getFilesAffectedBy: getFilesAffectedBy, + emitChangedFiles: emitChangedFiles, + getSemanticDiagnostics: getSemanticDiagnostics, + clear: clear + }; + function createProgramGraph(program) { + var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; + if (isModuleEmit !== currentIsModuleEmit) { + isModuleEmit = currentIsModuleEmit; + emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; + ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { + // Add new file info + createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, + // Remove existing file info + onDeleteValue: removeExistingFileInfo, + // We will update in place instead of deleting existing value and adding new one + onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } + }); + } + function registerChangedFile(path) { + changedFilesSet.set(path, true); + // All changed files need to re-evaluate its semantic diagnostics + semanticDiagnosticsPerFile.delete(path); + } + function addNewFileInfo(program, sourceFile) { + registerChangedFile(sourceFile.path); + emitHandler.onAddSourceFile(program, sourceFile); + return { version: sourceFile.version, signature: undefined }; + } + function removeExistingFileInfo(_existingFileInfo, path) { + // Since we dont need to track removed file as changed file + // We can just remove its diagnostics + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); + emitHandler.onRemoveSourceFile(path); + } + function updateExistingFileInfo(program, existingInfo, sourceFile) { + if (existingInfo.version !== sourceFile.version) { + registerChangedFile(sourceFile.path); + existingInfo.version = sourceFile.version; + emitHandler.onUpdateSourceFile(program, sourceFile); + } + else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { + registerChangedFile(sourceFile.path); + } + } + function ensureProgramGraph(program) { + if (!emitHandler) { + createProgramGraph(program); + } + } + function updateProgram(newProgram) { + if (emitHandler) { + createProgramGraph(newProgram); + } + } + function getFilesAffectedBy(program, path) { + ensureProgramGraph(program); + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); + } + function emitChangedFiles(program, writeFileCallback) { + ensureProgramGraph(program); + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + // With --out or --outFile all outputs go into single file, do it only once + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; + } + var seenFiles = ts.createMap(); + var result; + changedFilesSet.forEach(function (_true, path) { + // Get the affected Files by this program + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + // Affected files shouldnt have cached diagnostics + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + // Emit the affected file + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); + } + }); + }); + changedFilesSet.clear(); + return result || ts.emptyArray; + } + function getSemanticDiagnostics(program, cancellationToken) { + ensureProgramGraph(program); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + // We dont need to cache the diagnostics just return them from program + return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + var diagnostics; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + function clear() { + isModuleEmit = undefined; + emitHandler = undefined; + fileInfos.clear(); + semanticDiagnosticsPerFile.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * @return {boolean} indicates if the shape signature has changed since last update. + */ + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + info.signature = latestSignature; + } + else { + var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = options.computeHash(emitOutput.outputFiles[0].text); + info.signature = latestSignature; + } + else { + latestSignature = prevSignature; + } + } + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + // Use cached result + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getNonModuleEmitHandler() { + return { + onAddSourceFile: ts.noop, + onRemoveSourceFile: ts.noop, + onUpdateSourceFile: ts.noop, + onUpdateSourceFileWithSameVersion: ts.returnFalse, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function getFilesAffectedByUpdatedShape(program, sourceFile) { + var options = program.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (options && (options.out || options.outFile)) { + return [sourceFile]; + } + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + } + function getModuleEmitHandler() { + var references = ts.createMap(); + return { + onAddSourceFile: setReferences, + onRemoveSourceFile: onRemoveSourceFile, + onUpdateSourceFile: updateReferences, + onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, + getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape + }; + function setReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + } + function updateReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (newReferences) { + references.set(sourceFile.path, newReferences); + } + else { + references.delete(sourceFile.path); + } + } + function updateReferencesTrackingChangedReferences(program, sourceFile) { + var newReferences = getReferencedFiles(program, sourceFile); + if (!newReferences) { + // Changed if we had references + return references.delete(sourceFile.path); + } + var oldReferences = references.get(sourceFile.path); + references.set(sourceFile.path, newReferences); + if (!oldReferences || oldReferences.size !== newReferences.size) { + return true; + } + // If there are any new references that werent present previously there is change + return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || + // Otherwise its changed if there are more references previously than now + !!oldReferences.size; + } + function onRemoveSourceFile(removedFilePath) { + // Remove existing references + references.forEach(function (referencesInFile, filePath) { + if (referencesInFile.has(removedFilePath)) { + // add files referencing the removedFilePath, as changed files too + var referencedByInfo = fileInfos.get(filePath); + if (referencedByInfo) { + registerChangedFile(filePath); + } + } + }); + // Delete the entry for the removed file path + references.delete(removedFilePath); + } + function getReferencedByPaths(referencedFilePath) { + return ts.mapDefinedIter(references.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + }); + } + function getFilesAffectedByUpdatedShape(program, sourceFile) { + if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); + } + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFile]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + var path = sourceFile.path; + seenFileNamesMap.set(path, sourceFile); + var queue = getReferencedByPaths(path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = program.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { + queue.push.apply(queue, getReferencedByPaths(currentPath)); + } + } + } + // Return array of values that needs emit + return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); + } + } + } + ts.createBuilder = createBuilder; +})(ts || (ts = {})); /// /// /// +/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } - while (true) { - var fileName = ts.combinePaths(searchPath, configName); - if (fileExists(fileName)) { - return fileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); } ts.findConfigFile = findConfigFile; function resolveTripleslashReference(moduleName, containingFile) { @@ -70106,18 +73138,23 @@ var ts; var output = ""; for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { var diagnostic = diagnostics_1[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + output += formatDiagnostic(diagnostic, host); } return output; } ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + var errorMessage = category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; @@ -70145,6 +73182,7 @@ var ts; var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; + var context = ""; if (diagnostic.file) { var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; @@ -70156,12 +73194,12 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += host.getNewLine(); + context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -70170,27 +73208,26 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + host.getNewLine(); + context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += redForegroundEscapeSequence; + context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += redForegroundEscapeSequence; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. var lastCharForLine = i === lastLine ? lastLineChar : undefined; - output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); } else if (i === lastLine) { - output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); } else { // Squiggle the entire line. - output += lineContent.replace(/./g, "~"); + context += lineContent.replace(/./g, "~"); } - output += resetEscapeSequence; - output += host.getNewLine(); + context += resetEscapeSequence; } output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; @@ -70198,13 +73235,17 @@ var ts; var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += context; + } output += host.getNewLine(); } return output; } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { - if (typeof messageText === "string") { + if (ts.isString(messageText)) { return messageText; } else { @@ -70245,6 +73286,61 @@ var ts; } return resolutions; } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + // If we haven't create a program yet or has changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + /** + * Determined if source file needs to be re-created even if its text hasnt changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + // If any of these options change, we cant reuse old source file even if version match + // The change in options like these could result in change in syntax tree change + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' * that represent a compilation unit. @@ -70297,8 +73393,9 @@ var ts; var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -70330,9 +73427,11 @@ var ts; // See `sourceFileIsRedirectedTo`. var redirectTargetsSet = ts.createMap(); var filesByName = ts.createMap(); + var missingFilePaths; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); @@ -70363,10 +73462,22 @@ var ts; }); } } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); } - var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + ts.Debug.assert(!!missingFilePaths); // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks moduleResolutionCache = undefined; + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; program = { @@ -70398,7 +73509,7 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsSet: redirectTargetsSet }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -70431,8 +73542,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var sourceFile = files_2[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var sourceFile = files_1[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); } } @@ -70454,13 +73565,13 @@ var ts; // which per above occured during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_3 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_3.push(resolvedModule); } - return result_4; + return result_3; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -70478,19 +73589,20 @@ var ts; * * ResolvedModuleFull instance: can be reused. */ var result; + var reusedNames; /** A transient placeholder used to mark predicted resolution in the result list. */ var predictedToResolveToAmbientModuleMarker = {}; for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; - // If we want to reuse resolutions more aggressively, we can refine this to check for whether the - // text of the corresponding modulenames has changed. - if (file === oldSourceFile) { + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); if (oldResolvedModule) { if (ts.isTraceEnabled(options, host)) { ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); } (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); continue; } } @@ -70517,7 +73629,7 @@ var ts; } } var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { @@ -70591,6 +73703,12 @@ var ts; var filePaths = []; var modifiedSourceFiles = []; oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } var oldSourceFiles = oldProgram.getSourceFiles(); var SeenPackageName; (function (SeenPackageName) { @@ -70598,11 +73716,11 @@ var ts; SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified"; })(SeenPackageName || (SeenPackageName = {})); var seenPackageNames = ts.createMap(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; + for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target) - : host.getSourceFile(oldSourceFile.fileName, options.target); + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; } @@ -70674,6 +73792,12 @@ var ts; // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } @@ -70716,28 +73840,22 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } - // If a file has ceased to be missing, then we need to discard some of the old - // structure in order to pick it up. - // Caution: if the file has created and then deleted between since it was discovered to - // be missing, then the corresponding file watcher will have been closed and no new one - // will be created until we encounter a change that prevents complete structure reuse. - // During this interval, creation of the file will go unnoticed. We expect this to be - // both rare and low-impact. - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + if (host.hasChangedAutomaticTypeDirectiveNames) { return oldProgram.structureIsReused = 1 /* SafeModules */; } - for (var _c = 0, _d = oldProgram.getMissingFilePaths(); _c < _d.length; _c++) { - var p = _d[_c]; - filesByName.set(p, undefined); - } + missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _e = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _e < modifiedSourceFiles_2.length; _e++) { - var modifiedFile = modifiedSourceFiles_2[_e]; + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -70767,10 +73885,18 @@ var ts; if (file.hasNoDefaultLib) { return true; } - if (defaultLibraryPath && defaultLibraryPath.length !== 0) { - return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); } - return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); @@ -70864,9 +73990,6 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - if (ts.isCheckJsEnabledForFile(sourceFile, options)) { - sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); - } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -70906,13 +74029,18 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs; var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); + if (isCheckJs) { + diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); + } return ts.filter(diagnostics, shouldReportDiagnostic); }); } @@ -70950,22 +74078,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return; } // falls through - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 226 /* VariableDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 227 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -70973,41 +74101,41 @@ var ts; } } switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 259 /* HeritageClause */: + case 263 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 108 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 231 /* TypeAliasDeclaration */: + case 232 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 203 /* NonNullExpression */: + case 204 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 202 /* AsExpression */: + case 203 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 184 /* TypeAssertionExpression */: + case 185 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -71020,28 +74148,28 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } switch (parent.kind) { - case 229 /* ClassDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: + case 230 /* ClassDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 208 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 209 /* VariableStatement */); } break; - case 149 /* PropertyDeclaration */: + case 150 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -71053,16 +74181,16 @@ var ts; return; } break; - case 146 /* Parameter */: + case 147 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return; } break; - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 201 /* ExpressionWithTypeArguments */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 202 /* ExpressionWithTypeArguments */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -71195,9 +74323,9 @@ var ts; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 245 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; @@ -71212,7 +74340,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); @@ -71274,7 +74402,7 @@ var ts; fail(ts.Diagnostics.File_0_not_found, fileName); } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName); + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); } } return sourceFile; @@ -71365,7 +74493,7 @@ var ts; else { fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } - }); + }, shouldCreateNewSourceFile); if (packageId) { var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); @@ -71652,7 +74780,7 @@ var ts; if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } - if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0 /* ES3 */; @@ -71859,7 +74987,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -71957,31 +75085,32 @@ var ts; name: "target", shortName: "t", type: ts.createMapFromTemplate({ - "es3": 0 /* ES3 */, - "es5": 1 /* ES5 */, - "es6": 2 /* ES2015 */, - "es2015": 2 /* ES2015 */, - "es2016": 3 /* ES2016 */, - "es2017": 4 /* ES2017 */, - "esnext": 5 /* ESNext */, + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, }), paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", shortName: "m", type: ts.createMapFromTemplate({ - "none": ts.ModuleKind.None, - "commonjs": ts.ModuleKind.CommonJS, - "amd": ts.ModuleKind.AMD, - "system": ts.ModuleKind.System, - "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES2015, - "es2015": ts.ModuleKind.ES2015, - "esnext": ts.ModuleKind.ESNext + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -72001,6 +75130,7 @@ var ts; "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", // Host only "dom": "lib.dom.d.ts", @@ -72022,6 +75152,7 @@ var ts; "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", + "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -72149,6 +75280,20 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, { name: "noImplicitThis", type: "boolean", @@ -72196,8 +75341,8 @@ var ts; { name: "moduleResolution", type: ts.createMapFromTemplate({ - "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic, + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, }), paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, @@ -72388,8 +75533,8 @@ var ts; { name: "newLine", type: ts.createMapFromTemplate({ - "crlf": 0 /* CarriageReturnLineFeed */, - "lf": 1 /* LineFeed */ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ }), paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Advanced_Options, @@ -72744,7 +75889,7 @@ var ts; */ function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; /** @@ -72766,7 +75911,7 @@ var ts; */ function readJsonConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; function tryReadFile(fileName, readFile) { @@ -72857,7 +76002,7 @@ var ts; var result = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 261 /* PropertyAssignment */) { + if (element.kind !== 265 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -72919,9 +76064,9 @@ var ts; if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); var text = valueExpression.text; - if (option && typeof option.type !== "string") { + if (option && !ts.isString(option.type)) { var customOption = option; // Validate custom option type if (!customOption.type.has(text.toLowerCase())) { @@ -72932,7 +76077,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 178 /* ObjectLiteralExpression */: + case 193 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 179 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -72949,7 +76100,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -72968,13 +76119,13 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : - typeof option.type === "string" ? option.type : "string"; + ts.isString(option.type) ? option.type : "string"; } function isCompilerOptionsValue(option, value) { if (option) { @@ -72983,7 +76134,7 @@ var ts; if (option.type === "list") { return ts.isArray(value); } - var expectedType = typeof option.type === "string" ? option.type : "string"; + var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } } @@ -73188,12 +76339,13 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -73201,14 +76353,15 @@ var ts; raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec }; function getFileNames() { - var fileNames; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - fileNames = raw["files"]; - if (fileNames.length === 0) { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -73217,35 +76370,35 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } } - if (fileNames === undefined && includeSpecs === undefined) { + if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } return result; } @@ -73255,6 +76408,17 @@ var ts; } } } + /*@internal*/ + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + /*@internal*/ + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -73262,9 +76426,8 @@ var ts; * This *just* extracts options/include/exclude/files out of a config file. * It does *not* resolve the included files. */ - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); @@ -73305,11 +76468,11 @@ var ts; var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); // typingOptions has been deprecated and is only supported for backward compatibility purposes. // It should be removed in future releases - use typeAcquisition instead. - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { - if (typeof json.extends !== "string") { + if (!ts.isString(json.extends)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { @@ -73379,7 +76542,7 @@ var ts; return undefined; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); @@ -73398,7 +76561,7 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } @@ -73423,7 +76586,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -73483,7 +76646,7 @@ var ts; if (optType === "list" && ts.isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors); } - else if (typeof optType !== "string") { + else if (!ts.isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); } return normalizeNonListOptionValue(opt, basePath, value); @@ -73497,13 +76660,13 @@ var ts; return undefined; if (option.type === "list") { var listOption_1 = option; - if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else if (typeof option.type !== "string") { - return option.type.get(typeof value === "string" ? value.toLowerCase() : value); + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -73604,19 +76767,47 @@ var ts; /** * Expands an array of file specifications. * - * @param fileNames The literal file names to include. - * @param include The wildcard file specifications to include. - * @param exclude The wildcard file specifications to exclude. + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. * @param basePath The base path for any relative file specifications. * @param options Compiler options. * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; // Literal file names (provided via the "files" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including @@ -73626,31 +76817,21 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); - if (include) { - include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); - } - if (exclude) { - exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); - } - // Wildcard directories (provided as part of a wildcard path) are stored in a - // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), - // or a recursive directory. This information is used by filesystem watchers to monitor for - // new entries in these paths. - var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. - if (fileNames) { - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } - if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, /*depth*/ undefined); _a < _b.length; _a++) { + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { var file = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. @@ -73676,9 +76857,11 @@ var ts; var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); return { fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + spec: spec }; } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter(function (spec) { var diag = specToDiagnostic(spec, allowTrailingRecursion); @@ -74111,7 +77294,7 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -74122,36 +77305,36 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 146 /* Parameter */: - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 260 /* CatchClause */: - case 253 /* JsxAttribute */: + case 147 /* Parameter */: + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 264 /* CatchClause */: + case 257 /* JsxAttribute */: return 1 /* Value */; - case 145 /* TypeParameter */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 163 /* TypeLiteral */: + case 146 /* TypeParameter */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 164 /* TypeLiteral */: return 2 /* Type */; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 264 /* EnumMember */: - case 229 /* ClassDeclaration */: + case 268 /* EnumMember */: + case 230 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -74161,26 +77344,26 @@ var ts; else { return 4 /* Namespace */; } - case 232 /* EnumDeclaration */: - case 241 /* NamedImports */: - case 242 /* ImportSpecifier */: - case 237 /* ImportEqualsDeclaration */: - case 238 /* ImportDeclaration */: - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: + case 233 /* EnumDeclaration */: + case 242 /* NamedImports */: + case 243 /* ImportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 239 /* ImportDeclaration */: + case 244 /* ExportAssignment */: + case 245 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 265 /* SourceFile */: + case 269 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 243 /* ExportAssignment */) { + else if (node.parent.kind === 244 /* ExportAssignment */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -74209,15 +77392,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 143 /* QualifiedName */ && + if (node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 237 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 238 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 143 /* QualifiedName */) { + while (node.parent.kind === 144 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -74229,27 +77412,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 143 /* QualifiedName */) { - while (root.parent && root.parent.kind === 143 /* QualifiedName */) { + if (root.parent.kind === 144 /* QualifiedName */) { + while (root.parent && root.parent.kind === 144 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 159 /* TypeReference */ && !isLastClause; + return root.parent.kind === 160 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 179 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 179 /* PropertyAccessExpression */) { + if (root.parent.kind === 180 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 180 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 201 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 259 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 202 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 263 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 229 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 230 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 230 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || + (decl.kind === 231 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); } return false; } @@ -74259,24 +77442,24 @@ var ts; } switch (node.kind) { case 99 /* ThisKeyword */: - return !ts.isPartOfExpression(node); - case 169 /* ThisType */: + return !ts.isExpressionNode(node); + case 170 /* ThisType */: return true; } switch (node.parent.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return true; - case 201 /* ExpressionWithTypeArguments */: + case 202 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 181 /* CallExpression */); + return isCallOrNewExpressionTarget(node, 182 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 182 /* NewExpression */); + return isCallOrNewExpressionTarget(node, 183 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { @@ -74289,7 +77472,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 223 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -74299,13 +77482,13 @@ var ts; ts.getTargetLabel = getTargetLabel; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && - (node.parent.kind === 218 /* BreakStatement */ || node.parent.kind === 217 /* ContinueStatement */) && + (node.parent.kind === 219 /* BreakStatement */ || node.parent.kind === 218 /* ContinueStatement */) && node.parent.label === node; } ts.isJumpStatementTarget = isJumpStatementTarget; function isLabelOfLabeledStatement(node) { return node.kind === 71 /* Identifier */ && - node.parent.kind === 222 /* LabeledStatement */ && + node.parent.kind === 223 /* LabeledStatement */ && node.parent.label === node; } function isLabelName(node) { @@ -74313,15 +77496,15 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 143 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 144 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 233 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 234 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { @@ -74331,22 +77514,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 264 /* EnumMember */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 233 /* ModuleDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 265 /* PropertyAssignment */: + case 268 /* EnumMember */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 234 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 180 /* ElementAccessExpression */: + case 181 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 144 /* ComputedPropertyName */: + case 145 /* ComputedPropertyName */: return true; - case 173 /* LiteralType */: - return node.parent.parent.kind === 171 /* IndexedAccessType */; + case 174 /* LiteralType */: + return node.parent.parent.kind === 172 /* IndexedAccessType */; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -74356,7 +77539,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 283 /* JSDocTypedefTag */) { + if (node.kind === 288 /* JSDocTypedefTag */) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -74368,17 +77551,17 @@ var ts; return undefined; } switch (node.kind) { - case 265 /* SourceFile */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return node; } } @@ -74386,48 +77569,48 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: return "class" /* classElement */; - case 230 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 231 /* TypeAliasDeclaration */: return "type" /* typeElement */; - case 232 /* EnumDeclaration */: return "enum" /* enumElement */; - case 226 /* VariableDeclaration */: + case 231 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 232 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 233 /* EnumDeclaration */: return "enum" /* enumElement */; + case 227 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 176 /* BindingElement */: + case 177 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return "function" /* functionElement */; - case 153 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 154 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 154 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 155 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return "property" /* memberVariableElement */; - case 157 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 156 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 155 /* CallSignature */: return "call" /* callSignatureElement */; - case 152 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 145 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 264 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 146 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 237 /* ImportEqualsDeclaration */: - case 242 /* ImportSpecifier */: - case 239 /* ImportClause */: - case 246 /* ExportSpecifier */: - case 240 /* NamespaceImport */: + case 158 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 157 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 156 /* CallSignature */: return "call" /* callSignatureElement */; + case 153 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 146 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 268 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 147 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 238 /* ImportEqualsDeclaration */: + case 243 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 247 /* ExportSpecifier */: + case 241 /* NamespaceImport */: return "alias" /* alias */; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { @@ -74438,7 +77621,7 @@ var ts; var rightKind = getNodeKind(right); return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; case 3 /* PrototypeProperty */: - return "method" /* memberFunctionElement */; // instance method + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; case 4 /* ThisProperty */: return "property" /* memberVariableElement */; // property case 5 /* Property */: @@ -74468,7 +77651,7 @@ var ts; return true; case 71 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 146 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 147 /* Parameter */; default: return false; } @@ -74504,8 +77687,12 @@ var ts; return start < end; } ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + /** + * Assumes `candidate.start <= position` holds. + */ function positionBelongsToNode(candidate, position, sourceFile) { - return candidate.end > position || !isCompletedNode(candidate, sourceFile); + ts.Debug.assert(candidate.pos <= position); + return position < candidate.end || !isCompletedNode(candidate, sourceFile); } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { @@ -74513,42 +77700,42 @@ var ts; return false; } switch (n.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: - case 174 /* ObjectBindingPattern */: - case 163 /* TypeLiteral */: - case 207 /* Block */: - case 234 /* ModuleBlock */: - case 235 /* CaseBlock */: - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 179 /* ObjectLiteralExpression */: + case 175 /* ObjectBindingPattern */: + case 164 /* TypeLiteral */: + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 236 /* CaseBlock */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 182 /* NewExpression */: + case 183 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 181 /* CallExpression */: - case 185 /* ParenthesizedExpression */: - case 168 /* ParenthesizedType */: + case 182 /* CallExpression */: + case 186 /* ParenthesizedExpression */: + case 169 /* ParenthesizedType */: return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 187 /* ArrowFunction */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 188 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -74558,67 +77745,67 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 211 /* IfStatement */: + case 212 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 25 /* SemicolonToken */); - case 177 /* ArrayLiteralExpression */: - case 175 /* ArrayBindingPattern */: - case 180 /* ElementAccessExpression */: - case 144 /* ComputedPropertyName */: - case 165 /* TupleType */: + case 178 /* ArrayLiteralExpression */: + case 176 /* ArrayBindingPattern */: + case 181 /* ElementAccessExpression */: + case 145 /* ComputedPropertyName */: + case 166 /* TupleType */: return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 257 /* CaseClause */: - case 258 /* DefaultClause */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 213 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 212 /* DoStatement */: + case 213 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 106 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 162 /* TypeQuery */: + case 163 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 189 /* TypeOfExpression */: - case 188 /* DeleteExpression */: - case 190 /* VoidExpression */: - case 197 /* YieldExpression */: - case 198 /* SpreadElement */: + case 190 /* TypeOfExpression */: + case 189 /* DeleteExpression */: + case 191 /* VoidExpression */: + case 198 /* YieldExpression */: + case 199 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 183 /* TaggedTemplateExpression */: + case 184 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 196 /* TemplateExpression */: + case 197 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 205 /* TemplateSpan */: + case 206 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 244 /* ExportDeclaration */: - case 238 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 192 /* PrefixUnaryExpression */: + case 193 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 195 /* ConditionalExpression */: + case 196 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -74632,11 +77819,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = ts.lastOrUndefined(children); - if (last.kind === expectedLastToken) { + var last_2 = ts.lastOrUndefined(children); + if (last_2.kind === expectedLastToken) { return true; } - else if (last.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -74770,8 +77957,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { - var child = children_2[_i]; + for (var _i = 0, children_3 = children; _i < children_3.length; _i++) { + var child = children_3[_i]; var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || @@ -74829,7 +78016,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 269 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -74890,17 +78077,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 256 /* JsxExpression */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 260 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 256 /* JsxExpression */) { + if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 260 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 252 /* JsxClosingElement */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 253 /* JsxClosingElement */) { return true; } return false; @@ -74956,16 +78143,16 @@ var ts; result.push("abstract" /* abstractModifier */); if (flags & 1 /* Export */) result.push("export" /* exportedModifier */); - if (ts.isInAmbientContext(node)) + if (node.flags & 2097152 /* Ambient */) result.push("declare" /* ambientModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 159 /* TypeReference */ || node.kind === 181 /* CallExpression */) { + if (node.kind === 160 /* TypeReference */ || node.kind === 182 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 229 /* ClassDeclaration */ || node.kind === 230 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 230 /* ClassDeclaration */ || node.kind === 231 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -75016,38 +78203,19 @@ var ts; return result; } ts.cloneCompilerOptions = cloneCompilerOptions; - function compareDataObjects(dst, src) { - if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { - return false; - } - for (var e in dst) { - if (typeof dst[e] === "object") { - if (!compareDataObjects(dst[e], src[e])) { - return false; - } - } - else if (typeof dst[e] !== "function") { - if (dst[e] !== src[e]) { - return false; - } - } - } - return true; - } - ts.compareDataObjects = compareDataObjects; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 177 /* ArrayLiteralExpression */ || - node.kind === 178 /* ObjectLiteralExpression */) { + if (node.kind === 178 /* ArrayLiteralExpression */ || + node.kind === 179 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 194 /* BinaryExpression */ && + if (node.parent.kind === 195 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 216 /* ForOfStatement */ && + if (node.parent.kind === 217 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -75055,7 +78223,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 261 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 265 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -75089,20 +78257,18 @@ var ts; return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + ts.typeKeywords = [ + 119 /* AnyKeyword */, + 122 /* BooleanKeyword */, + 130 /* NeverKeyword */, + 133 /* NumberKeyword */, + 134 /* ObjectKeyword */, + 136 /* StringKeyword */, + 137 /* SymbolKeyword */, + 105 /* VoidKeyword */, + ]; function isTypeKeyword(kind) { - switch (kind) { - case 119 /* AnyKeyword */: - case 122 /* BooleanKeyword */: - case 130 /* NeverKeyword */: - case 133 /* NumberKeyword */: - case 134 /* ObjectKeyword */: - case 136 /* StringKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - return true; - default: - return false; - } + return ts.contains(ts.typeKeywords, kind); } ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ @@ -75125,7 +78291,7 @@ var ts; /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 146 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 147 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -75150,6 +78316,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { @@ -75304,7 +78471,7 @@ var ts; function getDeclaredName(typeChecker, symbol, location) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144 /* ComputedPropertyName */) { + if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { return ts.getTextOfIdentifierOrLiteral(location); } // Try to get the local symbol if we're dealing with an 'export default' @@ -75315,7 +78482,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 242 /* ImportSpecifier */ || location.parent.kind === 246 /* ExportSpecifier */) && + (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -75326,9 +78493,7 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -75349,6 +78514,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -75365,163 +78534,153 @@ var ts; return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; -})(ts || (ts = {})); -var ts; -(function (ts) { - /// Classifier - function createClassifier() { - var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false); - /// We do not have a full parser support to know when we should parse a regex or not - /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where - /// we have a series of divide operator. this list allows us to be more accurate by ruling out - /// locations where a regexp cannot exist. - var noRegexTable = []; - noRegexTable[71 /* Identifier */] = true; - noRegexTable[9 /* StringLiteral */] = true; - noRegexTable[8 /* NumericLiteral */] = true; - noRegexTable[12 /* RegularExpressionLiteral */] = true; - noRegexTable[99 /* ThisKeyword */] = true; - noRegexTable[43 /* PlusPlusToken */] = true; - noRegexTable[44 /* MinusMinusToken */] = true; - noRegexTable[20 /* CloseParenToken */] = true; - noRegexTable[22 /* CloseBracketToken */] = true; - noRegexTable[18 /* CloseBraceToken */] = true; - noRegexTable[101 /* TrueKeyword */] = true; - noRegexTable[86 /* FalseKeyword */] = true; - // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) - // classification on template strings. Because of the context free nature of templates, - // the only precise way to classify a template portion would be by propagating the stack across - // lines, just as we do with the end-of-line state. However, this is a burden for implementers, - // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead - // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. - // Situations in which this fails are - // 1) When template strings are nested across different lines: - // `hello ${ `world - // ` }` - // - // Where on the second line, you will get the closing of a template, - // a closing curly, and a new template. - // - // 2) When substitution expressions have curly braces and the curly brace falls on the next line: - // `hello ${ () => { - // return "world" } } ` - // - // Where on the second line, you will get the 'return' keyword, - // a string literal, and a template end consisting of '} } `'. - var templateStack = []; - /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ - function canFollow(keyword1, keyword2) { - if (ts.isAccessibilityModifier(keyword1)) { - if (keyword2 === 125 /* GetKeyword */ || - keyword2 === 135 /* SetKeyword */ || - keyword2 === 123 /* ConstructorKeyword */ || - keyword2 === 115 /* StaticKeyword */) { - // Allow things like "public get", "public constructor" and "public static". - // These are all legal. - return true; + function getSourceFileImportLocation(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } } - // Any other keyword following "public" is actually an identifier an not a real - // keyword. - return false; } - // Assume any other keyword combination is legal. This can be refined in the future - // if there are more cases we want the classifier to be better at. - return true; } - function convertClassifications(classifications, text) { - var entries = []; - var dense = classifications.spans; - var lastEnd = 0; - for (var i = 0; i < dense.length; i += 3) { - var start = dense[i]; - var length_6 = dense[i + 1]; - var type = dense[i + 2]; - // Make a whitespace entry between the last item and this one. - if (lastEnd >= 0) { - var whitespaceLength_1 = start - lastEnd; - if (whitespaceLength_1 > 0) { - entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); - } - } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; - } - var whitespaceLength = text.length - lastEnd; - if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); - } - return { entries: entries, finalLexState: classifications.endOfLineState }; - } - function convertClassification(type) { - switch (type) { - case 1 /* comment */: return ts.TokenClass.Comment; - case 3 /* keyword */: return ts.TokenClass.Keyword; - case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; - case 5 /* operator */: return ts.TokenClass.Operator; - case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; - case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; - case 10 /* punctuation */: return ts.TokenClass.Punctuation; - case 2 /* identifier */: - case 11 /* className */: - case 12 /* enumName */: - case 13 /* interfaceName */: - case 14 /* moduleName */: - case 15 /* typeParameterName */: - case 16 /* typeAliasName */: - case 9 /* text */: - case 17 /* parameterName */: - default: - return ts.TokenClass.Identifier; + } + ts.getSourceFileImportLocation = getSourceFileImportLocation; + /** + * Creates a deep, memberwise clone of a node with no source map location. + * + * WARNING: This is an expensive operation and is only intended to be used in refactorings + * and code fixes (because those are triggered by explicit user actions). + */ + function getSynthesizedDeepClone(node) { + if (node === undefined) { + return undefined; + } + var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + if (visited === node) { + // This only happens for leaf nodes - internal nodes always see their children change. + var clone_7 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_7)) { + clone_7.textSourceNode = node; } + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; + } + clone_7.pos = node.pos; + clone_7.end = node.end; + return clone_7; } + // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update + // the new node created by visitEachChild with the extra changes getSynthesizedClone + // would have made. + visited.parent = undefined; + return visited; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + /** + * Sets EmitFlags to suppress leading and trailing trivia on the node. + */ + /* @internal */ + function suppressLeadingAndTrailingTrivia(node) { + ts.Debug.assert(node !== undefined); + suppressLeading(node); + suppressTrailing(node); + function suppressLeading(node) { + ts.addEmitFlags(node, 512 /* NoLeadingComments */); + var firstChild = ts.forEachChild(node, function (child) { return child; }); + if (firstChild) { + suppressLeading(firstChild); + } + } + function suppressTrailing(node) { + ts.addEmitFlags(node, 1024 /* NoTrailingComments */); + var lastChild = undefined; + ts.forEachChild(node, function (child) { return (lastChild = child, undefined); }, function (children) { + // As an optimization, jump straight to the end of the list. + if (children.length) { + lastChild = ts.last(children); + } + return undefined; + }); + if (lastChild) { + suppressTrailing(lastChild); + } + } + } + ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createClassifier() { + var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { - return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); } // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), // we will be more conservative in order to avoid conflicting with the syntactic classifier. function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { - var offset = 0; var token = 0 /* Unknown */; var lastNonTriviaToken = 0 /* Unknown */; - // Empty out the template stack for reuse. - while (templateStack.length > 0) { - templateStack.pop(); - } - // If we're in a string literal, then prepend: "\ - // (and a newline). That way when we lex we'll think we're still in a string literal. + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` // - // If we're in a multiline comment, then prepend: /* - // (and a newline). That way when we lex we'll think we're still in a multiline comment. - switch (lexState) { - case 3 /* InDoubleQuoteStringLiteral */: - text = "\"\\\n" + text; - offset = 3; - break; - case 2 /* InSingleQuoteStringLiteral */: - text = "'\\\n" + text; - offset = 3; - break; - case 1 /* InMultiLineCommentTrivia */: - text = "/*\n" + text; - offset = 3; - break; - case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: - text = "`\n" + text; - offset = 2; - break; - case 5 /* InTemplateMiddleOrTail */: - text = "}\n" + text; - offset = 2; - // falls through - case 6 /* InTemplateSubstitutionPosition */: - templateStack.push(14 /* TemplateHead */); - break; + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate; + text = prefix + text; + var offset = prefix.length; + if (pushTemplate) { + templateStack.push(14 /* TemplateHead */); } scanner.setText(text); - var result = { - endOfLineState: 0 /* None */, - spans: [] - }; + var endOfLineState = 0 /* None */; + var spans = []; // We can run into an unfortunate interaction between the lexical and syntactic classifier // when the user is typing something generic. Consider the case where the user types: // @@ -75545,55 +78704,63 @@ var ts; do { token = scanner.scan(); if (!ts.isTrivia(token)) { - if ((token === 41 /* SlashToken */ || token === 63 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { - if (scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + handleToken(); + lastNonTriviaToken = token; + } + var end = scanner.getTextPos(); + pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans); + if (end >= text.length) { + var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack)); + if (end_1 !== undefined) { + endOfLineState = end_1; + } + } + } while (token !== 1 /* EndOfFileToken */); + function handleToken() { + switch (token) { + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 12 /* RegularExpressionLiteral */) { token = 12 /* RegularExpressionLiteral */; } - } - else if (lastNonTriviaToken === 23 /* DotToken */ && isKeyword(token)) { - token = 71 /* Identifier */; - } - else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { - // We have two keywords in a row. Only treat the second as a keyword if - // it's a sequence that could legally occur in the language. Otherwise - // treat it as an identifier. This way, if someone writes "private var" - // we recognize that 'var' is actually an identifier here. - token = 71 /* Identifier */; - } - else if (lastNonTriviaToken === 71 /* Identifier */ && - token === 27 /* LessThanToken */) { - // Could be the start of something generic. Keep track of that by bumping - // up the current count of generic contexts we may be in. - angleBracketStack++; - } - else if (token === 29 /* GreaterThanToken */ && angleBracketStack > 0) { - // If we think we're currently in something generic, then mark that that - // generic entity is complete. - angleBracketStack--; - } - else if (token === 119 /* AnyKeyword */ || - token === 136 /* StringKeyword */ || - token === 133 /* NumberKeyword */ || - token === 122 /* BooleanKeyword */ || - token === 137 /* SymbolKeyword */) { + break; + case 27 /* LessThanToken */: + if (lastNonTriviaToken === 71 /* Identifier */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + break; + case 29 /* GreaterThanToken */: + if (angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + break; + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, // causing a noisy experience for the user. token = 71 /* Identifier */; } - } - else if (token === 14 /* TemplateHead */) { + break; + case 14 /* TemplateHead */: templateStack.push(token); - } - else if (token === 17 /* OpenBraceToken */) { + break; + case 17 /* OpenBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { templateStack.push(token); } - } - else if (token === 18 /* CloseBraceToken */) { + break; + case 18 /* CloseBraceToken */: // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { @@ -75613,183 +78780,279 @@ var ts; templateStack.pop(); } } - } - lastNonTriviaToken = token; - } - processToken(); - } while (token !== 1 /* EndOfFileToken */); - return result; - function processToken() { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); - addResult(start, end, classFromKind(token)); - if (end >= text.length) { - if (token === 9 /* StringLiteral */) { - // Check to see if we finished up on a multiline string literal. - var tokenText = scanner.getTokenText(); - if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; - while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { - numBackslashes++; - } - // If we have an odd number of backslashes, then the multiline string is unclosed - if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); - result.endOfLineState = quoteChar === 34 /* doubleQuote */ - ? 3 /* InDoubleQuoteStringLiteral */ - : 2 /* InSingleQuoteStringLiteral */; - } + break; + default: + if (!ts.isKeyword(token)) { + break; } - } - else if (token === 3 /* MultiLineCommentTrivia */) { - // Check to see if the multiline comment was unclosed. - if (scanner.isUnterminated()) { - result.endOfLineState = 1 /* InMultiLineCommentTrivia */; + if (lastNonTriviaToken === 23 /* DotToken */) { + token = 71 /* Identifier */; } - } - else if (ts.isTemplateLiteralKind(token)) { - if (scanner.isUnterminated()) { - if (token === 16 /* TemplateTail */) { - result.endOfLineState = 5 /* InTemplateMiddleOrTail */; - } - else if (token === 13 /* NoSubstitutionTemplateLiteral */) { - result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; - } - else { - ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); - } + else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 71 /* Identifier */; } - } - else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 14 /* TemplateHead */) { - result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; - } } } - function addResult(start, end, classification) { - if (classification === 8 /* whiteSpace */) { - // Don't bother with whitespace classifications. They're not needed. - return; - } - if (start === 0 && offset > 0) { - // We're classifying the first token, and this was a case where we prepended - // text. We should consider the start of this token to be at the start of - // the original text. - start += offset; + return { endOfLineState: endOfLineState, spans: spans }; + } + return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications }; + } + ts.createClassifier = createClassifier; + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = ts.arrayToNumericMap([ + 71 /* Identifier */, + 9 /* StringLiteral */, + 8 /* NumericLiteral */, + 12 /* RegularExpressionLiteral */, + 99 /* ThisKeyword */, + 43 /* PlusPlusToken */, + 44 /* MinusMinusToken */, + 20 /* CloseParenToken */, + 22 /* CloseBracketToken */, + 18 /* CloseBraceToken */, + 101 /* TrueKeyword */, + 86 /* FalseKeyword */, + ], function (token) { return token; }, function () { return true; }); + function getNewEndOfLineState(scanner, token, lastOnTemplateStack) { + switch (token) { + case 9 /* StringLiteral */: { + // Check to see if we finished up on a multiline string literal. + if (!scanner.isUnterminated()) + return undefined; + var tokenText = scanner.getTokenText(); + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if ((numBackslashes & 1) === 0) + return undefined; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + } + case 3 /* MultiLineCommentTrivia */: + // Check to see if the multiline comment was unclosed. + return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined; + default: + if (ts.isTemplateLiteralKind(token)) { + if (!scanner.isUnterminated()) { + return undefined; + } + switch (token) { + case 16 /* TemplateTail */: + return 5 /* InTemplateMiddleOrTail */; + case 13 /* NoSubstitutionTemplateLiteral */: + return 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + default: + throw ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } } - // All our tokens are in relation to the augmented text. Move them back to be - // relative to the original text. - start -= offset; - end -= offset; - var length = end - start; - if (length > 0) { - result.spans.push(start); - result.spans.push(length); - result.spans.push(classification); + return lastOnTemplateStack === 14 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined; + } + } + function pushEncodedClassification(start, end, offset, classification, result) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended text. + // We should consider the start of this token to be at the start of the original text. + start += offset; + } + var length = end - start; + if (length > 0) { + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + result.push(start - offset, length, classification); + } + } + function convertClassificationsToResult(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0; i < dense.length; i += 3) { + var start = dense[i]; + var length_6 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } - function isBinaryExpressionOperatorToken(token) { - switch (token) { - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 48 /* AmpersandToken */: - case 50 /* CaretToken */: - case 49 /* BarToken */: - case 53 /* AmpersandAmpersandToken */: - case 54 /* BarBarToken */: - case 69 /* BarEqualsToken */: - case 68 /* AmpersandEqualsToken */: - case 70 /* CaretEqualsToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 59 /* PlusEqualsToken */: - case 60 /* MinusEqualsToken */: - case 61 /* AsteriskEqualsToken */: - case 63 /* SlashEqualsToken */: - case 64 /* PercentEqualsToken */: - case 58 /* EqualsToken */: - case 26 /* CommaToken */: - return true; - default: - return false; - } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace }); } - function isPrefixUnaryExpressionOperatorToken(token) { - switch (token) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - return true; - default: - return false; - } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return ts.TokenClass.Comment; + case 3 /* keyword */: return ts.TokenClass.Keyword; + case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral; + case 5 /* operator */: return ts.TokenClass.Operator; + case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral; + case 8 /* whiteSpace */: return ts.TokenClass.Whitespace; + case 10 /* punctuation */: return ts.TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + return ts.TokenClass.Identifier; + } + } + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (!ts.isAccessibilityModifier(keyword1)) { + // Assume any other keyword combination is legal. + // This can be refined in the future if there are more cases we want the classifier to be better at. + return true; } - function isKeyword(token) { - return token >= 72 /* FirstKeyword */ && token <= 142 /* LastKeyword */; + switch (keyword2) { + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + return true; // Allow things like "public get", "public constructor" and "public static". + default: + return false; // Any other keyword following "public" is actually an identifier, not a real keyword. } - function classFromKind(token) { - if (isKeyword(token)) { - return 3 /* keyword */; - } - else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { - return 5 /* operator */; - } - else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { - return 10 /* punctuation */; - } - switch (token) { - case 8 /* NumericLiteral */: - return 4 /* numericLiteral */; - case 9 /* StringLiteral */: + } + function getPrefixFromLexState(lexState) { + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + return { prefix: "\"\\\n" }; + case 2 /* InSingleQuoteStringLiteral */: + return { prefix: "'\\\n" }; + case 1 /* InMultiLineCommentTrivia */: + return { prefix: "/*\n" }; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + return { prefix: "`\n" }; + case 5 /* InTemplateMiddleOrTail */: + return { prefix: "}\n", pushTemplate: true }; + case 6 /* InTemplateSubstitutionPosition */: + return { prefix: "", pushTemplate: true }; + case 0 /* None */: + return { prefix: "" }; + default: + throw ts.Debug.assertNever(lexState); + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 48 /* AmpersandToken */: + case 50 /* CaretToken */: + case 49 /* BarToken */: + case 53 /* AmpersandAmpersandToken */: + case 54 /* BarBarToken */: + case 69 /* BarEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 59 /* PlusEqualsToken */: + case 60 /* MinusEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 58 /* EqualsToken */: + case 26 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function classFromKind(token) { + if (ts.isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 17 /* FirstPunctuation */ && token <= 70 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* StringLiteral */: + return 6 /* stringLiteral */; + case 12 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 71 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; - case 12 /* RegularExpressionLiteral */: - return 7 /* regularExpressionLiteral */; - case 7 /* ConflictMarkerTrivia */: - case 3 /* MultiLineCommentTrivia */: - case 2 /* SingleLineCommentTrivia */: - return 1 /* comment */; - case 5 /* WhitespaceTrivia */: - case 4 /* NewLineTrivia */: - return 8 /* whiteSpace */; - case 71 /* Identifier */: - default: - if (ts.isTemplateLiteralKind(token)) { - return 6 /* stringLiteral */; - } - return 2 /* identifier */; - } + } + return 2 /* identifier */; } - return { - getClassificationsForLine: getClassificationsForLine, - getEncodedLexicalClassifications: getEncodedLexicalClassifications - }; } - ts.createClassifier = createClassifier; /* @internal */ function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - return convertClassifications(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); + return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); } ts.getSemanticClassifications = getSemanticClassifications; function checkForClassificationCancellation(cancellationToken, kind) { @@ -75804,90 +79067,78 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } /* @internal */ function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { - var result = []; - processNode(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; - function pushClassification(start, length, type) { - result.push(start); - result.push(length); - result.push(type); - } - function classifySymbol(symbol, meaningAtPosition) { - var flags = symbol.getFlags(); - if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + var spans = []; + sourceFile.forEachChild(function cb(node) { + // Only walk into nodes that intersect the requested span. + if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (flags & 32 /* Class */) { - return 11 /* className */; - } - else if (flags & 384 /* Enum */) { - return 12 /* enumName */; - } - else if (flags & 524288 /* TypeAlias */) { - return 16 /* typeAliasName */; - } - else if (meaningAtPosition & 2 /* Type */) { - if (flags & 64 /* Interface */) { - return 13 /* interfaceName */; - } - else if (flags & 262144 /* TypeParameter */) { - return 15 /* typeParameterName */; - } - } - else if (flags & 1536 /* Module */) { - // Only classify a module as such if - // - It appears in a namespace context. - // - There exists a module declaration which actually impacts the value side. - if (meaningAtPosition & 4 /* Namespace */ || - (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { - return 14 /* moduleName */; + checkForClassificationCancellation(cancellationToken, node.kind); + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) { + var symbol = typeChecker.getSymbolAtLocation(node); + var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker); + if (type) { + pushClassification(node.getStart(sourceFile), node.getEnd(), type); } } + node.forEachChild(cb); + }); + return { spans: spans, endOfLineState: 0 /* None */ }; + function pushClassification(start, end, type) { + spans.push(start); + spans.push(end - start); + spans.push(type); + } + } + ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + function classifySymbol(symbol, meaningAtPosition, checker) { + var flags = symbol.getFlags(); + if ((flags & 2885600 /* Classifiable */) === 0 /* None */) { return undefined; - /** - * Returns true if there exists a module that introduces entities on the value side. - */ - function hasValueSideModule(symbol) { - return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 233 /* ModuleDeclaration */ && - ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; - }); - } } - function processNode(node) { - // Only walk into nodes that intersect the requested span. - if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { - var kind = node.kind; - checkForClassificationCancellation(cancellationToken, kind); - if (kind === 71 /* Identifier */ && !ts.nodeIsMissing(node)) { - var identifier = node; - // Only bother calling into the typechecker if this is an identifier that - // could possibly resolve to a type name. This makes classification run - // in a third of the time it would normally take. - if (classifiableNames.has(identifier.escapedText)) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); - } - } - } - } - ts.forEachChild(node, processNode); - } + else if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined; + } + else if (flags & 2097152 /* Alias */) { + return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker); + } + else if (meaningAtPosition & 2 /* Type */) { + return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined; + } + else { + return undefined; } } - ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; + /** Returns true if there exists a module that introduces entities on the value side. */ + function hasValueSideModule(symbol) { + return ts.some(symbol.declarations, function (declaration) { + return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } function getClassificationTypeName(type) { switch (type) { case 1 /* comment */: return "comment" /* comment */; @@ -75915,7 +79166,7 @@ var ts; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; } } - function convertClassifications(classifications) { + function convertClassificationsToSpans(classifications) { ts.Debug.assert(classifications.spans.length % 3 === 0); var dense = classifications.spans; var result = []; @@ -75929,7 +79180,7 @@ var ts; } /* @internal */ function getSyntacticClassifications(cancellationToken, sourceFile, span) { - return convertClassifications(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); + return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span)); } ts.getSyntacticClassifications = getSyntacticClassifications; /* @internal */ @@ -75937,8 +79188,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -76023,16 +79274,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 279 /* JSDocParameterTag */: + case 284 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 282 /* JSDocTemplateTag */: + case 287 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 281 /* JSDocTypeTag */: + case 286 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 280 /* JSDocReturnTag */: + case 285 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -76119,22 +79370,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 251 /* JsxOpeningElement */: + case 252 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 250 /* JsxSelfClosingElement */: + case 251 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 253 /* JsxAttribute */: + case 257 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -76162,17 +79413,17 @@ var ts; if (token) { if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 226 /* VariableDeclaration */ || - token.parent.kind === 149 /* PropertyDeclaration */ || - token.parent.kind === 146 /* Parameter */ || - token.parent.kind === 253 /* JsxAttribute */) { + if (token.parent.kind === 227 /* VariableDeclaration */ || + token.parent.kind === 150 /* PropertyDeclaration */ || + token.parent.kind === 147 /* Parameter */ || + token.parent.kind === 257 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 194 /* BinaryExpression */ || - token.parent.kind === 192 /* PrefixUnaryExpression */ || - token.parent.kind === 193 /* PostfixUnaryExpression */ || - token.parent.kind === 195 /* ConditionalExpression */) { + if (token.parent.kind === 195 /* BinaryExpression */ || + token.parent.kind === 193 /* PrefixUnaryExpression */ || + token.parent.kind === 194 /* PostfixUnaryExpression */ || + token.parent.kind === 196 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -76182,7 +79433,7 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { - return token.parent.kind === 253 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token.parent.kind === 257 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -76198,32 +79449,32 @@ var ts; else if (tokenKind === 71 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 230 /* InterfaceDeclaration */: + case 231 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 146 /* Parameter */: + case 147 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -76259,46 +79510,39 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); - var entries; if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { - entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); } else { - entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); } } else { // Check for node modules - entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); } - return { - isGlobalCompletion: false, - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries - }; } - PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames; + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already - rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); + rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within - var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; }); // Now find a path for each potential directory that is to be merged with the one containing the script - return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); + return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); @@ -76343,8 +79587,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var filePath = files_2[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -76361,8 +79605,8 @@ var ts; // If possible, get folder completion as well var directories = tryGetDirectories(host, baseDirectory); if (directories) { - for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { - var directory = directories_2[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var directory = directories_1[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); result.push(createCompletionEntryForModule(directoryName, "directory" /* directory */, span)); } @@ -76379,42 +79623,56 @@ var ts; */ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result; + var result = []; + var fileExtensions = ts.getSupportedExtensions(compilerOptions); if (baseUrl) { - var fileExtensions = ts.getSupportedExtensions(compilerOptions); var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host); - if (paths) { - for (var path in paths) { - if (paths.hasOwnProperty(path)) { - if (path === "*") { - if (paths[path]) { - for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) { - var pattern = _a[_i]; - for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { - var match = _c[_b]; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - } - } - } - } - else if (ts.startsWith(path, fragment)) { - var entry = paths[path] && paths[path].length === 1 && paths[path][0]; - if (entry) { - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + var _loop_6 = function (path) { + if (!paths.hasOwnProperty(path)) + return "continue"; + var patterns = paths[path]; + if (!patterns) + return "continue"; + if (path === "*") { + for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { + var pattern = patterns_1[_i]; + var _loop_7 = function (match) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (result.some(function (entry) { return entry.name === match; })) + return "continue"; + result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); + }; + for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { + var match = _b[_a]; + _loop_7(match); } } } + else if (ts.startsWith(path, fragment)) { + if (patterns.length === 1) { + if (result.some(function (entry) { return entry.name === path; })) + return "continue"; + result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); + } + } + }; + for (var path in paths) { + _loop_6(path); } } - else { - result = []; + if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (host.directoryExists(nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + } + }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { - var moduleName = _e[_d]; + for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { + var moduleName = _a[_i]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; @@ -76428,7 +79686,7 @@ var ts; var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = fragment.indexOf(ts.directorySeparator) !== -1; + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); @@ -76460,7 +79718,7 @@ var ts; } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module - var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; + var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); @@ -76493,53 +79751,36 @@ var ts; } } } - return ts.deduplicate(nonRelativeModuleNames); + return ts.deduplicate(nonRelativeModuleNames, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - if (!token) { - return undefined; - } var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - if (!commentRanges || !commentRanges.length) { - return undefined; - } - var range = ts.forEach(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end && commentRange; }); + var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { return undefined; } - var completionInfo = { - /** - * We don't want the editor to offer any other completions, such as snippets, inside a comment. - */ - isGlobalCompletion: false, - isMemberCompletion: false, - /** - * The user may type in a path that doesn't yet exist, creating a "new identifier" - * with respect to the collection of identifiers the server is aware of. - */ - isNewIdentifierLocation: true, - entries: [] - }; - var text = sourceFile.text.substr(range.pos, position - range.pos); + var text = sourceFile.text.slice(range.pos, position); var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - if (kind === "path") { + if (!match) { + return undefined; + } + var prefix = match[1], kind = match[2], toComplete = match[3]; + var scriptPath = ts.getDirectoryPath(sourceFile.path); + switch (kind) { + case "path": { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); + return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); } - else { + case "types": { // Give completions based on the typings available - var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + var span_11 = ts.createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); + return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } + default: + return undefined; } - return completionInfo; } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { @@ -76554,21 +79795,20 @@ var ts; else if (host.getDirectories) { var typeRoots = void 0; try { - // Wrap in try catch because getEffectiveTypeRoots touches the filesystem typeRoots = ts.getEffectiveTypeRoots(options, host); } - catch (e) { } + catch (_b) { } if (typeRoots) { - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; + for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { + var root = typeRoots_2[_c]; getCompletionEntriesFromDirectories(host, root, span, result); } } } if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories - for (var _c = 0, _d = findPackageJsons(scriptPath, host); _c < _d.length; _c++) { - var packageJson = _d[_c]; + for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { + var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); getCompletionEntriesFromDirectories(host, typesDir, span, result); } @@ -76579,32 +79819,23 @@ var ts; if (host.getDirectories && tryDirectoryExists(host, directory)) { var directories = tryGetDirectories(host, directory); if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); } } } } - function findPackageJsons(currentDir, host) { + function findPackageJsons(directory, host) { var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent = ts.getDirectoryPath(currentDir); - if (currentDir === parent) { - break; - } - currentDir = parent; - } - else { - break; + ts.forEachAncestorDirectory(directory, function (ancestor) { + var currentConfigPath = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (!currentConfigPath) { + return true; // break out } - } + paths.push(currentConfigPath); + }); return paths; } function enumerateNodeModulesVisibleToScript(host, scriptPath) { @@ -76704,7 +79935,7 @@ var ts; try { return ts.directoryProbablyExists(path, host); } - catch (e) { } + catch (_a) { } return undefined; } function tryIOAndConsumeErrors(host, toApply) { @@ -76715,7 +79946,7 @@ var ts; try { return toApply && toApply.apply(host, args); } - catch (e) { } + catch (_a) { } return undefined; } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); @@ -76733,20 +79964,21 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries_2 && pathCompletionsInfo(entries_2); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { + location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: @@ -76761,23 +79993,25 @@ var ts; }] }; } if (request) { - var entries_2 = request.kind === "JsDocTagName" + var entries_3 = request.kind === "JsDocTagName" + // If the current position is a jsDoc tag name, only tag names should be provided for completion ? ts.JsDoc.getJSDocTagNameCompletions() : request.kind === "JsDocTag" + // If the current position is a jsDoc tag, only tags should be provided for completion ? ts.JsDoc.getJSDocTagCompletions() : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -76796,7 +80030,7 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName)) { + if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { return; } uniqueNames.set(realName, true); @@ -76811,11 +80045,11 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); if (!displayName) { return undefined; } @@ -76831,34 +80065,57 @@ var ts; kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", + source: getSourceFromOrigin(origin), + hasAction: trueOrUndefined(origin !== undefined), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + function trueOrUndefined(b) { + return b ? true : undefined; + } + function getSourceFromOrigin(origin) { + return origin && ts.stripQuotes(origin.moduleSymbol.name); + } + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); - var uniqueNames = ts.createMap(); + // Tracks unique names. + // We don't set this for global variables or completions from external module exports, because we can have multiple of those. + // Based on the order we add things we will always see locals first, then globals, then module exports. + // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. + var uniques = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); - if (entry) { - var id = entry.name; - if (!uniqueNames.has(id)) { - entries.push(entry); - uniqueNames.set(id, true); - } + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); + } + entries.push(entry); } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniqueNames; + return uniques; } function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { var node = ts.findPrecedingToken(position, sourceFile); if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 261 /* PropertyAssignment */ && - node.parent.parent.kind === 178 /* ObjectLiteralExpression */ && + if (node.parent.kind === 265 /* PropertyAssignment */ && + node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -76883,12 +80140,17 @@ var ts; // a['/*completion position*/'] return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); } - else if (node.parent.kind === 238 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ + || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) + || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); - return Completions.PathCompletions.getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker); + // export * from "/*completion position*/"; + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + return pathCompletionsInfo(entries); } else if (isEqualityExpression(node.parent)) { // Get completions from the type of the other operand @@ -76915,6 +80177,17 @@ var ts; return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); } } + function pathCompletionsInfo(entries) { + return { + // We don't want the editor to offer any other completions, such as snippets, inside a comment. + isGlobalCompletion: false, + isMemberCompletion: false, + // The user may type in a path that doesn't yet exist, creating a "new identifier" + // with respect to the collection of identifiers the server is aware of. + isNewIdentifierLocation: true, + entries: entries, + }; + } function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; @@ -76962,13 +80235,13 @@ var ts; } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } - if (type && type.flags & 16384 /* TypeParameter */) { + if (type && type.flags & 32768 /* TypeParameter */) { type = typeChecker.getBaseConstraintOfType(type); } if (!type) { return; } - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); @@ -76987,59 +80260,133 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; - // Find the symbol with the matching entry name. - // We don't need to perform character checks here because we're only comparing the - // name against 'entryName' (which is known to be good), not building a new - // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); - if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; - } - } - // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); - if (keywordCompletion) { - return { - name: entryName, - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined - }; - } - return undefined; - } - Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { + var name = _a.name, source = _a.source; + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); if (!completionData) { - return undefined; + return { type: "none" }; + } + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; + if (request) { + return { type: "request", request: request }; } - var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); + var symbol = ts.find(symbols, function (s) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; + return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name + && getSourceFromOrigin(origin) === source; + }); + return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + } + function getSymbolName(symbol, origin, target) { + return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + } + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var name = entryId.name; + // Compute all the completion symbols again. + var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + switch (symbolCompletion.type) { + case "request": { + var request = symbolCompletion.request; + switch (request.kind) { + case "JsDocTagName": + return ts.JsDoc.getJSDocTagNameCompletionDetails(name); + case "JsDocTag": + return ts.JsDoc.getJSDocTagCompletionDetails(name); + case "JsDocParameterName": + return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + default: + return ts.Debug.assertNever(request); + } + } + case "symbol": { + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); + var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; + } + case "none": { + // Didn't find a symbol with this name. See if we can find a keyword instead. + if (ts.some(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; })) { + return { + name: name, + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], + documentation: undefined, + tags: undefined, + codeActions: undefined, + source: undefined, + }; + } + return undefined; + } + } + } + Completions.getCompletionEntryDetails = getCompletionEntryDetails; + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo) { + return { codeActions: undefined, sourceDisplay: undefined }; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); + ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + formatContext: formatContext, + symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), + getCanonicalFileName: getCanonicalFileName, + symbolToken: undefined, + kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + }); + return { sourceDisplay: sourceDisplay, codeActions: codeActions }; + } + function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { + var result = []; + ts.codefix.forEachExternalModule(checker, allSourceFiles, function (module) { + for (var _i = 0, _a = checker.getExportsOfModule(module); _i < _a.length; _i++) { + var exported = _a[_i]; + if (ts.skipAlias(exported, checker) === exportedSymbol) { + result.push(module); + } + } + }); + return result; + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { + var completion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { - var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); + function getRecommendedCompletion(currentToken, checker /*, symbolToOriginInfoMap: SymbolOriginInfoMap*/) { + var ty = checker.getContextualType(currentToken); + var symbol = ty && ty.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + } + function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { + var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); + if (chain) + return ts.first(chain); + return isModuleSymbol(symbol.parent) ? symbol : symbol.parent && getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker); + } + function isModuleSymbol(symbol) { + return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); + } + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 @@ -77088,11 +80435,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 284 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 289 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -77103,7 +80450,19 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { + symbols: ts.emptyArray, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0 /* None */, + symbolToOriginInfoMap: undefined, + recommendedCompletion: undefined, + }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -77141,11 +80500,11 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 179 /* PropertyAccessExpression */) { + if (parent.kind === 180 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent.kind === 143 /* QualifiedName */) { + else if (parent.kind === 144 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -77159,26 +80518,26 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 179 /* PropertyAccessExpression */) { + if (parent && parent.kind === 180 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } switch (parent.kind) { - case 252 /* JsxClosingElement */: + case 253 /* JsxClosingElement */: if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { // It has a left-hand side, so we're not in an opening JSX tag. break; } // falls through - case 250 /* JsxSelfClosingElement */: - case 249 /* JsxElement */: - case 251 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 250 /* JsxElement */: + case 252 /* JsxOpeningElement */: if (contextToken.kind === 27 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; @@ -77194,6 +80553,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -77226,15 +80586,15 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 277 /* JSDocAugmentsTag */: - case 279 /* JSDocParameterTag */: - case 284 /* JSDocPropertyTag */: - case 280 /* JSDocReturnTag */: - case 281 /* JSDocTypeTag */: - case 283 /* JSDocTypedefTag */: + case 284 /* JSDocParameterTag */: + case 289 /* JSDocPropertyTag */: + case 285 /* JSDocReturnTag */: + case 286 /* JSDocTypeTag */: + case 288 /* JSDocTypedefTag */: return true; } } @@ -77266,7 +80626,7 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 /* SourceFile */ && d.kind !== 233 /* ModuleDeclaration */ && d.kind !== 232 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 269 /* SourceFile */ && d.kind !== 234 /* ModuleDeclaration */ && d.kind !== 233 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -77278,23 +80638,21 @@ var ts; } } function addTypeProperties(type) { - // Filter private properties - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } - } - if (isJavaScriptFile && type.flags & 65536 /* Union */) { + if (ts.isSourceFileJavaScript(sourceFile)) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part // of the individual types to a higher status since we know what they are. - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); + } + else { + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } } } } @@ -77327,7 +80685,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType = void 0; - if ((jsxContainer.kind === 250 /* JsxSelfClosingElement */) || (jsxContainer.kind === 251 /* JsxOpeningElement */)) { + if ((jsxContainer.kind === 251 /* JsxSelfClosingElement */) || (jsxContainer.kind === 252 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { @@ -77375,17 +80733,22 @@ var ts; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; if (scopeNode) { isGlobalCompletion = - scopeNode.kind === 265 /* SourceFile */ || - scopeNode.kind === 196 /* TemplateExpression */ || - scopeNode.kind === 256 /* JsxExpression */ || + scopeNode.kind === 269 /* SourceFile */ || + scopeNode.kind === 197 /* TemplateExpression */ || + scopeNode.kind === 260 /* JsxExpression */ || + scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions ts.isStatement(scopeNode); } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + if (options.includeExternalModuleExports) { + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); + } + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -77413,22 +80776,22 @@ var ts; function isContextTokenValueLocation(contextToken) { return contextToken && contextToken.kind === 103 /* TypeOfKeyword */ && - contextToken.parent.kind === 162 /* TypeQuery */; + contextToken.parent.kind === 163 /* TypeQuery */; } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 56 /* ColonToken */: - return parentKind === 149 /* PropertyDeclaration */ || - parentKind === 148 /* PropertySignature */ || - parentKind === 146 /* Parameter */ || - parentKind === 226 /* VariableDeclaration */ || + return parentKind === 150 /* PropertyDeclaration */ || + parentKind === 149 /* PropertySignature */ || + parentKind === 147 /* Parameter */ || + parentKind === 227 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 58 /* EqualsToken */: - return parentKind === 231 /* TypeAliasDeclaration */; + return parentKind === 232 /* TypeAliasDeclaration */; case 118 /* AsKeyword */: - return parentKind === 202 /* AsExpression */; + return parentKind === 203 /* AsExpression */; } } } @@ -77446,6 +80809,57 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) { + var tokenTextLowerCase = tokenText.toLowerCase(); + ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + // Don't add a completion for a re-export, only for the original. + // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + continue; + } + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + else { + name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); + } + } + if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -77471,11 +80885,11 @@ var ts; return true; } if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 251 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 252 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 252 /* JsxClosingElement */ || contextToken.parent.kind === 250 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 249 /* JsxElement */; + if (contextToken.parent.kind === 253 /* JsxClosingElement */ || contextToken.parent.kind === 251 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 250 /* JsxElement */; } } return false; @@ -77485,40 +80899,40 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 26 /* CommaToken */: - return containingNodeKind === 181 /* CallExpression */ // func( a, | - || containingNodeKind === 152 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 182 /* NewExpression */ // new C(a, | - || containingNodeKind === 177 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 194 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 160 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 182 /* CallExpression */ // func( a, | + || containingNodeKind === 153 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 183 /* NewExpression */ // new C(a, | + || containingNodeKind === 178 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 195 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 161 /* FunctionType */; // var x: (s: string, list| case 19 /* OpenParenToken */: - return containingNodeKind === 181 /* CallExpression */ // func( | - || containingNodeKind === 152 /* Constructor */ // constructor( | - || containingNodeKind === 182 /* NewExpression */ // new C(a| - || containingNodeKind === 185 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 168 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 182 /* CallExpression */ // func( | + || containingNodeKind === 153 /* Constructor */ // constructor( | + || containingNodeKind === 183 /* NewExpression */ // new C(a| + || containingNodeKind === 186 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 169 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 21 /* OpenBracketToken */: - return containingNodeKind === 177 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 157 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 144 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 178 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 158 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 145 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 128 /* ModuleKeyword */: // module | case 129 /* NamespaceKeyword */:// namespace | return true; case 23 /* DotToken */: - return containingNodeKind === 233 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 234 /* ModuleDeclaration */; // module A.| case 17 /* OpenBraceToken */: - return containingNodeKind === 229 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 230 /* ClassDeclaration */; // class A{ | case 58 /* EqualsToken */: - return containingNodeKind === 226 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 194 /* BinaryExpression */; // x = a| + return containingNodeKind === 227 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 195 /* BinaryExpression */; // x = a| case 14 /* TemplateHead */: - return containingNodeKind === 196 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 197 /* TemplateExpression */; // `aa ${| case 15 /* TemplateMiddle */: - return containingNodeKind === 205 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 206 /* TemplateSpan */; // `aa ${10} dd ${| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 150 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -77562,18 +80976,18 @@ var ts; allowStringLiteral = true; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 174 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 175 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -77584,12 +80998,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 146 /* Parameter */) { + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 147 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 151 /* MethodDeclaration */ || rootDeclaration.parent.kind === 154 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 152 /* MethodDeclaration */ || rootDeclaration.parent.kind === 155 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -77624,9 +81038,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 241 /* NamedImports */ ? - 238 /* ImportDeclaration */ : - 244 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 242 /* NamedImports */ ? + 239 /* ImportDeclaration */ : + 245 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -77718,8 +81132,8 @@ var ts; case 17 /* OpenBraceToken */: // import { | case 26 /* CommaToken */:// import { a as 0, | switch (contextToken.parent.kind) { - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return contextToken.parent; } } @@ -77762,6 +81176,11 @@ var ts; if (ts.isClassLike(location)) { return location; } + // class c { method() { } b| } + if (isFromClassElementDeclaration(location) && + location.parent.name === location) { + return location.parent.parent; + } break; default: if (isFromClassElementDeclaration(contextToken) && @@ -77772,7 +81191,7 @@ var ts; } } // class c { method() { } | method2() { } } - if (location && location.kind === 286 /* SyntaxList */ && ts.isClassLike(location.parent)) { + if (location && location.kind === 290 /* SyntaxList */ && ts.isClassLike(location.parent)) { return location.parent; } return undefined; @@ -77802,14 +81221,14 @@ var ts; case 28 /* LessThanSlashToken */: case 41 /* SlashToken */: case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 254 /* JsxAttributes */: - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 250 /* JsxSelfClosingElement */ || parent.kind === 251 /* JsxOpeningElement */)) { + case 180 /* PropertyAccessExpression */: + case 258 /* JsxAttributes */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 251 /* JsxSelfClosingElement */ || parent.kind === 252 /* JsxOpeningElement */)) { return parent; } - else if (parent.kind === 253 /* JsxAttribute */) { + else if (parent.kind === 257 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77821,7 +81240,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent && ((parent.kind === 253 /* JsxAttribute */) || (parent.kind === 255 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 257 /* JsxAttribute */) || (parent.kind === 259 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77831,8 +81250,8 @@ var ts; break; case 18 /* CloseBraceToken */: if (parent && - parent.kind === 256 /* JsxExpression */ && - parent.parent && parent.parent.kind === 253 /* JsxAttribute */) { + parent.kind === 260 /* JsxExpression */ && + parent.parent && parent.parent.kind === 257 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77840,7 +81259,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 255 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 259 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -77859,57 +81278,57 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 26 /* CommaToken */: - return containingNodeKind === 226 /* VariableDeclaration */ || - containingNodeKind === 227 /* VariableDeclarationList */ || - containingNodeKind === 208 /* VariableStatement */ || - containingNodeKind === 232 /* EnumDeclaration */ || // enum a { foo, | + return containingNodeKind === 227 /* VariableDeclaration */ || + containingNodeKind === 228 /* VariableDeclarationList */ || + containingNodeKind === 209 /* VariableStatement */ || + containingNodeKind === 233 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 230 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 23 /* DotToken */: - return containingNodeKind === 175 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 176 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: - return containingNodeKind === 176 /* BindingElement */; // var {x :html| + return containingNodeKind === 177 /* BindingElement */; // var {x :html| case 21 /* OpenBracketToken */: - return containingNodeKind === 175 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 176 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: - return containingNodeKind === 260 /* CatchClause */ || + return containingNodeKind === 264 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 232 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 230 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 163 /* TypeLiteral */; // const x : { | + return containingNodeKind === 233 /* EnumDeclaration */ || // enum a { | + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface a { | + containingNodeKind === 164 /* TypeLiteral */; // const x : { | case 25 /* SemicolonToken */: - return containingNodeKind === 148 /* PropertySignature */ && + return containingNodeKind === 149 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 230 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 163 /* TypeLiteral */); // const x : { a; | + (contextToken.parent.parent.kind === 231 /* InterfaceDeclaration */ || // interface a { f; | + contextToken.parent.parent.kind === 164 /* TypeLiteral */); // const x : { a; | case 27 /* LessThanToken */: - return containingNodeKind === 229 /* ClassDeclaration */ || // class A< | - containingNodeKind === 199 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 230 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 231 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 230 /* ClassDeclaration */ || // class A< | + containingNodeKind === 200 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 231 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 232 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 150 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: - return containingNodeKind === 146 /* Parameter */ || + return containingNodeKind === 147 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 175 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 176 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 146 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 147 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118 /* AsKeyword */: - return containingNodeKind === 242 /* ImportSpecifier */ || - containingNodeKind === 246 /* ExportSpecifier */ || - containingNodeKind === 240 /* NamespaceImport */; + return containingNodeKind === 243 /* ImportSpecifier */ || + containingNodeKind === 247 /* ExportSpecifier */ || + containingNodeKind === 241 /* NamespaceImport */; case 125 /* GetKeyword */: case 135 /* SetKeyword */: if (isFromClassElementDeclaration(contextToken)) { @@ -77967,7 +81386,7 @@ var ts; return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 152 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -78015,12 +81434,12 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 261 /* PropertyAssignment */ && - m.kind !== 262 /* ShorthandPropertyAssignment */ && - m.kind !== 176 /* BindingElement */ && - m.kind !== 151 /* MethodDeclaration */ && - m.kind !== 153 /* GetAccessor */ && - m.kind !== 154 /* SetAccessor */) { + if (m.kind !== 265 /* PropertyAssignment */ && + m.kind !== 266 /* ShorthandPropertyAssignment */ && + m.kind !== 177 /* BindingElement */ && + m.kind !== 152 /* MethodDeclaration */ && + m.kind !== 154 /* GetAccessor */ && + m.kind !== 155 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -78028,7 +81447,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 176 /* BindingElement */ && m.propertyName) { + if (m.kind === 177 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -78055,10 +81474,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 149 /* PropertyDeclaration */ && - m.kind !== 151 /* MethodDeclaration */ && - m.kind !== 153 /* GetAccessor */ && - m.kind !== 154 /* SetAccessor */) { + if (m.kind !== 150 /* PropertyDeclaration */ && + m.kind !== 152 /* MethodDeclaration */ && + m.kind !== 154 /* GetAccessor */ && + m.kind !== 155 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -78113,7 +81532,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 253 /* JsxAttribute */) { + if (attr.kind === 257 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -78128,19 +81547,30 @@ var ts; * * @return undefined if the name is of external module */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { - var name = symbol.name; + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + var name = getSymbolName(symbol, origin, target); if (!name) return undefined; // First check of the displayName is not external module; if it is an external module, it is not valid entry if (symbol.flags & 1920 /* Namespace */) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } + // If the symbol is for a member of an object type and is the internal name of an ES + // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + if (symbol.flags & 106500 /* ClassMember */) { + var escapedName = symbol.escapedName; + if (escapedName.length >= 3 && + escapedName.charCodeAt(0) === 95 /* _ */ && + escapedName.charCodeAt(1) === 95 /* _ */ && + escapedName.charCodeAt(2) === 64 /* at */) { + return undefined; + } + } return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } /** @@ -78178,7 +81608,10 @@ var ts; } function getAllKeywordCompletions() { var allKeywordsCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 142 /* LastKeyword */; i++) { + for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { + // "undefined" is a global variable, so don't need a keyword completion for it. + if (i === 139 /* UndefinedKeyword */) + continue; allKeywordsCompletions.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -78266,13 +81699,15 @@ var ts; * tries to only include those types which declare properties, not methods. * This ensures that we don't try providing completions for all the methods on e.g. Array. */ - function getPropertiesForCompletion(type, checker) { - if (!(type.flags & 65536 /* Union */)) { - return checker.getPropertiesOfType(type); + function getPropertiesForCompletion(type, checker, isForAccess) { + if (!(type.flags & 131072 /* Union */)) { + return type.getApparentProperties(); } var types = type.types; - var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 /* Primitive */ || checker.isArrayLikeType(memberType)); }); - // If there are no property-only types, just provide completions for every type as usual. + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + var filteredTypes = isForAccess ? types : types.filter(function (memberType) { + return !(memberType.flags & 16382 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); + }); return checker.getAllPossiblePropertiesOfTypes(filteredTypes); } })(Completions = ts.Completions || (ts.Completions = {})); @@ -78334,89 +81769,44 @@ var ts; } return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - // returns true if 'node' is defined and has a matching 'kind'. - function hasKind(node, kind) { - return node !== undefined && node.kind === kind; - } - // Null-propagating 'parent' function. - function parent(node) { - return node && node.parent; - } function getHighlightSpans(node, sourceFile) { - if (!node) { - return undefined; - } switch (node.kind) { case 90 /* IfKeyword */: case 82 /* ElseKeyword */: - if (hasKind(node.parent, 211 /* IfStatement */)) { - return getIfElseOccurrences(node.parent, sourceFile); - } - break; + return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined; case 96 /* ReturnKeyword */: - if (hasKind(node.parent, 219 /* ReturnStatement */)) { - return highlightSpans(getReturnOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences); case 100 /* ThrowKeyword */: - if (hasKind(node.parent, 223 /* ThrowStatement */)) { - return highlightSpans(getThrowOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences); case 102 /* TryKeyword */: case 74 /* CatchKeyword */: case 87 /* FinallyKeyword */: - var tryStatement = node.kind === 74 /* CatchKeyword */ ? parent(parent(node)) : parent(node); - if (hasKind(tryStatement, 224 /* TryStatement */)) { - return highlightSpans(getTryCatchFinallyOccurrences(tryStatement, sourceFile)); - } - break; + var tryStatement = node.kind === 74 /* CatchKeyword */ ? node.parent.parent : node.parent; + return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences); case 98 /* SwitchKeyword */: - if (hasKind(node.parent, 221 /* SwitchStatement */)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 73 /* CaseKeyword */: case 79 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 221 /* SwitchStatement */)) { - return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent.parent.parent)); - } - break; + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 72 /* BreakKeyword */: case 77 /* ContinueKeyword */: - if (hasKind(node.parent, 218 /* BreakStatement */) || hasKind(node.parent, 217 /* ContinueStatement */)) { - return highlightSpans(getBreakOrContinueStatementOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); case 88 /* ForKeyword */: - if (hasKind(node.parent, 214 /* ForStatement */) || - hasKind(node.parent, 215 /* ForInStatement */) || - hasKind(node.parent, 216 /* ForOfStatement */)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; case 106 /* WhileKeyword */: case 81 /* DoKeyword */: - if (hasKind(node.parent, 213 /* WhileStatement */) || hasKind(node.parent, 212 /* DoStatement */)) { - return highlightSpans(getLoopBreakContinueOccurrences(node.parent)); - } - break; + return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences); case 123 /* ConstructorKeyword */: - if (hasKind(node.parent, 152 /* Constructor */)) { - return highlightSpans(getConstructorOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isConstructorDeclaration, getConstructorOccurrences); case 125 /* GetKeyword */: case 135 /* SetKeyword */: - if (hasKind(node.parent, 153 /* GetAccessor */) || hasKind(node.parent, 154 /* SetAccessor */)) { - return highlightSpans(getGetAndSetOccurrences(node.parent)); - } - break; + return useParent(node.parent, ts.isAccessor, getGetAndSetOccurrences); default: - if (ts.isModifierKind(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 208 /* VariableStatement */)) { - return highlightSpans(getModifierOccurrences(node.kind, node.parent)); - } + return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) + ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) + : undefined; + } + function useParent(node, nodeTest, getNodes) { + return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; } function highlightSpans(nodes) { return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); }); @@ -78431,21 +81821,20 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 223 /* ThrowStatement */) { + if (ts.isThrowStatement(node)) { statementAccumulator.push(node); } - else if (node.kind === 224 /* TryStatement */) { - var tryStatement = node; - if (tryStatement.catchClause) { - aggregate(tryStatement.catchClause); + else if (ts.isTryStatement(node)) { + if (node.catchClause) { + aggregate(node.catchClause); } else { // Exceptions thrown within a try block lacking a catch clause // are "owned" in the current context. - aggregate(tryStatement.tryBlock); + aggregate(node.tryBlock); } - if (tryStatement.finallyBlock) { - aggregate(tryStatement.finallyBlock); + if (node.finallyBlock) { + aggregate(node.finallyBlock); } } else if (!ts.isFunctionLike(node)) { @@ -78461,19 +81850,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_2 = child.parent; - if (ts.isFunctionBlock(parent_2) || parent_2.kind === 265 /* SourceFile */) { - return parent_2; + var parent = child.parent; + if (ts.isFunctionBlock(parent) || parent.kind === 269 /* SourceFile */) { + return parent; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_2.kind === 224 /* TryStatement */) { - var tryStatement = parent_2; + if (parent.kind === 225 /* TryStatement */) { + var tryStatement = parent; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_2; + child = parent; } return undefined; } @@ -78482,7 +81871,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 218 /* BreakStatement */ || node.kind === 217 /* ContinueStatement */) { + if (node.kind === 219 /* BreakStatement */ || node.kind === 218 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -78495,123 +81884,100 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node = statement.parent; node; node = node.parent) { + return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 221 /* SwitchStatement */: - if (statement.kind === 217 /* ContinueStatement */) { - continue; + case 222 /* SwitchStatement */: + if (statement.kind === 218 /* ContinueStatement */) { + return false; } // falls through - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: - if (!statement.label || isLabeledBy(node, statement.label.text)) { - return node; - } - break; + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: + return !statement.label || isLabeledBy(node, statement.label.text); default: // Don't cross function boundaries. - if (ts.isFunctionLike(node)) { - return undefined; - } - break; + // TODO: GH#20090 + return (ts.isFunctionLike(node) && "quit"); } - } - return undefined; + }); } function getModifierOccurrences(modifier, declaration) { - var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. - if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 229 /* ClassDeclaration */ || - container.kind === 199 /* ClassExpression */ || - (declaration.kind === 146 /* Parameter */ && hasKind(container, 152 /* Constructor */)))) { - return undefined; - } - } - else if (modifier === 115 /* StaticKeyword */) { - if (!(container.kind === 229 /* ClassDeclaration */ || container.kind === 199 /* ClassExpression */)) { - return undefined; - } - } - else if (modifier === 84 /* ExportKeyword */ || modifier === 124 /* DeclareKeyword */) { - if (!(container.kind === 234 /* ModuleBlock */ || container.kind === 265 /* SourceFile */)) { - return undefined; - } - } - else if (modifier === 117 /* AbstractKeyword */) { - if (!(container.kind === 229 /* ClassDeclaration */ || declaration.kind === 229 /* ClassDeclaration */)) { - return undefined; - } - } - else { - // unsupported modifier + if (!isLegalModifier(modifier, declaration)) { return undefined; } - var keywords = []; - var modifierFlag = getFlagFromModifier(modifier); - var nodes; + var modifierFlag = ts.modifierToFlag(modifier); + return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { + if (ts.getModifierFlags(node) & modifierFlag) { + var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); + ts.Debug.assert(!!mod); + return mod; + } + }); + } + function getNodesToSearchForModifier(declaration, modifierFlag) { + var container = declaration.parent; switch (container.kind) { - case 234 /* ModuleBlock */: - case 265 /* SourceFile */: + case 235 /* ModuleBlock */: + case 269 /* SourceFile */: + case 208 /* Block */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { - nodes = declaration.members.concat([declaration]); + return declaration.members.concat([declaration]); } else { - nodes = container.statements; + return container.statements; } - break; - case 152 /* Constructor */: - nodes = container.parameters.concat(container.parent.members); - break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - nodes = container.members; + case 153 /* Constructor */: + return container.parameters.concat(container.parent.members); + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. if (modifierFlag & 28 /* AccessibilityModifier */) { - var constructor = ts.forEach(container.members, function (member) { - return member.kind === 152 /* Constructor */ && member; - }); + var constructor = ts.find(container.members, ts.isConstructorDeclaration); if (constructor) { - nodes = nodes.concat(constructor.parameters); + return nodes.concat(constructor.parameters); } } else if (modifierFlag & 128 /* Abstract */) { - nodes = nodes.concat([container]); + return nodes.concat([container]); } - break; + return nodes; default: ts.Debug.fail("Invalid container kind."); } - ts.forEach(nodes, function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); - } - }); - return keywords; - function getFlagFromModifier(modifier) { - switch (modifier) { - case 114 /* PublicKeyword */: - return 4 /* Public */; - case 112 /* PrivateKeyword */: - return 8 /* Private */; - case 113 /* ProtectedKeyword */: - return 16 /* Protected */; - case 115 /* StaticKeyword */: - return 32 /* Static */; - case 84 /* ExportKeyword */: - return 1 /* Export */; - case 124 /* DeclareKeyword */: - return 2 /* Ambient */; - case 117 /* AbstractKeyword */: - return 128 /* Abstract */; - default: - ts.Debug.fail(); - } + } + function isLegalModifier(modifier, declaration) { + var container = declaration.parent; + switch (modifier) { + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + switch (container.kind) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + return true; + case 153 /* Constructor */: + return declaration.kind === 147 /* Parameter */; + default: + return false; + } + case 115 /* StaticKeyword */: + return container.kind === 230 /* ClassDeclaration */ || container.kind === 200 /* ClassExpression */; + case 84 /* ExportKeyword */: + case 124 /* DeclareKeyword */: + return container.kind === 235 /* ModuleBlock */ || container.kind === 269 /* SourceFile */; + case 117 /* AbstractKeyword */: + return container.kind === 230 /* ClassDeclaration */ || declaration.kind === 230 /* ClassDeclaration */; + default: + return false; } } function pushKeywordIf(keywordList, token) { @@ -78627,8 +81993,8 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 153 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 154 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 154 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 155 /* SetAccessor */); return keywords; function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); @@ -78651,7 +82017,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 212 /* DoStatement */) { + if (loopNode.kind === 213 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { @@ -78672,13 +82038,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -78731,12 +82097,11 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 207 /* Block */))) { + if (!func) { return undefined; } var keywords = []; - ts.forEachReturnStatement(func.body, function (returnStatement) { + ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) { pushKeywordIf(keywords, returnStatement.getFirstToken(), 96 /* ReturnKeyword */); }); // Include 'throw' statements that do not occur within a try block. @@ -78746,26 +82111,7 @@ var ts; return keywords; } function getIfElseOccurrences(ifStatement, sourceFile) { - var keywords = []; - // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 211 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { - ifStatement = ifStatement.parent; - } - // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. - while (ifStatement) { - var children = ifStatement.getChildren(); - pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); - // Generally the 'else' keyword is second-to-last, so we traverse backwards. - for (var i = children.length - 1; i >= 0; i--) { - if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { - break; - } - } - if (!hasKind(ifStatement.elseStatement, 211 /* IfStatement */)) { - break; - } - ifStatement = ifStatement.elseStatement; - } + var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). @@ -78773,15 +82119,15 @@ var ts; if (keywords[i].kind === 82 /* ElseKeyword */ && i < keywords.length - 1) { var elseKeyword = keywords[i]; var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. - var shouldCombindElseAndIf = true; + var shouldCombineElseAndIf = true; // Avoid recalculating getStart() by iterating backwards. - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) { if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) { - shouldCombindElseAndIf = false; + shouldCombineElseAndIf = false; break; } } - if (shouldCombindElseAndIf) { + if (shouldCombineElseAndIf) { result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), @@ -78796,12 +82142,35 @@ var ts; } return result; } + function getIfElseKeywords(ifStatement, sourceFile) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (true) { + var children = ifStatement.getChildren(sourceFile); + pushKeywordIf(keywords, children[0], 90 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 82 /* ElseKeyword */)) { + break; + } + } + if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + return keywords; + } /** * Whether or not a 'node' is preceded by a label of the given string. * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 222 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 223 /* LabeledStatement */; owner = owner.parent) { if (owner.label.escapedText === labelName) { return true; } @@ -78983,10 +82352,10 @@ var ts; } cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 181 /* CallExpression */: + case 182 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 226 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 227 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 71 /* Identifier */) { directImports.push(name); @@ -78997,19 +82366,19 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); break; - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name); } else { directImports.push(direct); } break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -79030,7 +82399,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 265 /* SourceFile */ || sourceFileLike.kind === 233 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 269 /* SourceFile */ || sourceFileLike.kind === 234 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -79085,7 +82454,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 237 /* ImportEqualsDeclaration */) { + if (decl.kind === 238 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -79099,7 +82468,7 @@ var ts; if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { return; } - if (decl.kind === 244 /* ExportDeclaration */) { + if (decl.kind === 245 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } @@ -79108,7 +82477,7 @@ var ts; return; } var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImportLike(namedBindings.name); return; } @@ -79160,7 +82529,7 @@ var ts; } } else { - var localSymbol = element.kind === 246 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 247 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -79176,7 +82545,7 @@ var ts; function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 244 /* ExportDeclaration */) + if (statement.kind !== 245 /* ExportDeclaration */) return; var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; if (moduleSpecifier || !exportClause) @@ -79195,7 +82564,7 @@ var ts; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 265 /* SourceFile */) { + if (searchSourceFile.kind === 269 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -79242,7 +82611,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 265 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 269 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -79257,18 +82626,18 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 244 /* ExportDeclaration */: - case 238 /* ImportDeclaration */: { + case 245 /* ExportDeclaration */: + case 239 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9 /* StringLiteral */) { action(decl, decl.moduleSpecifier); } break; } - case 237 /* ImportEqualsDeclaration */: { + case 238 /* ImportEqualsDeclaration */: { var decl = statement; var moduleReference = decl.moduleReference; - if (moduleReference.kind === 248 /* ExternalModuleReference */ && + if (moduleReference.kind === 249 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */) { action(decl, moduleReference.expression); } @@ -79281,11 +82650,11 @@ var ts; function importerFromModuleSpecifier(moduleSpecifier) { var decl = moduleSpecifier.parent; switch (decl.kind) { - case 181 /* CallExpression */: - case 238 /* ImportDeclaration */: - case 244 /* ExportDeclaration */: + case 182 /* CallExpression */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return decl; - case 248 /* ExternalModuleReference */: + case 249 /* ExternalModuleReference */: return decl.parent; default: ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); @@ -79303,7 +82672,7 @@ var ts; function getExport() { var parent = node.parent; if (symbol.exportSymbol) { - if (parent.kind === 179 /* PropertyAccessExpression */) { + if (parent.kind === 180 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) @@ -79413,10 +82782,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 226 /* VariableDeclaration */) { + if (parent.kind === 227 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 260 /* CatchClause */ ? undefined : p.parent.parent.kind === 208 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 264 /* CatchClause */ ? undefined : p.parent.parent.kind === 209 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -79425,15 +82794,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return parent.propertyName ? undefined : { isNamedImport: true }; - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -79451,9 +82820,6 @@ var ts; return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { - if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; - } var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.escapedText; }); @@ -79475,22 +82841,22 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 181 /* CallExpression */) { + if (node.kind === 182 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 265 /* SourceFile */) { + if (parent.kind === 269 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 234 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); + ts.Debug.assert(parent.kind === 235 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent)); return parent.parent; } function isAmbientModuleDeclaration(node) { - return node.kind === 233 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 234 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; } function isExternalModuleImportEquals(_a) { var moduleReference = _a.moduleReference; - return moduleReference.kind === 248 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; + return moduleReference.kind === 249 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -79530,16 +82896,16 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { - var result_5 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); }); - return result_5; + if (node.parent.kind === 266 /* ShorthandPropertyAssignment */) { + var result_4 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); + return result_4; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -79573,29 +82939,29 @@ var ts; var info = (function () { switch (def.type) { case "symbol": { - var symbol = def.symbol, node_2 = def.node; - var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var symbol = def.symbol, node_3 = def.node; + var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; + var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + var node_4 = def.node; + return { node: node_4, name: node_4.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_4.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { - var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var node_5 = def.node; + var name_6 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_6, kind: "keyword" /* keyword */, displayParts: [{ text: name_6, kind: "keyword" /* keyword */ }] }; } case "this": { - var node_5 = def.node; - var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + var node_6 = def.node; + var symbol = checker.getSymbolAtLocation(node_6); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_6.getSourceFile(), ts.getContainerNode(node_6), node_6).displayParts; + return { node: node_6, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { - var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + var node_7 = def.node; + return { node: node_7, name: node_7.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_7), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -79648,13 +83014,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, node, checker); } - else if (node.kind === 178 /* ObjectLiteralExpression */) { + else if (node.kind === 179 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } - else if (node.kind === 199 /* ClassExpression */) { + else if (node.kind === 200 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] @@ -79705,7 +83071,7 @@ var ts; /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 265 /* SourceFile */) { + if (node.kind === 269 /* SourceFile */) { return undefined; } if (!options.implementations) { @@ -79736,12 +83102,12 @@ var ts; return false; } switch (node.parent.kind) { - case 233 /* ModuleDeclaration */: - case 248 /* ExternalModuleReference */: - case 238 /* ImportDeclaration */: - case 244 /* ExportDeclaration */: + case 234 /* ModuleDeclaration */: + case 249 /* ExternalModuleReference */: + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: return true; - case 181 /* CallExpression */: + case 182 /* CallExpression */: return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; @@ -79764,10 +83130,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: references.push({ type: "node", node: decl.name }); break; default: @@ -79812,19 +83178,25 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79 /* DefaultKeyword */) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -79892,7 +83264,7 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); return { @@ -79984,9 +83356,9 @@ var ts; checker.getPropertySymbolOfDestructuringAssignment(location); } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 177 /* BindingElement */); if (bindingElement && - bindingElement.parent.kind === 174 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 175 /* ObjectBindingPattern */ && !bindingElement.propertyName) { return bindingElement; } @@ -80016,7 +83388,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 186 /* FunctionExpression */ || valueDeclaration.kind === 199 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 187 /* FunctionExpression */ || valueDeclaration.kind === 200 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -80026,7 +83398,7 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 229 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 230 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -80055,7 +83427,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 269 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -80090,8 +83462,8 @@ var ts; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 5 /* Latest */))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } @@ -80336,12 +83708,12 @@ var ts; for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 152 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 153 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 151 /* MethodDeclaration */) { + if (decl && decl.kind === 152 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { @@ -80362,7 +83734,7 @@ var ts; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 152 /* Constructor */); + ts.Debug.assert(decl.kind === 153 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { @@ -80382,7 +83754,7 @@ var ts; if (refNode.kind !== 71 /* Identifier */) { return; } - if (refNode.parent.kind === 262 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 266 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -80401,7 +83773,7 @@ var ts; } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { var body = parent.body; - if (body.kind === 207 /* Block */) { + if (body.kind === 208 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); @@ -80424,7 +83796,7 @@ var ts; if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { result.push(componentType.symbol); } - if (componentType.getFlags() & 196608 /* UnionOrIntersection */) { + if (componentType.getFlags() & 393216 /* UnionOrIntersection */) { getSymbolsForClassAndInterfaceComponents(componentType, result); } } @@ -80442,12 +83814,12 @@ var ts; } function getContainingClassIfInHeritageClause(node) { if (node && node.parent) { - if (node.kind === 201 /* ExpressionWithTypeArguments */ - && node.parent.kind === 259 /* HeritageClause */ + if (node.kind === 202 /* ExpressionWithTypeArguments */ + && node.parent.kind === 263 /* HeritageClause */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; } - else if (node.kind === 71 /* Identifier */ || node.kind === 179 /* PropertyAccessExpression */) { + else if (node.kind === 71 /* Identifier */ || node.kind === 180 /* PropertyAccessExpression */) { return getContainingClassIfInHeritageClause(node.parent); } } @@ -80458,13 +83830,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 185 /* ParenthesizedExpression */: + case 186 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 187 /* ArrowFunction */: - case 186 /* FunctionExpression */: - case 178 /* ObjectLiteralExpression */: - case 199 /* ClassExpression */: - case 177 /* ArrayLiteralExpression */: + case 188 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 179 /* ObjectLiteralExpression */: + case 200 /* ClassExpression */: + case 178 /* ArrayLiteralExpression */: return true; default: return false; @@ -80518,7 +83890,7 @@ var ts; } return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); } - else if (declaration.kind === 230 /* InterfaceDeclaration */) { + else if (declaration.kind === 231 /* InterfaceDeclaration */) { if (parentIsInterface) { return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); } @@ -80546,13 +83918,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -80583,27 +83955,27 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 265 /* SourceFile */: + case 269 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -80612,7 +83984,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 265 /* SourceFile */) { + if (searchSpaceNode.kind === 269 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this"); @@ -80636,28 +84008,28 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 230 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { result.push(FindAllReferences.nodeEntry(node)); } break; - case 265 /* SourceFile */: - if (container.kind === 265 /* SourceFile */ && !ts.isExternalModule(container)) { + case 269 /* SourceFile */: + if (container.kind === 269 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(FindAllReferences.nodeEntry(node)); } break; @@ -80680,9 +84052,9 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); - if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { - references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); + var node_8 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + if (node_8 && node_8.kind === 9 /* StringLiteral */ && node_8.text === searchText) { + references.push(FindAllReferences.nodeEntry(node_8, /*isInString*/ true)); } } } @@ -80697,7 +84069,7 @@ var ts; // If the location is name of property symbol from object literal destructuring pattern // Search the property symbol // for ( { property: p2 } of elems) { } - if (containingObjectLiteralElement.kind !== 262 /* ShorthandPropertyAssignment */) { + if (containingObjectLiteralElement.kind !== 266 /* ShorthandPropertyAssignment */) { var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); if (propertySymbol) { result.push(propertySymbol); @@ -80729,10 +84101,7 @@ var ts; // we should include both parameter declaration symbol and property declaration symbol // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 146 /* Parameter */ && - ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { - ts.addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); - } + ts.addRange(result, getParameterPropertySymbols(symbol, checker)); // If this is symbol of binding element without propertyName declaration in Object binding pattern // Include the property in the search var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); @@ -80757,6 +84126,11 @@ var ts; } } } + function getParameterPropertySymbols(symbol, checker) { + return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isParameterPropertyDeclaration(symbol.valueDeclaration) + ? checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name) + : undefined; + } /** * Find symbol of the given property-name and add the symbol to the given result array * @param symbol a symbol to start searching for the given propertyName @@ -80789,7 +84163,7 @@ var ts; getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 230 /* InterfaceDeclaration */) { + else if (declaration.kind === 231 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -80811,16 +84185,24 @@ var ts; } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { + var checker = state.checker; if (search.includes(referenceSymbol)) { return referenceSymbol; } + if (referenceSymbol.flags & 1 /* FunctionScopedVariable */) { + ts.Debug.assert(!(referenceSymbol.flags & 4 /* Property */)); + var paramProps = getParameterPropertySymbols(referenceSymbol, checker); + if (paramProps) { + return getRelatedSymbol(search, ts.find(paramProps, function (x) { return !!(x.flags & 4 /* Property */); }), referenceLocation, state); + } + } // If the reference location is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this symbol to // compare to our searchSymbol var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, state.checker), function (contextualSymbol) { - return ts.find(state.checker.getRootSymbols(contextualSymbol), search.includes); + var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { + return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); }); if (contextualSymbol) { return contextualSymbol; @@ -80829,7 +84211,7 @@ var ts; // Get the property symbol from the object literal's type and look if thats the search symbol // In below eg. get 'property' from type of elems iterating type // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, state.checker); + var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, checker); if (propertySymbol && search.includes(propertySymbol)) { return propertySymbol; } @@ -80837,7 +84219,7 @@ var ts; // If the reference location is the binding element and doesn't have property name // then include the binding element in the related symbols // let { a } : { a }; - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, checker); if (bindingElementPropertySymbol) { var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); if (fromBindingElement) @@ -80869,7 +84251,7 @@ var ts; } } function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 144 /* ComputedPropertyName */) { + if (node.name.kind === 145 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { @@ -80885,20 +84267,20 @@ var ts; var contextualType = checker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; + var result_5 = []; var symbol = contextualType.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } - if (contextualType.flags & 65536 /* Union */) { + if (contextualType.flags & 131072 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -80939,7 +84321,7 @@ var ts; if (node.initializer) { return true; } - else if (node.kind === 226 /* VariableDeclaration */) { + else if (node.kind === 227 /* VariableDeclaration */) { var parentStatement = getParentStatementOfVariableDeclaration(node); return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } @@ -80949,18 +84331,18 @@ var ts; } else { switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: return true; } } return false; } function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 208 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 227 /* VariableDeclarationList */); + if (node.parent && node.parent.parent && node.parent.parent.kind === 209 /* VariableStatement */) { + ts.Debug.assert(node.parent.kind === 228 /* VariableDeclarationList */); return node.parent.parent; } } @@ -81013,7 +84395,7 @@ var ts; if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== symbol.parent) { return [localParentType.symbol]; } - else if (localParentType.flags & 196608 /* UnionOrIntersection */) { + else if (localParentType.flags & 393216 /* UnionOrIntersection */) { return getSymbolsForClassAndInterfaceComponents(localParentType); } } @@ -81078,7 +84460,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 262 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 266 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -81142,14 +84524,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 65536 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_7 = []; + if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_6 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_7, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); + ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); } }); - return result_7; + return result_6; } if (!type.symbol) { return undefined; @@ -81157,6 +84539,24 @@ var ts; return getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function getDefinitionAndBoundSpan(program, sourceFile, position) { + var definitions = getDefinitionAtPosition(program, sourceFile, position); + if (!definitions || definitions.length === 0) { + return undefined; + } + // Check if position is on triple slash reference. + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (comment) { + return { + definitions: definitions, + textSpan: ts.createTextSpanFromBounds(comment.pos, comment.end) + }; + } + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); + return { definitions: definitions, textSpan: textSpan }; + } + GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; // Go to the original declaration for cases: // // (1) when the aliased symbol was declared in the location(parent). @@ -81170,11 +84570,11 @@ var ts; return true; } switch (declaration.kind) { - case 239 /* ImportClause */: - case 237 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 238 /* ImportEqualsDeclaration */: return true; - case 242 /* ImportSpecifier */: - return declaration.parent.kind === 241 /* NamedImports */; + case 243 /* ImportSpecifier */: + return declaration.parent.kind === 242 /* NamedImports */; default: return false; } @@ -81222,7 +84622,7 @@ var ts; var definition; for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 152 /* Constructor */ : isSignatureDeclaration(d)) { + if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { declarations.push(d); if (d.body) definition = d; @@ -81237,10 +84637,10 @@ var ts; } function isSignatureDeclaration(node) { switch (node.kind) { - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: return true; default: return false; @@ -81320,6 +84720,7 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { + var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -81339,6 +84740,7 @@ var ts; "fileOverview", "function", "ignore", + "inheritDoc", "inner", "lends", "link", @@ -81390,14 +84792,36 @@ var ts; forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - if (tag.kind === 276 /* JSDocTag */) { - tags.push({ name: tag.tagName.text, text: tag.comment }); - } + tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; + function getCommentText(tag) { + var comment = tag.comment; + switch (tag.kind) { + case 282 /* JSDocAugmentsTag */: + return withNode(tag.class); + case 287 /* JSDocTemplateTag */: + return withList(tag.typeParameters); + case 286 /* JSDocTypeTag */: + return withNode(tag.typeExpression); + case 288 /* JSDocTypedefTag */: + case 289 /* JSDocPropertyTag */: + case 284 /* JSDocParameterTag */: + var name = tag.name; + return name ? withNode(name) : comment; + default: + return comment; + } + function withNode(node) { + return node.getText() + " " + comment; + } + function withList(list) { + return list.map(function (x) { return x.getText(); }) + " " + 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. @@ -81427,6 +84851,7 @@ var ts; })); } JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions; + JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; function getJSDocTagCompletions() { return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -81438,6 +84863,18 @@ var ts; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocTagCompletionDetails(name) { + return { + name: name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; function getJSDocParameterNameCompletions(tag) { if (!ts.isIdentifier(tag.name)) { return ts.emptyArray; @@ -81459,16 +84896,24 @@ var ts; }); } JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; + function getJSDocParameterNameCompletionDetails(name) { + return { + name: name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + displayParts: [ts.textPart(name)], + documentation: ts.emptyArray, + tags: ts.emptyArray, + codeActions: undefined, + }; + } + JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. - * Valid positions are - * - outside of comments, statements, and expressions, and - * - preceding a: - * - function/constructor/method declaration - * - class declarations - * - variable statements - * - namespace declarations + * Invalid positions are + * - within comments, strings (including template literals and regex), and JSXText + * - within a token * * Hosts should ideally check that: * - The line is all whitespace up to 'position' before performing the insertion. @@ -81491,32 +84936,29 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - return undefined; + // if climbing the tree did not find a declaration with parameters, complete to a single line comment + return singleLineTemplate; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.getStart() < position) { + if (commentOwner.kind === 10 /* JsxText */) { return undefined; } + if (commentOwner.getStart() < position || parameters.length === 0) { + // if climbing the tree found a declaration with parameters but the request was made inside it + // or if there are no parameters, complete to a single line comment + return singleLineTemplate; + } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = ""; - if (parameters) { - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 /* Identifier */ ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; - } - } - } + var docParams = parameters.map(function (_a, i) { + var name = _a.name; + var nameText = ts.isIdentifier(name) ? name.text : "param" + i; + var type = isJavaScriptFile ? "{any} " : ""; + return indentationStr + " * @param " + type + nameText + newLine; + }).join(""); // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -81534,36 +84976,25 @@ var ts; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; function getCommentOwnerInfo(tokenAtPos) { - // TODO: add support for: - // - enums/enum members - // - interfaces - // - property declarations - // - potentially property assignments for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + case 151 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 229 /* ClassDeclaration */: - return { commentOwner: commentOwner }; - case 208 /* VariableStatement */: { + case 209 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return { commentOwner: commentOwner, parameters: parameters_1 }; + return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; } - case 265 /* SourceFile */: + case 269 /* SourceFile */: return undefined; - case 233 /* ModuleDeclaration */: - // If in walking up the tree, we hit a a nested namespace declaration, - // then we must be somewhere within a dotted namespace name; however we don't - // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 233 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 194 /* BinaryExpression */: { + case 195 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { return undefined; @@ -81571,6 +85002,10 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } + case 10 /* JsxText */: { + var parameters_3 = ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_3 }; + } } } } @@ -81583,17 +85018,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 185 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 186 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return rightHandSide.parameters; - case 199 /* ClassExpression */: + case 200 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 152 /* Constructor */) { + if (member.kind === 153 /* Constructor */) { return member.parameters; } } @@ -81678,7 +85113,7 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); addInferredTypings(module, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed @@ -81741,7 +85176,7 @@ var ts; if (!ts.hasJavaScriptFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); }); if (fromFileNames.length) { @@ -81765,19 +85200,19 @@ var ts; return; } // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); if (log) log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); var packageNames = []; - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; var normalizedFileName = ts.normalizePath(fileName); var baseFileName = ts.getBaseFileName(normalizedFileName); if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_8.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -81805,6 +85240,66 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + throw ts.Debug.fail(); // Shouldn't have called this. + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ @@ -81815,7 +85310,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_8 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -81827,7 +85322,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_6(sourceFile); + _loop_8(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -81864,9 +85359,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 239 /* ImportClause */: - case 242 /* ImportSpecifier */: - case 237 /* ImportEqualsDeclaration */: + case 240 /* ImportClause */: + case 243 /* ImportSpecifier */: + case 238 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -81893,7 +85388,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (name.kind === 144 /* ComputedPropertyName */) { + else if (name.kind === 145 /* ComputedPropertyName */) { return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); } else { @@ -81915,7 +85410,7 @@ var ts; } return true; } - if (expression.kind === 179 /* PropertyAccessExpression */) { + if (expression.kind === 180 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -81929,7 +85424,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } @@ -81958,12 +85453,8 @@ var ts; } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. - // Right now we just sort by kind first, and then by name of the item. - // We first sort case insensitively. So "Aaa" will come before "bar". - // Then we sort case sensitively, so "aaa" will come before "Aaa". - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + return ts.compareValues(i1.matchKind, i2.matchKind) + || ts.compareStringsCaseSensitiveUI(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -82114,7 +85605,7 @@ var ts; return; } switch (node.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -82126,21 +85617,21 @@ var ts; } } break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 150 /* MethodSignature */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 151 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 239 /* ImportClause */: + case 240 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -82152,7 +85643,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 240 /* NamespaceImport */) { + if (namedBindings.kind === 241 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -82163,8 +85654,8 @@ var ts; } } break; - case 176 /* BindingElement */: - case 226 /* VariableDeclaration */: + case 177 /* BindingElement */: + case 227 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -82185,12 +85676,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -82200,9 +85691,9 @@ var ts; } endNode(); break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -82210,22 +85701,39 @@ var ts; } endNode(); break; - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 246 /* ExportSpecifier */: - case 237 /* ImportEqualsDeclaration */: - case 157 /* IndexSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 231 /* TypeAliasDeclaration */: + case 247 /* ExportSpecifier */: + case 238 /* ImportEqualsDeclaration */: + case 158 /* IndexSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 232 /* TypeAliasDeclaration */: addLeafNode(node); break; + case 195 /* BinaryExpression */: { + var special = ts.getSpecialPropertyAssignmentKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 3 /* PrototypeProperty */: + addNodeWithRecursiveChild(node, node.right); + break; + case 4 /* ThisProperty */: + case 5 /* Property */: + case 0 /* None */: + break; + default: + ts.Debug.assertNever(special); + } + } + // falls through default: if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283 /* JSDocTypedefTag */) { + if (tag.kind === 288 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -82267,57 +85775,58 @@ var ts; nameToItems.set(name, [itemWithSameName, child]); return true; } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { - merge(a, b); - return true; - } - return false; - } }); - /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - return a.kind === b.kind && (a.kind !== 233 /* ModuleDeclaration */ || areSameModule(a, b)); - // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. - // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! - function areSameModule(a, b) { - if (a.body.kind !== b.body.kind) { - return false; - } - if (a.body.kind !== 233 /* ModuleDeclaration */) { - return true; - } - return areSameModule(a.body, b.body); - } + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); + return true; } - /** Merge source into target. Source should be thrown away after this is called. */ - function merge(target, source) { - target.additionalNodes = target.additionalNodes || []; - target.additionalNodes.push(source.node); - if (source.additionalNodes) { - (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); - } - target.children = ts.concatenate(target.children, source.children); - if (target.children) { - mergeChildren(target.children); - sortChildren(target.children); - } - var _a; + return false; + } + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + if (a.kind !== b.kind) { + return false; + } + switch (a.kind) { + case 150 /* PropertyDeclaration */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); + case 234 /* ModuleDeclaration */: + return areSameModule(a, b); + default: + return true; } } + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + return a.body.kind === b.body.kind && (a.body.kind !== 234 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + } + /** Merge source into target. Source should be thrown away after this is called. */ + function merge(target, source) { + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { children.sort(compareChildren); } function compareChildren(child1, child2) { - var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); - if (name1 && name2) { - var cmp = ts.compareStringsCaseInsensitive(name1, name2); - return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); - } - else { - return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); - } + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** * This differs from getItemName because this is just used for sorting. @@ -82325,7 +85834,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 233 /* ModuleDeclaration */) { + if (node.kind === 234 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -82333,18 +85842,18 @@ var ts; return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 199 /* ClassExpression */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 200 /* ClassExpression */: return getFunctionOrClassName(node); - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; } } function getItemName(node) { - if (node.kind === 233 /* ModuleDeclaration */) { + if (node.kind === 234 /* ModuleDeclaration */) { return getModuleName(node); } var name = ts.getNameOfDeclaration(node); @@ -82355,16 +85864,16 @@ var ts; } } switch (node.kind) { - case 265 /* SourceFile */: + case 269 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -82372,15 +85881,15 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 152 /* Constructor */: + case 153 /* Constructor */: return "constructor"; - case 156 /* ConstructSignature */: + case 157 /* ConstructSignature */: return "new()"; - case 155 /* CallSignature */: + case 156 /* CallSignature */: return "()"; - case 157 /* IndexSignature */: + case 158 /* IndexSignature */: return "[]"; - case 283 /* JSDocTypedefTag */: + case 288 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -82392,7 +85901,7 @@ var ts; } else { var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 208 /* VariableStatement */) { + if (parentNode && parentNode.kind === 209 /* VariableStatement */) { if (parentNode.declarationList.declarations.length > 0) { var nameIdentifier = parentNode.declarationList.declarations[0].name; if (nameIdentifier.kind === 71 /* Identifier */) { @@ -82421,24 +85930,24 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 232 /* EnumDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 265 /* SourceFile */: - case 231 /* TypeAliasDeclaration */: - case 283 /* JSDocTypedefTag */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 233 /* EnumDeclaration */: + case 231 /* InterfaceDeclaration */: + case 234 /* ModuleDeclaration */: + case 269 /* SourceFile */: + case 232 /* TypeAliasDeclaration */: + case 288 /* JSDocTypedefTag */: return true; - case 152 /* Constructor */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 226 /* VariableDeclaration */: + case 153 /* Constructor */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 227 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -82448,10 +85957,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 234 /* ModuleBlock */: - case 265 /* SourceFile */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: + case 235 /* ModuleBlock */: + case 269 /* SourceFile */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: return true; default: return hasSomeImportantChild(item); @@ -82460,7 +85969,7 @@ var ts; function hasSomeImportantChild(item) { return ts.forEach(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 226 /* VariableDeclaration */ && childKind !== 176 /* BindingElement */; + return childKind !== 227 /* VariableDeclaration */ && childKind !== 177 /* BindingElement */; }); } } @@ -82516,7 +86025,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 233 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 234 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -82527,18 +86036,18 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 233 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 234 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 144 /* ComputedPropertyName */; + return !member.name || member.name.kind === 145 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 265 /* SourceFile */ + return node.kind === 269 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 226 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 227 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -82547,14 +86056,14 @@ var ts; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } - else if (node.parent.kind === 226 /* VariableDeclaration */) { + else if (node.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } - else if (node.parent.kind === 194 /* BinaryExpression */ && + else if (node.parent.kind === 195 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } - else if (node.parent.kind === 261 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 265 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } else if (ts.getModifierFlags(node) & 512 /* Default */) { @@ -82566,9 +86075,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 187 /* ArrowFunction */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: + case 188 /* ArrowFunction */: + case 187 /* FunctionExpression */: + case 200 /* ClassExpression */: return true; default: return false; @@ -82581,206 +86090,168 @@ var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { - var collapseText = "..."; - var maxDepth = 20; - var defaultLabel = "#region"; - var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { - var elements = []; - var depth = 0; + var res = []; + addNodeOutliningSpans(sourceFile, cancellationToken, res); + addRegionOutliningSpans(sourceFile, res); + return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); + } + OutliningElementsCollector.collectElements = collectElements; + function addNodeOutliningSpans(sourceFile, cancellationToken, out) { + var depthRemaining = 40; + sourceFile.forEachChild(function walk(n) { + if (depthRemaining === 0) + return; + cancellationToken.throwIfCancellationRequested(); + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); + } + var span = getOutliningSpanForNode(n, sourceFile); + if (span) + out.push(span); + depthRemaining--; + n.forEachChild(walk); + depthRemaining++; + }); + } + function addRegionOutliningSpans(sourceFile, out) { var regions = []; - walk(sourceFile); - gatherRegions(); - return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); - /** If useFullStart is true, then the collapsing span includes leading whitespace, including linebreaks. */ - function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { - if (hintSpanNode && startElement && endElement) { - var span_13 = { - textSpan: ts.createTextSpanFromBounds(useFullStart ? startElement.getFullStart() : startElement.getStart(), endElement.getEnd()), - hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_13); + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + var lineText = sourceFile.text.substring(currentLineStart, lineEnd); + var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?$/); + if (!result || ts.isInComment(sourceFile, currentLineStart)) { + continue; + } + if (!result[1]) { + var span_13 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span_13, span_13, /*autoCollapse*/ false, result[2] || "#region")); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + out.push(region); + } } } - function addOutliningSpanComments(commentSpan, autoCollapse) { - if (commentSpan) { - var span_14 = { - textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), - bannerText: collapseText, - autoCollapse: autoCollapse, - }; - elements.push(span_14); - } - } - function addOutliningForLeadingCommentsForNode(n) { - var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); - if (comments) { - var firstSingleLineCommentStart = -1; - var lastSingleLineCommentEnd = -1; - var isFirstSingleLineComment = true; - var singleLineCommentCount = 0; - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var currentComment = comments_3[_i]; - cancellationToken.throwIfCancellationRequested(); + } + function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (!comments) + return; + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var singleLineCommentCount = 0; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var _a = comments_3[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + cancellationToken.throwIfCancellationRequested(); + switch (kind) { + case 2 /* SingleLineCommentTrivia */: // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last - if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { - if (isFirstSingleLineComment) { - firstSingleLineCommentStart = currentComment.pos; - } - isFirstSingleLineComment = false; - lastSingleLineCommentEnd = currentComment.end; - singleLineCommentCount++; - } - else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); - addOutliningSpanComments(currentComment, /*autoCollapse*/ false); - singleLineCommentCount = 0; - lastSingleLineCommentEnd = -1; - isFirstSingleLineComment = true; + if (singleLineCommentCount === 0) { + firstSingleLineCommentStart = pos; } - } - combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + lastSingleLineCommentEnd = end; + singleLineCommentCount++; + break; + case 3 /* MultiLineCommentTrivia */: + combineAndAddMultipleSingleLineComments(); + out.push(createOutliningSpanFromBounds(pos, end)); + singleLineCommentCount = 0; + break; + default: + ts.Debug.assertNever(kind); } } - function combineAndAddMultipleSingleLineComments(count, start, end) { + combineAndAddMultipleSingleLineComments(); + function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments - if (count > 1) { - var multipleSingleLineComments = { - kind: 2 /* SingleLineCommentTrivia */, - pos: start, - end: end, - }; - addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); - } - } - function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 187 /* ArrowFunction */; - } - function gatherRegions() { - var lineStarts = sourceFile.getLineStarts(); - for (var i = 0; i < lineStarts.length; i++) { - var currentLineStart = lineStarts[i]; - var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); - var comment = sourceFile.text.substring(currentLineStart, lineEnd); - var result = comment.match(regionMatch); - if (result && !ts.isInComment(sourceFile, currentLineStart)) { - if (!result[1]) { - var start = sourceFile.getFullText().indexOf("//", currentLineStart); - var textSpan = ts.createTextSpanFromBounds(start, lineEnd); - var region = { - textSpan: textSpan, - hintSpan: textSpan, - bannerText: result[2] || defaultLabel, - autoCollapse: false - }; - regions.push(region); - } - else { - var region = regions.pop(); - if (region) { - region.textSpan.length = lineEnd - region.textSpan.start; - region.hintSpan.length = lineEnd - region.textSpan.start; - elements.push(region); + if (singleLineCommentCount > 1) { + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + } + } + } + function createOutliningSpanFromBounds(pos, end) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + } + function getOutliningSpanForNode(n, sourceFile) { + switch (n.kind) { + case 208 /* Block */: + if (ts.isFunctionBlock(n)) { + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 188 /* ArrowFunction */); + } + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collapse the block, but consider its hint span + // to be the entire span of the parent. + switch (n.parent.kind) { + case 213 /* DoStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 212 /* IfStatement */: + case 214 /* WhileStatement */: + case 221 /* WithStatement */: + case 264 /* CatchClause */: + return spanForNode(n.parent); + case 225 /* TryStatement */: + // Could be the try-block, or the finally-block. + var tryStatement = n.parent; + if (tryStatement.tryBlock === n) { + return spanForNode(n.parent); } - } - } - } - } - function walk(n) { - cancellationToken.throwIfCancellationRequested(); - if (depth > maxDepth) { - return; - } - if (ts.isDeclaration(n)) { - addOutliningForLeadingCommentsForNode(n); - } - switch (n.kind) { - case 207 /* Block */: - if (!ts.isFunctionBlock(n)) { - var parent = n.parent; - var openBrace_1 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace_1 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - // Check if the block is standalone, or 'attached' to some parent statement. - // If the latter, we want to collapse the block, but consider its hint span - // to be the entire span of the parent. - if (parent.kind === 212 /* DoStatement */ || - parent.kind === 215 /* ForInStatement */ || - parent.kind === 216 /* ForOfStatement */ || - parent.kind === 214 /* ForStatement */ || - parent.kind === 211 /* IfStatement */ || - parent.kind === 213 /* WhileStatement */ || - parent.kind === 220 /* WithStatement */ || - parent.kind === 260 /* CatchClause */) { - addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); - break; - } - if (parent.kind === 224 /* TryStatement */) { - // Could be the try-block, or the finally-block. - var tryStatement = parent; - if (tryStatement.tryBlock === n) { - addOutliningSpan(parent, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); - break; - } - else if (tryStatement.finallyBlock === n) { - var finallyKeyword = ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile); - if (finallyKeyword) { - addOutliningSpan(finallyKeyword, openBrace_1, closeBrace_1, autoCollapse(n), /*useFullStart*/ true); - break; - } - } - // fall through. + else if (tryStatement.finallyBlock === n) { + return spanForNode(ts.findChildOfKind(tryStatement, 87 /* FinallyKeyword */, sourceFile)); } + // falls through + default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - var span_15 = ts.createTextSpanFromNode(n); - elements.push({ - textSpan: span_15, - hintSpan: span_15, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); - break; - } - // falls through - case 234 /* ModuleBlock */: { - var openBrace_2 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace_2 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n.parent, openBrace_2, closeBrace_2, autoCollapse(n), /*useFullStart*/ true); - break; - } - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 235 /* CaseBlock */: { - var openBrace_3 = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace_3 = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace_3, closeBrace_3, autoCollapse(n), /*useFullStart*/ true); - break; - } - // If the block has no leading keywords and is inside an array literal, - // we only want to collapse the span of the block. - // Otherwise, the collapsed section will include the end of the previous line. - case 178 /* ObjectLiteralExpression */: - var openBrace = ts.findChildOfKind(n, 17 /* OpenBraceToken */, sourceFile); - var closeBrace = ts.findChildOfKind(n, 18 /* CloseBraceToken */, sourceFile); - addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); - break; - case 177 /* ArrayLiteralExpression */: - var openBracket = ts.findChildOfKind(n, 21 /* OpenBracketToken */, sourceFile); - var closeBracket = ts.findChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n), /*useFullStart*/ !ts.isArrayLiteralExpression(n.parent)); - break; + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + } + case 235 /* ModuleBlock */: + return spanForNode(n.parent); + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 236 /* CaseBlock */: + return spanForNode(n); + case 179 /* ObjectLiteralExpression */: + return spanForObjectOrArrayLiteral(n); + case 178 /* ArrayLiteralExpression */: + return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + } + function spanForObjectOrArrayLiteral(node, open) { + if (open === void 0) { open = 17 /* OpenBraceToken */; } + // If the block has no leading keywords and is inside an array literal, + // we only want to collapse the span of the block. + // Otherwise, the collapsed section will include the end of the previous line. + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + } + function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { + if (autoCollapse === void 0) { autoCollapse = false; } + if (useFullStart === void 0) { useFullStart = true; } + if (open === void 0) { open = 17 /* OpenBraceToken */; } + var openToken = ts.findChildOfKind(n, open, sourceFile); + var close = open === 17 /* OpenBraceToken */ ? 18 /* CloseBraceToken */ : 22 /* CloseBracketToken */; + var closeToken = ts.findChildOfKind(n, close, sourceFile); + if (!openToken || !closeToken) { + return undefined; } - depth++; - ts.forEachChild(n, walk); - depth--; + var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); + return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - OutliningElementsCollector.collectElements = collectElements; + function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + if (hintSpan === void 0) { hintSpan = textSpan; } + if (autoCollapse === void 0) { autoCollapse = false; } + if (bannerText === void 0) { bannerText = "..."; } + return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); /* @internal */ @@ -82895,10 +86366,10 @@ var ts; // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span_16 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_16, chunk.text, /*ignoreCase:*/ true)) { + var span_14 = wordSpans_1[_i]; + if (partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_16, chunk.text, /*ignoreCase:*/ false)); + /*isCaseSensitive:*/ partStartsWith(candidate, span_14, chunk.text, /*ignoreCase:*/ false)); } } } @@ -83125,7 +86596,7 @@ var ts; if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -83138,7 +86609,7 @@ var ts; if (ch >= 97 /* a */ && ch <= 122 /* z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 5 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -83147,19 +86618,19 @@ var ts; return str === str.toLowerCase(); } // Assumes 'value' is already lowercase. - function indexOfIgnoringCase(string, value) { - var n = string.length - value.length; + function indexOfIgnoringCase(str, value) { + var n = str.length - value.length; for (var i = 0; i <= n; i++) { - if (startsWithIgnoringCase(string, value, i)) { + if (startsWithIgnoringCase(str, value, i)) { return i; } } return -1; } // Assumes 'value' is already lowercase. - function startsWithIgnoringCase(string, value, start) { + function startsWithIgnoringCase(str, value, start) { for (var i = 0; i < value.length; i++) { - var ch1 = toLowerCase(string.charCodeAt(i + start)); + var ch1 = toLowerCase(str.charCodeAt(i + start)); var ch2 = value.charCodeAt(i); if (ch1 !== ch2) { return false; @@ -83446,7 +86917,7 @@ var ts; else { if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import d from "mod"; @@ -83477,7 +86948,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import {a as A} from "mod"; @@ -83493,7 +86964,7 @@ var ts; token = nextToken(); if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import * as NS from "mod" @@ -83523,7 +86994,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export {a as A} from "mod"; @@ -83535,7 +87006,7 @@ var ts; } else if (token === 39 /* AsteriskToken */) { token = nextToken(); - if (token === 140 /* FromKeyword */) { + if (token === 141 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export * from "mod" @@ -83818,7 +87289,7 @@ var ts; } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 181 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 182 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -83826,7 +87297,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 71 /* Identifier */ ? expression - : expression.kind === 179 /* PropertyAccessExpression */ + : expression.kind === 180 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.escapedText) { @@ -83904,25 +87375,25 @@ var ts; var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 183 /* TaggedTemplateExpression */) { + else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 184 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 183 /* TaggedTemplateExpression */) { + else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 184 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 197 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 205 /* TemplateSpan */ && node.parent.parent.parent.kind === 183 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 206 /* TemplateSpan */ && node.parent.parent.parent.kind === 184 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 196 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 197 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -84059,7 +87530,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 196 /* TemplateExpression */) { + if (template.kind === 197 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -84068,7 +87539,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 265 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 269 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -84137,7 +87608,7 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(), + documentation: candidateSignature.getDocumentationComment(typeChecker), tags: candidateSignature.getJsDocTags() }; }); @@ -84153,7 +87624,7 @@ var ts; }); return { name: parameter.name, - documentation: parameter.getDocumentationComment(), + documentation: parameter.getDocumentationComment(typeChecker), displayParts: displayParts, isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) }; @@ -84181,7 +87652,7 @@ var ts; function getSymbolKind(typeChecker, symbol, location) { var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 199 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -84261,10 +87732,16 @@ var ts; } return unionPropertyKind; } - if (location.parent && ts.isJsxAttribute(location.parent)) { - return "JSX attribute" /* jsxAttribute */; + // If we requested completions after `x.` at the top-level, we may be at a source file location. + switch (location.parent && location.parent.kind) { + // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. + case 252 /* JsxOpeningElement */: + return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; + case 257 /* JsxAttribute */: + return "JSX attribute" /* jsxAttribute */; + default: + return "property" /* memberVariableElement */; } - return "property" /* memberVariableElement */; } return "" /* unknown */; } @@ -84293,7 +87770,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 180 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -84314,11 +87791,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - if (!signature && candidateSignatures.length) { - // Use the first candidate: - signature = candidateSignatures[0]; - } - var useConstructSignatures = callExpressionLike.kind === 182 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 183 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -84355,13 +87828,14 @@ var ts; // If it is call or construct signature of lambda's write type name displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); + if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(ts.lineBreakPart()); + } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); - } addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); break; default: @@ -84372,7 +87846,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 153 /* Constructor */)) { // 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 @@ -84380,21 +87854,21 @@ var ts; return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 152 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 153 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 152 /* Constructor */) { + if (functionDeclaration_1.kind === 153 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 155 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 156 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -84403,7 +87877,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { - if (ts.getDeclarationOfKind(symbol, 199 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -84447,7 +87921,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 233 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -84468,23 +87942,23 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 145 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 146 /* TypeParameter */); ts.Debug.assert(decl !== undefined); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 156 /* ConstructSignature */) { + if (declaration.kind === 157 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 155 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 231 /* TypeAliasDeclaration */) { + else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -84501,7 +87975,7 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 264 /* EnumMember */) { + if (declaration.kind === 268 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -84513,18 +87987,24 @@ var ts; } if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); + switch (symbol.declarations[0].kind) { + case 237 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(129 /* NamespaceKeyword */)); + break; + case 244 /* ExportAssignment */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 237 /* ImportEqualsDeclaration */) { + if (declaration.kind === 238 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -84595,23 +88075,23 @@ var ts; } } if (!documentation) { - documentation = symbol.getDocumentationComment(); + documentation = symbol.getDocumentationComment(typeChecker); tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbolFlags & 4 /* Property */) { // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 265 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 269 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 194 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 195 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); if (!rhsSymbol) { continue; } - documentation = rhsSymbol.getDocumentationComment(); + documentation = rhsSymbol.getDocumentationComment(typeChecker); tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; @@ -84639,8 +88119,10 @@ var ts; addNewLineIfDisplayPartsExist(); if (symbolKind) { pushTypePart(symbolKind); - displayParts.push(ts.spacePart()); - addFullSymbolName(symbol); + if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } } } function pushTypePart(symbolKind) { @@ -84670,7 +88152,7 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(); + documentation = signature.getDocumentationComment(typeChecker); tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -84687,16 +88169,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 186 /* FunctionExpression */) { + if (declaration.kind === 187 /* FunctionExpression */) { return true; } - if (declaration.kind !== 226 /* VariableDeclaration */ && declaration.kind !== 228 /* FunctionDeclaration */) { + if (declaration.kind !== 227 /* VariableDeclaration */ && declaration.kind !== 229 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 265 /* SourceFile */ || parent.kind === 234 /* ModuleBlock */) { + if (parent.kind === 269 /* SourceFile */ || parent.kind === 235 /* ModuleBlock */) { return false; } } @@ -84808,13 +88290,13 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_7 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } var value = options[opt.name]; // Value should be a key of opt.type - if (typeof value === "string") { + if (ts.isString(value)) { // If value is not a string, this will fail options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } @@ -84827,12 +88309,102 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_7(opt); + _loop_9(opt); } return options; } ts.fixupCompilerOptions = fixupCompilerOptions; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingRequestKind; + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; + })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingContext = /** @class */ (function () { + function FormattingContext(sourceFile, formattingRequestKind, options) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + this.options = options; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); + ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); + ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); + ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); + ts.Debug.assert(commonParent !== undefined, "commonParent is null"); + this.currentTokenSpan = currentRange; + this.currentTokenParent = currentTokenParent; + this.nextTokenSpan = nextRange; + this.nextTokenParent = nextTokenParent; + this.contextNode = commonParent; + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + }()); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -84840,8 +88412,8 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); - var jsxScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -84916,10 +88488,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 253 /* JsxAttribute */: - case 251 /* JsxOpeningElement */: - case 252 /* JsxClosingElement */: - case 250 /* JsxSelfClosingElement */: + case 257 /* JsxAttribute */: + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; } @@ -85069,129 +88641,12 @@ var ts; formatting.getFormattingScanner = getFormattingScanner; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var FormattingContext = /** @class */ (function () { - function FormattingContext(sourceFile, formattingRequestKind, options) { - this.sourceFile = sourceFile; - this.formattingRequestKind = formattingRequestKind; - this.options = options; - } - FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); - ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); - ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); - ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); - ts.Debug.assert(commonParent !== undefined, "commonParent is null"); - this.currentTokenSpan = currentRange; - this.currentTokenParent = currentTokenParent; - this.nextTokenSpan = nextRange; - this.nextTokenParent = nextTokenParent; - this.contextNode = commonParent; - // drop cached results - this.contextNodeAllOnSameLine = undefined; - this.nextNodeAllOnSameLine = undefined; - this.tokensAreOnSameLine = undefined; - this.contextNodeBlockIsOnOneLine = undefined; - this.nextNodeBlockIsOnOneLine = undefined; - }; - FormattingContext.prototype.ContextNodeAllOnSameLine = function () { - if (this.contextNodeAllOnSameLine === undefined) { - this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); - } - return this.contextNodeAllOnSameLine; - }; - FormattingContext.prototype.NextNodeAllOnSameLine = function () { - if (this.nextNodeAllOnSameLine === undefined) { - this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); - } - return this.nextNodeAllOnSameLine; - }; - FormattingContext.prototype.TokensAreOnSameLine = function () { - if (this.tokensAreOnSameLine === undefined) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine === endLine); - } - return this.tokensAreOnSameLine; - }; - FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { - if (this.contextNodeBlockIsOnOneLine === undefined) { - this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); - } - return this.contextNodeBlockIsOnOneLine; - }; - FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { - if (this.nextNodeBlockIsOnOneLine === undefined) { - this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); - } - return this.nextNodeBlockIsOnOneLine; - }; - FormattingContext.prototype.NodeIsOnOneLine = function (node) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine === endLine; - }; - FormattingContext.prototype.BlockIsOnOneLine = function (node) { - var openBrace = ts.findChildOfKind(node, 17 /* OpenBraceToken */, this.sourceFile); - var closeBrace = ts.findChildOfKind(node, 18 /* CloseBraceToken */, this.sourceFile); - if (openBrace && closeBrace) { - var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; - var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; - return startLine === endLine; - } - return false; - }; - return FormattingContext; - }()); - formatting.FormattingContext = FormattingContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var FormattingRequestKind; - (function (FormattingRequestKind) { - FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; - FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; - FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; - FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; - })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rule = /** @class */ (function () { - function Rule(Descriptor, Operation, Flag) { - if (Flag === void 0) { Flag = 0 /* None */; } - this.Descriptor = Descriptor; - this.Operation = Operation; - this.Flag = Flag; - } - return Rule; - }()); - formatting.Rule = Rule; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { + formatting.anyContext = ts.emptyArray; var RuleAction; (function (RuleAction) { RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; @@ -85199,46 +88654,6 @@ var ts; RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; RuleAction[RuleAction["Delete"] = 8] = "Delete"; })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleDescriptor = /** @class */ (function () { - function RuleDescriptor(LeftTokenRange, RightTokenRange) { - this.LeftTokenRange = LeftTokenRange; - this.RightTokenRange = RightTokenRange; - } - RuleDescriptor.prototype.toString = function () { - return "[leftRange=" + this.LeftTokenRange + "," + - "rightRange=" + this.RightTokenRange + "]"; - }; - RuleDescriptor.create1 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create2 = function (left, right) { - return RuleDescriptor.create4(left, formatting.Shared.TokenRange.FromToken(right)); - }; - RuleDescriptor.create3 = function (left, right) { - return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), right); - }; - RuleDescriptor.create4 = function (left, right) { - return new RuleDescriptor(left, right); - }; - return RuleDescriptor; - }()); - formatting.RuleDescriptor = RuleDescriptor; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { var RuleFlags; (function (RuleFlags) { RuleFlags[RuleFlags["None"] = 0] = "None"; @@ -85246,971 +88661,691 @@ var ts; })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RuleOperation = /** @class */ (function () { - function RuleOperation(Context, Action) { - this.Context = Context; - this.Action = Action; - } - RuleOperation.prototype.toString = function () { - return "[context=" + this.Context + "," + - "action=" + this.Action + "]"; - }; - RuleOperation.create1 = function (action) { - return RuleOperation.create2(formatting.RuleOperationContext.Any, action); - }; - RuleOperation.create2 = function (context, action) { - return new RuleOperation(context, action); - }; - return RuleOperation; - }()); - formatting.RuleOperation = RuleOperation; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var RuleOperationContext = /** @class */ (function () { - function RuleOperationContext() { - var funcs = []; - for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i] = arguments[_i]; - } - this.customContextChecks = funcs; + function getAllRules() { + var allTokens = []; + for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { + allTokens.push(token); } - RuleOperationContext.prototype.IsAny = function () { - return this === RuleOperationContext.Any; - }; - RuleOperationContext.prototype.InContext = function (context) { - if (this.IsAny()) { - return true; - } - for (var _i = 0, _a = this.customContextChecks; _i < _a.length; _i++) { - var check = _a[_i]; - if (!check(context)) { - return false; - } - } - return true; - }; - RuleOperationContext.Any = new RuleOperationContext(); - return RuleOperationContext; - }()); - formatting.RuleOperationContext = RuleOperationContext; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Rules = /** @class */ (function () { - function Rules() { - /// - /// Common Rules - /// + function anyTokenExcept(token) { + return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + } + var anyToken = { tokens: allTokens, isSpecific: false }; + var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); + var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 143 /* LastKeyword */); + var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); + var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 143 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */]; + var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; + var unaryPrefixExpressions = [ + 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, + 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ + ]; + var unaryPreincrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; + var unaryPostincrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var unaryPredecrementExpressions = [71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */]; + var unaryPostdecrementExpressions = [71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */]; + var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]; + var typeNames = [71 /* Identifier */].concat(ts.typeKeywords); + // Place a space before open brace in a function declaration + // TypeScript: Function can have return types, which can be made of tons of different token kinds + var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments; + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); + // Place a space before open brace in a control flow construct + var controlOpenBraceLeftTokenRange = tokenRangeFrom([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); + // These rules are higher in priority than user-configurable + var highPriorityCommonRules = [ // Leave comments alone - this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); - this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); - // Space after keyword but not before ; or : or ? - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 25 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - // Space after }. - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* CloseBraceToken */, formatting.Shared.TokenRange.FromRange(0 /* FirstToken */, 142 /* LastToken */, [20 /* CloseParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); - // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseBraceToken */, 82 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseBraceToken */, 106 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // No space for dot - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // No space before and after indexer - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); - // Place a space before open brace in a function declaration - this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); - // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) - this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); - // Place a space before open brace in a control flow construct - this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); - // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); - this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); - this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenBraceToken */, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); - // Insert new line after { and before } in multi-line contexts. - this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); - // For functions and control block place } on a new line [multi-line rule] - this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), + rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), + rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2 /* Space */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(43 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(44 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 43 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 44 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPreincrementOperator", 43 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterUnaryPredecrementOperator", 44 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(43 /* PlusPlusToken */, 37 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* PlusToken */, 37 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(37 /* PlusToken */, 43 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(44 /* MinusMinusToken */, 38 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(38 /* MinusToken */, 38 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(38 /* MinusToken */, 44 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 26 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterNewKeywordOnConstructorSignature = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* NewKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConstructorSignatureContext), 8 /* Delete */)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110 /* LetKeyword */, 76 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); - this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(89 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(105 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(96 /* ReturnKeyword */, 25 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. - // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); - // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([102 /* TryKeyword */, 87 /* FinallyKeyword */]), 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 18 /* CloseBraceToken */, anyTokenExcept(20 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2 /* Space */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 18 /* CloseBraceToken */, 82 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenCloseBraceAndWhile", 18 /* CloseBraceToken */, 106 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceBetweenFunctionKeywordAndStar", 89 /* FunctionKeyword */, 39 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 8 /* Delete */), + rule("SpaceAfterStarInGeneratorDeclaration", 39 /* AsteriskToken */, [71 /* Identifier */, 19 /* OpenParenToken */], [isFunctionDeclarationOrFunctionExpressionContext], 2 /* Space */), + rule("SpaceAfterFunctionInFuncDecl", 89 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 2 /* Space */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 17 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 4 /* NewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* GetKeyword */, 135 /* SetKeyword */]), 71 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + rule("SpaceAfterGetSetInMember", [125 /* GetKeyword */, 135 /* SetKeyword */], 71 /* Identifier */, [isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBetweenYieldKeywordAndStar", 116 /* YieldKeyword */, 39 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 8 /* Delete */), + rule("SpaceBetweenYieldOrYieldStarAndOperand", [116 /* YieldKeyword */, 39 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 2 /* Space */), + rule("NoSpaceBetweenReturnAndSemicolon", 96 /* ReturnKeyword */, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterCertainKeywords", [104 /* VarKeyword */, 100 /* ThrowKeyword */, 94 /* NewKeyword */, 80 /* DeleteKeyword */, 96 /* ReturnKeyword */, 103 /* TypeOfKeyword */, 121 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterLetConstInVariableDeclaration", [110 /* LetKeyword */, 76 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 8 /* Delete */), // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. - this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - // TypeScript-specific higher priority rules - this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123 /* ConstructorKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(123 /* ConstructorKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterConstructor"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterVoidOperator", 105 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 2 /* Space */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), + // template string + rule("NoSpaceBetweenTagAndTemplateString", 71 /* Identifier */, [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 41 /* SlashToken */, 29 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 58 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterEqualInJsxAttribute", 58 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 8 /* Delete */), + // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([128 /* ModuleKeyword */, 132 /* RequireKeyword */]), 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("NoSpaceAfterModuleImport", [128 /* ModuleKeyword */, 132 /* RequireKeyword */], 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([117 /* AbstractKeyword */, 75 /* ClassKeyword */, 124 /* DeclareKeyword */, 79 /* DefaultKeyword */, 83 /* EnumKeyword */, 84 /* ExportKeyword */, 85 /* ExtendsKeyword */, 125 /* GetKeyword */, 108 /* ImplementsKeyword */, 91 /* ImportKeyword */, 109 /* InterfaceKeyword */, 128 /* ModuleKeyword */, 129 /* NamespaceKeyword */, 112 /* PrivateKeyword */, 114 /* PublicKeyword */, 113 /* ProtectedKeyword */, 131 /* ReadonlyKeyword */, 135 /* SetKeyword */, 115 /* StaticKeyword */, 138 /* TypeKeyword */, 140 /* FromKeyword */, 127 /* KeyOfKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 140 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceAfterCertainTypeScriptKeywords", [ + 117 /* AbstractKeyword */, + 75 /* ClassKeyword */, + 124 /* DeclareKeyword */, + 79 /* DefaultKeyword */, + 83 /* EnumKeyword */, + 84 /* ExportKeyword */, + 85 /* ExtendsKeyword */, + 125 /* GetKeyword */, + 108 /* ImplementsKeyword */, + 91 /* ImportKeyword */, + 109 /* InterfaceKeyword */, + 128 /* ModuleKeyword */, + 129 /* NamespaceKeyword */, + 112 /* PrivateKeyword */, + 114 /* PublicKeyword */, + 113 /* ProtectedKeyword */, + 131 /* ReadonlyKeyword */, + 135 /* SetKeyword */, + 115 /* StaticKeyword */, + 138 /* TypeKeyword */, + 141 /* FromKeyword */, + 127 /* KeyOfKeyword */, + ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 141 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { - this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); + rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions - this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 36 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(36 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceBeforeArrow", anyToken, 36 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceAfterArrow", 36 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Optional parameters and let args - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(24 /* DotDotDotToken */, 71 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 26 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - // generics and type assertions - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 27 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(20 /* CloseParenToken */, 27 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 29 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(29 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + rule("NoSpaceAfterEllipsis", 24 /* DotDotDotToken */, 71 /* Identifier */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOptionalParameters", 55 /* QuestionToken */, [20 /* CloseParenToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // Remove spaces in empty interface literals. e.g.: x: {} - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenBraceToken */, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 8 /* Delete */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), // decorators - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(57 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([117 /* AbstractKeyword */, 71 /* Identifier */, 84 /* ExportKeyword */, 79 /* DefaultKeyword */, 75 /* ClassKeyword */, 115 /* StaticKeyword */, 114 /* PublicKeyword */, 112 /* PrivateKeyword */, 113 /* ProtectedKeyword */, 125 /* GetKeyword */, 135 /* SetKeyword */, 21 /* OpenBracketToken */, 39 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); - this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(89 /* FunctionKeyword */, 39 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); - this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(39 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([71 /* Identifier */, 19 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(116 /* YieldKeyword */, 39 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116 /* YieldKeyword */, 39 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); - // Async-await - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(120 /* AsyncKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(120 /* AsyncKeyword */, 89 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - // template string - this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(71 /* Identifier */, formatting.Shared.TokenRange.FromTokens([13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // jsx opening element - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 71 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 41 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* SlashToken */, 29 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 58 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(58 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // No space before non-null assertion operator - this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 51 /* ExclamationToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8 /* Delete */)); - /// - /// Rules controlled by user options - /// - // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(26 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); - // Insert space before and after binary operators - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + rule("SpaceBeforeAt", anyToken, 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [ + 117 /* AbstractKeyword */, + 71 /* Identifier */, + 84 /* ExportKeyword */, + 79 /* DefaultKeyword */, + 75 /* ClassKeyword */, + 115 /* StaticKeyword */, + 114 /* PublicKeyword */, + 112 /* PrivateKeyword */, + 113 /* ProtectedKeyword */, + 125 /* GetKeyword */, + 135 /* SetKeyword */, + 21 /* OpenBracketToken */, + 39 /* AsteriskToken */, + ], [isEndOfDecoratorContextOnSameLine], 2 /* Space */), + rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 51 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterNewKeywordOnConstructorSignature", 94 /* NewKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 8 /* Delete */), + ]; + // These rules are applied after high priority + var userConfigurableRules = [ + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8 /* Delete */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), // Insert space after keywords in control flow statements - this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 2 /* Space */)); - this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), Rules.IsControlDeclContext), 8 /* Delete */)); - // Open Brace braces after function - // TypeScript: Function can have return types, which can be made of tons of different token kinds - this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); - // Open Brace braces after TypeScript module/class/interface - this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); - // Open Brace braces after control block - this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); - // Insert space after semicolon in for statement - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + rule("SpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2 /* Space */), + rule("NoSpaceAfterKeywordInControl", keywords, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 8 /* Delete */), // Insert space after opening and before closing nonempty parenthesis - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenOpenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenParenToken */, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("SpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBetweenOpenParens", 19 /* OpenParenToken */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenParens", 19 /* OpenParenToken */, 20 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenParen", 19 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseParen", anyToken, 20 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing nonempty brackets - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(21 /* OpenBracketToken */, 22 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + rule("SpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceBetweenBrackets", 21 /* OpenBracketToken */, 22 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBracket", 21 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBracket", anyToken, 22 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 8 /* Delete */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("SpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 2 /* Space */), + rule("NoSpaceBetweenEmptyBraceBrackets", 17 /* OpenBraceToken */, 18 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 8 /* Delete */), + rule("NoSpaceAfterOpenBrace", 17 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBrace", anyToken, 18 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after opening and before closing template string braces - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14 /* TemplateHead */, 15 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([14 /* TemplateHead */, 15 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15 /* TemplateMiddle */, 16 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([15 /* TemplateMiddle */, 16 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + rule("SpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 2 /* Space */), + rule("NoSpaceAfterTemplateHeadAndMiddle", [14 /* TemplateHead */, 15 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [15 /* TemplateMiddle */, 16 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 8 /* Delete */), // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - // Insert space after function keyword for anonymous functions - this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89 /* FunctionKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(89 /* FunctionKeyword */, 19 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), Rules.IsFunctionDeclContext), 8 /* Delete */)); - // No space after type assertion - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); - this.SpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(29 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabled("insertSpaceAfterTypeAssertion"), Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 2 /* Space */)); - // These rules are higher in priority than user-configurable rules. - this.HighPriorityCommonRules = [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, - // TypeScript-specific rules - this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceBeforeArrow, this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - this.NoSpaceBeforeNonNullAssertionOperator, - this.NoSpaceAfterNewKeywordOnConstructorSignature - ]; - // These rules are applied after high priority rules. - this.UserConfigurableRules = [ - this.SpaceAfterConstructor, this.NoSpaceAfterConstructor, - this.SpaceAfterComma, this.NoSpaceAfterComma, - this.SpaceAfterAnonymousFunctionKeyword, this.NoSpaceAfterAnonymousFunctionKeyword, - this.SpaceAfterKeywordInControl, this.NoSpaceAfterKeywordInControl, - this.SpaceAfterOpenParen, this.SpaceBeforeCloseParen, this.SpaceBetweenOpenParens, this.NoSpaceBetweenParens, this.NoSpaceAfterOpenParen, this.NoSpaceBeforeCloseParen, - this.SpaceAfterOpenBracket, this.SpaceBeforeCloseBracket, this.NoSpaceBetweenBrackets, this.NoSpaceAfterOpenBracket, this.NoSpaceBeforeCloseBracket, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NoSpaceBetweenEmptyBraceBrackets, this.NoSpaceAfterOpenBrace, this.NoSpaceBeforeCloseBrace, - this.SpaceAfterTemplateHeadAndMiddle, this.SpaceBeforeTemplateMiddleAndTail, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - this.SpaceAfterOpenBraceInJsxExpression, this.SpaceBeforeCloseBraceInJsxExpression, this.NoSpaceAfterOpenBraceInJsxExpression, this.NoSpaceBeforeCloseBraceInJsxExpression, - this.SpaceAfterSemicolonInFor, this.NoSpaceAfterSemicolonInFor, - this.SpaceBeforeBinaryOperator, this.SpaceAfterBinaryOperator, this.NoSpaceBeforeBinaryOperator, this.NoSpaceAfterBinaryOperator, - this.SpaceBeforeOpenParenInFuncDecl, this.NoSpaceBeforeOpenParenInFuncDecl, - this.NewLineBeforeOpenBraceInControl, - this.NewLineBeforeOpenBraceInFunction, this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock, - this.SpaceAfterTypeAssertion, this.NoSpaceAfterTypeAssertion - ]; - // These rules are lower in priority than user-configurable rules. - this.LowPriorityCommonRules = [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; - if (ts.Debug.isDebugging) { - var o = this; - for (var name in o) { - var rule = o[name]; - if (rule instanceof formatting.Rule) { - rule.debugName = name; - } - } + rule("SpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 2 /* Space */), + rule("NoSpaceAfterOpenBraceInJsxExpression", 17 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 18 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 8 /* Delete */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 2 /* Space */), + rule("NoSpaceAfterSemicolonInFor", 25 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 8 /* Delete */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), + rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 8 /* Delete */), + rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 2 /* Space */), + rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 8 /* Delete */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), + rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), + rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + ]; + // These rules are lower in priority than user-configurable + var lowPriorityCommonRules = [ + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), + rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), + rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2 /* Space */), + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + ]; + return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); + } + formatting.getAllRules = getAllRules; + function rule(debugName, left, right, context, action, flags) { + if (flags === void 0) { flags = 0 /* None */; } + return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } }; + } + function tokenRangeFrom(tokens) { + return { tokens: tokens, isSpecific: true }; + } + function toTokenRange(arg) { + return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg; + } + function tokenRangeFromRange(from, to, except) { + if (except === void 0) { except = []; } + var tokens = []; + for (var token = from; token <= to; token++) { + if (!ts.contains(except, token)) { + tokens.push(token); } } - /// - /// Contexts - /// - Rules.IsOptionEnabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; - }; - Rules.IsOptionDisabled = function (optionName) { - return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; - }; - Rules.IsOptionDisabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; - }; - Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; - }; - Rules.IsOptionEnabledOrUndefined = function (optionName) { - return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; - }; - Rules.IsForContext = function (context) { - return context.contextNode.kind === 214 /* ForStatement */; - }; - Rules.IsNotForContext = function (context) { - return !Rules.IsForContext(context); - }; - Rules.IsBinaryOpContext = function (context) { - switch (context.contextNode.kind) { - case 194 /* BinaryExpression */: - case 195 /* ConditionalExpression */: - case 202 /* AsExpression */: - case 246 /* ExportSpecifier */: - case 242 /* ImportSpecifier */: - case 158 /* TypePredicate */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - return true; - // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 176 /* BindingElement */: - // equals in type X = ... - case 231 /* TypeAliasDeclaration */: - // equal in import a = module('a'); - case 237 /* ImportEqualsDeclaration */: - // equal in let a = 0; - case 226 /* VariableDeclaration */: - // equal in p = 0; - case 146 /* Parameter */: - case 264 /* EnumMember */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; - // "in" keyword in for (let x in []) { } - case 215 /* ForInStatement */: - // "in" keyword in [P in keyof T]: T[P] - case 145 /* TypeParameter */: - return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; - // Technically, "of" is not a binary operator, but format it the same way as "in" - case 216 /* ForOfStatement */: - return context.currentTokenSpan.kind === 142 /* OfKeyword */ || context.nextTokenSpan.kind === 142 /* OfKeyword */; - } - return false; - }; - Rules.IsNotBinaryOpContext = function (context) { - return !Rules.IsBinaryOpContext(context); - }; - Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 195 /* ConditionalExpression */; - }; - Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { - return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); - }; - Rules.IsBraceWrappedContext = function (context) { - return context.contextNode.kind === 174 /* ObjectBindingPattern */ || Rules.IsSingleLineBlockContext(context); - }; - // This check is done before an open brace in a control construct, a function, or a typescript block declaration - Rules.IsBeforeMultilineBlockContext = function (context) { - return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); - }; - Rules.IsMultilineBlockContext = function (context) { - return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsSingleLineBlockContext = function (context) { - return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); - }; - Rules.IsBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.contextNode); - }; - Rules.IsBeforeBlockContext = function (context) { - return Rules.NodeIsBlockContext(context.nextTokenParent); - }; - // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children - Rules.NodeIsBlockContext = function (node) { - if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) { - // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return tokenRangeFrom(tokens); + } + /// + /// Contexts + /// + function isOptionEnabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; + } + function isOptionDisabled(optionName) { + return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; }; + } + function isOptionDisabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; + } + function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + } + function isOptionEnabledOrUndefined(optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; + } + function isForContext(context) { + return context.contextNode.kind === 215 /* ForStatement */; + } + function isNotForContext(context) { + return !isForContext(context); + } + function isBinaryOpContext(context) { + switch (context.contextNode.kind) { + case 195 /* BinaryExpression */: + case 196 /* ConditionalExpression */: + case 203 /* AsExpression */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 159 /* TypePredicate */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: return true; - } - switch (node.kind) { - case 207 /* Block */: - case 235 /* CaseBlock */: - case 178 /* ObjectLiteralExpression */: - case 234 /* ModuleBlock */: - return true; - } - return false; - }; - Rules.IsFunctionDeclContext = function (context) { - switch (context.contextNode.kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - // case SyntaxKind.MemberFunctionDeclaration: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - // case SyntaxKind.MethodSignature: - case 155 /* CallSignature */: - case 186 /* FunctionExpression */: - case 152 /* Constructor */: - case 187 /* ArrowFunction */: - // case SyntaxKind.ConstructorDeclaration: - // case SyntaxKind.SimpleArrowFunctionExpression: - // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 230 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one - return true; - } - return false; - }; - Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 228 /* FunctionDeclaration */ || context.contextNode.kind === 186 /* FunctionExpression */; - }; - Rules.IsTypeScriptDeclWithBlockContext = function (context) { - return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); - }; - Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { - switch (node.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 163 /* TypeLiteral */: - case 233 /* ModuleDeclaration */: - case 244 /* ExportDeclaration */: - case 245 /* NamedExports */: - case 238 /* ImportDeclaration */: - case 241 /* NamedImports */: - return true; - } - return false; - }; - Rules.IsAfterCodeBlockContext = function (context) { - switch (context.currentTokenParent.kind) { - case 229 /* ClassDeclaration */: - case 233 /* ModuleDeclaration */: - case 232 /* EnumDeclaration */: - case 260 /* CatchClause */: - case 234 /* ModuleBlock */: - case 221 /* SwitchStatement */: + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 177 /* BindingElement */: + // equals in type X = ... + case 232 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 238 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 227 /* VariableDeclaration */: + // equal in p = 0; + case 147 /* Parameter */: + case 268 /* EnumMember */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 216 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + case 146 /* TypeParameter */: + return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 217 /* ForOfStatement */: + return context.currentTokenSpan.kind === 143 /* OfKeyword */ || context.nextTokenSpan.kind === 143 /* OfKeyword */; + } + return false; + } + function isNotBinaryOpContext(context) { + return !isBinaryOpContext(context); + } + function isConditionalOperatorContext(context) { + return context.contextNode.kind === 196 /* ConditionalExpression */; + } + function isSameLineTokenOrBeforeBlockContext(context) { + return context.TokensAreOnSameLine() || isBeforeBlockContext(context); + } + function isBraceWrappedContext(context) { + return context.contextNode.kind === 175 /* ObjectBindingPattern */ || isSingleLineBlockContext(context); + } + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + function isBeforeMultilineBlockContext(context) { + return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + } + function isMultilineBlockContext(context) { + return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isSingleLineBlockContext(context) { + return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + } + function isBlockContext(context) { + return nodeIsBlockContext(context.contextNode); + } + function isBeforeBlockContext(context) { + return nodeIsBlockContext(context.nextTokenParent); + } + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + function nodeIsBlockContext(node) { + if (nodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 208 /* Block */: + case 236 /* CaseBlock */: + case 179 /* ObjectLiteralExpression */: + case 235 /* ModuleBlock */: + return true; + } + return false; + } + function isFunctionDeclContext(context) { + switch (context.contextNode.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + case 156 /* CallSignature */: + case 187 /* FunctionExpression */: + case 153 /* Constructor */: + case 188 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 231 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one + return true; + } + return false; + } + function isFunctionDeclarationOrFunctionExpressionContext(context) { + return context.contextNode.kind === 229 /* FunctionDeclaration */ || context.contextNode.kind === 187 /* FunctionExpression */; + } + function isTypeScriptDeclWithBlockContext(context) { + return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); + } + function nodeIsTypeScriptDeclWithBlockContext(node) { + switch (node.kind) { + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 164 /* TypeLiteral */: + case 234 /* ModuleDeclaration */: + case 245 /* ExportDeclaration */: + case 246 /* NamedExports */: + case 239 /* ImportDeclaration */: + case 242 /* NamedImports */: + return true; + } + return false; + } + function isAfterCodeBlockContext(context) { + switch (context.currentTokenParent.kind) { + case 230 /* ClassDeclaration */: + case 234 /* ModuleDeclaration */: + case 233 /* EnumDeclaration */: + case 264 /* CatchClause */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + return true; + case 208 /* Block */: { + var blockParent = context.currentTokenParent.parent; + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 188 /* ArrowFunction */ && blockParent.kind !== 187 /* FunctionExpression */) { return true; - case 207 /* Block */: { - var blockParent = context.currentTokenParent.parent; - // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 187 /* ArrowFunction */ && blockParent.kind !== 186 /* FunctionExpression */) { - return true; - } } } + } + return false; + } + function isControlDeclContext(context) { + switch (context.contextNode.kind) { + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 221 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 264 /* CatchClause */: + return true; + default: + return false; + } + } + function isObjectContext(context) { + return context.contextNode.kind === 179 /* ObjectLiteralExpression */; + } + function isFunctionCallContext(context) { + return context.contextNode.kind === 182 /* CallExpression */; + } + function isNewContext(context) { + return context.contextNode.kind === 183 /* NewExpression */; + } + function isFunctionCallOrNewContext(context) { + return isFunctionCallContext(context) || isNewContext(context); + } + function isPreviousTokenNotComma(context) { + return context.currentTokenSpan.kind !== 26 /* CommaToken */; + } + function isNextTokenNotCloseBracket(context) { + return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; + } + function isArrowFunctionContext(context) { + return context.contextNode.kind === 188 /* ArrowFunction */; + } + function isNonJsxSameLineTokenContext(context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; + } + function isNonJsxElementContext(context) { + return context.contextNode.kind !== 250 /* JsxElement */; + } + function isJsxExpressionContext(context) { + return context.contextNode.kind === 260 /* JsxExpression */; + } + function isNextTokenParentJsxAttribute(context) { + return context.nextTokenParent.kind === 257 /* JsxAttribute */; + } + function isJsxAttributeContext(context) { + return context.contextNode.kind === 257 /* JsxAttribute */; + } + function isJsxSelfClosingElementContext(context) { + return context.contextNode.kind === 251 /* JsxSelfClosingElement */; + } + function isNotBeforeBlockInFunctionDeclarationContext(context) { + return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); + } + function isEndOfDecoratorContextOnSameLine(context) { + return context.TokensAreOnSameLine() && + context.contextNode.decorators && + nodeIsInDecoratorContext(context.currentTokenParent) && + !nodeIsInDecoratorContext(context.nextTokenParent); + } + function nodeIsInDecoratorContext(node) { + while (ts.isExpressionNode(node)) { + node = node.parent; + } + return node.kind === 148 /* Decorator */; + } + function isStartOfVariableDeclarationList(context) { + return context.currentTokenParent.kind === 228 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + } + function isNotFormatOnEnter(context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + } + function isModuleDeclContext(context) { + return context.contextNode.kind === 234 /* ModuleDeclaration */; + } + function isObjectTypeContext(context) { + return context.contextNode.kind === 164 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + } + function isConstructorSignatureContext(context) { + return context.contextNode.kind === 157 /* ConstructSignature */; + } + function isTypeArgumentOrParameterOrAssertion(token, parent) { + if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { return false; - }; - Rules.IsControlDeclContext = function (context) { - switch (context.contextNode.kind) { - case 211 /* IfStatement */: - case 221 /* SwitchStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 213 /* WhileStatement */: - case 224 /* TryStatement */: - case 212 /* DoStatement */: - case 220 /* WithStatement */: - // TODO - // case SyntaxKind.ElseClause: - case 260 /* CatchClause */: - return true; - default: - return false; - } - }; - Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 178 /* ObjectLiteralExpression */; - }; - Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 181 /* CallExpression */; - }; - Rules.IsNewContext = function (context) { - return context.contextNode.kind === 182 /* NewExpression */; - }; - Rules.IsFunctionCallOrNewContext = function (context) { - return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); - }; - Rules.IsPreviousTokenNotComma = function (context) { - return context.currentTokenSpan.kind !== 26 /* CommaToken */; - }; - Rules.IsNextTokenNotCloseBracket = function (context) { - return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; - }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 187 /* ArrowFunction */; - }; - Rules.IsNonJsxSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; - }; - Rules.IsNonJsxElementContext = function (context) { - return context.contextNode.kind !== 249 /* JsxElement */; - }; - Rules.IsJsxExpressionContext = function (context) { - return context.contextNode.kind === 256 /* JsxExpression */; - }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 253 /* JsxAttribute */; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 253 /* JsxAttribute */; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 250 /* JsxSelfClosingElement */; - }; - Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { - return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); - }; - Rules.IsEndOfDecoratorContextOnSameLine = function (context) { - return context.TokensAreOnSameLine() && - context.contextNode.decorators && - Rules.NodeIsInDecoratorContext(context.currentTokenParent) && - !Rules.NodeIsInDecoratorContext(context.nextTokenParent); - }; - Rules.NodeIsInDecoratorContext = function (node) { - while (ts.isPartOfExpression(node)) { - node = node.parent; - } - return node.kind === 147 /* Decorator */; - }; - Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 227 /* VariableDeclarationList */ && - context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; - }; - Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind !== 2 /* FormatOnEnter */; - }; - Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 233 /* ModuleDeclaration */; - }; - Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 163 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; - }; - Rules.IsConstructorSignatureContext = function (context) { - return context.contextNode.kind === 156 /* ConstructSignature */; - }; - Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { - if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { + } + switch (parent.kind) { + case 160 /* TypeReference */: + case 185 /* TypeAssertionExpression */: + case 232 /* TypeAliasDeclaration */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 202 /* ExpressionWithTypeArguments */: + return true; + default: return false; - } - switch (parent.kind) { - case 159 /* TypeReference */: - case 184 /* TypeAssertionExpression */: - case 231 /* TypeAliasDeclaration */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 201 /* ExpressionWithTypeArguments */: - return true; - default: - return false; - } - }; - Rules.IsTypeArgumentOrParameterOrAssertionContext = function (context) { - return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || - Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); - }; - Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 184 /* TypeAssertionExpression */; - }; - Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 190 /* VoidExpression */; - }; - Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 197 /* YieldExpression */ && context.contextNode.expression !== undefined; - }; - Rules.IsNonNullAssertionContext = function (context) { - return context.contextNode.kind === 203 /* NonNullExpression */; - }; - return Rules; - }()); - formatting.Rules = Rules; + } + } + function isTypeArgumentOrParameterOrAssertionContext(context) { + return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + } + function isTypeAssertionContext(context) { + return context.contextNode.kind === 185 /* TypeAssertionExpression */; + } + function isVoidOpContext(context) { + return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 191 /* VoidExpression */; + } + function isYieldOrYieldStarWithOperand(context) { + return context.contextNode.kind === 198 /* YieldExpression */ && context.contextNode.expression !== undefined; + } + function isNonNullAssertionContext(context) { + return context.contextNode.kind === 204 /* NonNullExpression */; + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// +/// /* @internal */ var ts; (function (ts) { var formatting; (function (formatting) { - var RulesMap = /** @class */ (function () { - function RulesMap() { - this.map = []; - this.mapRowLength = 0; - } - RulesMap.create = function (rules) { - var result = new RulesMap(); - result.Initialize(rules); - return result; - }; - RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 142 /* LastToken */ + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); - // This array is used only during construction of the rulesbucket in the map - var rulesBucketConstructionStateList = new Array(this.map.length); // new Array(this.map.length); - this.FillRules(rules, rulesBucketConstructionStateList); - return this.map; - }; - RulesMap.prototype.FillRules = function (rules, rulesBucketConstructionStateList) { - var _this = this; - rules.forEach(function (rule) { - _this.FillRule(rule, rulesBucketConstructionStateList); - }); - }; - RulesMap.prototype.GetRuleBucketIndex = function (row, column) { - ts.Debug.assert(row <= 142 /* LastKeyword */ && column <= 142 /* LastKeyword */, "Must compute formatting context from tokens"); - var rulesBucketIndex = (row * this.mapRowLength) + column; - return rulesBucketIndex; + function getFormatContext(options) { + return { options: options, getRule: getRulesMap() }; + } + formatting.getFormatContext = getFormatContext; + var rulesMapCache; + function getRulesMap() { + if (rulesMapCache === undefined) { + rulesMapCache = createRulesMap(formatting.getAllRules()); + } + return rulesMapCache; + } + function createRulesMap(rules) { + var map = buildMap(rules); + return function (context) { + var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; + return bucket && ts.find(bucket, function (rule) { return ts.every(rule.context, function (c) { return c(context); }); }); }; - RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { - var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); - rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { - rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { - var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); - var rulesBucket = _this.map[rulesBucketIndex]; + } + function buildMap(rules) { + // Map from bucket index to array of rules + var map = new Array(mapRowLength * mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(map.length); + for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { + var rule = rules_1[_i]; + var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific; + for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) { + var left = _b[_a]; + for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) { + var right = _d[_c]; + var index = getRuleBucketIndex(left, right); + var rulesBucket = map[index]; if (rulesBucket === undefined) { - rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); - } - rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); - }); - }); - }; - RulesMap.prototype.GetRule = function (context) { - var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); - var bucket = this.map[bucketIndex]; - if (bucket) { - for (var _i = 0, _a = bucket.Rules(); _i < _a.length; _i++) { - var rule = _a[_i]; - if (rule.Operation.Context.InContext(context)) { - return rule; + rulesBucket = map[index] = []; } + addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index); } } - return undefined; - }; - return RulesMap; - }()); - formatting.RulesMap = RulesMap; - var MaskBitSize = 5; - var Mask = 0x1f; + } + return map; + } + function getRuleBucketIndex(row, column) { + ts.Debug.assert(row <= 143 /* LastKeyword */ && column <= 143 /* LastKeyword */, "Must compute formatting context from tokens"); + return (row * mapRowLength) + column; + } + var maskBitSize = 5; + var mask = 31; // MaskBitSize bits + var mapRowLength = 143 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; - RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; - RulesPosition[RulesPosition["ContextRulesSpecific"] = MaskBitSize * 2] = "ContextRulesSpecific"; - RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; - RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; - RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; - })(RulesPosition = formatting.RulesPosition || (formatting.RulesPosition = {})); - var RulesBucketConstructionState = /** @class */ (function () { - function RulesBucketConstructionState() { - //// The Rules list contains all the inserted rules into a rulebucket in the following order: - //// 1- Ignore rules with specific token combination - //// 2- Ignore rules with any token combination - //// 3- Context rules with specific token combination - //// 4- Context rules with any token combination - //// 5- Non-context rules with specific token combination - //// 6- Non-context rules with any token combination - //// - //// The member rulesInsertionIndexBitmap is used to describe the number of rules - //// in each sub-bucket (above) hence can be used to know the index of where to insert - //// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. - //// - //// Example: - //// In order to insert a rule to the end of sub-bucket (3), we get the index by adding - //// the values in the bitmap segments 3rd, 2nd, and 1st. - this.rulesInsertionIndexBitmap = 0; - } - RulesBucketConstructionState.prototype.GetInsertionIndex = function (maskPosition) { - var index = 0; - var pos = 0; - var indexBitmap = this.rulesInsertionIndexBitmap; - while (pos <= maskPosition) { - index += (indexBitmap & Mask); - indexBitmap >>= MaskBitSize; - pos += MaskBitSize; - } - return index; - }; - RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { - var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; - value++; - ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); - var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); - temp |= value << maskPosition; - this.rulesInsertionIndexBitmap = temp; - }; - return RulesBucketConstructionState; - }()); - formatting.RulesBucketConstructionState = RulesBucketConstructionState; - var RulesBucket = /** @class */ (function () { - function RulesBucket() { - this.rules = []; - } - RulesBucket.prototype.Rules = function () { - return this.rules; - }; - RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { - var position; - if (rule.Operation.Action === 1 /* Ignore */) { - position = specificTokens ? - RulesPosition.IgnoreRulesSpecific : - RulesPosition.IgnoreRulesAny; - } - else if (!rule.Operation.Context.IsAny()) { - position = specificTokens ? - RulesPosition.ContextRulesSpecific : - RulesPosition.ContextRulesAny; - } - else { - position = specificTokens ? - RulesPosition.NoContextRulesSpecific : - RulesPosition.NoContextRulesAny; - } - var state = constructionState[rulesBucketIndex]; - if (state === undefined) { - state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); - } - var index = state.GetInsertionIndex(position); - this.rules.splice(index, 0, rule); - state.IncreaseInsertionIndex(position); - }; - return RulesBucket; - }()); - formatting.RulesBucket = RulesBucket; - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var Shared; - (function (Shared) { - var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 142 /* LastToken */; token++) { - allTokens.push(token); + RulesPosition[RulesPosition["IgnoreRulesAny"] = maskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny"; + })(RulesPosition || (RulesPosition = {})); + // The Rules list contains all the inserted rules into a rulebucket in the following order: + // 1- Ignore rules with specific token combination + // 2- Ignore rules with any token combination + // 3- Context rules with specific token combination + // 4- Context rules with any token combination + // 5- Non-context rules with specific token combination + // 6- Non-context rules with any token combination + // + // The member rulesInsertionIndexBitmap is used to describe the number of rules + // in each sub-bucket (above) hence can be used to know the index of where to insert + // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + // + // Example: + // In order to insert a rule to the end of sub-bucket (3), we get the index by adding + // the values in the bitmap segments 3rd, 2nd, and 1st. + function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) { + var position = rule.action === 1 /* Ignore */ + ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny + : rule.context !== formatting.anyContext + ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny + : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + var state = constructionState[rulesBucketIndex] || 0; + rules.splice(getInsertionIndex(state, position), 0, rule); + constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); + } + function getInsertionIndex(indexBitmap, maskPosition) { + var index = 0; + for (var pos = 0; pos <= maskPosition; pos += maskBitSize) { + index += indexBitmap & mask; + indexBitmap >>= maskBitSize; } - var TokenValuesAccess = /** @class */ (function () { - function TokenValuesAccess(tokens) { - if (tokens === void 0) { tokens = []; } - this.tokens = tokens; - } - TokenValuesAccess.prototype.GetTokens = function () { - return this.tokens; - }; - TokenValuesAccess.prototype.Contains = function (token) { - return this.tokens.indexOf(token) >= 0; - }; - TokenValuesAccess.prototype.isSpecific = function () { return true; }; - return TokenValuesAccess; - }()); - var TokenSingleValueAccess = /** @class */ (function () { - function TokenSingleValueAccess(token) { - this.token = token; - } - TokenSingleValueAccess.prototype.GetTokens = function () { - return [this.token]; - }; - TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue === this.token; - }; - TokenSingleValueAccess.prototype.isSpecific = function () { return true; }; - return TokenSingleValueAccess; - }()); - var TokenAllAccess = /** @class */ (function () { - function TokenAllAccess() { - } - TokenAllAccess.prototype.GetTokens = function () { - return allTokens; - }; - TokenAllAccess.prototype.Contains = function () { - return true; - }; - TokenAllAccess.prototype.toString = function () { - return "[allTokens]"; - }; - TokenAllAccess.prototype.isSpecific = function () { return false; }; - return TokenAllAccess; - }()); - var TokenAllExceptAccess = /** @class */ (function () { - function TokenAllExceptAccess(except) { - this.except = except; - } - TokenAllExceptAccess.prototype.GetTokens = function () { - var _this = this; - return allTokens.filter(function (t) { return t !== _this.except; }); - }; - TokenAllExceptAccess.prototype.Contains = function (token) { - return token !== this.except; - }; - TokenAllExceptAccess.prototype.isSpecific = function () { return false; }; - return TokenAllExceptAccess; - }()); - var TokenRange; - (function (TokenRange) { - function FromToken(token) { - return new TokenSingleValueAccess(token); - } - TokenRange.FromToken = FromToken; - function FromTokens(tokens) { - return new TokenValuesAccess(tokens); - } - TokenRange.FromTokens = FromTokens; - function FromRange(from, to, except) { - if (except === void 0) { except = []; } - var tokens = []; - for (var token = from; token <= to; token++) { - if (ts.indexOf(except, token) < 0) { - tokens.push(token); - } - } - return new TokenValuesAccess(tokens); - } - TokenRange.FromRange = FromRange; - function AnyExcept(token) { - return new TokenAllExceptAccess(token); - } - TokenRange.AnyExcept = AnyExcept; - TokenRange.Any = new TokenAllAccess(); - TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(allTokens.concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(72 /* FirstKeyword */, 142 /* LastKeyword */); - TokenRange.BinaryOperators = TokenRange.FromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([ - 92 /* InKeyword */, 93 /* InstanceOfKeyword */, 142 /* OfKeyword */, 118 /* AsKeyword */, 126 /* IsKeyword */ - ]); - TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([ - 43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */ - ]); - TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([ - 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, - 17 /* OpenBraceToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 19 /* OpenParenToken */, 99 /* ThisKeyword */, 94 /* NewKeyword */ - ]); - TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([ - 71 /* Identifier */, 20 /* CloseParenToken */, 22 /* CloseBracketToken */, 94 /* NewKeyword */ - ]); - TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([ - 71 /* Identifier */, 133 /* NumberKeyword */, 136 /* StringKeyword */, 122 /* BooleanKeyword */, - 137 /* SymbolKeyword */, 105 /* VoidKeyword */, 119 /* AnyKeyword */ - ]); - })(TokenRange = Shared.TokenRange || (Shared.TokenRange = {})); - })(Shared = formatting.Shared || (formatting.Shared = {})); - })(formatting = ts.formatting || (ts.formatting = {})); -})(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/* @internal */ -var ts; -(function (ts) { - var formatting; - (function (formatting) { - var RulesProvider = /** @class */ (function () { - function RulesProvider() { - this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); - this.rulesMap = formatting.RulesMap.create(activeRules); - } - RulesProvider.prototype.getRulesMap = function () { - return this.rulesMap; - }; - RulesProvider.prototype.getFormatOptions = function () { - return this.options; - }; - RulesProvider.prototype.ensureUpToDate = function (options) { - if (!this.options || !ts.compareDataObjects(this.options, options)) { - this.options = ts.clone(options); - } - }; - return RulesProvider; - }()); - formatting.RulesProvider = RulesProvider; + return index; + } + function increaseInsertionIndex(indexBitmap, maskPosition) { + var value = ((indexBitmap >> maskPosition) & mask) + 1; + ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); + } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/// -/// -/// +/// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -86220,7 +89355,7 @@ var ts; (function (Constants) { Constants[Constants["Unknown"] = -1] = "Unknown"; })(Constants || (Constants = {})); - function formatOnEnter(position, sourceFile, rulesProvider, options) { + function formatOnEnter(position, sourceFile, formatContext) { var line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { return []; @@ -86246,15 +89381,15 @@ var ts; // end value is exclusive so add 1 to the result end: endOfFormatSpan + 1 }; - return formatSpan(span, sourceFile, options, rulesProvider, 2 /* FormatOnEnter */); + return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); } formatting.formatOnEnter = formatOnEnter; - function formatOnSemicolon(position, sourceFile, rulesProvider, options) { + function formatOnSemicolon(position, sourceFile, formatContext) { var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; - function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + function formatOnOpeningCurly(position, sourceFile, formatContext) { var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); if (!openingCurly) { return []; @@ -86277,29 +89412,29 @@ var ts; pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), end: position }; - return formatSpan(textRange, sourceFile, options, rulesProvider, 4 /* FormatOnOpeningCurlyBrace */); + return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); } formatting.formatOnOpeningCurly = formatOnOpeningCurly; - function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { + function formatOnClosingCurly(position, sourceFile, formatContext) { var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); - return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5 /* FormatOnClosingCurlyBrace */); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; - function formatDocument(sourceFile, rulesProvider, options) { + function formatDocument(sourceFile, formatContext) { var span = { pos: 0, end: sourceFile.text.length }; - return formatSpan(span, sourceFile, options, rulesProvider, 0 /* FormatDocument */); + return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); } formatting.formatDocument = formatDocument; - function formatSelection(start, end, sourceFile, rulesProvider, options) { + function formatSelection(start, end, sourceFile, formatContext) { // format from the beginning of the line var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), end: end, }; - return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */); + return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); } formatting.formatSelection = formatSelection; /** @@ -86339,17 +89474,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 234 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 265 /* SourceFile */: - case 207 /* Block */: - case 234 /* ModuleBlock */: + return body && body.kind === 235 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 269 /* SourceFile */: + case 208 /* Block */: + case 235 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -86463,13 +89598,13 @@ var ts; return 0; } /* @internal */ - function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; - function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + function formatNodeLines(node, sourceFile, formatContext, requestKind) { if (!node) { return []; } @@ -86477,14 +89612,15 @@ var ts; pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), end: node.end }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + return formatSpan(span, sourceFile, formatContext, requestKind); } - function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { + function formatSpan(originalRange, sourceFile, formatContext, requestKind) { // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } - function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { + var options = _a.options, getRule = _a.getRule; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRange; @@ -86568,19 +89704,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 229 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 230 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 228 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 232 /* EnumDeclaration */: return 232 /* EnumDeclaration */; - case 153 /* GetAccessor */: return 125 /* GetKeyword */; - case 154 /* SetAccessor */: return 135 /* SetKeyword */; - case 151 /* MethodDeclaration */: + case 230 /* ClassDeclaration */: return 75 /* ClassKeyword */; + case 231 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; + case 229 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; + case 233 /* EnumDeclaration */: return 233 /* EnumDeclaration */; + case 154 /* GetAccessor */: return 125 /* GetKeyword */; + case 155 /* SetAccessor */: return 135 /* SetKeyword */; + case 152 /* MethodDeclaration */: if (node.asteriskToken) { return 39 /* AsteriskToken */; } // falls through - case 149 /* PropertyDeclaration */: - case 146 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 147 /* Parameter */: return ts.getNameOfDeclaration(node).kind; } } @@ -86618,16 +89754,16 @@ var ts; return indentation; case 41 /* SlashToken */: case 29 /* GreaterThanToken */: { - if (container.kind === 251 /* JsxOpeningElement */ || - container.kind === 252 /* JsxClosingElement */ || - container.kind === 250 /* JsxSelfClosingElement */) { + if (container.kind === 252 /* JsxOpeningElement */ || + container.kind === 253 /* JsxClosingElement */ || + container.kind === 251 /* JsxSelfClosingElement */) { return indentation; } break; } case 21 /* OpenBracketToken */: case 22 /* CloseBracketToken */: { - if (container.kind !== 172 /* MappedType */) { + if (container.kind !== 173 /* MappedType */) { return indentation; } break; @@ -86699,9 +89835,9 @@ var ts; if (child.decorators) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } - // if child is a list item - try to get its indentation + // if child is a list item - try to get its indentation, only if parent is within the original range. var childIndentationAmount = -1 /* Unknown */; - if (isListItem) { + if (isListItem && ts.rangeContainsRange(originalRange, parent)) { childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); if (childIndentationAmount !== -1 /* Unknown */) { inheritedIndentation = childIndentationAmount; @@ -86737,11 +89873,15 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 147 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 148 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + if (child.kind === 10 /* JsxText */) { + var range = { pos: child.getStart(), end: child.getEnd() }; + indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); + } childContextNode = node; - if (isFirstListItem && parent.kind === 177 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 178 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -86799,27 +89939,24 @@ var ts; if (currentTokenInfo.leadingTrivia) { processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); } - var lineAdded; + var lineAction = 0 /* None */; var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { var rangeHasError = rangeContainsError(currentTokenInfo.token); // save previousRange since processRange will overwrite this value with current one var savePreviousRange = previousRange; - lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); - if (rangeHasError) { - // do not indent comments\token if token range overlaps with some error - indentToken = false; - } - else { - if (lineAdded !== undefined) { - indentToken = lineAdded; - } - else { + lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + // do not indent comments\token if token range overlaps with some error + if (!rangeHasError) { + if (lineAction === 0 /* None */) { // indent token only if end line of previous range does not match start line of the token var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } + else { + indentToken = lineAction === 1 /* LineAdded */; + } } } if (currentTokenInfo.trailingTrivia) { @@ -86838,7 +89975,7 @@ var ts; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -86856,7 +89993,7 @@ var ts; } // indent token only if is it is in target range and does not overlap with any error ranges if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { - insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); lastIndentedLine = tokenStart.line; indentationOnLastIndentedLine = tokenIndentation; } @@ -86876,7 +90013,7 @@ var ts; } function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); - var lineAdded; + var lineAction = 0 /* None */; if (!rangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line @@ -86884,32 +90021,32 @@ var ts; trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { - lineAdded = + lineAction = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } previousRange = range; previousParent = parent; previousRangeStartLine = rangeStart.line; - return lineAdded; + return lineAction; } function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); - var rule = rulesProvider.getRulesMap().GetRule(formattingContext); + var rule = getRule(formattingContext); var trimTrailingWhitespaces; - var lineAdded; + var lineAction = 0 /* None */; if (rule) { applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.Operation.Action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAdded = false; + if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { + lineAction = 2 /* LineRemoved */; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); } } - else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAdded = true; + else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { + lineAction = 1 /* LineAdded */; // Handle the case where token2 is moved to the new line. // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. @@ -86918,7 +90055,7 @@ var ts; } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -86927,7 +90064,7 @@ var ts; // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } - return lineAdded; + return lineAction; } function insertIndentation(pos, indentation, lineAdded) { var indentationString = getIndentationString(indentation, options); @@ -86959,7 +90096,8 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { + function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine) { + if (indentFinalLine === void 0) { indentFinalLine = true; } // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; @@ -86979,7 +90117,9 @@ var ts; parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } - parts.push({ pos: startPos, end: commentRange.end }); + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } } var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); @@ -87060,7 +90200,7 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - switch (rule.Operation.Action) { + switch (rule.action) { case 1 /* Ignore */: // no action required return; @@ -87074,7 +90214,7 @@ var ts; // exit early if we on different lines and rule cannot change number of newlines // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines - if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } // edit should not be applied if we have one line feed between elements @@ -87085,7 +90225,7 @@ var ts; break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines - if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } var posDelta = currentRange.pos - previousRange.end; @@ -87096,6 +90236,12 @@ var ts; } } } + var LineAction; + (function (LineAction) { + LineAction[LineAction["None"] = 0] = "None"; + LineAction[LineAction["LineAdded"] = 1] = "LineAdded"; + LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved"; + })(LineAction || (LineAction = {})); /** * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ @@ -87143,12 +90289,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 187 /* ArrowFunction */: + case 153 /* Constructor */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 188 /* ArrowFunction */: if (node.typeParameters === list) { return 27 /* LessThanToken */; } @@ -87156,8 +90302,8 @@ var ts; return 19 /* OpenParenToken */; } break; - case 181 /* CallExpression */: - case 182 /* NewExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -87165,7 +90311,7 @@ var ts; return 19 /* OpenParenToken */; } break; - case 159 /* TypeReference */: + case 160 /* TypeReference */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -87233,7 +90379,6 @@ var ts; formatting.getIndentationString = getIndentationString; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -87246,16 +90391,19 @@ var ts; Value[Value["Unknown"] = -1] = "Unknown"; })(Value || (Value = {})); /** - * Computed indentation for a given position in source file - * @param position - position in file - * @param sourceFile - target source file - * @param options - set of editor options that control indentation - * @param assumeNewLineBeforeCloseBrace - false when getIndentation is called on the text from the real source file. - * true - when we need to assume that position is on the newline. This is usefult for codefixes, i.e. + * @param assumeNewLineBeforeCloseBrace + * `false` when called on text from a real source file. + * `true` when we need to assume `position` is on a newline. + * + * This is useful for codefixes. Consider + * ``` * function f() { * |} - * when inserting some text after open brace we would like to get the value of indentation as if newline was already there. - * However by default indentation at position | will be 0 so 'assumeNewLineBeforeCloseBrace' allows to override this behavior, + * ``` + * with `position` at `|`. + * + * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. + * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. */ function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) { if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; } @@ -87270,19 +90418,7 @@ var ts; var precedingToken = ts.findPrecedingToken(position, sourceFile); var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword if (enclosingCommentRange) { - var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; - var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; - ts.Debug.assert(commentStartLine >= 0); - if (previousLine <= commentStartLine) { - return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); - } - var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); - var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; - if (column === 0) { - return column; - } - var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); - return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { return getBaseIndentation(options); @@ -87297,44 +90433,61 @@ var ts; // for block indentation, we should look for a line which contains something that's not // whitespace. if (options.indentStyle === ts.IndentStyle.Block) { - // move backwards until we find a line with a non-whitespace character, - // then find the first non-whitespace character for that line. - var current_1 = position; - while (current_1 > 0) { - var char = sourceFile.text.charCodeAt(current_1); - if (!ts.isWhiteSpaceLike(char)) { - break; - } - current_1--; - } - var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); - return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); + return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 194 /* BinaryExpression */) { + if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 195 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } } + return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options); + } + SmartIndenter.getIndentation = getIndentation; + function getCommentIndent(sourceFile, position, options, enclosingCommentRange) { + var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1; + var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line; + ts.Debug.assert(commentStartLine >= 0); + if (previousLine <= commentStartLine) { + return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); + } + var startPostionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile); + var _a = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options), column = _a.column, character = _a.character; + if (column === 0) { + return column; + } + var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column; + } + function getBlockIndent(sourceFile, position, options) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current = position; + while (current > 0) { + var char = sourceFile.text.charCodeAt(current); + if (!ts.isWhiteSpaceLike(char)) { + break; + } + current--; + } + var lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); + } + function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) { // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' // if such node is found - compute initial indentation for 'position' inside this node var previous; var current = precedingToken; - var currentStart; - var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { - currentStart = getStartLineAndCharacterForNode(current, sourceFile); + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous, /*isNextChild*/ true)) { + var currentStart = getStartLineAndCharacterForNode(current, sourceFile); var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); - if (nextTokenKind !== 0 /* Unknown */) { + var indentationDelta = nextTokenKind !== 0 /* Unknown */ // handle cases when codefix is about to be inserted before the close brace - indentationDelta = assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0; - } - else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; - } - break; + ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 + : lineAtPosition !== currentStart.line ? options.indentSize : 0; + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -87348,27 +90501,23 @@ var ts; previous = current; current = current.parent; } - if (!current) { - // no parent was found - return the base indentation of the SourceFile - return getBaseIndentation(options); - } - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); } - SmartIndenter.getIndentation = getIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); - return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; function getBaseIndentation(options) { return options.baseIndentSize || 0; } SmartIndenter.getBaseIndentation = getBaseIndentation; - function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { var parent = current.parent; - var parentStart; - // walk upwards and collect indentations for pairs of parent-child nodes - // indentation is not added if parent and child nodes start on the same line or if parent is IfStatement and child starts on the same line with 'else clause' + // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if + // * parent and child nodes start on the same line, or + // * parent is an IfStatement and child starts on the same line as an 'else clause'. while (parent) { var useActualIndentation = true; if (ignoreActualIndentationRange) { @@ -87382,8 +90531,8 @@ var ts; return actualIndentation + indentationDelta; } } - parentStart = getParentStart(parent, current, sourceFile); - var parentAndChildShareLine = parentStart.line === currentStart.line || + var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); + var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // try to fetch actual indentation for current node from source text @@ -87397,21 +90546,28 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current, isNextChild) && !parentAndChildShareLine) { indentationDelta += options.indentSize; } + // In our AST, a call argument's `parent` is the call-expression, not the argument list. + // We would like to increase indentation based on the relationship between an argument and its argument-list, + // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list. + // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression + // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation. + // + // Instead, when at an argument, we unspoof the starting position of the enclosing call expression + // *after* applying indentation for the argument. + var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); current = parent; - currentStart = parentStart; parent = current.parent; + currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart; } return indentationDelta + getBaseIndentation(options); } - function getParentStart(parent, child, sourceFile) { + function getContainingListOrParentStart(parent, child, sourceFile) { var containingList = getContainingList(child, sourceFile); - if (containingList) { - return sourceFile.getLineAndCharacterOfPosition(containingList.pos); - } - return sourceFile.getLineAndCharacterOfPosition(parent.getStart(sourceFile)); + var startPos = containingList ? containingList.pos : parent.getStart(sourceFile); + return sourceFile.getLineAndCharacterOfPosition(startPos); } /* * Function returns Value.Unknown if indentation cannot be determined @@ -87435,7 +90591,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 265 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 269 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -87473,8 +90629,17 @@ var ts; function getStartLineAndCharacterForNode(n, sourceFile) { return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } + function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) { + if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) { + return false; + } + var expressionOfCallExpressionEnd = parent.expression.getEnd(); + var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line; + return expressionOfCallExpressionEndLine === childStartLine; + } + SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 211 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 212 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -87489,37 +90654,37 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 159 /* TypeReference */: + case 160 /* TypeReference */: return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); - case 178 /* ObjectLiteralExpression */: + case 179 /* ObjectLiteralExpression */: return node.parent.properties; - case 177 /* ArrayLiteralExpression */: + case 178 /* ArrayLiteralExpression */: return node.parent.elements; - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 152 /* Constructor */: - case 161 /* ConstructorType */: - case 156 /* ConstructSignature */: { + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 153 /* Constructor */: + case 162 /* ConstructorType */: + case 157 /* ConstructSignature */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); } - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); - case 182 /* NewExpression */: - case 181 /* CallExpression */: { + case 183 /* NewExpression */: + case 182 /* CallExpression */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); } - case 227 /* VariableDeclarationList */: + case 228 /* VariableDeclarationList */: return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); - case 241 /* NamedImports */: - case 245 /* NamedExports */: + case 242 /* NamedImports */: + case 246 /* NamedExports */: return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); } } @@ -87557,10 +90722,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: node = node.expression; break; default: @@ -87624,90 +90789,122 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 210 /* ExpressionStatement */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 177 /* ArrayLiteralExpression */: - case 207 /* Block */: - case 234 /* ModuleBlock */: - case 178 /* ObjectLiteralExpression */: - case 163 /* TypeLiteral */: - case 172 /* MappedType */: - case 165 /* TupleType */: - case 235 /* CaseBlock */: - case 258 /* DefaultClause */: - case 257 /* CaseClause */: - case 185 /* ParenthesizedExpression */: - case 179 /* PropertyAccessExpression */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 208 /* VariableStatement */: - case 226 /* VariableDeclaration */: - case 243 /* ExportAssignment */: - case 219 /* ReturnStatement */: - case 195 /* ConditionalExpression */: - case 175 /* ArrayBindingPattern */: - case 174 /* ObjectBindingPattern */: - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - case 256 /* JsxExpression */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 146 /* Parameter */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 168 /* ParenthesizedType */: - case 183 /* TaggedTemplateExpression */: - case 191 /* AwaitExpression */: - case 245 /* NamedExports */: - case 241 /* NamedImports */: - case 246 /* ExportSpecifier */: - case 242 /* ImportSpecifier */: - case 261 /* PropertyAssignment */: - case 149 /* PropertyDeclaration */: + case 211 /* ExpressionStatement */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 233 /* EnumDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 178 /* ArrayLiteralExpression */: + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 179 /* ObjectLiteralExpression */: + case 164 /* TypeLiteral */: + case 173 /* MappedType */: + case 166 /* TupleType */: + case 236 /* CaseBlock */: + case 262 /* DefaultClause */: + case 261 /* CaseClause */: + case 186 /* ParenthesizedExpression */: + case 180 /* PropertyAccessExpression */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 209 /* VariableStatement */: + case 227 /* VariableDeclaration */: + case 244 /* ExportAssignment */: + case 220 /* ReturnStatement */: + case 196 /* ConditionalExpression */: + case 176 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 252 /* JsxOpeningElement */: + case 251 /* JsxSelfClosingElement */: + case 260 /* JsxExpression */: + case 151 /* MethodSignature */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 147 /* Parameter */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 169 /* ParenthesizedType */: + case 184 /* TaggedTemplateExpression */: + case 192 /* AwaitExpression */: + case 246 /* NamedExports */: + case 242 /* NamedImports */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 265 /* PropertyAssignment */: + case 150 /* PropertyDeclaration */: return true; } return false; } - /* @internal */ function nodeWillIndentChild(parent, child, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 214 /* ForStatement */: - case 211 /* IfStatement */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 187 /* ArrowFunction */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return childKind !== 207 /* Block */; - case 244 /* ExportDeclaration */: - return childKind !== 245 /* NamedExports */; - case 238 /* ImportDeclaration */: - return childKind !== 239 /* ImportClause */ || - (child.namedBindings && child.namedBindings.kind !== 241 /* NamedImports */); - case 249 /* JsxElement */: - return childKind !== 252 /* JsxClosingElement */; + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 215 /* ForStatement */: + case 212 /* IfStatement */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 188 /* ArrowFunction */: + case 153 /* Constructor */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return childKind !== 208 /* Block */; + case 245 /* ExportDeclaration */: + return childKind !== 246 /* NamedExports */; + case 239 /* ImportDeclaration */: + return childKind !== 240 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 242 /* NamedImports */); + case 250 /* JsxElement */: + return childKind !== 253 /* JsxClosingElement */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; } SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; - /* - Function returns true when the parent node should indent the given child by an explicit rule - */ - function shouldIndentChildNode(parent, child) { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false); + function isControlFlowEndingStatement(kind, parent) { + switch (kind) { + case 220 /* ReturnStatement */: + case 224 /* ThrowStatement */: + switch (parent.kind) { + case 208 /* Block */: + var grandParent = parent.parent; + switch (grandParent && grandParent.kind) { + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + // We may want to write inner functions after this. + return false; + default: + return true; + } + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 269 /* SourceFile */: + case 235 /* ModuleBlock */: + return true; + default: + throw ts.Debug.fail(); + } + case 218 /* ContinueStatement */: + case 219 /* BreakStatement */: + return true; + default: + return false; + } + } + /** + * True when the parent node should indent the given child by an explicit rule. + * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. + */ + function shouldIndentChildNode(parent, child, isNextChild) { + if (isNextChild === void 0) { isNextChild = false; } + return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false)) + && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -87723,22 +90920,22 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -87815,7 +91012,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 178 /* ObjectLiteralExpression */)); + return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 179 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -87825,15 +91022,20 @@ var ts; return s; } var ChangeTracker = /** @class */ (function () { - function ChangeTracker(newLine, rulesProvider, validator) { + function ChangeTracker(newLine, formatContext, validator) { this.newLine = newLine; - this.rulesProvider = rulesProvider; + this.formatContext = formatContext; this.validator = validator; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -87955,9 +91157,9 @@ var ts; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { if (options === void 0) { options = {}; } if ((ts.isStatementButNotDeclaration(after)) || - after.kind === 149 /* PropertyDeclaration */ || - after.kind === 148 /* PropertySignature */ || - after.kind === 150 /* MethodSignature */) { + after.kind === 150 /* PropertyDeclaration */ || + after.kind === 149 /* PropertySignature */ || + after.kind === 151 /* MethodSignature */) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { @@ -88086,7 +91288,7 @@ var ts; options: {} }); // use the same indentation as 'after' item - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.rulesProvider.getFormatOptions()); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false); if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { @@ -88170,7 +91372,7 @@ var ts; if (this.validator) { this.validator(nonformattedText); } - var formatOptions = this.rulesProvider.getFormatOptions(); + var formatOptions = this.formatContext.options; var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos; var initialIndentation = options.indentation !== undefined ? options.indentation @@ -88182,7 +91384,7 @@ var ts; : ts.formatting.SmartIndenter.shouldIndentChildNode(node) ? (formatOptions.indentSize || 0) : 0; - return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.rulesProvider); + return applyFormatting(nonformattedText, sourceFile, initialIndentation, delta, this.formatContext); }; ChangeTracker.normalize = function (changes) { // order changes by start position @@ -88203,14 +91405,14 @@ var ts; printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { + function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, formatContext) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { text: nonFormattedText.text, lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(nonFormattedText.text, changes); } function applyChanges(text, changes) { @@ -88396,7 +91598,7 @@ var ts; refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { return ts.flatMapIter(refactors.values(), function (refactor) { - return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); }); } refactor_1.getApplicableRefactors = getApplicableRefactors; @@ -88413,6 +91615,29 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decorator = ts.getAncestor(token, 148 /* Decorator */); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -88421,7 +91646,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var qualifiedName = ts.getAncestor(token, 143 /* QualifiedName */); + var qualifiedName = ts.getAncestor(token, 144 /* QualifiedName */); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); if (!ts.isIdentifier(qualifiedName.left)) { return undefined; @@ -88536,7 +91761,7 @@ var ts; var checker = context.program.getTypeChecker(); var leftExpression = token.parent.expression; var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 32768 /* Object */) { + if (leftExpressionType.flags & 65536 /* Object */) { var symbol = leftExpressionType.symbol; if (symbol.flags & 32 /* Class */) { classDeclaration = symbol.declarations && symbol.declarations[0]; @@ -88562,13 +91787,13 @@ var ts; actions = [methodCodeAction]; } if (makeStatic) { - if (classDeclaration.kind === 199 /* ClassExpression */) { + if (classDeclaration.kind === 200 /* ClassExpression */) { return actions; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), changes: staticInitializationChangeTracker.getChanges() @@ -88583,7 +91808,7 @@ var ts; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), changes: propertyInitializationChangeTracker.getChanges() @@ -88599,7 +91824,7 @@ var ts; actions = [methodCodeAction]; } var typeNode; - if (token.parent.parent.kind === 194 /* BinaryExpression */) { + if (token.parent.parent.kind === 195 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); @@ -88614,8 +91839,9 @@ var ts; /*initializer*/ undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - (actions || (actions = [])).push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; + actions = ts.append(actions, { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: propertyChangeTracker.getChanges() }); if (!makeStatic) { @@ -88640,15 +91866,14 @@ var ts; return actions; } function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 181 /* CallExpression */) { + if (token.parent.parent.kind === 182 /* CallExpression */) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? - ts.Diagnostics.Declare_method_0 : - ts.Diagnostics.Declare_static_method_0), [tokenName]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), changes: methodDeclarationChangeTracker.getChanges() }; } @@ -88681,7 +91906,9 @@ var ts; } else { var meaning = ts.getMeaningFromLocation(node); - suggestion = checker.getSuggestionForNonexistentSymbol(node, ts.getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } if (suggestion) { return [{ @@ -88713,6 +91940,41 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); // These errors should only happen on the module name. + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, sourceFile.fileName, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + // If !registry, registry not available yet, can't do anything. + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + changes: [], + commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -88778,10 +92040,11 @@ var ts; } // figure out if the `this` access is actually inside the supercall // i.e. super(this.a), since in that case we won't suggest a fix - if (superCall.expression && superCall.expression.kind === 181 /* CallExpression */) { + if (superCall.expression && superCall.expression.kind === 182 /* CallExpression */) { var expressionArguments = superCall.expression.arguments; - for (var i = 0; i < expressionArguments.length; i++) { - if (expressionArguments[i].expression === token) { + for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { + var arg = expressionArguments_1[_i]; + if (arg.expression === token) { return undefined; } } @@ -88794,7 +92057,7 @@ var ts; changes: changeTracker.getChanges() }]; function findSuperCall(n) { - if (n.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + if (n.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { return n; } if (ts.isFunctionLike(n)) { @@ -88914,9 +92177,9 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - return deleteIdentifierOrPrefixWithUnderscore(token); - case 149 /* PropertyDeclaration */: - case 240 /* NamespaceImport */: + return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); + case 150 /* PropertyDeclaration */: + case 241 /* NamespaceImport */: return [deleteNode(token.parent)]; default: return deleteDefault(); @@ -88945,12 +92208,12 @@ var ts; }] }; } - function deleteIdentifierOrPrefixWithUnderscore(identifier) { + function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { var parent = identifier.parent; switch (parent.kind) { - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 145 /* TypeParameter */: + case 146 /* TypeParameter */: var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); @@ -88962,15 +92225,17 @@ var ts; else { return [deleteNodeInList(parent)]; } - case 146 /* Parameter */: + case 147 /* Parameter */: var functionDeclaration = parent.parent; - return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), - prefixIdentifierWithUnderscore(identifier)]; + var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); + return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code + ? [deleteAction] + : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; // handle case where 'import a = A;' - case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 237 /* ImportEqualsDeclaration */); + case 238 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); return [deleteNode(importEquals)]; - case 242 /* ImportSpecifier */: + case 243 /* ImportSpecifier */: var namedImports = parent.parent; if (namedImports.elements.length === 1) { return deleteNamedImportBinding(namedImports); @@ -88979,10 +92244,10 @@ var ts; // delete import specifier return [deleteNodeInList(parent)]; } - case 239 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' var importClause = parent; if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); + var importDecl = ts.getAncestor(importClause, 239 /* ImportDeclaration */); return [deleteNode(importDecl)]; } else { @@ -88997,7 +92262,7 @@ var ts; return [deleteNode(importClause.name)]; } } - case 240 /* NamespaceImport */: + case 241 /* NamespaceImport */: return deleteNamedImportBinding(parent); default: return deleteDefault(); @@ -89018,26 +92283,26 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 238 /* ImportDeclaration */); + var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); return [deleteNode(importDecl)]; } } // token.parent is a variableDeclaration function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { - case 214 /* ForStatement */: + case 215 /* ForStatement */: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); + ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; return [ replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), prefixIdentifierWithUnderscore(identifier) ]; - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: // There is no valid fix in the case of: // for .. in return [prefixIdentifierWithUnderscore(identifier)]; @@ -89091,22 +92356,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments var decl = ts.findAncestor(node, function (n) { - return n.kind === 202 /* AsExpression */ || - n.kind === 155 /* CallSignature */ || - n.kind === 156 /* ConstructSignature */ || - n.kind === 228 /* FunctionDeclaration */ || - n.kind === 153 /* GetAccessor */ || - n.kind === 157 /* IndexSignature */ || - n.kind === 172 /* MappedType */ || - n.kind === 151 /* MethodDeclaration */ || - n.kind === 150 /* MethodSignature */ || - n.kind === 146 /* Parameter */ || - n.kind === 149 /* PropertyDeclaration */ || - n.kind === 148 /* PropertySignature */ || - n.kind === 154 /* SetAccessor */ || - n.kind === 231 /* TypeAliasDeclaration */ || - n.kind === 184 /* TypeAssertionExpression */ || - n.kind === 226 /* VariableDeclaration */; + return n.kind === 203 /* AsExpression */ || + n.kind === 156 /* CallSignature */ || + n.kind === 157 /* ConstructSignature */ || + n.kind === 229 /* FunctionDeclaration */ || + n.kind === 154 /* GetAccessor */ || + n.kind === 158 /* IndexSignature */ || + n.kind === 173 /* MappedType */ || + n.kind === 152 /* MethodDeclaration */ || + n.kind === 151 /* MethodSignature */ || + n.kind === 147 /* Parameter */ || + n.kind === 150 /* PropertyDeclaration */ || + n.kind === 149 /* PropertySignature */ || + n.kind === 155 /* SetAccessor */ || + n.kind === 232 /* TypeAliasDeclaration */ || + n.kind === 185 /* TypeAssertionExpression */ || + n.kind === 227 /* VariableDeclaration */; }); if (!decl) return; @@ -89117,10 +92382,10 @@ var ts; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; - if (jsdocType.kind === 270 /* JSDocNullableType */) { + if (jsdocType.kind === 274 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); } return actions; @@ -89144,6 +92409,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -89164,9 +92430,6 @@ var ts; this.symbolIdToActionMap = []; } ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) { - if (!newAction) { - return; - } var actions = this.symbolIdToActionMap[symbolId]; if (!actions) { this.symbolIdToActionMap[symbolId] = [newAction]; @@ -89185,7 +92448,7 @@ var ts; continue; } switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) { - case ModuleSpecifierComparison.Better: + case 0 /* Better */: // the new one is not worth considering if it is a new import. // However if it is instead a insertion into existing import, the user might want to use // the module specifier even it is worse by our standards. So keep it. @@ -89193,7 +92456,7 @@ var ts; return; } // falls through - case ModuleSpecifierComparison.Equal: + case 1 /* Equal */: // the current one is safe. But it is still possible that the new one is worse // than another existing one. For example, you may have new imports from "./foo/bar" // and "bar", when the new one is "bar/bar2" and the current one is "./foo/bar". The new @@ -89201,7 +92464,7 @@ var ts; // but the new one is worse than the other one, so should not add to the list. updatedNewImports.push(existingAction); break; - case ModuleSpecifierComparison.Worse: + case 2 /* Worse */: // the existing one is worse, remove from the list. continue; } @@ -89225,14 +92488,14 @@ var ts; }; ImportCodeActionMap.prototype.compareModuleSpecifiers = function (moduleSpecifier1, moduleSpecifier2) { if (moduleSpecifier1 === moduleSpecifier2) { - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; } // if moduleSpecifier1 (ms1) is a substring of ms2, then it is better if (moduleSpecifier2.indexOf(moduleSpecifier1) === 0) { - return ModuleSpecifierComparison.Better; + return 0 /* Better */; } if (moduleSpecifier1.indexOf(moduleSpecifier2) === 0) { - return ModuleSpecifierComparison.Worse; + return 2 /* Worse */; } // if both are relative paths, and ms1 has fewer levels, then it is better if (ts.isExternalModuleNameRelative(moduleSpecifier1) && ts.isExternalModuleNameRelative(moduleSpecifier2)) { @@ -89240,515 +92503,605 @@ var ts; var moduleSpecifier1LevelCount = (moduleSpecifier1.match(regex) || []).length; var moduleSpecifier2LevelCount = (moduleSpecifier2.match(regex) || []).length; return moduleSpecifier1LevelCount < moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Better + ? 0 /* Better */ : moduleSpecifier1LevelCount === moduleSpecifier2LevelCount - ? ModuleSpecifierComparison.Equal - : ModuleSpecifierComparison.Worse; + ? 1 /* Equal */ + : 2 /* Worse */; } // the equal cases include when the two specifiers are not comparable. - return ModuleSpecifierComparison.Equal; + return 1 /* Equal */; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName = void 0; - if (umdSymbol.flags & 2097152 /* Alias */) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); - symbolName = symbol.name; - } - else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + formatContext: context.formatContext, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbols, context) { + moduleSymbols = ts.toArray(moduleSymbols); + var declarations = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + }); + var actions = []; + if (context.symbolToken) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } - return getCodeActionForImport(symbol, symbolName, /*isDefault*/ false, /*isNamespaceImport*/ true); } - var candidateModules = checker.getAmbientModules(); - for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { - var otherSourceFile = allSourceFiles_1[_i]; - if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) { - candidateModules.push(otherSourceFile.symbol); - } + return actions.concat(getCodeActionsForAddImport(moduleSymbols, context, declarations)); + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 239 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 241 /* NamespaceImport */ ? namedBindings.name : undefined; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); - } - } - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(name !== "default"); - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } + else { + return declaration.name; } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + } + // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238 /* ImportDeclaration */: - return parent; - case 248 /* ExternalModuleReference */: - return parent.parent; - default: - return undefined; - } - } } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 239 /* ImportDeclaration */: + return parent; + case 249 /* ExternalModuleReference */: + return parent.parent; + case 245 /* ExportDeclaration */: + case 182 /* CallExpression */:// For "require()" calls + // Ignore these, can't add imports to them. + return undefined; + default: + ts.Debug.fail(); } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - // With an existing import statement, there are more than one actions the user can do. - return getCodeActionsForExistingImport(existingDeclarations); + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); + var importDecl = kind !== 3 /* Equals */ + ? ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, createImportClauseOfKind(kind, symbolName), quotedModuleSpecifier) + : ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - return [getCodeActionForNewImport()]; + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { - // case: - // import * as ns from "foo" - namespaceImportDeclaration = declaration; - } - else { - // cases: - // import default from "foo" - // import { bar } from "foo" or combination with the first one - // import "foo" - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - // case: - // import foo = require("foo") - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); - } - } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); - } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - /** - * If the existing import declaration already has a named import list, just - * insert the identifier into that list. - */ - var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText()); - actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); + }); + // if this file doesn't have any import statements, insert an import statement and then insert a new line + // between the only import statement and user code. Otherwise just insert the statement because chances + // are there are already a new line seperating code and import statements. + return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + var id = ts.createIdentifier(symbolName); + switch (kind) { + case 1 /* Default */: + return ts.createImportClause(id, /*namedBindings*/ undefined); + case 2 /* Namespace */: + return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id)); + case 0 /* Named */: + return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; + var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; } - else { - // we need to create a new import statement, but the existing module specifier can be reused. - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); + // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) + return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + } + codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + function getRelativePathNParents(relativePath) { + var count = 0; + for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { + count++; + } + return count; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var pattern = _a[_i]; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); - } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeName.length >= prefix.length + suffix.length && + ts.startsWith(relativeName, prefix) && + ts.endsWith(relativeName, suffix)) { + var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); + return key.replace("\*", matchedStar); } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); - } - else { - namespacePrefix = declaration.name.getText(); - } - namespacePrefix = ts.stripQuotes(namespacePrefix); - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; - } - } - } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSourceFileImportLocation(node) { - // For a source file, it is possible there are detached comments we should not skip - var text = node.text; - var ranges = ts.getLeadingCommentRanges(text, 0); - if (!ranges) - return 0; - var position = 0; - // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end + 1; - ranges = ranges.slice(1); - } - // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(node.text, range.pos, range.end)) { - position = range.end + 1; - continue; + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } - break; } - return position; } - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } - }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - relativeName = removeExtensionAndIndexPostFix(relativeName); - if (options.paths) { - for (var key in options.paths) { - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); - } - } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - if (normalizedTargetPath !== undefined) { - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - } - return undefined; - } - function tryGetModuleNameFromTypeRoots() { - var typeRoots = ts.getEffectiveTypeRoots(options, context.host); - if (typeRoots) { - var normalizedTypeRoots = ts.map(typeRoots, function (typeRoot) { return ts.toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName); }); - for (var _i = 0, normalizedTypeRoots_1 = normalizedTypeRoots; _i < normalizedTypeRoots_1.length; _i++) { - var typeRoot = normalizedTypeRoots_1[_i]; - if (ts.startsWith(moduleFileName, typeRoot)) { - var relativeFileName = moduleFileName.substring(typeRoot.length + 1); - return removeExtensionAndIndexPostFix(relativeFileName); - } - } - } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + else { + state = 3 /* PackageContent */; } - return fileName; + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName, options) { + var noExtension = ts.removeFileExtension(fileName); + return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionsForAddImport(moduleSymbols, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 239 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + }); + if (fromExistingImport) { + return [fromExistingImport]; + } + var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 239 /* ImportDeclaration */ + ? node.moduleSpecifier + : node.moduleReference.kind === 249 /* ExternalModuleReference */ + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile, kind = context.kind; + var name = importClause.name; + var namedBindings = (importClause.kind !== 238 /* ImportEqualsDeclaration */ && importClause).namedBindings; + switch (kind) { + case 1 /* Default */: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0 /* Named */: { + var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 242 /* NamedImports */ && namedBindings.elements.length !== 0) { + // There are already named imports; add another. + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 242 /* NamedImports */ && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); + }); } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + return undefined; + } + case 2 /* Namespace */: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + case 3 /* Equals */: + return undefined; + default: + ts.Debug.assertNever(kind); + } + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + /** + * Cases: + * import * as ns from "mod" + * import default, * as ns from "mod" + * import ns = require("mod") + * + * Because there is no import list, we alter the reference to include the + * namespace instead of altering the import declaration. For example, "foo" would + * become "ns.foo" + */ + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", + /*moduleSpecifier*/ undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken, compilerOptions = context.compilerOptions; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; + } + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbolName = symbol.name; + } + else { + throw ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: getUmdImportKind(compilerOptions) })); + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + throw ts.Debug.assertNever(moduleKind); + } + } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) + && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); } } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol, sourceFile); + } } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + } + codefix.forEachExternalModule = forEachExternalModule; + /** + * 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) { + // 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)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var res = ""; + var lastCharWasValid = true; + var firstCharCode = moduleSpecifier.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < moduleSpecifier.length; i++) { + var ch = moduleSpecifier.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -89887,17 +93240,17 @@ var ts; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 148 /* PropertySignature */: - case 149 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 149 /* PropertySignature */: + case 150 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); var property = ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined); return property; - case 150 /* MethodSignature */: - case 151 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 152 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -89915,8 +93268,8 @@ var ts; return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); } var signatureDeclarations = []; - for (var i = 0; i < signatures.length; i++) { - var signature = signatures[i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); if (methodDeclaration) { signatureDeclarations.push(methodDeclaration); @@ -89939,7 +93292,7 @@ var ts; return undefined; } function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 151 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); if (signatureDeclaration) { signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; @@ -89993,8 +93346,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var i = 0; i < signatures.length; i++) { - var sig = signatures[i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -90041,10 +93394,580 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ], + getCodeActions: getActionsForAddExplicitTypeAnnotation + }); + function getActionsForAddExplicitTypeAnnotation(_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var writer; + if (ts.isInJavaScriptFile(token)) { + return undefined; + } + switch (token.kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + // Allowed + break; + default: + return undefined; + } + var containingFunction = ts.getContainingFunction(token); + var checker = program.getTypeChecker(); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + return getCodeActionForVariableDeclaration(token.parent); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: + return getCodeActionForVariableUsage(token); + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessor(containingFunction)) { + return getCodeActionForSetAccessor(containingFunction); + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return getCodeActionForParameters(token.parent); + // Get Accessor declarations + 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: + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; + } + return undefined; + function getCodeActionForVariableDeclaration(declaration) { + if (!ts.isIdentifier(declaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(declaration.name); + var typeString = type && typeToString(type, declaration); + if (!typeString) { + return undefined; + } + return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); + } + function getCodeActionForVariableUsage(token) { + var symbol = checker.getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + return true; + case 187 /* FunctionExpression */: + return !!declaration.name; + } + return false; + } + function getCodeActionForParameters(parameterDeclaration) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } + var types = inferTypeForParametersFromUsage(containingFunction) || + ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); + if (!types) { + return undefined; + } + var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { + if (type && !parameter.type && !parameter.initializer) { + var typeString = typeToString(type, containingFunction); + return typeString ? { + span: { start: parameter.end, length: 0 }, + newText: ": " + typeString + } : undefined; + } + }).filter(function (c) { return !!c; }); + return textChanges.length ? [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: textChanges + }] + }] : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || + inferTypeForVariableFromUsage(setAccessorParameter.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function getCodeActionForGetAccessor(getAccessorDeclaration) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; + } + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); + var typeString = type && typeToString(type, containingFunction); + if (!typeString) { + return undefined; + } + var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); + return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function createCodeActions(name, start, typeString) { + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), + changes: [{ + fileName: sourceFile.fileName, + textChanges: [{ + span: { start: start, length: 0 }, + newText: typeString + }] + }] + }]; + } + function getReferences(token) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); + ts.Debug.assert(!!references, "Found no references!"); + ts.Debug.assert(references.length === 1, "Found more references than expected"); + return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token) { + return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction) { + switch (containingFunction.kind) { + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 153 /* Constructor */; + var searchToken = isConstructor ? + getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); + } + } + } + function getTypeAccessiblityWriter() { + if (!writer) { + var str_1 = ""; + var typeIsAccessible_1 = true; + var writeText = function (text) { return str_1 += text; }; + writer = { + string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str_1 += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible_1 = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } + }; + } + writer.clear(); + return writer; + } + function typeToString(type, enclosingDeclaration) { + var writer = getTypeAccessiblityWriter(); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); + } + function getFirstChildOfKind(node, sourcefile, kind) { + for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { + var child = _a[_i]; + if (child.kind === kind) + return child; + } + return undefined; + } + } + var InferFromReference; + (function (InferFromReference) { + function inferTypeFromReferences(references, checker, cancellationToken) { + var usageContext = {}; + for (var _i = 0, references_1 = references; _i < references_1.length; _i++) { + var reference = references_1[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + return getTypeFromUsageContext(usageContext, checker); + } + InferFromReference.inferTypeFromReferences = inferTypeFromReferences; + function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (declaration.parameters) { + var usageContext = {}; + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + inferTypeFromContext(reference, checker, usageContext); + } + var isConstructor = declaration.kind === 153 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + if (callContexts) { + var paramTypes = []; + for (var parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) { + var types = []; + var isRestParameter_1 = ts.isRestParameter(declaration.parameters[parameterIndex]); + for (var _a = 0, callContexts_1 = callContexts; _a < callContexts_1.length; _a++) { + var callContext = callContexts_1[_a]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter_1) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; + } + } + return paramTypes; + } + } + return undefined; + } + InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; + function inferTypeFromContext(node, checker, usageContext) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 194 /* PostfixUnaryExpression */: + usageContext.isNumber = true; + break; + case 193 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); + break; + case 195 /* BinaryExpression */: + inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); + break; + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); + break; + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpressionContext(node.parent, checker, usageContext); + } + else { + inferTypeFromContextualType(node, checker, usageContext); + } + break; + case 180 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); + break; + case 181 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); + break; + default: + return inferTypeFromContextualType(node, checker, usageContext); + } + } + function inferTypeFromContextualType(node, checker, usageContext) { + if (ts.isExpressionNode(node)) { + addCandidateType(usageContext, checker.getContextualType(node)); + } + } + function inferTypeFromPrefixUnaryExpressionContext(node, usageContext) { + switch (node.operator) { + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + usageContext.isNumber = true; + break; + case 37 /* PlusToken */: + usageContext.isNumberOrString = true; + break; + } + } + function inferTypeFromBinaryExpressionContext(node, parent, checker, usageContext) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 40 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + // ShiftOperator + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + case 48 /* AmpersandToken */: + case 49 /* BarToken */: + case 50 /* CaretToken */: + // CompoundAssignmentOperator + case 60 /* MinusEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 61 /* AsteriskEqualsToken */: + case 63 /* SlashEqualsToken */: + case 64 /* PercentEqualsToken */: + case 68 /* AmpersandEqualsToken */: + case 69 /* BarEqualsToken */: + case 70 /* CaretEqualsToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + case 38 /* MinusToken */: + // RelationalOperator + case 27 /* LessThanToken */: + case 30 /* LessThanEqualsToken */: + case 29 /* GreaterThanToken */: + case 31 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, operandType); + } + else { + usageContext.isNumber = true; + } + break; + case 59 /* PlusEqualsToken */: + case 37 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 272 /* EnumLike */) { + addCandidateType(usageContext, otherOperandType); + } + else if (otherOperandType.flags & 84 /* NumberLike */) { + usageContext.isNumber = true; + } + else if (otherOperandType.flags & 524322 /* StringLike */) { + usageContext.isString = true; + } + else { + usageContext.isNumberOrString = true; + } + break; + // AssignmentOperators + case 58 /* EqualsToken */: + case 32 /* EqualsEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 92 /* InKeyword */: + if (node === parent.left) { + usageContext.isString = true; + } + break; + // LogicalOperator + case 54 /* BarBarToken */: + if (node === parent.left && + (node.parent.parent.kind === 227 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); + } + break; + case 53 /* AmpersandAmpersandToken */: + case 26 /* CommaToken */: + case 93 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabelContext(parent, checker, usageContext) { + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpressionContext(parent, checker, usageContext) { + var callContext = { + argumentTypes: [], + returnType: {} + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + callContext.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + inferTypeFromContext(parent, checker, callContext.returnType); + if (parent.kind === 182 /* CallExpression */) { + (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); + } + else { + (usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext); + } + } + function inferTypeFromPropertyAccessExpressionContext(parent, checker, usageContext) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usageContext.properties) { + usageContext.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsageContext = usageContext.properties.get(name) || {}; + inferTypeFromContext(parent, checker, propertyUsageContext); + usageContext.properties.set(name, propertyUsageContext); + } + function inferTypeFromPropertyElementExpressionContext(parent, node, checker, usageContext) { + if (node === parent.argumentExpression) { + usageContext.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent); + var indexUsageContext = {}; + inferTypeFromContext(parent, checker, indexUsageContext); + if (indexType.flags & 84 /* NumberLike */) { + usageContext.numberIndexContext = indexUsageContext; + } + else { + usageContext.stringIndexContext = indexUsageContext; + } + } + } + function getTypeFromUsageContext(usageContext, checker) { + if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { + return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + } + else if (usageContext.isNumber) { + return checker.getNumberType(); + } + else if (usageContext.isString) { + return checker.getStringType(); + } + else if (usageContext.candidateTypes) { + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + } + else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { + return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + var members_5 = ts.createUnderscoreEscapedMap(); + var callSignatures = []; + var constructSignatures = []; + var stringIndexInfo = void 0; + var numberIndexInfo = void 0; + if (usageContext.properties) { + usageContext.properties.forEach(function (context, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + members_5.set(name, symbol); + }); + } + if (usageContext.callContexts) { + for (var _i = 0, _a = usageContext.callContexts; _i < _a.length; _i++) { + var callContext = _a[_i]; + callSignatures.push(getSignatureFromCallContext(callContext, checker)); + } + } + if (usageContext.constructContexts) { + for (var _b = 0, _c = usageContext.constructContexts; _b < _c.length; _b++) { + var constructContext = _c[_b]; + constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); + } + } + if (usageContext.numberIndexContext) { + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + } + if (usageContext.stringIndexContext) { + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + } + return checker.createAnonymousType(/*symbol*/ undefined, members_5, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + return undefined; + } + } + function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { + var types = []; + if (callContexts) { + for (var _i = 0, callContexts_2 = callContexts; _i < callContexts_2.length; _i++) { + var callContext = callContexts_2[_i]; + if (callContext.argumentTypes.length > parameterIndex) { + if (isRestParameter) { + types = ts.concatenate(types, ts.map(callContext.argumentTypes.slice(parameterIndex), function (a) { return checker.getBaseTypeOfLiteralType(a); })); + } + else { + types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); + } + } + } + } + if (types.length) { + var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + return isRestParameter ? checker.createArrayType(type) : type; + } + return undefined; + } + function getSignatureFromCallContext(callContext, checker) { + var parameters = []; + for (var i = 0; i < callContext.argumentTypes.length; i++) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); + parameters.push(symbol); + } + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + } + function addCandidateType(context, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 16384 /* Never */)) { + (context.candidateTypes || (context.candidateTypes = [])).push(type); + } + } + function hasCallContext(usageContext) { + return usageContext && usageContext.callContexts; + } + })(InferFromReference || (InferFromReference = {})); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// /// +/// /// /// /// @@ -90055,6 +93978,237 @@ var ts; /// /// /// +/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var annotateWithTypeFromJSDoc; + (function (annotateWithTypeFromJSDoc) { + var actionName = "annotate"; + var annotateTypeFromJSDoc = { + name: "Annotate with type from JSDoc", + description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions + }; + refactor.registerRefactor(annotateTypeFromJSDoc); + function getAvailableActions(context) { + if (ts.isInJavaScriptFile(context.file)) { + return undefined; + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { + return [{ + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, + actions: [ + { + description: annotateTypeFromJSDoc.description, + name: actionName + } + ] + }]; + } + } + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { + if (actionName !== action) { + return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); + } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 147 /* Parameter */) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(token, isDeclarationWithType); + var jsdocType = ts.getJSDocType(decl); + if (!decl || !jsdocType || decl.type) { + return ts.Debug.fail("!decl || !jsdocType || decl.type: !" + decl + " || !" + jsdocType + " || " + decl.type); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var declarationWithType = addType(decl, transformJSDocType(jsdocType)); + ts.suppressLeadingAndTrailingTrivia(declarationWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, declarationWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function getEditsForFunctionAnnotation(context) { + var sourceFile = context.file; + var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var functionWithType = addTypesToFunctionLike(decl); + ts.suppressLeadingAndTrailingTrivia(functionWithType); + changeTracker.replaceRange(sourceFile, { pos: decl.getStart(), end: decl.end }, functionWithType); + return { + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined + }; + } + function isDeclarationWithType(node) { + return ts.isFunctionLikeDeclaration(node) || + node.kind === 227 /* VariableDeclaration */ || + node.kind === 147 /* Parameter */ || + node.kind === 149 /* PropertySignature */ || + node.kind === 150 /* PropertyDeclaration */; + } + function addTypesToFunctionLike(decl) { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(decl, /*checkJSDoc*/ true); + var parameters = decl.parameters.map(function (p) { return ts.createParameter(p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, transformJSDocType(ts.getEffectiveTypeAnnotationNode(p, /*checkJSDoc*/ true)), p.initializer); }); + var returnType = transformJSDocType(ts.getEffectiveReturnTypeNode(decl, /*checkJSDoc*/ true)); + switch (decl.kind) { + case 229 /* FunctionDeclaration */: + return ts.createFunctionDeclaration(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 153 /* Constructor */: + return ts.createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); + case 187 /* FunctionExpression */: + return ts.createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); + case 188 /* ArrowFunction */: + return ts.createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); + case 152 /* MethodDeclaration */: + return ts.createMethod(decl.decorators, decl.modifiers, decl.asteriskToken, decl.name, decl.questionToken, typeParameters, parameters, returnType, decl.body); + case 154 /* GetAccessor */: + return ts.createGetAccessor(decl.decorators, decl.modifiers, decl.name, decl.parameters, returnType, decl.body); + case 155 /* SetAccessor */: + return ts.createSetAccessor(decl.decorators, decl.modifiers, decl.name, parameters, decl.body); + default: + return ts.Debug.assertNever(decl, "Unexpected SyntaxKind: " + decl.kind); + } + } + function addType(decl, jsdocType) { + switch (decl.kind) { + case 227 /* VariableDeclaration */: + return ts.createVariableDeclaration(decl.name, jsdocType, decl.initializer); + case 149 /* PropertySignature */: + return ts.createPropertySignature(decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + case 150 /* PropertyDeclaration */: + return ts.createProperty(decl.decorators, decl.modifiers, decl.name, decl.questionToken, jsdocType, decl.initializer); + default: + return ts.Debug.fail("Unexpected SyntaxKind: " + decl.kind); + } + } + function transformJSDocType(node) { + if (node === undefined) { + return undefined; + } + switch (node.kind) { + case 272 /* JSDocAllType */: + case 273 /* JSDocUnknownType */: + return ts.createTypeReferenceNode("any", ts.emptyArray); + case 276 /* JSDocOptionalType */: + return transformJSDocOptionalType(node); + case 275 /* JSDocNonNullableType */: + return transformJSDocType(node.type); + case 274 /* JSDocNullableType */: + return transformJSDocNullableType(node); + case 278 /* JSDocVariadicType */: + return transformJSDocVariadicType(node); + case 277 /* JSDocFunctionType */: + return transformJSDocFunctionType(node); + case 147 /* Parameter */: + return transformJSDocParameter(node); + case 160 /* TypeReference */: + return transformJSDocTypeReference(node); + default: + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; + } + } + function transformJSDocOptionalType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]); + } + function transformJSDocNullableType(node) { + return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]); + } + function transformJSDocVariadicType(node) { + return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType)); + } + function transformJSDocFunctionType(node) { + var parameters = node.parameters && node.parameters.map(transformJSDocType); + return ts.createFunctionTypeNode(ts.emptyArray, parameters, node.type); + } + function transformJSDocParameter(node) { + var index = node.parent.parameters.indexOf(node); + var isRest = node.type.kind === 278 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var name = node.name || (isRest ? "rest" : "arg" + index); + var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; + return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + } + function transformJSDocTypeReference(node) { + var name = node.typeName; + var args = node.typeArguments; + if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } + var text = node.typeName.text; + switch (node.typeName.text) { + case "String": + case "Boolean": + case "Object": + case "Number": + text = text.toLowerCase(); + break; + case "array": + case "date": + case "promise": + text = text[0].toUpperCase() + text.slice(1); + break; + } + name = ts.createIdentifier(text); + if ((text === "Array" || text === "Promise") && !node.typeArguments) { + args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]); + } + else { + args = ts.visitNodes(node.typeArguments, transformJSDocType); + } + } + return ts.createTypeReferenceNode(name, args); + } + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -90074,14 +94228,14 @@ var ts; if (!ts.isInJavaScriptFile(context.file)) { return undefined; } - var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var symbol = checker.getSymbolAtLocation(node); - if (symbol && ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + var symbol = getConstructorSymbol(context); + if (!symbol) { + return undefined; + } + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { symbol = symbol.valueDeclaration.initializer.symbol; } - if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { + if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { name: convertFunctionToES6Class.name, @@ -90101,12 +94255,9 @@ var ts; if (actionName !== action) { return undefined; } - var start = context.startPosition; var sourceFile = context.file; - var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var ctorSymbol = checker.getSymbolAtLocation(token); - var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; + var ctorSymbol = getConstructorSymbol(context); + var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { @@ -90117,12 +94268,12 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: precedingNode = ctorDeclaration; deleteNode(ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 226 /* VariableDeclaration */: + case 227 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; if (ctorDeclaration.parent.declarations.length === 1) { deleteNode(precedingNode); @@ -90198,7 +94349,7 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 210 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 211 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; deleteNode(nodeToDelete); if (!assignmentBinaryExpression.right) { @@ -90206,26 +94357,28 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186 /* FunctionExpression */: { + case 187 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyComments(assignmentBinaryExpression, method); return method; } - case 187 /* ArrowFunction */: { + case 188 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 207 /* Block */) { + if (arrowFunctionBody.kind === 208 /* Block */) { bodyBlock = arrowFunctionBody; } else { var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyComments(assignmentBinaryExpression, method); return method; @@ -90260,7 +94413,7 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 187 /* FunctionExpression */) { return undefined; } if (node.name.kind !== 71 /* Identifier */) { @@ -90270,7 +94423,8 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(precedingNode, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -90280,11 +94434,21 @@ var ts; if (node.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); } - var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var modifiers = getModifierKindFromSource(node, 84 /* ExportKeyword */); + var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } + function getModifierKindFromSource(source, kind) { + return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + } + } + function getConstructorSymbol(_a) { + var startPosition = _a.startPosition, file = _a.file, program = _a.program; + var checker = program.getTypeChecker(); + var token = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return checker.getSymbolAtLocation(token); } })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); @@ -90296,16 +94460,19 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var extractMethod; - (function (extractMethod_1) { - var extractMethod = { - name: "Extract Method", - description: ts.Diagnostics.Extract_function.message, + var extractSymbol; + (function (extractSymbol_1) { + var extractSymbol = { + name: "Extract Symbol", + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction, }; - refactor.registerRefactor(extractMethod); - /** Compute the associated code actions */ + refactor.registerRefactor(extractSymbol); + /** + * Compute the associated code actions + * Exported for tests. + */ function getAvailableActions(context) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -90317,69 +94484,111 @@ var ts; // No extractions possible return undefined; } - var actions = []; - var usedNames = ts.createMap(); + var functionActions = []; + var usedFunctionNames = ts.createMap(); + var constantActions = []; + var usedConstantNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; + var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; // Skip these since we don't have a way to report errors yet - if (errors.length) { - continue; + if (functionExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = functionExtraction.description; + if (!usedFunctionNames.has(description)) { + usedFunctionNames.set(description, true); + functionActions.push({ + description: description, + name: "function_scope_" + i + }); + } } - // Don't issue refactorings with duplicated names. - // Scopes come back in "innermost first" order, so extractions will - // preferentially go into nearer scopes - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); - if (!usedNames.has(description)) { - usedNames.set(description, true); - actions.push({ - description: description, - name: "scope_" + i - }); + // Skip these since we don't have a way to report errors yet + if (constantExtraction.errors.length === 0) { + // Don't issue refactorings with duplicated names. + // Scopes come back in "innermost first" order, so extractions will + // preferentially go into nearer scopes + var description = constantExtraction.description; + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); + constantActions.push({ + description: description, + name: "constant_scope_" + i + }); + } } // *do* increment i anyway because we'll look for the i-th scope // later when actually doing the refactoring if the user requests it i++; } - if (actions.length === 0) { - return undefined; + var infos = []; + if (functionActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), + actions: functionActions + }); } - return [{ - name: extractMethod.name, - description: extractMethod.description, - inlineable: true, - actions: actions - }]; + if (constantActions.length) { + infos.push({ + name: extractSymbol.name, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), + actions: constantActions + }); + } + return infos.length ? infos : undefined; } + extractSymbol_1.getAvailableActions = getAvailableActions; + /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; - var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); - ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); - var index = +parsedIndexMatch[1]; - ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - return getExtractionAtIndex(targetRange, context, index); + var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); + if (parsedFunctionIndexMatch) { + var index = +parsedFunctionIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName); + if (parsedConstantIndexMatch) { + var index = +parsedConstantIndexMatch[1]; + ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + ts.Debug.fail("Unrecognized action name"); } + extractSymbol_1.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { function createMessage(message) { return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; } - Messages.CannotExtractFunction = createMessage("Cannot extract function."); - Messages.StatementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages.CannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages.TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages.FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages.InsufficientSelection = createMessage("Select more than a single identifier."); - Messages.CannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages.CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns"); - Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages.CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - })(Messages || (Messages = {})); + Messages.cannotExtractRange = createMessage("Cannot extract range."); + Messages.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages.expressionExpected = createMessage("expression expected."); + Messages.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); + Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -90402,7 +94611,7 @@ var ts; function getRangeToExtract(sourceFile, span) { var length = span.length; if (length === 0) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) @@ -90415,46 +94624,24 @@ var ts; var rangeFacts = RangeFacts.None; if (!start || !end) { // cannot find either start or end node - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractFunction)] }; + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start.parent !== end.parent) { - // handle cases like 1 + [2 + 3] + 4 - // user selection is marked with []. - // in this case 2 + 3 does not belong to the same tree node - // instead the shape of the tree looks like this: - // + - // / \ - // + 4 - // / \ - // + 3 - // / \ - // 1 2 - // in this case there is no such one node that covers ends of selection and is located inside the selection - // to handle this we check if both start and end of the selection belong to some binary operation - // and start node is parented by the parent of the end node - // if this is the case - expand the selection to the entire parent of end node (in this case it will be [1 + 2 + 3] + 4) - var startParent = ts.skipParentheses(start.parent); - var endParent = ts.skipParentheses(end.parent); - if (ts.isBinaryExpression(startParent) && ts.isBinaryExpression(endParent) && ts.isNodeDescendantOf(startParent, endParent)) { - start = end = endParent; - } - else { - // start and end nodes belong to different subtrees - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); - } + // start and end nodes belong to different subtrees + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } if (start !== end) { // start and end should be statements and parent should be either block or a source file if (!isBlockLike(start.parent)) { - return createErrorResult(sourceFile, span.start, length, Messages.CannotExtractFunction); + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { - var errors = checkNode(statement); - if (errors) { - return { errors: errors }; + var errors_1 = checkNode(statement); + if (errors_1) { + return { errors: errors_1 }; } statements.push(statement); } @@ -90464,40 +94651,72 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - else { - // We have a single node (start) - var errors = checkRootNode(start) || checkNode(start); - if (errors) { - return { errors: errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; + if (ts.isReturnStatement(start) && !start.expression) { + // Makes no sense to extract an expression-less return statement. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + // We have a single node (start) + var node = refineNode(start); + var errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors: errors }; } - function createErrorResult(sourceFile, start, length, message) { - return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + /** + * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. + * @param node The unrefined extraction node. + */ + function refineNode(node) { + if (ts.isReturnStatement(node)) { + if (node.expression) { + return node.expression; + } + } + else if (ts.isVariableStatement(node)) { + var numInitializers = 0; + var lastInitializer = undefined; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + // No special handling if there are multiple initializers. + } + else if (ts.isVariableDeclaration(node)) { + if (node.initializer) { + return node.initializer; + } + } + return node; } function checkRootNode(node) { if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { - return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; + return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)]; } return undefined; } function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 149 /* PropertyDeclaration */) { + if (current.kind === 150 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 146 /* Parameter */) { + else if (current.kind === 147 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 152 /* Constructor */) { + if (ctorOrMethod.kind === 153 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 151 /* MethodDeclaration */) { + else if (current.kind === 152 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -90514,11 +94733,11 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; + if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; } - if (ts.isInAmbientContext(nodeToCheck)) { - return [ts.createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)]; + if (nodeToCheck.flags & 2097152 /* Ambient */) { + return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; } // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default) var containingClass = ts.getContainingClass(nodeToCheck); @@ -90536,26 +94755,26 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 226 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 227 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { - case 238 /* ImportDeclaration */: - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + case 239 /* ImportDeclaration */: + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; case 97 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 181 /* CallExpression */) { + if (node.parent.kind === 182 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractFunction)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; } } @@ -90564,13 +94783,13 @@ var ts; } break; } - if (!node || ts.isFunctionLike(node) || ts.isClassLike(node)) { + if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: - if (node.parent.kind === 265 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { + case 229 /* FunctionDeclaration */: + case 230 /* ClassDeclaration */: + if (node.parent.kind === 269 /* SourceFile */ && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } break; } @@ -90579,20 +94798,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 211 /* IfStatement */: + case 212 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 224 /* TryStatement */: + case 225 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 207 /* Block */: - if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + case 208 /* Block */: + if (node.parent && node.parent.kind === 225 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 257 /* CaseClause */: + case 261 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -90604,11 +94823,11 @@ var ts; break; } switch (node.kind) { - case 169 /* ThisType */: + case 170 /* ThisType */: case 99 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -90616,36 +94835,36 @@ var ts; seenLabels.pop(); break; } - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { // attempts to jump to label that is not in range to be extracted - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } } else { - if (!(permittedJumps & (node.kind === 218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 219 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 191 /* AwaitExpression */: + case 192 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 197 /* YieldExpression */: + case 198 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } else { - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement)); + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement)); } break; default: @@ -90656,12 +94875,12 @@ var ts; } } } - extractMethod_1.getRangeToExtract = getRangeToExtract; + extractSymbol_1.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; } - else if (ts.isPartOfExpression(node)) { + else if (ts.isExpressionNode(node)) { // If our selection is the expression in an ExpressionStatement, expand // the selection to include the enclosing Statement (this stops us // from trying to care about the return value of the extracted function @@ -90670,9 +94889,8 @@ var ts; } return undefined; } - function isValidExtractionTarget(node) { - // Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method - return (node.kind === 228 /* FunctionDeclaration */) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); + function isScope(node) { + return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); } /** * Computes possible places we could extract the function into. For example, @@ -90680,127 +94898,174 @@ var ts; * depending on what's in the extracted body. */ function collectEnclosingScopes(range) { - var current = isReadonlyArray(range.range) ? ts.firstOrUndefined(range.range) : range.range; + var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; if (range.facts & RangeFacts.UsesThis) { // if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class var containingClass = ts.getContainingClass(current); if (containingClass) { - return [containingClass]; + var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration); + return containingFunction + ? [containingFunction, containingClass] + : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 147 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. // Walk up to the closest parent of a place where we can logically put a sibling: // * Function declaration // * Class declaration or expression // * Module/namespace or source file - if (current !== start && isValidExtractionTarget(current)) { - (scopes = scopes || []).push(current); - } - // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current && current.parent && current.parent.kind === 146 /* Parameter */) { - // Skip all the way to the outer scope of the function that declared this parameter - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLike(parent); }).parent; - } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 269 /* SourceFile */) { + return scopes; + } } } - return scopes; } - // exported only for tests - function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; - ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; + ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + var expression = ts.isExpression(target) + ? target + : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); } - extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; /** * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes * or an error explaining why we can't extract into that scope. */ - // exported only for tests function getPossibleExtractions(targetRange, context) { - var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope; // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 - return scopes.map(function (scope, i) { - return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + var extractions = scopes.map(function (scope, i) { + var functionDescriptionPart = getDescriptionForFunctionInScope(scope); + var constantDescriptionPart = getDescriptionForConstantInScope(scope); + var scopeDescription = ts.isFunctionLikeDeclaration(scope) + ? getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); + var functionDescription; + var constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } + else if (scopeDescription === 0 /* Module */) { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } + else { + functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + // Customize the phrasing for the innermost scope to increase clarity. + if (i === 0 && !ts.isClassLike(scope)) { + constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i], + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i], + }, + }; }); + return extractions; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; } - function getDescriptionForScope(scope) { + function getDescriptionForFunctionInScope(scope) { return ts.isFunctionLikeDeclaration(scope) - ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + ? "inner function" : ts.isClassLike(scope) - ? "method in " + getDescriptionForClassLikeDeclaration(scope) - : "function in " + getDescriptionForModuleLikeDeclaration(scope); + ? "method" + : "function"; + } + function getDescriptionForConstantInScope(scope) { + return ts.isClassLike(scope) + ? "readonly field" + : "constant"; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 152 /* Constructor */: + case 153 /* Constructor */: return "constructor"; - case 186 /* FunctionExpression */: + case 187 /* FunctionExpression */: return scope.name ? "function expression '" + scope.name.text + "'" : "anonymous function expression"; - case 228 /* FunctionDeclaration */: + case 229 /* FunctionDeclaration */: return "function '" + scope.name.text + "'"; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: return "arrow function"; - case 151 /* MethodDeclaration */: + case 152 /* MethodDeclaration */: return "method '" + scope.name.getText(); - case 153 /* GetAccessor */: + case 154 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 154 /* SetAccessor */: + case 155 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 229 /* ClassDeclaration */ + return scope.kind === 230 /* ClassDeclaration */ ? "class '" + scope.name.text + "'" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 234 /* ModuleBlock */ + return scope.kind === 235 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" - : scope.externalModuleIndicator ? "module scope" : "global scope"; + : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } - function getUniqueName(fileText) { - var functionNameText = "newFunction"; - for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { - functionNameText = "newFunction_" + i; + var SpecialScope; + (function (SpecialScope) { + SpecialScope[SpecialScope["Module"] = 0] = "Module"; + SpecialScope[SpecialScope["Global"] = 1] = "Global"; + })(SpecialScope || (SpecialScope = {})); + function getUniqueName(baseName, fileText) { + var nameText = baseName; + for (var i = 1; ts.stringContains(fileText, nameText); i++) { + nameText = baseName + "_" + i; } - return functionNameText; + return nameText; } /** * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors */ - function extractFunctionInScope(node, scope, _a, range, context) { + function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(file.text); + var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType = undefined; @@ -90813,7 +95078,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -90841,9 +95106,10 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType); + returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); } - var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; + ts.suppressLeadingAndTrailingTrivia(body); var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -90863,13 +95129,16 @@ var ts; /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; - var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { + prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, + suffix: context.newLineCharacter + }); } var newNodes = []; // replace range with function call @@ -90882,33 +95151,89 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { call = ts.createAwait(call); } - if (writes) { + if (exposedVariableDeclarations.length && !writes) { + // No need to mix declarations and writes. + // How could any variables be exposed if there's a return statement? + ts.Debug.assert(!returnValueProperty); + ts.Debug.assert(!(range.facts & RangeFacts.HasReturn)); + if (exposedVariableDeclarations.length === 1) { + // Declaring exactly one variable: let x = newFunction(); + var variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns + variableDeclaration.parent.flags))); + } + else { + // Declaring multiple variables / return properties: + // let {x, y} = newFunction(); + var bindingElements = []; + var typeElements = []; + var commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + var sawExplicitType = false; + for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { + var variableDeclaration = exposedVariableDeclarations_1[_i]; + bindingElements.push(ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); + // Being returned through an object literal will have widened the type. + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + typeElements.push(ts.createPropertySignature( + /*modifiers*/ undefined, + /*name*/ variableDeclaration.symbol.name, + /*questionToken*/ undefined, + /*type*/ variableType, + /*initializer*/ undefined)); + sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined; + if (typeLiteral) { + ts.setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), + /*type*/ typeLiteral, + /*initializer*/ call)], commonNodeFlags))); + } + } + else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping. + for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) { + var variableDeclaration = exposedVariableDeclarations_2[_c]; + var flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = (flags & ~2 /* Const */) | 1 /* Let */; + } + newNodes.push(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); + } + } if (returnValueProperty) { // has both writes and return, need to create variable declaration to hold return value; newNodes.push(ts.createVariableStatement( - /*modifiers*/ undefined, [ts.createVariableDeclaration(returnValueProperty, ts.createKeywordTypeNode(119 /* AnyKeyword */))])); + /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty)); } // propagate writes back if (assignments.length === 1) { - if (returnValueProperty) { - newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); - } - else { - newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); - if (range.facts & RangeFacts.HasReturn) { - newNodes.push(ts.createReturn()); - } + // We would only have introduced a return value property if there had been + // other assignments to make. + ts.Debug.assert(!returnValueProperty); + newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); } } else { // emit e.g. // { a, b, __return } = newFunction(a, b); // return __return; - newNodes.push(ts.createStatement(ts.createBinary(ts.createObjectLiteral(assignments), 58 /* EqualsToken */, call))); + newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call))); if (returnValueProperty) { newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty))); } @@ -90925,40 +95250,165 @@ var ts; newNodes.push(call); } } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes, { - nodeSeparator: context.newLineCharacter, - suffix: context.newLineCharacter // insert newline only when replacing statements - }); + var replacementRange = isReadonlyArray(range.range) + ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } + : { pos: range.range.getStart(), end: range.range.end }; + changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === undefined) { + return undefined; + } + var clone = ts.getSynthesizedDeepClone(typeNode); + var withoutParens = clone; + while (ts.isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 139 /* UndefinedKeyword */; }) + ? clone + : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(139 /* UndefinedKeyword */)]); + } + } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ + function extractConstantInScope(node, scope, _a, rangeFacts, context) { + var substitutions = _a.substitutions; + var checker = context.program.getTypeChecker(); + // Make a unique name for the extracted variable + var file = scope.getSourceFile(); + var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var isJS = ts.isInJavaScriptFile(scope); + var variableType = isJS + ? undefined + : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + var initializer = transformConstantInitializer(node, substitutions); + ts.suppressLeadingAndTrailingTrivia(initializer); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + if (ts.isClassLike(scope)) { + ts.Debug.assert(!isJS); // See CannotExtractToJSClass + var modifiers = []; + modifiers.push(ts.createToken(112 /* PrivateKeyword */)); + if (rangeFacts & RangeFacts.InStaticRegion) { + modifiers.push(ts.createToken(115 /* StaticKeyword */)); + } + modifiers.push(ts.createToken(131 /* ReadonlyKeyword */)); + var newVariable = ts.createProperty( + /*decorators*/ undefined, modifiers, localNameText, + /*questionToken*/ undefined, variableType, initializer); + var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion + ? ts.createIdentifier(scope.name.getText()) + : ts.createThis(), ts.createIdentifier(localNameText)); + // Declare + var maxInsertionPos = node.pos; + var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + // Consume + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); + var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); + // If the node is part of an initializer in a list of variable declarations, insert a new + // variable declaration into the list (in case it depends on earlier ones). + // CONSIDER: If the declaration list isn't const, we might want to split it into multiple + // lists so that the newly extracted one can be const. + var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + // Declare + // CONSIDER: could detect that each is on a separate line + changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // Consume + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + else if (node.parent.kind === 211 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + // If the parent is an expression statement and the target scope is the immediately enclosing one, + // replace the statement with the declaration. + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }, newVariableStatement); + } + else { + var newVariableStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + // Declare + var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + // If we're at the beginning of the file, we need to take care not to insert before header comments + // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved + // for imports. + var insertionPos = ts.getSourceFileImportLocation(file); + changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { + prefix: insertionPos === 0 ? undefined : context.newLineCharacter, + suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter + }); + } + else { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + // Consume + if (node.parent.kind === 211 /* ExpressionStatement */) { + // If the parent is an expression statement, delete it. + changeTracker.deleteRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }); + } + else { + var localReference = ts.createIdentifier(localNameText); + changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); + } + } } var edits = changeTracker.getChanges(); - var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; - var renameFilename = renameRange.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + var renameFilename = node.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } - function getRenameLocation(edits, renameFilename, functionNameText) { + function getContainingVariableDeclarationIfInList(node, scope) { + var prevNode = undefined; + while (node !== undefined && node !== scope) { + if (ts.isVariableDeclaration(node) && + node.initializer === prevNode && + ts.isVariableDeclarationList(node.parent) && + node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + function getRenameLocation(edits, renameFilename, functionNameText, isDeclaredBeforeUse) { var delta = 0; + var lastPos = -1; for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; ts.Debug.assert(fileName === renameFilename); for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { var change = textChanges_2[_b]; - var span_17 = change.span, newText = change.newText; - // TODO(acasey): We are assuming that the call expression comes before the function declaration, - // because we want the new cursor to be on the call expression, - // which is closer to where the user was before extracting the function. + var span_15 = change.span, newText = change.newText; var index = newText.indexOf(functionNameText); if (index !== -1) { - return span_17.start + delta + index; + lastPos = span_15.start + delta + index; + // If the reference comes first, return immediately. + if (!isDeclaredBeforeUse) { + return lastPos; + } } - delta += newText.length - span_17.length; + delta += newText.length - span_15.length; } } - throw new Error(); // Didn't find the text we inserted? + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(isDeclaredBeforeUse); + ts.Debug.assert(lastPos >= 0); + return lastPos; } function getFirstDeclaration(type) { var firstDeclaration = undefined; @@ -90976,28 +95426,9 @@ var ts; function compareTypesByDeclarationOrder(_a, _b) { var type1 = _a.type, declaration1 = _a.declaration; var type2 = _b.type, declaration2 = _b.declaration; - if (declaration1) { - if (declaration2) { - var positionDiff = declaration1.pos - declaration2.pos; - if (positionDiff !== 0) { - return positionDiff; - } - } - else { - return 1; // Sort undeclared type parameters to the front. - } - } - else if (declaration2) { - return -1; // Sort undeclared type parameters to the front. - } - var name1 = type1.symbol ? type1.symbol.getName() : ""; - var name2 = type2.symbol ? type2.symbol.getName() : ""; - var nameDiff = ts.compareStrings(name1, name2); - if (nameDiff !== 0) { - return nameDiff; - } - // IDs are guaranteed to be unique, so this ensures a total ordering. - return type1.id - type2.id; + return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues) + || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") + || ts.compareValues(type1.id, type2.id); } function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); @@ -91009,21 +95440,22 @@ var ts; return functionReference; } } - function transformFunctionBody(body, writes, substitutions, hasReturn) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) { + var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; + if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + // already block, no declarations or writes to propagate back, no substitutions - can use node as is return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; } var returnValueProperty; var ignoreReturns = false; var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { + if (hasWritesOrVariableDeclarations || substitutions.size) { var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !hasReturn && ts.isStatement(body)) { + if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) { // add return at the end to propagate writes back in case if control flow falls out of the function body // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (assignments.length === 1) { rewrittenStatements.push(ts.createReturn(assignments[0].name)); } @@ -91037,8 +95469,8 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); + if (!ignoreReturns && node.kind === 220 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { returnValueProperty = "__return"; @@ -91054,16 +95486,25 @@ var ts; } else { var oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node); var substitution = substitutions.get(ts.getNodeId(node).toString()); - var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); ignoreReturns = oldIgnoreReturns; return result; } } } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size + ? visitor(initializer) + : initializer; + function visitor(node) { + var substitution = substitutions.get(ts.getNodeId(node).toString()); + return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext); + } + } function getStatementsOrClassElements(scope) { - if (ts.isFunctionLike(scope)) { + if (ts.isFunctionLikeDeclaration(scope)) { var body = scope.body; if (ts.isBlock(body)) { return body.statements; @@ -91084,13 +95525,70 @@ var ts; * If `scope` contains a function after `minPos`, then return the first such function. * Otherwise, return `undefined`. */ - function getNodeToInsertBefore(minPos, scope) { + function getNodeToInsertFunctionBefore(minPos, scope) { return ts.find(getStatementsOrClassElements(scope), function (child) { - return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child); }); } - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + function getNodeToInsertPropertyBefore(maxPos, scope) { + var members = scope.members; + ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. + var prevMember = undefined; + var allProperties = true; + for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { + var member = members_6[_i]; + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !ts.isPropertyDeclaration(member)) { + // If it is non-vacuously true that all preceding members are properties, + // insert before the current member (i.e. at the end of the list of properties). + if (prevMember !== undefined) { + return member; + } + allProperties = false; + } + prevMember = member; + } + ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + ts.Debug.assert(!ts.isClassLike(scope)); + var prevScope = undefined; + for (var curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (var curr = (prevScope || node).parent;; curr = curr.parent) { + if (isBlockLike(curr)) { + var prevStatement = undefined; + for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + // There must be at least one statement since we started in one. + ts.Debug.assert(prevStatement !== undefined); + return prevStatement; + } + if (curr === scope) { + ts.Debug.fail("Didn't encounter a block-like before encountering scope"); + break; + } + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); + var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + return variableAssignments === undefined + ? writeAssignments + : writeAssignments === undefined + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return ts.isArray(v); @@ -91106,7 +95604,7 @@ var ts; */ function getEnclosingTextRange(targetRange, sourceFile) { return isReadonlyArray(targetRange.range) - ? { pos: targetRange.range[0].getStart(sourceFile), end: targetRange.range[targetRange.range.length - 1].getEnd() } + ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() } : targetRange.range; } var Usage; @@ -91120,19 +95618,51 @@ var ts; var allTypeParameterUsages = ts.createMap(); // Key is type ID var usagesPerScope = []; var substitutionsPerScope = []; - var errorsPerScope = []; + var functionErrorsPerScope = []; + var constantErrorsPerScope = []; var visibleDeclarationsInExtractedRange = []; + var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID + var exposedVariableDeclarations = []; + var firstExposedNonVariableDeclaration = undefined; + var expression = !isReadonlyArray(targetRange.range) + ? targetRange.range + : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0]) + ? targetRange.range[0].expression + : undefined; + var expressionDiagnostic = undefined; + if (expression === undefined) { + var statements = targetRange.range; + var start = ts.first(statements).getStart(); + var end = ts.last(statements).end; + expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } + else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); + } // initialize results for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { - var _ = scopes_1[_i]; + var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - errorsPerScope.push([]); + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 229 /* FunctionDeclaration */ + ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] + : []); + var constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { + // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this + constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; - var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); - var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range; var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); // Unfortunately, this code takes advantage of the knowledge that the generated method @@ -91169,7 +95699,23 @@ var ts; // copy allTypeParameterUsages into all remaining scopes. ts.Debug.assert(i_1 === scopes.length); } - var _loop_8 = function (i) { + // If there are any declarations in the extracted block that are used in the same enclosing + // lexical scope, we can't move the extraction "up" as those declarations will become unreachable + if (visibleDeclarationsInExtractedRange.length) { + var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) + ? scopes[0] + : ts.getEnclosingBlockScopeContainer(scopes[0]); + ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + var _loop_10 = function (i) { + var scopeUsages = usagesPerScope[i]; + // Special case: in the innermost scope, all usages are available. + // (The computed value reflects the value at the top-level of the scope, but the + // local will actually be declared at the same level as the extracted expression). + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } var hasWrite = false; var readonlyClassPropertyWrite = undefined; usagesPerScope[i].usages.forEach(function (value) { @@ -91182,22 +95728,28 @@ var ts; } } }); - if (hasWrite && !isReadonlyArray(targetRange.range) && ts.isExpression(targetRange.range)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); + // If an expression was extracted, then there shouldn't have been any variable declarations. + ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); + var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); + } + else if (firstExposedNonVariableDeclaration) { + var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } }; for (var i = 0; i < scopes.length; i++) { - _loop_8(i); - } - // If there are any declarations in the extracted block that are used in the same enclosing - // lexical scope, we can't move the extraction "up" as those declarations will become unreachable - if (visibleDeclarationsInExtractedRange.length) { - ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + _loop_10(i); } - return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function hasTypeParameters(node) { return ts.isDeclarationWithTypeParameters(node) && node.typeParameters !== undefined && @@ -91219,7 +95771,7 @@ var ts; var visitedTypes = symbolWalker.walkType(type).visitedTypes; for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { var visitedType = visitedTypes_1[_i]; - if (visitedType.flags & 16384 /* TypeParameter */) { + if (visitedType.flags & 32768 /* TypeParameter */) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); } } @@ -91231,7 +95783,7 @@ var ts; recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node.symbol); + visibleDeclarationsInExtractedRange.push(node); } if (ts.isAssignmentExpression(node)) { // use 'write' as default usage for values @@ -91266,19 +95818,15 @@ var ts; if (symbolId) { for (var i = 0; i < scopes.length; i++) { // push substitution from map to map to simplify rewriting - var substitition = substitutionsPerScope[i].get(symbolId); - if (substitition) { - usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitition); + var substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution); } } } } function recordUsagebySymbol(identifier, usage, isTypeName) { - // If the identifier is both a property name and its value, we're only interested in its value - // (since the name is a declaration and will be included in the extracted range). - var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier - ? checker.getShorthandAssignmentValueSymbol(identifier.parent) - : checker.getSymbolAtLocation(identifier); + var symbol = getSymbolReferencedByIdentifier(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -91319,9 +95867,14 @@ var ts; if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) { // this is write to a reference located outside of the target scope and range is extracted into generator // currently this is unsupported scenario - for (var _a = 0, errorsPerScope_1 = errorsPerScope; _a < errorsPerScope_1.length; _a++) { - var errors = errorsPerScope_1[_a]; - errors.push(ts.createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators)); + var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) { + var errors = functionErrorsPerScope_1[_a]; + errors.push(diag); + } + for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) { + var errors = constantErrorsPerScope_1[_b]; + errors.push(diag); } } for (var i = 0; i < scopes.length; i++) { @@ -91339,7 +95892,9 @@ var ts; // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument // so there's no problem. if (!(symbol.flags & 262144 /* TypeParameter */)) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag); + constantErrorsPerScope[i].push(diag); } } else { @@ -91355,17 +95910,37 @@ var ts; return; } // Otherwise check and recurse. - var sym = checker.getSymbolAtLocation(node); - if (sym && visibleDeclarationsInExtractedRange.some(function (d) { return d === sym; })) { - for (var _i = 0, errorsPerScope_2 = errorsPerScope; _i < errorsPerScope_2.length; _i++) { - var scope = errorsPerScope_2[_i]; - scope.push(ts.createDiagnosticForNode(node, Messages.CannotExtractExportedEntity)); + var sym = ts.isIdentifier(node) + ? getSymbolReferencedByIdentifier(node) + : checker.getSymbolAtLocation(node); + if (sym) { + var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; }); + if (decl) { + if (ts.isVariableDeclaration(decl)) { + var idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } + else { + // CONSIDER: this includes binding elements, which we could + // expose in the same way as variables. + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } } - return true; - } - else { - ts.forEachChild(node, checkForUsedDeclarations); } + ts.forEachChild(node, checkForUsedDeclarations); + } + /** + * Return the symbol referenced by an identifier (even if it declares a different symbol). + */ + function getSymbolReferencedByIdentifier(identifier) { + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); } function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) { if (!symbol) { @@ -91378,7 +95953,9 @@ var ts; if (prefix === undefined) { return undefined; } - return isTypeNode ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) : ts.createPropertyAccess(prefix, symbol.name); + return isTypeNode + ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name)) + : ts.createPropertyAccess(prefix, symbol.name); } } function getParentNodeInSpan(node, file, span) { @@ -91404,40 +95981,205 @@ var ts; */ function isExtractableExpression(node) { switch (node.parent.kind) { - case 264 /* EnumMember */: + case 268 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 238 /* ImportDeclaration */ && - node.parent.kind !== 242 /* ImportSpecifier */; - case 198 /* SpreadElement */: - case 174 /* ObjectBindingPattern */: - case 176 /* BindingElement */: + return node.parent.kind !== 239 /* ImportDeclaration */ && + node.parent.kind !== 243 /* ImportSpecifier */; + case 199 /* SpreadElement */: + case 175 /* ObjectBindingPattern */: + case 177 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 176 /* BindingElement */ && - node.parent.kind !== 242 /* ImportSpecifier */ && - node.parent.kind !== 246 /* ExportSpecifier */; + return node.parent.kind !== 177 /* BindingElement */ && + node.parent.kind !== 243 /* ImportSpecifier */ && + node.parent.kind !== 247 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 207 /* Block */: - case 265 /* SourceFile */: - case 234 /* ModuleBlock */: - case 257 /* CaseClause */: + case 208 /* Block */: + case 269 /* SourceFile */: + case 235 /* ModuleBlock */: + case 261 /* CaseClause */: + return true; + default: + return false; + } + } + })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { + // Then it will be available via `fixCannotFindModule`. + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); // Should be defined if we said there was an action available. + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(node) || !isModuleIdentifier(node)) { + return undefined; + } + var resolvedTo = ts.getResolvedModule(file, node.text); + // Still offer to install types if it resolved to e.g. a ".js" file. + // `tryGetCodeActionForInstallPackageTypes` will verify that we're looking for a valid package name, + // so the fix won't trigger for imports of ".js" files that couldn't be better replaced by typings. + if (resolvedTo && ts.extensionIsTypeScript(resolvedTo.extension)) { + return undefined; + } + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, file.fileName, node.text); + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 239 /* ImportDeclaration */: + case 249 /* ExternalModuleReference */: return true; default: return false; } } - })(extractMethod = refactor.extractMethod || (refactor.extractMethod = {})); + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage) { + var actionName = "Convert to default import"; + var useDefaultImport = { + name: actionName, + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(useDefaultImport); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition, program = context.program; + if (!program.getCompilerOptions().allowSyntheticDefaultImports) { + return undefined; + } + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var module = ts.getResolvedModule(file, importInfo.moduleSpecifier.text); + var resolvedFile = program.getSourceFile(module.resolvedFileName); + if (!(resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals)) { + return undefined; + } + return [ + { + name: useDefaultImport.name, + description: useDefaultImport.description, + actions: [ + { + description: useDefaultImport.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + var file = context.file, startPosition = context.startPosition; + ts.Debug.assertEqual(actionName, _actionName); + var importInfo = getConvertibleImportAtPosition(file, startPosition); + if (!importInfo) { + return undefined; + } + var importStatement = importInfo.importStatement, name = importInfo.name, moduleSpecifier = importInfo.moduleSpecifier; + var newImportClause = ts.createImportClause(name, /*namedBindings*/ undefined); + var newImportStatement = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newImportClause, moduleSpecifier); + return { + edits: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, importStatement, newImportStatement); }), + renameFilename: undefined, + renameLocation: undefined, + }; + } + function getConvertibleImportAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + while (true) { + switch (node.kind) { + case 238 /* ImportEqualsDeclaration */: + var eq = node; + var moduleReference = eq.moduleReference; + return moduleReference.kind === 249 /* ExternalModuleReference */ && ts.isStringLiteral(moduleReference.expression) + ? { importStatement: eq, name: eq.name, moduleSpecifier: moduleReference.expression } + : undefined; + case 239 /* ImportDeclaration */: + var d = node; + var importClause = d.importClause; + return !importClause.name && importClause.namedBindings.kind === 241 /* NamespaceImport */ && ts.isStringLiteral(d.moduleSpecifier) + ? { importStatement: d, name: importClause.namedBindings.name, moduleSpecifier: d.moduleSpecifier } + : undefined; + // For known child node kinds of convertible imports, try again with parent node. + case 241 /* NamespaceImport */: + case 249 /* ExternalModuleReference */: + case 91 /* ImportKeyword */: + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 39 /* AsteriskToken */: + break; + default: + return undefined; + } + node = node.parent; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/// /// -/// +/// +/// +/// /// /// /// @@ -91470,14 +96212,13 @@ var ts; var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.5"; - /* @internal */ - var ruleProvider; + ts.servicesVersion = "0.7"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; + node.flags = parent.flags & 6387712 /* ContextFlags */; return node; } var NodeObject = /** @class */ (function () { @@ -91489,31 +96230,43 @@ var ts; this.parent = undefined; this.kind = kind; } + NodeObject.prototype.assertHasRealPosition = function (message) { + // tslint:disable-next-line:debug-assert + ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation"); + }; NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); }; NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) { + this.assertHasRealPosition(); return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); }; NodeObject.prototype.getFullStart = function () { + this.assertHasRealPosition(); return this.pos; }; NodeObject.prototype.getEnd = function () { + this.assertHasRealPosition(); return this.end; }; NodeObject.prototype.getWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { + this.assertHasRealPosition(); return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + this.assertHasRealPosition(); return this.getStart(sourceFile) - this.pos; }; NodeObject.prototype.getFullText = function (sourceFile) { + this.assertHasRealPosition(); return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; NodeObject.prototype.getText = function (sourceFile) { + this.assertHasRealPosition(); if (!sourceFile) { sourceFile = this.getSourceFile(); } @@ -91535,7 +96288,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(290 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -91559,9 +96312,9 @@ var ts; } if (ts.isJSDocCommentContainingNode(this)) { /** Don't add trivia for "tokens" since this is in a comment. */ - var children_3 = []; - this.forEachChild(function (child) { children_3.push(child); }); - this._children = children_3; + var children_4 = []; + this.forEachChild(function (child) { children_4.push(child); }); + this._children = children_4; return; } var children = []; @@ -91598,37 +96351,42 @@ var ts; this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children.length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { + this.assertHasRealPosition(); if (!this._children) this.createChildren(sourceFile); return this._children[index]; }; NodeObject.prototype.getChildren = function (sourceFile) { + this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); if (!this._children) this.createChildren(sourceFile); return this._children; }; NodeObject.prototype.getFirstToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 /* FirstJSDocNode */ || kid.kind > 285 /* LastJSDocNode */; }); - return child.kind < 143 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 271 /* FirstJSDocNode */ || kid.kind > 289 /* LastJSDocNode */; }); + return child.kind < 144 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { + this.assertHasRealPosition(); var children = this.getChildren(sourceFile); var child = ts.lastOrUndefined(children); if (!child) { return undefined; } - return child.kind < 143 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 144 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -91668,7 +96426,10 @@ var ts; return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + if (!sourceFile) { + sourceFile = this.getSourceFile(); + } + return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; TokenOrIdentifierObject.prototype.getChildCount = function () { return 0; @@ -91700,7 +96461,7 @@ var ts; }; Object.defineProperty(SymbolObject.prototype, "name", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedName); + return ts.symbolName(this); }, enumerable: true, configurable: true @@ -91714,9 +96475,29 @@ var ts; SymbolObject.prototype.getDeclarations = function () { return this.declarations; }; - SymbolObject.prototype.getDocumentationComment = function () { + SymbolObject.prototype.getDocumentationComment = function (checker) { if (this.documentationComment === undefined) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.declarations) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); + if (this.documentationComment.length === 0 || this.declarations.some(hasJSDocInheritDocTag)) { + if (checker) { + for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); + if (inheritedDocs.length > 0) { + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + break; + } + } + } + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -91744,7 +96525,7 @@ var ts; } Object.defineProperty(IdentifierObject.prototype, "text", { get: function () { - return ts.unescapeLeadingUnderscores(this.escapedText); + return ts.idText(this); }, enumerable: true, configurable: true @@ -91785,13 +96566,19 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & 32768 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) + return this.flags & 65536 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; TypeObject.prototype.getNonNullableType = function () { return this.checker.getNonNullableType(this); }; + TypeObject.prototype.getConstraint = function () { + return this.checker.getBaseConstraintOfType(this); + }; + TypeObject.prototype.getDefault = function () { + return this.checker.getDefaultFromTypeParameter(this); + }; return TypeObject; }()); var SignatureObject = /** @class */ (function () { @@ -91812,7 +96599,19 @@ var ts; }; SignatureObject.prototype.getDocumentationComment = function () { if (this.documentationComment === undefined) { - this.documentationComment = this.declaration ? ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : []; + if (this.declaration) { + this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]); + if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { + var inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); + if (this.documentationComment.length > 0) { + inheritedDocs.push(ts.lineBreakPart()); + } + this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); + } + } + else { + this.documentationComment = []; + } } return this.documentationComment; }; @@ -91824,6 +96623,55 @@ var ts; }; return SignatureObject; }()); + /** + * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it. + * @param node the Node in question. + * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. + */ + function hasJSDocInheritDocTag(node) { + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + } + /** + * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses + * implemented interfaces until a symbol is found with the same name and with documentation. + * @param declaration The possibly-inherited declaration to find comments for. + * @param propertyName The name of the possibly-inherited property. + * @param typeChecker A TypeChecker, used to find inherited properties. + * @returns A filled array of documentation comments if any were found, otherwise an empty array. + */ + function findInheritedJSDocComments(declaration, propertyName, typeChecker) { + var foundDocs = false; + return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { + if (foundDocs) { + return ts.emptyArray; + } + var superType = typeChecker.getTypeAtLocation(superTypeNode); + if (!superType) { + return ts.emptyArray; + } + var baseProperty = typeChecker.getPropertyOfType(superType, propertyName); + if (!baseProperty) { + return ts.emptyArray; + } + var inheritedDocs = baseProperty.getDocumentationComment(typeChecker); + foundDocs = inheritedDocs.length > 0; + return inheritedDocs; + }); + } + /** + * Finds and returns the `TypeNode` for all super classes and implemented interfaces given a declaration. + * @param declaration The possibly-inherited declaration. + * @returns A filled array of `TypeNode`s containing all super classes and implemented interfaces if any exist, otherwise an empty array. + */ + function getAllSuperTypeNodes(declaration) { + var container = declaration.parent; + if (!container || (!ts.isClassDeclaration(container) && !ts.isInterfaceDeclaration(container))) { + return ts.emptyArray; + } + var extended = ts.getClassExtendsHeritageClauseElement(container); + var types = extended ? [extended] : ts.emptyArray; + return ts.isClassLike(container) ? ts.concatenate(types, ts.getClassImplementsHeritageClauseElements(container)) : types; + } var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -91881,13 +96729,13 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_9 = ts.getTextOfIdentifierOrLiteral(name); - if (result_9 !== undefined) { - return result_9; + var result_8 = ts.getTextOfIdentifierOrLiteral(name); + if (result_8 !== undefined) { + return result_8; } - if (name.kind === 144 /* ComputedPropertyName */) { + if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; - if (expr.kind === 179 /* PropertyAccessExpression */) { + if (expr.kind === 180 /* PropertyAccessExpression */) { return expr.name.text; } return ts.getTextOfIdentifierOrLiteral(expr); @@ -91897,10 +96745,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -91920,31 +96768,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: - case 233 /* ModuleDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 246 /* ExportSpecifier */: - case 242 /* ImportSpecifier */: - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 163 /* TypeLiteral */: + case 230 /* ClassDeclaration */: + case 200 /* ClassExpression */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 233 /* EnumDeclaration */: + case 234 /* ModuleDeclaration */: + case 238 /* ImportEqualsDeclaration */: + case 247 /* ExportSpecifier */: + case 243 /* ImportSpecifier */: + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 164 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 146 /* Parameter */: + case 147 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: { + case 227 /* VariableDeclaration */: + case 177 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -91955,19 +96803,19 @@ var ts; } } // falls through - case 264 /* EnumMember */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 268 /* EnumMember */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: addDeclaration(node); break; - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -91979,7 +96827,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 241 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -91988,7 +96836,7 @@ var ts; } } break; - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -92098,35 +96946,34 @@ var ts; scriptKind: ts.getScriptKind(fileName, this.host) }; } + else { + entry = fileName; + } this.fileNameToEntry.set(path, entry); return entry; }; HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.containsEntryByPath = function (path) { - return this.fileNameToEntry.has(path); + HostCache.prototype.getHostFileInformation = function (path) { + var entry = this.fileNameToEntry.get(path); + return !ts.isString(entry) ? entry : undefined; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.containsEntryByPath(path) - ? this.getEntryByPath(path) - : this.createEntry(fileName, path); + var info = this.getEntryByPath(path) || this.createEntry(fileName, path); + return ts.isString(info) ? undefined : info; }; HostCache.prototype.getRootFileNames = function () { - var fileNames = []; - this.fileNameToEntry.forEach(function (value) { - if (value) { - fileNames.push(value.hostFileName); - } + return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { + return ts.isString(entry) ? entry : entry.hostFileName; }); - return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntryByPath(path); + var file = this.getHostFileInformation(path); return file && file.scriptSnapshot; }; return HostCache; @@ -92146,7 +96993,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 5 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -92273,7 +97120,6 @@ var ts; function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); - ruleProvider = ruleProvider || new ts.formatting.RulesProvider(); var program; var lastProjectVersion; var lastTypesRootVersion = 0; @@ -92297,16 +97143,12 @@ var ts; } return sourceFile; } - function getRuleProvider(options) { - ruleProvider.ensureUpToDate(options); - return ruleProvider; - } function synchronizeHostData() { // perform fast check if host supports it if (host.getProjectVersion) { var hostProjectVersion = host.getProjectVersion(); if (hostProjectVersion) { - if (lastProjectVersion === hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) { return; } lastProjectVersion = hostProjectVersion; @@ -92320,8 +97162,10 @@ var ts; } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); + var rootFileNames = hostCache.getRootFileNames(); + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (programUpToDate()) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -92329,18 +97173,7 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var oldSettings = program && program.getCompilerOptions(); var newSettings = hostCache.compilationSettings(); - var shouldCreateNewSourceFiles = oldSettings && - (oldSettings.target !== newSettings.target || - oldSettings.module !== newSettings.module || - oldSettings.moduleResolution !== newSettings.moduleResolution || - oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || - oldSettings.baseUrl !== newSettings.baseUrl || - !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -92348,23 +97181,17 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: function (fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - return hostCache.containsEntryByPath(path) ? - !!hostCache.getEntryByPath(path) : - (host.fileExists && host.fileExists(fileName)); - }, + fileExists: fileExists, readFile: function (fileName) { // stub missing host functionality var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - if (hostCache.containsEntryByPath(path)) { - var entry = hostCache.getEntryByPath(path); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var entry = hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); } return host.readFile && host.readFile(fileName); }, @@ -92373,13 +97200,16 @@ var ts; }, getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; - } + }, + onReleaseOldSourceFile: onReleaseOldSourceFile, + hasInvalidatedResolution: hasInvalidatedResolution, + hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames }; if (host.trace) { compilerHost.trace = function (message) { return host.trace(message); }; } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + compilerHost.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }; } if (host.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile) { @@ -92387,31 +97217,31 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - var newProgram = ts.createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program); - // Release any files we have acquired in the old program but are - // not part of the new program. - if (program) { - var oldSourceFiles = program.getSourceFiles(); - var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings); - for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { - var oldSourceFile = oldSourceFiles_2[_i]; - if (!newProgram.getSourceFile(oldSourceFile.fileName) || shouldCreateNewSourceFiles) { - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); - } - } - } + program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; - program = newProgram; // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; - function getOrCreateSourceFile(fileName) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + function fileExists(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache.getEntryByPath(path); + return entry ? + !ts.isString(entry) : + (host.fileExists && host.fileExists(fileName)); + } + // Release any files we have acquired in the old program but are + // not part of the new program. + function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); + documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + } + function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path) { + function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { ts.Debug.assert(hostCache !== undefined); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined @@ -92423,7 +97253,7 @@ var ts; // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. - if (!shouldCreateNewSourceFiles) { + if (!shouldCreateNewSourceFile) { // Check if the old program had this file already var oldSourceFile = program && program.getSourceFileByPath(path); if (oldSourceFile) { @@ -92459,43 +97289,6 @@ var ts; // Could not find this file in the old program, create a new SourceFile for it. return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } - function sourceFileUpToDate(sourceFile) { - if (!sourceFile) { - return false; - } - var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile.version === hostCache.getVersion(path); - } - function programUpToDate() { - // If we haven't create a program yet, then it is not up-to-date - if (!program) { - return false; - } - // If number of files in the program do not match, it is not up-to-date - var rootFileNames = hostCache.getRootFileNames(); - if (program.getSourceFiles().length !== rootFileNames.length) { - return false; - } - // If any file is not up-to-date, then the whole program is not up-to-date - for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { - var fileName = rootFileNames_2[_i]; - if (!sourceFileUpToDate(program.getSourceFile(fileName))) { - return false; - } - } - var currentOptions = program.getCompilerOptions(); - var newOptions = hostCache.compilationSettings(); - // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { - return false; - } - // If everything matches but the text of config file is changed, - // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } - return true; - } } function getProgram() { synchronizeHostData(); @@ -92539,17 +97332,18 @@ var ts; synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } - function getCompletionsAtPosition(fileName, position) { + function getCompletionsAtPosition(fileName, position, options) { + if (options === void 0) { options = { includeExternalModuleExports: false }; } synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } - function getCompletionEntrySymbol(fileName, position, entryName) { + function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -92567,10 +97361,10 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: case 99 /* ThisKeyword */: - case 169 /* ThisType */: + case 170 /* ThisType */: case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -92580,7 +97374,7 @@ var ts; kindModifiers: "" /* none */, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } @@ -92616,6 +97410,10 @@ var ts; synchronizeHostData(); return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } + function getDefinitionAndBoundSpan(fileName, position) { + synchronizeHostData(); + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); + } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); @@ -92701,16 +97499,8 @@ var ts; function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var outputFiles = []; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { - outputFiles: outputFiles, - emitSkipped: emitOutput.emitSkipped - }; + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } // Signature help /** @@ -92736,15 +97526,15 @@ var ts; return; } switch (node.kind) { - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: + case 180 /* PropertyAccessExpression */: + case 144 /* QualifiedName */: case 9 /* StringLiteral */: case 86 /* FalseKeyword */: case 101 /* TrueKeyword */: case 95 /* NullKeyword */: case 97 /* SuperKeyword */: case 99 /* ThisKeyword */: - case 169 /* ThisType */: + case 170 /* ThisType */: case 71 /* Identifier */: break; // Cant create the text span @@ -92761,7 +97551,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 233 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 234 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -92876,29 +97666,24 @@ var ts; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsForDocument(fileName, options) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var settings = toEditorSettings(options); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); if (!ts.isInComment(sourceFile, position)) { - if (key === "{") { - return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); - } - else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + switch (key) { + case "{": + return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext); + case "}": + return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext); + case ";": + return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext); + case "\n": + return ts.formatting.formatOnEnter(position, sourceFile, formatContext); } } return []; @@ -92908,12 +97693,26 @@ var ts; var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); - var rulesProvider = getRuleProvider(formatOptions); - return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function applyCodeActionCommand(fileName, actionOrUndefined) { + var action = typeof fileName === "string" ? actionOrUndefined : fileName; + return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + } + function applySingleCodeActionCommand(action) { + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -93071,8 +97870,7 @@ var ts; (char >= 48 /* _0 */ && char <= 57 /* _9 */); } function isNodeModulesFile(path) { - var node_modulesFolderName = "/node_modules/"; - return path.indexOf(node_modulesFolderName) !== -1; + return ts.stringContains(path, "/node_modules/"); } } function getRenameInfo(fileName, position) { @@ -93088,8 +97886,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), - rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + host: host, + formatContext: ts.formatting.getFormatContext(formatOptions), + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -93118,6 +97917,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getDefinitionAndBoundSpan: getDefinitionAndBoundSpan, getImplementationAtPosition: getImplementationAtPosition, getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, @@ -93142,6 +97942,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -93184,19 +97985,19 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 248 /* ExternalModuleReference */ || + node.parent.kind === 249 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: return true; } return false; @@ -93209,13 +98010,13 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 144 /* ComputedPropertyName */) { + if (node.parent.kind === 145 /* ComputedPropertyName */) { return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: return isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 178 /* ObjectLiteralExpression */ || node.parent.parent.kind === 254 /* JsxAttributes */) && + (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -93232,20 +98033,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_10 = []; + var result_9 = []; var symbol = type.getProperty(name); - if (type.flags & 65536 /* Union */) { + if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_10.push(symbol); + result_9.push(symbol); } }); - return result_10; + return result_9; } if (symbol) { - result_10.push(symbol); - return result_10; + result_9.push(symbol); + return result_9; } } return undefined; @@ -93254,7 +98055,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 180 /* ElementAccessExpression */ && + node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -93303,7 +98104,7 @@ var ts; } } // Cannot set breakpoint in ambient declarations - if (ts.isInAmbientContext(tokenAtLocation)) { + if (tokenAtLocation.flags & 2097152 /* Ambient */) { return undefined; } // Get the span in the node based on its syntax @@ -93335,114 +98136,114 @@ var ts; function spanInNode(node) { if (node) { switch (node.kind) { - case 208 /* VariableStatement */: + case 209 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 226 /* VariableDeclaration */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: + case 227 /* VariableDeclaration */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: return spanInVariableDeclaration(node); - case 146 /* Parameter */: + case 147 /* Parameter */: return spanInParameterDeclaration(node); - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 207 /* Block */: + case 208 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: return spanInBlock(node); - case 260 /* CatchClause */: + case 264 /* CatchClause */: return spanInBlock(node.block); - case 210 /* ExpressionStatement */: + case 211 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 219 /* ReturnStatement */: + case 220 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 213 /* WhileStatement */: + case 214 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 212 /* DoStatement */: + case 213 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 225 /* DebuggerStatement */: + case 226 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 211 /* IfStatement */: + case 212 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 222 /* LabeledStatement */: + case 223 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: + case 219 /* BreakStatement */: + case 218 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 214 /* ForStatement */: + case 215 /* ForStatement */: return spanInForStatement(node); - case 215 /* ForInStatement */: + case 216 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 216 /* ForOfStatement */: + case 217 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 221 /* SwitchStatement */: + case 222 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 257 /* CaseClause */: - case 258 /* DefaultClause */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 224 /* TryStatement */: + case 225 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 223 /* ThrowStatement */: + case 224 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 243 /* ExportAssignment */: + case 244 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 238 /* ImportDeclaration */: + case 239 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 244 /* ExportDeclaration */: + case 245 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 176 /* BindingElement */: + case 230 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 177 /* BindingElement */: // span on complete node return textSpan(node); - case 220 /* WithStatement */: + case 221 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 147 /* Decorator */: + case 148 /* Decorator */: return spanInNodeArray(node.parent.decorators); - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: return undefined; // Tokens: case 25 /* SemicolonToken */: @@ -93472,7 +98273,7 @@ var ts; case 74 /* CatchKeyword */: case 87 /* FinallyKeyword */: return spanInNextNode(node); - case 142 /* OfKeyword */: + case 143 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -93485,13 +98286,13 @@ var ts; // a or ...c or d: x from // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern if ((node.kind === 71 /* Identifier */ || - node.kind === 198 /* SpreadElement */ || - node.kind === 261 /* PropertyAssignment */ || - node.kind === 262 /* ShorthandPropertyAssignment */) && + node.kind === 199 /* SpreadElement */ || + node.kind === 265 /* PropertyAssignment */ || + node.kind === 266 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); } - if (node.kind === 194 /* BinaryExpression */) { + if (node.kind === 195 /* BinaryExpression */) { var binaryExpression = node; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -93512,24 +98313,24 @@ var ts; return spanInNode(binaryExpression.left); } } - if (ts.isPartOfExpression(node)) { + if (ts.isExpressionNode(node)) { switch (node.parent.kind) { - case 212 /* DoStatement */: + case 213 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 147 /* Decorator */: + case 148 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: return textSpan(node); - case 194 /* BinaryExpression */: + case 195 /* BinaryExpression */: if (node.parent.operatorToken.kind === 26 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 187 /* ArrowFunction */: + case 188 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -93538,13 +98339,13 @@ var ts; } } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 261 /* PropertyAssignment */ && + if (node.parent.kind === 265 /* PropertyAssignment */ && node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 184 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 185 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNextNode(node.parent.type); } // return type of function go to previous token @@ -93552,8 +98353,8 @@ var ts; return spanInPreviousNode(node); } // initializer of variable/parameter declaration go to previous node - if ((node.parent.kind === 226 /* VariableDeclaration */ || - node.parent.kind === 146 /* Parameter */)) { + if ((node.parent.kind === 227 /* VariableDeclaration */ || + node.parent.kind === 147 /* Parameter */)) { var paramOrVarDecl = node.parent; if (paramOrVarDecl.initializer === node || paramOrVarDecl.type === node || @@ -93561,7 +98362,7 @@ var ts; return spanInPreviousNode(node); } } - if (node.parent.kind === 194 /* BinaryExpression */) { + if (node.parent.kind === 195 /* BinaryExpression */) { var binaryExpression = node.parent; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && (binaryExpression.right === node || @@ -93575,7 +98376,7 @@ var ts; } } function textSpanFromVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 227 /* VariableDeclarationList */ && + if (variableDeclaration.parent.kind === 228 /* VariableDeclarationList */ && variableDeclaration.parent.declarations[0] === variableDeclaration) { // First declaration - include let keyword return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); @@ -93587,7 +98388,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 215 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 216 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } // If this is a destructuring pattern, set breakpoint in binding pattern @@ -93598,10 +98399,10 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 216 /* ForOfStatement */) { + variableDeclaration.parent.parent.kind === 217 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (variableDeclaration.parent.kind === 227 /* VariableDeclarationList */ && + if (variableDeclaration.parent.kind === 228 /* VariableDeclarationList */ && variableDeclaration.parent.declarations[0] !== variableDeclaration) { // If we cannot set breakpoint on this declaration, set it on previous one // Because the variable declaration may be binding pattern and @@ -93638,7 +98439,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 229 /* ClassDeclaration */ && functionDeclaration.kind !== 152 /* Constructor */); + (functionDeclaration.parent.kind === 230 /* ClassDeclaration */ && functionDeclaration.kind !== 153 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -93661,26 +98462,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 233 /* ModuleDeclaration */: + case 234 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 213 /* WhileStatement */: - case 211 /* IfStatement */: - case 215 /* ForInStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 216 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 227 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 228 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -93705,23 +98506,23 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 200 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 201 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 176 /* BindingElement */) { + if (bindingPattern.parent.kind === 177 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 175 /* ArrayBindingPattern */ && node.kind !== 174 /* ObjectBindingPattern */); - var elements = node.kind === 177 /* ArrayLiteralExpression */ ? + ts.Debug.assert(node.kind !== 176 /* ArrayBindingPattern */ && node.kind !== 175 /* ObjectBindingPattern */); + var elements = node.kind === 178 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 200 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 201 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -93729,18 +98530,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 194 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 195 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 232 /* EnumDeclaration */: + case 233 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 229 /* ClassDeclaration */: + case 230 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -93748,25 +98549,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 234 /* ModuleBlock */: + case 235 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 232 /* EnumDeclaration */: - case 229 /* ClassDeclaration */: + case 233 /* EnumDeclaration */: + case 230 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 207 /* Block */: + case 208 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 260 /* CatchClause */: + case 264 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 235 /* CaseBlock */: + case 236 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -93774,7 +98575,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 174 /* ObjectBindingPattern */: + case 175 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -93790,7 +98591,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 175 /* ArrayBindingPattern */: + case 176 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -93805,12 +98606,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 212 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 181 /* CallExpression */ || - node.parent.kind === 182 /* NewExpression */) { + if (node.parent.kind === 213 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 182 /* CallExpression */ || + node.parent.kind === 183 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 185 /* ParenthesizedExpression */) { + if (node.parent.kind === 186 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -93819,21 +98620,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 185 /* ParenthesizedExpression */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 188 /* ArrowFunction */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 153 /* Constructor */: + case 214 /* WhileStatement */: + case 213 /* DoStatement */: + case 215 /* ForStatement */: + case 217 /* ForOfStatement */: + case 182 /* CallExpression */: + case 183 /* NewExpression */: + case 186 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -93843,20 +98644,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 261 /* PropertyAssignment */ || - node.parent.kind === 146 /* Parameter */) { + node.parent.kind === 265 /* PropertyAssignment */ || + node.parent.kind === 147 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 184 /* TypeAssertionExpression */) { + if (node.parent.kind === 185 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 212 /* DoStatement */) { + if (node.parent.kind === 213 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -93864,7 +98665,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 216 /* ForOfStatement */) { + if (node.parent.kind === 217 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -94114,7 +98915,7 @@ var ts; if (logPerformance) { var end = ts.timestamp(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof result === "string") { + if (ts.isString(result)) { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -94296,6 +99097,14 @@ var ts; var _this = this; return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + }; /// GOTO Type /** * Computes the definition location of the type of the symbol @@ -94371,14 +99180,17 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/, source) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; @@ -94657,6 +99469,4 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.6"; - -//# sourceMappingURL=typescriptServices.js.map +var toolsVersion = ts.versionMajorMinor; diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index af4a4c801b263..40c31cebe5086 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -34,443 +34,12 @@ var __extends = (this && this.__extends) || (function () { })(); var ts; (function (ts) { - var SyntaxKind; - (function (SyntaxKind) { - SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; - SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; - SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; - SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; - SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; - SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; - SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; - SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; - SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; - SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; - SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText"; - SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces"; - SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; - SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral"; - SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead"; - SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle"; - SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail"; - SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken"; - SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken"; - SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken"; - SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken"; - SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken"; - SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken"; - SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken"; - SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken"; - SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken"; - SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken"; - SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken"; - SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken"; - SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken"; - SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken"; - SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken"; - SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken"; - SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken"; - SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken"; - SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken"; - SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken"; - SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken"; - SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken"; - SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken"; - SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken"; - SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken"; - SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken"; - SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken"; - SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken"; - SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken"; - SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken"; - SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken"; - SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken"; - SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken"; - SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken"; - SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken"; - SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken"; - SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken"; - SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken"; - SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken"; - SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken"; - SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken"; - SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken"; - SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken"; - SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken"; - SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken"; - SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier"; - SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword"; - SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword"; - SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword"; - SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword"; - SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword"; - SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword"; - SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword"; - SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword"; - SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword"; - SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword"; - SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword"; - SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword"; - SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword"; - SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword"; - SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword"; - SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword"; - SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword"; - SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword"; - SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword"; - SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword"; - SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword"; - SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword"; - SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword"; - SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword"; - SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword"; - SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword"; - SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword"; - SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword"; - SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword"; - SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword"; - SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword"; - SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword"; - SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword"; - SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword"; - SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword"; - SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword"; - SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword"; - SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword"; - SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword"; - SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword"; - SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword"; - SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword"; - SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword"; - SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword"; - SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword"; - SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword"; - SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword"; - SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword"; - SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword"; - SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword"; - SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword"; - SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword"; - SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword"; - SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword"; - SyntaxKind[SyntaxKind["IsKeyword"] = 126] = "IsKeyword"; - SyntaxKind[SyntaxKind["KeyOfKeyword"] = 127] = "KeyOfKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 128] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 129] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["NeverKeyword"] = 130] = "NeverKeyword"; - SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 131] = "ReadonlyKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 132] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 133] = "NumberKeyword"; - SyntaxKind[SyntaxKind["ObjectKeyword"] = 134] = "ObjectKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 135] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 136] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 137] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 138] = "TypeKeyword"; - SyntaxKind[SyntaxKind["UndefinedKeyword"] = 139] = "UndefinedKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 140] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 141] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 142] = "OfKeyword"; - SyntaxKind[SyntaxKind["QualifiedName"] = 143] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 144] = "ComputedPropertyName"; - SyntaxKind[SyntaxKind["TypeParameter"] = 145] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 146] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 147] = "Decorator"; - SyntaxKind[SyntaxKind["PropertySignature"] = 148] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 149] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 150] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 151] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 152] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 153] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 154] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 155] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 156] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 157] = "IndexSignature"; - SyntaxKind[SyntaxKind["TypePredicate"] = 158] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 159] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 160] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 161] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 162] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 163] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 164] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 165] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 166] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 167] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 168] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 169] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 170] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 171] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 172] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 173] = "LiteralType"; - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 174] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 175] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 176] = "BindingElement"; - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 177] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 178] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 179] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 180] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 181] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 182] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 183] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 184] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 185] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 186] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 187] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 188] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 189] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 190] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 191] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 192] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 193] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 194] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 195] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 196] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 197] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 198] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 199] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 200] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 201] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 202] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 203] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 204] = "MetaProperty"; - SyntaxKind[SyntaxKind["TemplateSpan"] = 205] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 206] = "SemicolonClassElement"; - SyntaxKind[SyntaxKind["Block"] = 207] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 208] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 209] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 210] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 211] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 212] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 213] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 214] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 215] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 216] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 217] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 218] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 219] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 220] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 221] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 222] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 223] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 224] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 225] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 226] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 227] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 228] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 229] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 230] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 231] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 232] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 233] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 234] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 235] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 236] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 237] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 238] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 239] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 240] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 241] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 242] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 243] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 244] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 245] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 246] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 247] = "MissingDeclaration"; - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 248] = "ExternalModuleReference"; - SyntaxKind[SyntaxKind["JsxElement"] = 249] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 250] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 251] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 252] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 253] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 254] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 255] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 256] = "JsxExpression"; - SyntaxKind[SyntaxKind["CaseClause"] = 257] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 258] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 259] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 260] = "CatchClause"; - SyntaxKind[SyntaxKind["PropertyAssignment"] = 261] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 262] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 263] = "SpreadAssignment"; - SyntaxKind[SyntaxKind["EnumMember"] = 264] = "EnumMember"; - SyntaxKind[SyntaxKind["SourceFile"] = 265] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 266] = "Bundle"; - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 267] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 269] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 270] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; - SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; - SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; - SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; - SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment"; - SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; - SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; - SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 142] = "LastKeyword"; - SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; - SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 158] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 173] = "LastTypeNode"; - SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; - SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; - SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 142] = "LastToken"; - SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; - SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; - SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; - SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken"; - SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken"; - SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; - SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; - SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 143] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 267] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; - })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); - var NodeFlags; - (function (NodeFlags) { - NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Let"] = 1] = "Let"; - NodeFlags[NodeFlags["Const"] = 2] = "Const"; - NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace"; - NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized"; - NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn"; - NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation"; - NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions"; - NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext"; - NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext"; - NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext"; - NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext"; - NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError"; - NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; - NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; - NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; - NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; - NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; - NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; - NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; - NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags"; - NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; - })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); - var ModifierFlags; - (function (ModifierFlags) { - ModifierFlags[ModifierFlags["None"] = 0] = "None"; - ModifierFlags[ModifierFlags["Export"] = 1] = "Export"; - ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient"; - ModifierFlags[ModifierFlags["Public"] = 4] = "Public"; - ModifierFlags[ModifierFlags["Private"] = 8] = "Private"; - ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected"; - ModifierFlags[ModifierFlags["Static"] = 32] = "Static"; - ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly"; - ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract"; - ModifierFlags[ModifierFlags["Async"] = 256] = "Async"; - ModifierFlags[ModifierFlags["Default"] = 512] = "Default"; - ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; - ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; - ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; - ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); - var JsxFlags; - (function (JsxFlags) { - JsxFlags[JsxFlags["None"] = 0] = "None"; - JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; - JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; - })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {})); - var RelationComparisonResult; - (function (RelationComparisonResult) { - RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; - RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; - RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; - })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); - var NumericLiteralFlags; - (function (NumericLiteralFlags) { - NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None"; - NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific"; - NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal"; - NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier"; - NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier"; - NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier"; - })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {})); - var FlowFlags; - (function (FlowFlags) { - FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; - FlowFlags[FlowFlags["Start"] = 2] = "Start"; - FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel"; - FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel"; - FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; - FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; - FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; - FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; - FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; - FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; - FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; - FlowFlags[FlowFlags["Label"] = 12] = "Label"; - FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; - })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; }()); ts.OperationCanceledException = OperationCanceledException; - var StructureIsReused; - (function (StructureIsReused) { - StructureIsReused[StructureIsReused["Not"] = 0] = "Not"; - StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules"; - StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely"; - })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {})); var ExitStatus; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -495,47 +64,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); - var TypeFormatFlags; - (function (TypeFormatFlags) { - TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; - })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); - var SymbolFormatFlags; - (function (SymbolFormatFlags) { - SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; - SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; - SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; - })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); - var SymbolAccessibility; - (function (SymbolAccessibility) { - SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; - SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; - SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; - })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); - var SyntheticSymbolKind; - (function (SyntheticSymbolKind) { - SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection"; - SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread"; - })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {})); - var TypePredicateKind; - (function (TypePredicateKind) { - TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; - TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; - })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -550,231 +78,6 @@ var ts; TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature"; TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType"; })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); - var SymbolFlags; - (function (SymbolFlags) { - SymbolFlags[SymbolFlags["None"] = 0] = "None"; - SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; - SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; - SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; - SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; - SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; - SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; - SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; - SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; - SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; - SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; - SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; - SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; - SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; - SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; - SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; - SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; - SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; - SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; - SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; - SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; - SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; - SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias"; - SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; - SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; - SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; - SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; - SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; - SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; - SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; - SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; - SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; - SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; - SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; - SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; - SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; - SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; - SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; - SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; - SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; - SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; - })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); - var EnumKind; - (function (EnumKind) { - EnumKind[EnumKind["Numeric"] = 0] = "Numeric"; - EnumKind[EnumKind["Literal"] = 1] = "Literal"; - })(EnumKind = ts.EnumKind || (ts.EnumKind = {})); - var CheckFlags; - (function (CheckFlags) { - CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; - CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; - CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod"; - CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; - CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; - CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; - })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); - var InternalSymbolName; - (function (InternalSymbolName) { - InternalSymbolName["Call"] = "__call"; - InternalSymbolName["Constructor"] = "__constructor"; - InternalSymbolName["New"] = "__new"; - InternalSymbolName["Index"] = "__index"; - InternalSymbolName["ExportStar"] = "__export"; - InternalSymbolName["Global"] = "__global"; - InternalSymbolName["Missing"] = "__missing"; - InternalSymbolName["Type"] = "__type"; - InternalSymbolName["Object"] = "__object"; - InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; - InternalSymbolName["Class"] = "__class"; - InternalSymbolName["Function"] = "__function"; - InternalSymbolName["Computed"] = "__computed"; - InternalSymbolName["Resolving"] = "__resolving__"; - InternalSymbolName["ExportEquals"] = "export="; - InternalSymbolName["Default"] = "default"; - })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); - var NodeCheckFlags; - (function (NodeCheckFlags) { - NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; - NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; - NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget"; - NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; - NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; - NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; - NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; - NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; - NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; - NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; - })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); - var TypeFlags; - (function (TypeFlags) { - TypeFlags[TypeFlags["Any"] = 1] = "Any"; - TypeFlags[TypeFlags["String"] = 2] = "String"; - TypeFlags[TypeFlags["Number"] = 4] = "Number"; - TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 32768] = "Object"; - TypeFlags[TypeFlags["Union"] = 65536] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 131072] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 262144] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 524288] = "IndexedAccess"; - TypeFlags[TypeFlags["FreshLiteral"] = 1048576] = "FreshLiteral"; - TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; - TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; - TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic"; - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable"; - TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable"; - TypeFlags[TypeFlags["Narrowable"] = 17810175] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit"; - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; - TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; - })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); - var ObjectFlags; - (function (ObjectFlags) { - ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; - ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface"; - ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference"; - ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple"; - ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous"; - ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped"; - ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated"; - ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; - ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; - ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; - })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); - var SignatureKind; - (function (SignatureKind) { - SignatureKind[SignatureKind["Call"] = 0] = "Call"; - SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; - })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); - var IndexKind; - (function (IndexKind) { - IndexKind[IndexKind["String"] = 0] = "String"; - IndexKind[IndexKind["Number"] = 1] = "Number"; - })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); - var InferencePriority; - (function (InferencePriority) { - InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; - })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); - var InferenceFlags; - (function (InferenceFlags) { - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; - })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); - var Ternary; - (function (Ternary) { - Ternary[Ternary["False"] = 0] = "False"; - Ternary[Ternary["Maybe"] = 1] = "Maybe"; - Ternary[Ternary["True"] = -1] = "True"; - })(Ternary = ts.Ternary || (ts.Ternary = {})); - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -796,312 +99,6 @@ var ts; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); - var JsxEmit; - (function (JsxEmit) { - JsxEmit[JsxEmit["None"] = 0] = "None"; - JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; - JsxEmit[JsxEmit["React"] = 2] = "React"; - JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative"; - })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {})); - var NewLineKind; - (function (NewLineKind) { - NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; - NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; - })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {})); - var ScriptKind; - (function (ScriptKind) { - ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; - ScriptKind[ScriptKind["JS"] = 1] = "JS"; - ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; - ScriptKind[ScriptKind["TS"] = 3] = "TS"; - ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; - ScriptKind[ScriptKind["External"] = 5] = "External"; - ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; - })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); - var ScriptTarget; - (function (ScriptTarget) { - ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; - ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; - ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; - ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; - ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; - ScriptTarget[ScriptTarget["ESNext"] = 5] = "ESNext"; - ScriptTarget[ScriptTarget["Latest"] = 5] = "Latest"; - })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); - var LanguageVariant; - (function (LanguageVariant) { - LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; - LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; - })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); - var DiagnosticStyle; - (function (DiagnosticStyle) { - DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; - DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; - })(DiagnosticStyle = ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); - var WatchDirectoryFlags; - (function (WatchDirectoryFlags) { - WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; - WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; - })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); - var CharacterCodes; - (function (CharacterCodes) { - CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; - CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; - CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; - CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; - CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; - CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; - CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; - CharacterCodes[CharacterCodes["space"] = 32] = "space"; - CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; - CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; - CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; - CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; - CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; - CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; - CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; - CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; - CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; - CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; - CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; - CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; - CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; - CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; - CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; - CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; - CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; - CharacterCodes[CharacterCodes["_"] = 95] = "_"; - CharacterCodes[CharacterCodes["$"] = 36] = "$"; - CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; - CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; - CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; - CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; - CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; - CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; - CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; - CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; - CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; - CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; - CharacterCodes[CharacterCodes["a"] = 97] = "a"; - CharacterCodes[CharacterCodes["b"] = 98] = "b"; - CharacterCodes[CharacterCodes["c"] = 99] = "c"; - CharacterCodes[CharacterCodes["d"] = 100] = "d"; - CharacterCodes[CharacterCodes["e"] = 101] = "e"; - CharacterCodes[CharacterCodes["f"] = 102] = "f"; - CharacterCodes[CharacterCodes["g"] = 103] = "g"; - CharacterCodes[CharacterCodes["h"] = 104] = "h"; - CharacterCodes[CharacterCodes["i"] = 105] = "i"; - CharacterCodes[CharacterCodes["j"] = 106] = "j"; - CharacterCodes[CharacterCodes["k"] = 107] = "k"; - CharacterCodes[CharacterCodes["l"] = 108] = "l"; - CharacterCodes[CharacterCodes["m"] = 109] = "m"; - CharacterCodes[CharacterCodes["n"] = 110] = "n"; - CharacterCodes[CharacterCodes["o"] = 111] = "o"; - CharacterCodes[CharacterCodes["p"] = 112] = "p"; - CharacterCodes[CharacterCodes["q"] = 113] = "q"; - CharacterCodes[CharacterCodes["r"] = 114] = "r"; - CharacterCodes[CharacterCodes["s"] = 115] = "s"; - CharacterCodes[CharacterCodes["t"] = 116] = "t"; - CharacterCodes[CharacterCodes["u"] = 117] = "u"; - CharacterCodes[CharacterCodes["v"] = 118] = "v"; - CharacterCodes[CharacterCodes["w"] = 119] = "w"; - CharacterCodes[CharacterCodes["x"] = 120] = "x"; - CharacterCodes[CharacterCodes["y"] = 121] = "y"; - CharacterCodes[CharacterCodes["z"] = 122] = "z"; - CharacterCodes[CharacterCodes["A"] = 65] = "A"; - CharacterCodes[CharacterCodes["B"] = 66] = "B"; - CharacterCodes[CharacterCodes["C"] = 67] = "C"; - CharacterCodes[CharacterCodes["D"] = 68] = "D"; - CharacterCodes[CharacterCodes["E"] = 69] = "E"; - CharacterCodes[CharacterCodes["F"] = 70] = "F"; - CharacterCodes[CharacterCodes["G"] = 71] = "G"; - CharacterCodes[CharacterCodes["H"] = 72] = "H"; - CharacterCodes[CharacterCodes["I"] = 73] = "I"; - CharacterCodes[CharacterCodes["J"] = 74] = "J"; - CharacterCodes[CharacterCodes["K"] = 75] = "K"; - CharacterCodes[CharacterCodes["L"] = 76] = "L"; - CharacterCodes[CharacterCodes["M"] = 77] = "M"; - CharacterCodes[CharacterCodes["N"] = 78] = "N"; - CharacterCodes[CharacterCodes["O"] = 79] = "O"; - CharacterCodes[CharacterCodes["P"] = 80] = "P"; - CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; - CharacterCodes[CharacterCodes["R"] = 82] = "R"; - CharacterCodes[CharacterCodes["S"] = 83] = "S"; - CharacterCodes[CharacterCodes["T"] = 84] = "T"; - CharacterCodes[CharacterCodes["U"] = 85] = "U"; - CharacterCodes[CharacterCodes["V"] = 86] = "V"; - CharacterCodes[CharacterCodes["W"] = 87] = "W"; - CharacterCodes[CharacterCodes["X"] = 88] = "X"; - CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; - CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; - CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; - CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; - CharacterCodes[CharacterCodes["at"] = 64] = "at"; - CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; - CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; - CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; - CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; - CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; - CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; - CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; - CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; - CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; - CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; - CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; - CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; - CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; - CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; - CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; - CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; - CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; - CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; - CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; - CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; - CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; - CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; - CharacterCodes[CharacterCodes["question"] = 63] = "question"; - CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; - CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; - CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; - CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; - CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; - CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; - CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; - CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; - CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; - })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); - var Extension; - (function (Extension) { - Extension["Ts"] = ".ts"; - Extension["Tsx"] = ".tsx"; - Extension["Dts"] = ".d.ts"; - Extension["Js"] = ".js"; - Extension["Jsx"] = ".jsx"; - })(Extension = ts.Extension || (ts.Extension = {})); - var TransformFlags; - (function (TransformFlags) { - TransformFlags[TransformFlags["None"] = 0] = "None"; - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; - TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; - })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); - var EmitFlags; - (function (EmitFlags) { - EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; - EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; - EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; - EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis"; - EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap"; - EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap"; - EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap"; - EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps"; - EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps"; - EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps"; - EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps"; - EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments"; - EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments"; - EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments"; - EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments"; - EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; - EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; - EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; - EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; - EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; - EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; - })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); - var ExternalEmitHelpers; - (function (ExternalEmitHelpers) { - ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends"; - ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign"; - ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest"; - ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate"; - ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata"; - ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param"; - ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter"; - ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator"; - ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; - ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; - ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; - ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; - ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; - })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); - var EmitHint; - (function (EmitHint) { - EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; - EmitHint[EmitHint["Expression"] = 1] = "Expression"; - EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; - EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; - })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -1110,9 +107,7 @@ var ts; (function (ts) { var performance; (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (_markName) { }; + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; var enabled = false; var profilerStart = 0; var counts; @@ -1164,7 +159,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.versionMajorMinor = "2.6"; + ts.versionMajorMinor = "2.7"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { @@ -1174,12 +169,10 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { - ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; - ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } function createMap() { @@ -1284,12 +277,6 @@ var ts; return getCanonicalFileName(nonCanonicalizedPath); } ts.toPath = toPath; - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); function length(array) { return array ? array.length : 0; } @@ -1306,6 +293,16 @@ var ts; return undefined; } ts.forEach = forEach; + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1321,10 +318,12 @@ var ts; } ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { + var result = []; Debug.assert(arrayA.length === arrayB.length); for (var i = 0; i < arrayA.length; i++) { - callback(arrayA[i], arrayB[i], i); + result.push(callback(arrayA[i], arrayB[i], i)); } + return result; } ts.zipWith = zipWith; function zipToMap(keys, values) { @@ -1357,6 +356,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -1376,11 +385,12 @@ var ts; Debug.fail(); } ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (equalityComparer(v, value)) { return true; } } @@ -1443,22 +453,6 @@ var ts; return array; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var item = array_2[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var i = 0; i < array.length; i++) { @@ -1485,6 +479,14 @@ var ts; return result; } ts.map = map; + function mapIterator(iter, mapFn) { + return { next: next }; + function next() { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + } + ts.mapIterator = mapIterator; function sameMap(array, f) { var result; if (array) { @@ -1509,8 +511,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -1550,8 +552,14 @@ var ts; if (done) break; var res = mapfn(value); - if (res) - result.push.apply(result, res); + if (res) { + if (isArray(res)) { + result.push.apply(result, res); + } + else { + result.push(res); + } + } } return result; } @@ -1592,6 +600,20 @@ var ts; return result; } ts.mapDefined = mapDefined; + function mapDefinedIter(iter, mapFn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapFn(value); + if (res !== undefined) { + result.push(res); + } + } + return result; + } + ts.mapDefinedIter = mapDefinedIter; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1654,8 +676,8 @@ var ts; function some(array, predicate) { if (array) { if (predicate) { - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; if (predicate(v)) { return true; } @@ -1676,25 +698,64 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - function deduplicate(array, areEqual) { - var result; - if (array) { - result = []; - loop: for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } - } - result.push(item); - } + function deduplicateRelational(array, equalityComparer, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); } return result; } + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } ts.deduplicate = deduplicate; - function arrayIsEqualTo(array1, array2, equaler) { + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + case true: + case 0: + continue; + case -1: + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (!array1 || !array2) { return array1 === array2; } @@ -1702,8 +763,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; - if (!equals) { + if (!equalityComparer(array1[i], array2[i])) { return false; } } @@ -1747,30 +807,36 @@ var ts; return result || array; } ts.compact = compact; - function relativeComplement(arrayA, arrayB, comparer, offsetA, offsetB) { - if (comparer === void 0) { comparer = compareValues; } - if (offsetA === void 0) { offsetA = 0; } - if (offsetB === void 0) { offsetB = 0; } + function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; var result = []; - outer: for (; offsetB < arrayB.length; offsetB++) { - inner: for (; offsetA < arrayA.length; offsetA++) { + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0); + } switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1: break inner; - case 0: continue outer; - case 1: continue inner; + case -1: + result.push(arrayB[offsetB]); + continue loopB; + case 0: + continue loopB; + case 1: + continue loopA; } } - result.push(arrayB[offsetB]); } return result; } ts.relativeComplement = relativeComplement; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result += v[prop]; } return result; @@ -1789,23 +855,22 @@ var ts; return offset < 0 ? array.length + offset : offset; } function addRange(to, from, start, end) { - if (from === undefined) + if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); end = end === undefined ? from.length : toOffset(from, end); for (var i = start; i < end && i < from.length; i++) { - var v = from[i]; - if (v !== undefined) { + if (from[i] !== undefined) { to.push(from[i]); } } return to; } ts.addRange = addRange; - function pushIfUnique(array, toAdd) { - if (contains(array, toAdd)) { + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { return false; } else { @@ -1814,9 +879,9 @@ var ts; } } ts.pushIfUnique = pushIfUnique; - function appendIfUnique(array, toAdd) { + function appendIfUnique(array, toAdd, equalityComparer) { if (array) { - pushIfUnique(array, toAdd); + pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -1824,12 +889,47 @@ var ts; } } ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function best(iter, isBetter) { + var x = iter.next(); + if (x.done) { + return undefined; + } + var best = x.value; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return best; + } + if (isBetter(value, best)) { + best = value; + } + } + } + ts.best = best; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; function stableSort(array, comparer) { - if (comparer === void 0) { comparer = compareValues; } - return array - .map(function (_, i) { return i; }) - .sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }) - .map(function (i) { return array[i]; }); + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); } ts.stableSort = stableSort; function rangeEquals(array1, array2, pos, end) { @@ -1856,10 +956,20 @@ var ts; return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; function lastOrUndefined(array) { return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; function singleOrUndefined(array) { return array && array.length === 1 ? array[0] @@ -1878,26 +988,25 @@ var ts; return result; } ts.replaceElement = replaceElement; - function binarySearch(array, value, comparer, offset) { + function binarySearch(array, value, keySelector, keyComparer, offset) { if (!array || array.length === 0) { return -1; } var low = offset || 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; + var key = keySelector(value); while (low <= high) { var middle = low + ((high - low) >> 1); - var midValue = array[middle]; - if (comparer(midValue, value) === 0) { - return middle; - } - else if (comparer(midValue, value) > 0) { - high = middle - 1; - } - else { - low = middle + 1; + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1: + low = middle + 1; + break; + case 0: + return middle; + case 1: + high = middle - 1; + break; } } return ~low; @@ -1927,30 +1036,6 @@ var ts; return initial; } ts.reduceLeft = reduceLeft; - function reduceRight(array, f, initial, start, count) { - if (array) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start > size - 1 ? size - 1 : start; - var end = count === undefined || pos - count < 0 ? 0 : pos - count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos--; - } - else { - result = initial; - } - while (pos >= end) { - result = f(result, array[pos], pos); - pos--; - } - return result; - } - } - return initial; - } - ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; function hasProperty(map, key) { return hasOwnProperty.call(map, key); @@ -2037,6 +1122,7 @@ var ts; } ts.assign = assign; function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } if (left === right) return true; if (!left || !right) @@ -2045,7 +1131,7 @@ var ts; if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) + if (!equalityComparer(left[key], right[key])) return false; } } @@ -2060,13 +1146,22 @@ var ts; ts.equalOwnProperties = equalOwnProperties; function arrayToMap(array, makeKey, makeValue) { var result = createMap(); - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; result.set(makeKey(value), makeValue ? makeValue(value) : value); } return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2132,6 +1227,14 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -2142,8 +1245,12 @@ var ts; Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); } ts.cast = cast; - function noop() { } + function noop(_) { } ts.noop = noop; + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + function returnTrue() { return true; } + ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; function notImplemented() { @@ -2298,47 +1405,137 @@ var ts; return headChain; } ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + a < b ? -1 : + 1; + } function compareValues(a, b) { - if (a === b) - return 0; - if (a === undefined) - return -1; - if (b === undefined) - return 1; - return a < b ? -1 : 1; + return compareComparableValues(a, b); } ts.compareValues = compareValues; - function compareStrings(a, b, ignoreCase) { + function compareStringsCaseInsensitive(a, b) { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; - if (ignoreCase) { - if (ts.collator) { - var result = ts.localeCompareIsCorrect ? - ts.collator.compare(a, b) : - a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); - return result < 0 ? -1 : result > 0 ? 1 : 0; - } - a = a.toUpperCase(); - b = b.toUpperCase(); + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 : a > b ? 1 : 0; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { if (a === b) return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var value = comparer(a, b); + return value < 0 ? -1 : value > 0 ? 1 : 0; } - return a < b ? -1 : 1; - } - ts.compareStrings = compareStrings; - function compareStringsCaseInsensitive(a, b) { - return compareStrings(a, b, true); - } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + function createIntlCollatorStringComparer(locale) { + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 : a > b ? 1 : 0; + } + } + function getStringComparerFactory() { + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + return createFallbackStringComparer; + } + function createStringComparer(locale) { + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 : + a === undefined ? -1 : + b === undefined ? 1 : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } function compareDiagnostics(d1, d2) { - return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || @@ -2348,14 +1545,14 @@ var ts; ts.compareDiagnostics = compareDiagnostics; function compareMessageText(text1, text2) { while (text1 && text2) { - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + var string1 = isString(text1) ? text1 : text1.messageText; + var string2 = isString(text2) ? text2 : text2.messageText; + var res = compareStringsCaseSensitive(string1, string2); if (res) { return res; } - text1 = typeof text1 === "string" ? undefined : text1.next; - text2 = typeof text2 === "string" ? undefined : text2.next; + text1 = isString(text1) ? undefined : text1.next; + text2 = isString(text2) ? undefined : text2.next; } if (!text1 && !text2) { return 0; @@ -2363,26 +1560,9 @@ var ts; return text1 ? 1 : -1; } function sortAndDeduplicateDiagnostics(diagnostics) { - return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + return sortAndDeduplicate(diagnostics, compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function deduplicateSortedDiagnostics(diagnostics) { - if (diagnostics.length < 2) { - return diagnostics; - } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; - if (!isDupe) { - newDiagnostics.push(currentDiagnostic); - previousDiagnostic = currentDiagnostic; - } - } - return newDiagnostics; - } - ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; function normalizeSlashes(path) { return path.replace(/\\/g, "/"); } @@ -2402,7 +1582,6 @@ var ts; if (path.charCodeAt(1) === 58) { if (path.charCodeAt(2) === 47) return 3; - return 2; } if (path.lastIndexOf("file:///", 0) === 0) { return "file:///".length; @@ -2461,7 +1640,7 @@ var ts; } ts.getDirectoryPath = getDirectoryPath; function isUrl(path) { - return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + return path && !isRootedDiskPath(path) && stringContains(path, "://"); } ts.isUrl = isUrl; function pathIsRelative(path) { @@ -2490,6 +1669,17 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2645,8 +1835,9 @@ var ts; var aComponents = getNormalizedPathComponents(a, currentDirectory); var bComponents = getNormalizedPathComponents(b, currentDirectory); var sharedLength = Math.min(aComponents.length, bComponents.length); + var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; for (var i = 0; i < sharedLength; i++) { - var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + var result = comparer(aComponents[i], bComponents[i]); if (result !== 0) { return result; } @@ -2668,9 +1859,9 @@ var ts; if (childComponents.length < parentComponents.length) { return false; } + var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; for (var i = 0; i < parentComponents.length; i++) { - var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); - if (result !== 0) { + if (!equalityComparer(parentComponents[i], childComponents[i])) { return false; } } @@ -2690,8 +1881,16 @@ var ts; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; function hasExtension(fileName) { - return getBaseFileName(fileName).indexOf(".") >= 0; + return stringContains(getBaseFileName(fileName), "."); } ts.hasExtension = hasExtension; function fileExtensionIs(path, extension) { @@ -2833,13 +2032,13 @@ var ts; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); + var comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive; var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var regexFlag = useCaseSensitiveFileNames ? "" : "i"; var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -2847,7 +2046,6 @@ var ts; return flatten(results); function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - files = files.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); @@ -2865,8 +2063,8 @@ var ts; } } }; - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; + for (var _i = 0, _b = sort(files, comparer); _i < _b.length; _i++) { + var current = _b[_i]; _loop_1(current); } if (depth !== undefined) { @@ -2875,9 +2073,8 @@ var ts; return; } } - directories = directories.slice().sort(comparer); - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var current = directories_1[_b]; + for (var _c = 0, _d = sort(directories, comparer); _c < _d.length; _c++) { + var current = _d[_c]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && @@ -2897,7 +2094,7 @@ var ts; var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); var _loop_2 = function (includeBasePath) { if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); @@ -2950,7 +2147,7 @@ var ts; if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; }))); + return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -2974,13 +2171,6 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; - var ExtensionPriority; - (function (ExtensionPriority) { - ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; - ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; - ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; - ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; - })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { @@ -3035,6 +2225,11 @@ var ts; return (removeFileExtension(path) + newExtension); } ts.changeExtension = changeExtension; + function removeMinAndVersionNumbers(fileName) { + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; function Symbol(flags, name) { this.flags = flags; this.escapedName = name; @@ -3046,8 +2241,7 @@ var ts; this.checker = checker; } } - function Signature() { - } + function Signature() { } function Node(kind, pos, end) { this.id = 0; this.kind = kind; @@ -3074,13 +2268,6 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - var AssertionLevel; - (function (AssertionLevel) { - AssertionLevel[AssertionLevel["None"] = 0] = "None"; - AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; - AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; - AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; - })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {})); var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; @@ -3269,6 +2456,14 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3279,6 +2474,168 @@ var ts; ts.and = and; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; + function createCachedDirectoryStructureHost(host) { + var cachedReadDirectoryResult = createMap(); + var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); + var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, + newLine: host.newLine, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + write: function (s) { return host.write(s); }, + writeFile: writeFile, + fileExists: fileExists, + directoryExists: directoryExists, + createDirectory: createDirectory, + getCurrentDirectory: getCurrentDirectory, + getDirectories: getDirectories, + readDirectory: readDirectory, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache, + exit: function (code) { return host.exit(code); } + }; + function toPath(fileName) { + return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + } + else { + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (parentResult) { + var baseName = getBaseNameOfFileName(fileOrDirectory); + if (parentResult) { + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + } + } + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; })(ts || (ts = {})); var ts; (function (ts) { @@ -3310,12 +2667,13 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { + var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); var fileWatcherCallbacks = ts.createMultiMap(); @@ -3337,7 +2695,7 @@ var ts; watcher.referenceCount += 1; return; } - watcher = _fs.watch(dirPath || ".", { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher = fsWatchDirectory(dirPath || ".", function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers.set(dirPath, watcher); return; @@ -3358,7 +2716,7 @@ var ts; fileWatcherCallbacks.remove(filePath, callback); } function fileEventHandler(eventName, relativeFileName, baseDirPath) { - var fileName = typeof relativeFileName !== "string" + var fileName = !ts.isString(relativeFileName) ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); if ((eventName === "change" || eventName === "rename")) { @@ -3389,6 +2747,65 @@ var ts; } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + function fsWatchFile(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); + return { + close: function () { return _fs.unwatchFile(fileName, fileChanged); } + }; + function fileChanged(curr, prev) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { + return; + } + callback(fileName, eventKind); + } + } + function fsWatchDirectory(directoryName, callback, recursive) { + var options; + var watcher = !directoryExists(directoryName) ? + watchMissingDirectory() : + watchPresentDirectory(); + return { + close: function () { + watcher.close(); + } + }; + function watchPresentDirectory() { + if (options === undefined) { + if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + } + var dirWatcher = _fs.watch(directoryName, options, callback); + dirWatcher.on("error", function () { + if (!directoryExists(directoryName)) { + watcher = watchMissingDirectory(); + callback("rename", ""); + } + }); + return dirWatcher; + } + function watchMissingDirectory() { + return fsWatchFile(directoryName, function (_fileName, eventKind) { + if (eventKind === FileWatcherEventKind.Created && directoryExists(directoryName)) { + watcher.close(); + watcher = watchPresentDirectory(); + callback("rename", ""); + } + }); + } + } function readFile(fileName, _encoding) { if (!fileExists(fileName)) { return undefined; @@ -3414,7 +2831,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } var fd; try { @@ -3461,11 +2878,6 @@ var ts; function readDirectory(path, extensions, excludes, includes, depth) { return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); } - var FileSystemEntryKind; - (function (FileSystemEntryKind) { - FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; - FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; - })(FileSystemEntryKind || (FileSystemEntryKind = {})); function fileSystemEntryExists(path, entryKind) { try { var stat = _fs.statSync(path); @@ -3487,7 +2899,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } - var noOpFileWatcher = { close: ts.noop }; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -3505,43 +2916,15 @@ var ts; }; } else { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval || 250 }, fileChanged); - return { - close: function () { return _fs.unwatchFile(fileName, fileChanged); } - }; - } - function fileChanged(curr, prev) { - var isCurrZero = +curr.mtime === 0; - var isPrevZero = +prev.mtime === 0; - var created = !isCurrZero && isPrevZero; - var deleted = isCurrZero && !isPrevZero; - var eventKind = created - ? FileWatcherEventKind.Created - : deleted - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { - return; - } - callback(fileName, eventKind); + return fsWatchFile(fileName, callback, pollingInterval); } }, watchDirectory: function (directoryName, callback, recursive) { - var options; - if (!directoryExists(directoryName)) { - return noOpFileWatcher; - } - if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - return _fs.watch(directoryName, options, function (eventName, relativeFileName) { + return fsWatchDirectory(directoryName, function (eventName, relativeFileName) { if (eventName === "rename") { callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName))); } - }); + }, recursive); }, resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, @@ -3588,7 +2971,7 @@ var ts; return stat.size; } } - catch (e) { } + catch (_a) { } return 0; }, exit: function (exitCode) { @@ -3602,7 +2985,7 @@ var ts; try { require("source-map-support").install(); } - catch (e) { + catch (_a) { } }, setTimeout: setTimeout, @@ -3622,7 +3005,7 @@ var ts; }, writeFile: function (path, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = "\uFEFF" + data; + data = utf8ByteOrderMark + data; } ChakraHost.writeFile(path, data); }, @@ -3644,7 +3027,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -3809,11 +3192,11 @@ var ts; An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), @@ -3894,6 +3277,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "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."), @@ -3913,6 +3297,13 @@ var ts; Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, ts.DiagnosticCategory.Error, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, ts.DiagnosticCategory.Error, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, ts.DiagnosticCategory.Error, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, ts.DiagnosticCategory.Error, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4114,7 +3505,7 @@ var ts; No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), - Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), @@ -4130,7 +3521,7 @@ var ts; await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), @@ -4159,14 +3550,16 @@ var ts; Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), - Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), + Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4240,6 +3633,11 @@ var ts; A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "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."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4263,16 +3661,16 @@ var ts; Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), @@ -4315,6 +3713,14 @@ var ts; Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, ts.DiagnosticCategory.Error, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -4343,6 +3749,7 @@ var ts; File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -4356,7 +3763,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -4458,7 +3865,6 @@ var ts; Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), - The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), @@ -4514,6 +3920,8 @@ var ts; Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), 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."), @@ -4563,6 +3971,13 @@ var ts; Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4580,37 +3995,50 @@ var ts; super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, ts.DiagnosticCategory.Error, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, ts.DiagnosticCategory.Error, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"), Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), - Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), - Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), - Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), - Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), - Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), - Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), - Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), - Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), - Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), - Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), - Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), - Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), - Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), - Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), - Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), - Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), + Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), + Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), }; })(ts || (ts = {})); var ts; @@ -4651,6 +4079,7 @@ var ts; clear: function () { return str = ""; }, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, reportPrivateInBaseOfClassExpression: ts.noop, }; } @@ -4733,7 +4162,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 265) { + while (node && node.kind !== 269) { node = node.parent; } return node; @@ -4741,11 +4170,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 207: - case 235: - case 214: + case 208: + case 236: case 215: case 216: + case 217: return true; } return false; @@ -4821,7 +4250,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 286 && node._children.length > 0) { + if (node.kind === 290 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -4855,15 +4284,13 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getPos(range) { + return range.pos; + } function indexOfNode(nodeArray, node) { - return ts.binarySearch(nodeArray, node, compareNodePos); + return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } ts.indexOfNode = indexOfNode; - function compareNodePos(_a, _b) { - var aPos = _a.pos; - var bPos = _b.pos; - return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; - } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -4898,7 +4325,7 @@ var ts; } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { - return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; function escapeLeadingUnderscores(identifier) { @@ -4920,14 +4347,18 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 226 && node.parent.kind === 260; + return node.kind === 227 && node.parent.kind === 264; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { - return node && node.kind === 233 && + return node && node.kind === 234 && (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isModuleWithStringLiteralName(node) { + return ts.isModuleDeclaration(node) && node.name.kind === 9; + } + ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName; function isNonGlobalAmbientModule(node) { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } @@ -4937,11 +4368,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node && node.kind === 233 && (!node.body); + return node && node.kind === 234 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 || - node.kind === 233 || + return node.kind === 269 || + node.kind === 234 || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -4954,36 +4385,36 @@ var ts; return false; } switch (node.parent.kind) { - case 265: + case 269: return ts.isExternalModule(node.parent); - case 234: + case 235: return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; + return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 265: - case 235: - case 260: - case 233: - case 214: + case 269: + case 236: + case 264: + case 234: case 215: case 216: - case 152: - case 151: + case 217: case 153: + case 152: case 154: - case 228: - case 186: + case 155: + case 229: case 187: + case 188: return true; - case 207: + case 208: return parentNode && !ts.isFunctionLike(parentNode); } return false; @@ -4991,25 +4422,25 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 155: case 156: - case 150: case 157: - case 160: + case 151: + case 158: case 161: - case 273: - case 229: - case 199: + case 162: + case 277: case 230: + case 200: case 231: - case 282: - case 228: - case 151: + case 232: + case 287: + case 229: case 152: case 153: case 154: - case 186: + case 155: case 187: + case 188: return true; default: ts.assertTypeIsNever(node); @@ -5017,6 +4448,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 239: + case 238: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -5042,7 +4483,7 @@ var ts; case 9: case 8: return escapeLeadingUnderscores(name.text); - case 144: + case 145: if (isStringOrNumericLiteral(name.expression)) { return escapeLeadingUnderscores(name.expression.text); } @@ -5053,22 +4494,22 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71: - return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); - case 143: + return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); + case 144: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179: + case 180: return entityNameToString(name.expression) + "." + entityNameToString(name.name); } } ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) { var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; function createDiagnosticForNodeFromMessageChain(node, messageChain) { @@ -5093,7 +4534,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207) { + if (node.body && node.body.kind === 208) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -5105,29 +4546,29 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 265: + case 269: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 226: - case 176: - case 229: - case 199: + case 227: + case 177: case 230: + case 200: + case 231: + case 234: case 233: - case 232: - case 264: - case 228: - case 186: - case 151: - case 153: + case 268: + case 229: + case 187: + case 152: case 154: - case 231: + case 155: + case 232: errorNode = node.name; break; - case 187: + case 188: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -5144,7 +4585,7 @@ var ts; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isConstEnumDeclaration(node) { - return node.kind === 232 && isConst(node); + return node.kind === 233 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function isConst(node) { @@ -5157,15 +4598,15 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 181 && n.expression.kind === 97; + return n.kind === 182 && n.expression.kind === 97; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 181 && n.expression.kind === 91; + return n.kind === 182 && n.expression.kind === 91; } ts.isImportCall = isImportCall; function isPrologueDirective(node) { - return node.kind === 210 + return node.kind === 211 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; @@ -5174,11 +4615,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 || - node.kind === 145 || - node.kind === 186 || + var commentRanges = (node.kind === 147 || + node.kind === 146 || node.kind === 187 || - node.kind === 185) ? + node.kind === 188 || + node.kind === 186) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { @@ -5193,7 +4634,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (158 <= node.kind && node.kind <= 173) { + if (159 <= node.kind && node.kind <= 174) { return true; } switch (node.kind) { @@ -5206,56 +4647,56 @@ var ts; case 130: return true; case 105: - return node.parent.kind !== 190; - case 201: + return node.parent.kind !== 191; + case 202: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 71: - if (node.parent.kind === 143 && node.parent.right === node) { + if (node.parent.kind === 144 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 179 && node.parent.name === node) { + else if (node.parent.kind === 180 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 143: - case 179: + ts.Debug.assert(node.kind === 71 || node.kind === 144 || node.kind === 180, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 144: + case 180: case 99: var parent = node.parent; - if (parent.kind === 162) { + if (parent.kind === 163) { return false; } - if (158 <= parent.kind && parent.kind <= 173) { + if (159 <= parent.kind && parent.kind <= 174) { return true; } switch (parent.kind) { - case 201: + case 202: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 145: + case 146: return node === parent.constraint; + case 150: case 149: - case 148: - case 146: - case 226: + case 147: + case 227: return node === parent.type; - case 228: - case 186: + case 229: case 187: + case 188: + case 153: case 152: case 151: - case 150: - case 153: case 154: - return node === parent.type; case 155: + return node === parent.type; case 156: case 157: + case 158: return node === parent.type; - case 184: + case 185: return node === parent.type; - case 181: case 182: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; case 183: + return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + case 184: return false; } } @@ -5276,23 +4717,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219: + case 220: return visitor(node); - case 235: - case 207: - case 211: + case 236: + case 208: case 212: case 213: case 214: case 215: case 216: - case 220: + case 217: case 221: - case 257: - case 258: case 222: - case 224: - case 260: + case 261: + case 262: + case 223: + case 225: + case 264: return ts.forEachChild(node, traverse); } } @@ -5302,24 +4743,24 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 197: + case 198: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 232: - case 230: case 233: case 231: - case 229: - case 199: + case 234: + case 232: + case 230: + case 200: return; default: if (ts.isFunctionLike(node)) { var name = node.name; - if (name && name.kind === 144) { + if (name && name.kind === 145) { traverse(name.expression); return; } @@ -5332,10 +4773,10 @@ var ts; } ts.forEachYieldExpression = forEachYieldExpression; function getRestParameterElementType(node) { - if (node && node.kind === 164) { + if (node && node.kind === 165) { return node.elementType; } - else if (node && node.kind === 159) { + else if (node && node.kind === 160) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -5343,32 +4784,55 @@ var ts; } } ts.getRestParameterElementType = getRestParameterElementType; + function getMembersOfDeclaration(node) { + switch (node.kind) { + case 231: + case 230: + case 200: + case 164: + return node.members; + case 179: + return node.properties; + } + } + ts.getMembersOfDeclaration = getMembersOfDeclaration; function isVariableLike(node) { if (node) { switch (node.kind) { - case 176: - case 264: - case 146: - case 261: + case 177: + case 268: + case 147: + case 265: + case 150: case 149: - case 148: - case 262: - case 226: + case 266: + case 227: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 228 + && node.parent.parent.kind === 209; + } + ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; + function isValidESSymbolDeclaration(node) { + return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : + ts.isPropertySignature(node) && hasReadonlyModifier(node); + } + ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 228: - case 186: + case 155: + case 229: + case 187: return true; } return false; @@ -5379,7 +4843,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 222) { + if (node.statement.kind !== 223) { return node.statement; } node = node.statement; @@ -5387,17 +4851,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 && ts.isFunctionLike(node.parent); + return node && node.kind === 208 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 151 && node.parent.kind === 178; + return node && node.kind === 152 && node.parent.kind === 179; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 && - (node.parent.kind === 178 || - node.parent.kind === 199); + return node.kind === 152 && + (node.parent.kind === 179 || + node.parent.kind === 200); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -5410,7 +4874,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 261) { + if (property.kind === 265) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); } @@ -5432,39 +4896,39 @@ var ts; return undefined; } switch (node.kind) { - case 144: + case 145: if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148: + if (node.parent.kind === 147 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { node = node.parent; } break; - case 187: + case 188: if (!includeArrowFunctions) { continue; } - case 228: - case 186: - case 233: - case 149: - case 148: - case 151: + case 229: + case 187: + case 234: case 150: + case 149: case 152: + case 151: case 153: case 154: case 155: case 156: case 157: - case 232: - case 265: + case 158: + case 233: + case 269: return node; } } @@ -5474,9 +4938,9 @@ var ts; var container = getThisContainer(node, false); if (container) { switch (container.kind) { - case 152: - case 228: - case 186: + case 153: + case 229: + case 187: return container; } } @@ -5490,25 +4954,25 @@ var ts; return node; } switch (node.kind) { - case 144: + case 145: node = node.parent; break; - case 228: - case 186: + case 229: case 187: + case 188: if (!stopOnFunctions) { continue; } - case 149: - case 148: - case 151: case 150: + case 149: case 152: + case 151: case 153: case 154: + case 155: return node; - case 147: - if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + case 148: + if (node.parent.kind === 147 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { @@ -5520,14 +4984,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 || func.kind === 187) { + if (func.kind === 187 || func.kind === 188) { var prev = func; var parent = func.parent; - while (parent.kind === 185) { + while (parent.kind === 186) { prev = parent; parent = parent.parent; } - if (parent.kind === 181 && parent.expression === prev) { + if (parent.kind === 182 && parent.expression === prev) { return parent; } } @@ -5535,27 +4999,33 @@ var ts; ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; function isSuperProperty(node) { var kind = node.kind; - return (kind === 179 || kind === 180) + return (kind === 180 || kind === 181) && node.expression.kind === 97; } ts.isSuperProperty = isSuperProperty; + function isThisProperty(node) { + var kind = node.kind; + return (kind === 180 || kind === 181) + && node.expression.kind === 99; + } + ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 159: + case 160: return node.typeName; - case 201: + case 202: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71: - case 143: + case 144: return node; } return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 183) { + if (node.kind === 184) { return node.tag; } else if (ts.isJsxOpeningLikeElement(node)) { @@ -5564,101 +5034,102 @@ var ts; return node.expression; } ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { + function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 229: + case 230: return true; - case 149: - return node.parent.kind === 229; - case 153: + case 150: + return parent.kind === 230; case 154: - case 151: + case 155: + case 152: return node.body !== undefined - && node.parent.kind === 229; - case 146: - return node.parent.body !== undefined - && (node.parent.kind === 152 - || node.parent.kind === 151 - || node.parent.kind === 154) - && node.parent.parent.kind === 229; + && parent.kind === 230; + case 147: + return parent.body !== undefined + && (parent.kind === 153 + || parent.kind === 152 + || parent.kind === 155) + && grandparent.kind === 230; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { + function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node); + && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + function nodeOrChildIsDecorated(node, parent, grandparent) { + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { + function childIsDecorated(node, parent) { switch (node.kind) { - case 229: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151: - case 154: - return ts.forEach(node.parameters, nodeIsDecorated); + case 230: + return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); + case 152: + case 155: + return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 251 || - parent.kind === 250 || - parent.kind === 252) { + if (parent.kind === 252 || + parent.kind === 251 || + parent.kind === 253) { return parent.tagName === node; } return false; } ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { + function isExpressionNode(node) { switch (node.kind) { case 97: case 95: case 101: case 86: case 12: - case 177: case 178: case 179: case 180: case 181: case 182: case 183: - case 202: case 184: case 203: case 185: + case 204: case 186: - case 199: case 187: - case 190: + case 200: case 188: + case 191: case 189: - case 192: + case 190: case 193: case 194: case 195: - case 198: case 196: + case 199: + case 197: case 13: - case 200: - case 249: + case 201: case 250: - case 197: - case 191: - case 204: + case 251: + case 254: + case 198: + case 192: + case 205: return true; - case 143: - while (node.parent.kind === 143) { + case 144: + while (node.parent.kind === 144) { node = node.parent; } - return node.parent.kind === 162 || isJSXTagName(node); + return node.parent.kind === 163 || isJSXTagName(node); case 71: - if (node.parent.kind === 162 || isJSXTagName(node)) { + if (node.parent.kind === 163 || isJSXTagName(node)) { return true; } case 8: @@ -5669,59 +5140,59 @@ var ts; return false; } } - ts.isPartOfExpression = isPartOfExpression; + ts.isExpressionNode = isExpressionNode; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 226: - case 146: + case 227: + case 147: + case 150: case 149: - case 148: - case 264: - case 261: - case 176: + case 268: + case 265: + case 177: return parent.initializer === node; - case 210: case 211: case 212: case 213: - case 219: + case 214: case 220: case 221: - case 257: - case 223: + case 222: + case 261: + case 224: return parent.expression === node; - case 214: + case 215: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 228) || forStatement.condition === node || forStatement.incrementor === node; - case 215: case 216: + case 217: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 228) || forInStatement.expression === node; - case 184: - case 202: + case 185: + case 203: return node === parent.expression; - case 205: + case 206: return node === parent.expression; - case 144: + case 145: return node === parent.expression; - case 147: - case 256: - case 255: - case 263: + case 148: + case 260: + case 259: + case 267: return true; - case 201: + case 202: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: - return isPartOfExpression(parent); + return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind === 248; + return node.kind === 238 && node.moduleReference.kind === 249; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -5730,7 +5201,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind !== 248; + return node.kind === 238 && node.moduleReference.kind !== 249; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -5745,8 +5216,16 @@ var ts; return node && !!(node.flags & 1048576); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 || node.typeArguments[0].kind === 133); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181) { + if (callExpression.kind !== 182) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -5764,10 +5243,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226) { + if (s.valueDeclaration && s.valueDeclaration.kind === 227) { var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); + return declaration.initializer && (declaration.initializer.kind === 187 || declaration.initializer.kind === 200); } return false; } @@ -5787,12 +5270,11 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { + function getSpecialPropertyAssignmentKind(expr) { + if (!isInJavaScriptFile(expr)) { return 0; } - var expr = expression; - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { + if (expr.operatorToken.kind !== 58 || expr.left.kind !== 180) { return 0; } var lhs = expr.left; @@ -5811,7 +5293,7 @@ var ts; else if (lhs.expression.kind === 99) { return 4; } - else if (lhs.expression.kind === 179) { + else if (lhs.expression.kind === 180) { var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; @@ -5826,36 +5308,42 @@ var ts; return 0; } ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function isSpecialPropertyDeclaration(expr) { + return isInJavaScriptFile(expr) && + expr.parent && expr.parent.kind === 211 && + !!ts.getJSDocTypeTag(expr.parent); + } + ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; function getExternalModuleName(node) { - if (node.kind === 238) { + if (node.kind === 239) { return node.moduleSpecifier; } - if (node.kind === 237) { + if (node.kind === 238) { var reference = node.moduleReference; - if (reference.kind === 248) { + if (reference.kind === 249) { return reference.expression; } } - if (node.kind === 244) { + if (node.kind === 245) { return node.moduleSpecifier; } - if (node.kind === 233 && node.name.kind === 9) { + if (isModuleWithStringLiteralName(node)) { return node.name; } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { - if (node.kind === 237) { + if (node.kind === 238) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 241) { return importClause.namedBindings; } } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 238 + return node.kind === 239 && node.importClause && !!node.importClause.name; } @@ -5863,13 +5351,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 146: + case 147: + case 152: case 151: + case 266: + case 265: case 150: - case 262: - case 261: case 149: - case 148: return node.questionToken !== undefined; } } @@ -5877,7 +5365,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 273 && + return node.kind === 277 && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; @@ -5890,37 +5378,55 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; + function getSourceOfAssignment(node) { + return ts.isExpressionStatement(node) && + node.expression && ts.isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === 58 && + node.expression.right; + } + ts.getSourceOfAssignment = getSourceOfAssignment; + function getSingleInitializerOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0].initializer === child) && + node.declarationList.declarations[0].initializer; + } + ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; + function getSingleVariableOfVariableStatement(node, child) { + return ts.isVariableStatement(node) && + node.declarationList.declarations.length > 0 && + (!child || node.declarationList.declarations[0] === child) && + node.declarationList.declarations[0]; + } + ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; + function getNestedModuleDeclaration(node) { + return node.kind === 234 && + node.body && + node.body.kind === 234 && + node.body; + } + ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); return result || ts.emptyArray; function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocCommentsAndTagsWorker(variableStatementNode); - } - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 && - parent.operatorToken.kind === 58 && - parent.parent.kind === 210; - if (isSourceOfAssignmentExpressionStatement) { + if (parent && (parent.kind === 265 || getNestedModuleDeclaration(parent))) { + getJSDocCommentsAndTagsWorker(parent); + } + if (parent && parent.parent && + (getSingleVariableOfVariableStatement(parent.parent, node) || getSourceOfAssignment(parent.parent))) { getJSDocCommentsAndTagsWorker(parent.parent); } - var isModuleDeclaration = node.kind === 233 && - parent && parent.kind === 233; - var isPropertyAssignmentExpression = parent && parent.kind === 261; - if (isModuleDeclaration || isPropertyAssignmentExpression) { + if (parent && parent.parent && parent.parent.parent && getSingleInitializerOfVariableStatement(parent.parent.parent, node)) { + getJSDocCommentsAndTagsWorker(parent.parent.parent); + } + if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 || + node.kind === 180 && node.parent && node.parent.kind === 211) { getJSDocCommentsAndTagsWorker(parent); } - if (node.kind === 146) { + if (node.kind === 147) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { @@ -5940,17 +5446,29 @@ var ts; return undefined; } var name = node.name.escapedText; - ts.Debug.assert(node.parent.kind === 275); - var func = node.parent.parent; - if (!ts.isFunctionLike(func)) { + var decl = getHostSignatureFromJSDoc(node); + if (!decl) { return undefined; } - var parameter = ts.find(func.parameters, function (p) { - return p.name.kind === 71 && p.name.escapedText === name; - }); + var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 71 && p.name.escapedText === name; }); return parameter && parameter.symbol; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getHostSignatureFromJSDoc(node) { + var host = getJSDocHost(node); + var decl = getSourceOfAssignment(host) || + getSingleInitializerOfVariableStatement(host) || + getSingleVariableOfVariableStatement(host) || + getNestedModuleDeclaration(host) || + host; + return decl && ts.isFunctionLike(decl) ? decl : undefined; + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getJSDocHost(node) { + ts.Debug.assert(node.parent.kind === 279); + return node.parent.parent; + } + ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { var name = node.name.escapedText; var typeParameters = node.parent.parent.parent.typeParameters; @@ -5958,61 +5476,42 @@ var ts; } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); + var last = ts.lastOrUndefined(s.parameters); + return last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 274 || - ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { - return true; - } - } - return isDeclaredRestParam(node); + return node.dotDotDotToken !== undefined; } ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - return node && node.dotDotDotToken !== undefined; - } - ts.isDeclaredRestParam = isDeclaredRestParam; - var AssignmentKind; - (function (AssignmentKind) { - AssignmentKind[AssignmentKind["None"] = 0] = "None"; - AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite"; - AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound"; - })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {})); function getAssignmentTargetKind(node) { var parent = node.parent; while (true) { switch (parent.kind) { - case 194: + case 195: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 ? 1 : 2 : 0; - case 192: case 193: + case 194: var unaryOperator = parent.operator; return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; - case 215: case 216: + case 217: return parent.initializer === node ? 1 : 0; - case 185: - case 177: - case 198: + case 186: + case 178: + case 199: node = parent; break; - case 262: + case 266: if (parent.name !== node) { return 0; } node = parent.parent; break; - case 261: + case 265: if (parent.name === node) { return 0; } @@ -6029,15 +5528,26 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; + } + function walkUpParenthesizedTypes(node) { + return walkUp(node, 169); + } + ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; + function walkUpParenthesizedExpressions(node) { + return walkUp(node, 186); + } + ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function isDeleteTarget(node) { - if (node.kind !== 179 && node.kind !== 180) { + if (node.kind !== 180 && node.kind !== 181) { return false; } - node = node.parent; - while (node && node.kind === 185) { - node = node.parent; - } - return node && node.kind === 188; + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 189; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -6049,16 +5559,6 @@ var ts; return false; } ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; function isDeclarationName(name) { switch (name.kind) { case 71: @@ -6087,49 +5587,49 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && - node.parent.kind === 144 && + node.parent.kind === 145 && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { + case 150: case 149: - case 148: + case 152: case 151: - case 150: - case 153: case 154: - case 264: - case 261: - case 179: + case 155: + case 268: + case 265: + case 180: return parent.name === node; - case 143: + case 144: if (parent.right === node) { - while (parent.kind === 143) { + while (parent.kind === 144) { parent = parent.parent; } - return parent.kind === 162; + return parent.kind === 163; } return false; - case 176: - case 242: + case 177: + case 243: return parent.propertyName === node; - case 246: - case 253: + case 247: + case 257: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 237 || - node.kind === 236 || - node.kind === 239 && !!node.name || - node.kind === 240 || - node.kind === 242 || - node.kind === 246 || - node.kind === 243 && exportAssignmentIsAlias(node); + return node.kind === 238 || + node.kind === 237 || + node.kind === 240 && !!node.name || + node.kind === 241 || + node.kind === 243 || + node.kind === 247 || + node.kind === 244 && exportAssignmentIsAlias(node); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -6213,34 +5713,39 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 72 <= token && token <= 142; + return 72 <= token && token <= 143; } ts.isKeyword = isKeyword; + function isContextualKeyword(token) { + return 117 <= token && token <= 143; + } + ts.isContextualKeyword = isContextualKeyword; + function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); + } + ts.isNonContextualKeyword = isNonContextualKeyword; + function isStringANonContextualKeyword(name) { + var token = ts.stringToToken(name); + return token !== undefined && isNonContextualKeyword(token); + } + ts.isStringANonContextualKeyword = isStringANonContextualKeyword; function isTrivia(token) { return 2 <= token && token <= 7; } ts.isTrivia = isTrivia; - var FunctionFlags; - (function (FunctionFlags) { - FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; - FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; - FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; - })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { if (!node) { return 4; } var flags = 0; switch (node.kind) { - case 228: - case 186: - case 151: + case 229: + case 187: + case 152: if (node.asteriskToken) { flags |= 1; } - case 187: + case 188: if (hasModifier(node, 256)) { flags |= 2; } @@ -6254,10 +5759,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 228: - case 186: + case 229: case 187: - case 151: + case 188: + case 152: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256); @@ -6277,7 +5782,7 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 144 && + return name.kind === 145 && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -6293,11 +5798,10 @@ var ts; if (name.kind === 9 || name.kind === 8) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 144) { + if (name.kind === 145) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.escapedText; - return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); } else if (nameExpression.kind === 9 || nameExpression.kind === 8) { return escapeLeadingUnderscores(nameExpression.text); @@ -6309,7 +5813,7 @@ var ts; function getTextOfIdentifierOrLiteral(node) { if (node) { if (node.kind === 71) { - return ts.unescapeLeadingUnderscores(node.escapedText); + return ts.idText(node); } if (node.kind === 9 || node.kind === 8) { @@ -6346,11 +5850,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 146; + return root.kind === 147; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 176) { + while (node.kind === 177) { node = node.parent.parent; } return node; @@ -6358,15 +5862,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 152 - || kind === 186 - || kind === 228 + return kind === 153 || kind === 187 - || kind === 151 - || kind === 153 + || kind === 229 + || kind === 188 + || kind === 152 || kind === 154 - || kind === 233 - || kind === 265; + || kind === 155 + || kind === 234 + || kind === 269; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -6378,30 +5882,25 @@ var ts; return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } ts.getOriginalSourceFile = getOriginalSourceFile; - var Associativity; - (function (Associativity) { - Associativity[Associativity["Left"] = 0] = "Left"; - Associativity[Associativity["Right"] = 1] = "Right"; - })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 182: + case 183: return hasArguments ? 0 : 1; - case 192: - case 189: + case 193: case 190: - case 188: case 191: - case 195: - case 197: + case 189: + case 192: + case 196: + case 198: return 1; - case 194: + case 195: switch (operator) { case 40: case 58: @@ -6425,15 +5924,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + var hasArguments = expression.kind === 183 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 194) { + if (expression.kind === 195) { return expression.operatorToken.kind; } - else if (expression.kind === 192 || expression.kind === 193) { + else if (expression.kind === 193 || expression.kind === 194) { return expression.operator; } else { @@ -6451,36 +5950,37 @@ var ts; case 86: case 8: case 9: - case 177: case 178: - case 186: + case 179: case 187: - case 199: - case 249: + case 188: + case 200: case 250: + case 251: + case 254: case 12: case 13: - case 196: - case 185: - case 200: + case 197: + case 186: + case 201: return 19; - case 183: - case 179: + case 184: case 180: + case 181: return 18; - case 182: + case 183: return hasArguments ? 18 : 17; - case 181: + case 182: return 17; - case 193: + case 194: return 16; - case 192: - case 189: + case 193: case 190: - case 188: case 191: + case 189: + case 192: return 15; - case 194: + case 195: switch (operatorKind) { case 51: case 52: @@ -6538,13 +6038,13 @@ var ts; default: return -1; } - case 195: + case 196: return 4; - case 197: - return 2; case 198: + return 2; + case 199: return 1; - case 289: + case 293: return 0; default: return -1; @@ -6554,6 +6054,7 @@ var ts; function createDiagnosticCollection() { var nonFileDiagnostics = []; var fileDiagnostics = ts.createMap(); + var hasReadNonFileDiagnostics = false; var diagnosticsModified = false; var modificationCount = 0; return { @@ -6579,6 +6080,10 @@ var ts; } } else { + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); @@ -6587,6 +6092,7 @@ var ts; } function getGlobalDiagnostics() { sortAndDeduplicate(); + hasReadNonFileDiagnostics = true; return nonFileDiagnostics; } function getDiagnostics(fileName) { @@ -6650,8 +6156,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; + var ch = name.charCodeAt(0); + return (ch >= 97 && ch <= 122) || name.indexOf("-") > -1; } ts.isIntrinsicJsxName = isIntrinsicJsxName; function get16BitUnicodeEscapeSequence(charCode) { @@ -6834,7 +6340,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 152 && nodeIsPresent(member.body)) { + if (member.kind === 153 && nodeIsPresent(member.body)) { return member; } }); @@ -6879,10 +6385,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 153) { + if (accessor.kind === 154) { getAccessor = accessor; } - else if (accessor.kind === 154) { + else if (accessor.kind === 155) { setAccessor = accessor; } else { @@ -6891,7 +6397,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 153 || member.kind === 154) + if ((member.kind === 154 || member.kind === 155) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -6902,10 +6408,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 153 && !getAccessor) { + if (member.kind === 154 && !getAccessor) { getAccessor = member; } - if (member.kind === 154 && !setAccessor) { + if (member.kind === 155 && !setAccessor) { setAccessor = member; } } @@ -6920,37 +6426,37 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function getEffectiveTypeAnnotationNode(node) { + function getEffectiveTypeAnnotationNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; - function getEffectiveReturnTypeNode(node) { + function getEffectiveReturnTypeNode(node, checkJSDoc) { if (node.type) { return node.type; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node) { + function getEffectiveTypeParameterDeclarations(node, checkJSDoc) { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (checkJSDoc || isInJavaScriptFile(node)) { var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; - function getEffectiveSetAccessorTypeAnnotationNode(node) { + function getEffectiveSetAccessorTypeAnnotationNode(node, checkJSDoc) { var parameter = getSetAccessorValueParameter(node); - return parameter && getEffectiveTypeAnnotationNode(parameter); + return parameter && getEffectiveTypeAnnotationNode(parameter, checkJSDoc); } ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { @@ -7109,6 +6615,14 @@ var ts; return !!getSelectedModifierFlags(node, flags); } ts.hasModifier = hasModifier; + function hasStaticModifier(node) { + return hasModifier(node, 32); + } + ts.hasStaticModifier = hasStaticModifier; + function hasReadonlyModifier(node) { + return hasModifier(node, 64); + } + ts.hasReadonlyModifier = hasReadonlyModifier; function getSelectedModifierFlags(node, flags) { return getModifierFlags(node) & flags; } @@ -7164,7 +6678,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 && + if (node.kind === 202 && node.parent.token === 85 && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -7182,8 +6696,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, true)) { var kind = node.left.kind; - return kind === 178 - || kind === 177; + return kind === 179 + || kind === 178; } return false; } @@ -7193,7 +6707,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 + return node.kind === 202 && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 @@ -7203,21 +6717,21 @@ var ts; ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 || - node.kind === 179 && isEntityNameExpression(node.expression); + node.kind === 180 && isEntityNameExpression(node.expression); } ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 && node.parent.right === node) || - (node.parent.kind === 179 && node.parent.name === node); + return (node.parent.kind === 144 && node.parent.right === node) || + (node.parent.kind === 180 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 178 && + return expression.kind === 179 && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 177 && + return expression.kind === 178 && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -7287,17 +6801,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options) { + function getNewLineCharacter(options, system) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; + return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -7433,8 +6944,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 232: case 233: + case 234: return parseNode === parseNode.parent.name; } } @@ -7475,25 +6986,6 @@ var ts; return 0; } ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol; - function levenshtein(s1, s2) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - for (var i = 0; i < s2.length + 1; i++) { - previous[i] = i; - current[i] = -1; - } - for (var i = 1; i < s1.length + 1; i++) { - current[0] = i; - for (var j = 1; j < s2.length + 1; j++) { - current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2)); - } - var tmp = previous; - previous = current; - current = tmp; - } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; function skipAlias(symbol, checker) { return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; } @@ -7510,38 +7002,113 @@ var ts; return accessKind(node) !== 0; } ts.isWriteAccess = isWriteAccess; - var AccessKind; - (function (AccessKind) { - AccessKind[AccessKind["Read"] = 0] = "Read"; - AccessKind[AccessKind["Write"] = 1] = "Write"; - AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; - })(AccessKind || (AccessKind = {})); function accessKind(node) { var parent = node.parent; if (!parent) return 0; switch (parent.kind) { + case 194: case 193: - case 192: var operator = parent.operator; return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; - case 194: + case 195: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; - case 179: + case 180: return parent.name !== node ? 0 : accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 210 ? 1 : 2; + return parent.parent && parent.parent.kind === 211 ? 1 : 2; + } + } + function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + function clearMap(map, onDeleteValue) { + map.forEach(onDeleteValue); + map.clear(); + } + ts.clearMap = clearMap; + function mutateMap(map, newMap, options) { + var createNewValue = options.createNewValue, onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue; + map.forEach(function (existingValue, key) { + var valueInNewMap = newMap.get(key); + if (valueInNewMap === undefined) { + map.delete(key); + onDeleteValue(existingValue, key); + } + else if (onExistingValue) { + onExistingValue(existingValue, valueInNewMap, key); + } + }); + newMap.forEach(function (valueInNewMap, key) { + if (!map.has(key)) { + map.set(key, createNewValue(key, valueInNewMap)); + } + }); + } + 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); + } + ts.isAbstractConstructorType = isAbstractConstructorType; + function isAbstractConstructorSymbol(symbol) { + if (symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, 128); + } + return false; + } + ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.find(symbol.declarations, ts.isClassLike); + } + ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; + function getObjectFlags(type) { + return type.flags & 65536 ? type.objectFlags : 0; + } + ts.getObjectFlags = getObjectFlags; + function typeHasCallOrConstructSignatures(type, checker) { + return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; + } + ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 5: + case 6: return "lib.esnext.full.d.ts"; case 4: return "lib.es2017.full.d.ts"; @@ -7670,9 +7237,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 145) { + if (d && d.kind === 146) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 231) { return current; } } @@ -7680,7 +7247,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92) && node.parent.kind === 153 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -7698,7 +7265,7 @@ var ts; } ts.isEmptyBindingElement = isEmptyBindingElement; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 || ts.isBindingPattern(node))) { + while (node && (node.kind === 177 || ts.isBindingPattern(node))) { node = node.parent; } return node; @@ -7706,14 +7273,14 @@ var ts; function getCombinedModifierFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = ts.getModifierFlags(node); - if (node.kind === 226) { + if (node.kind === 227) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228) { flags |= ts.getModifierFlags(node); node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209) { flags |= ts.getModifierFlags(node); } return flags; @@ -7722,14 +7289,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 226) { + if (node.kind === 227) { node = node.parent; } - if (node && node.kind === 227) { + if (node && node.kind === 228) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 208) { + if (node && node.kind === 209) { flags |= node.flags; } return flags; @@ -7748,6 +7315,7 @@ var ts; if (!trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, undefined, errors); } + ts.setUILocale(locale); function trySetLanguageAndTerritory(language, territory, errors) { var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); @@ -7811,6 +7379,14 @@ var ts; return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; } ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function idText(identifier) { + return unescapeLeadingUnderscores(identifier.escapedText); + } + ts.idText = idText; + function symbolName(symbol) { + return unescapeLeadingUnderscores(symbol.escapedName); + } + ts.symbolName = symbolName; function unescapeIdentifier(id) { return id; } @@ -7824,18 +7400,18 @@ var ts; return getDeclarationIdentifier(hostNode); } switch (hostNode.kind) { - case 208: + case 209: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 210: + case 211: var expr = hostNode.expression; switch (expr.kind) { - case 179: - return expr.name; case 180: + return expr.name; + case 181: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -7844,10 +7420,10 @@ var ts; return undefined; case 1: return undefined; - case 185: { + case 186: { return getDeclarationIdentifier(hostNode.expression); } - case 222: { + case 223: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -7869,27 +7445,37 @@ var ts; if (!declaration) { return undefined; } - if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { - return declaration.name.right; - } - if (declaration.kind === 194) { - var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { - case 1: - case 4: - case 5: - case 3: - return expr.left.name; - default: - return undefined; + switch (declaration.kind) { + case 71: + return declaration; + case 289: + case 284: { + var name = declaration.name; + if (name.kind === 144) { + return name.right; + } + break; + } + case 195: { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + case 288: + return getNameOfJSDocTypedef(declaration); + case 244: { + var expression = declaration.expression; + return ts.isIdentifier(expression) ? expression : undefined; } } - else if (declaration.kind === 283) { - return getNameOfJSDocTypedef(declaration); - } - else { - return declaration.name; - } + return declaration.name; } ts.getNameOfDeclaration = getNameOfDeclaration; function getJSDocParameterTags(param) { @@ -7901,27 +7487,27 @@ var ts; } ts.getJSDocParameterTags = getJSDocParameterTags; function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); + return !!getFirstJSDocTag(node, 284); } ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); + return getFirstJSDocTag(node, 282); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); + return getFirstJSDocTag(node, 283); } ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); + return getFirstJSDocTag(node, 285); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); + return getFirstJSDocTag(node, 287); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getJSDocTypeTag(node) { - var tag = getFirstJSDocTag(node, 281); + var tag = getFirstJSDocTag(node, 286); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -7929,8 +7515,8 @@ var ts; } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { + var tag = getFirstJSDocTag(node, 286); + if (!tag && node.kind === 147) { var paramTags = getJSDocParameterTags(node); if (paramTags) { tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); @@ -7956,6 +7542,11 @@ var ts; var tags = getJSDocTags(node); return ts.find(tags, function (doc) { return doc.kind === kind; }); } + function getAllJSDocTagsOfKind(node, kind) { + var tags = getJSDocTags(node); + return ts.filter(tags, function (doc) { return doc.kind === kind; }); + } + ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -7995,584 +7586,600 @@ var ts; } ts.isIdentifier = isIdentifier; function isQualifiedName(node) { - return node.kind === 143; + return node.kind === 144; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 144; + return node.kind === 145; } ts.isComputedPropertyName = isComputedPropertyName; function isTypeParameterDeclaration(node) { - return node.kind === 145; + return node.kind === 146; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 146; + return node.kind === 147; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 147; + return node.kind === 148; } ts.isDecorator = isDecorator; function isPropertySignature(node) { - return node.kind === 148; + return node.kind === 149; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 149; + return node.kind === 150; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 150; + return node.kind === 151; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 151; + return node.kind === 152; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 152; + return node.kind === 153; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 153; + return node.kind === 154; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 154; + return node.kind === 155; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 155; + return node.kind === 156; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 156; + return node.kind === 157; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 157; + return node.kind === 158; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isTypePredicateNode(node) { - return node.kind === 158; + return node.kind === 159; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 159; + return node.kind === 160; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 160; + return node.kind === 161; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 161; + return node.kind === 162; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 162; + return node.kind === 163; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 163; + return node.kind === 164; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 164; + return node.kind === 165; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 165; + return node.kind === 166; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 166; + return node.kind === 167; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 167; + return node.kind === 168; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 168; + return node.kind === 169; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 169; + return node.kind === 170; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 170; + return node.kind === 171; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 171; + return node.kind === 172; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 172; + return node.kind === 173; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 173; + return node.kind === 174; } ts.isLiteralTypeNode = isLiteralTypeNode; function isObjectBindingPattern(node) { - return node.kind === 174; + return node.kind === 175; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 175; + return node.kind === 176; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 176; + return node.kind === 177; } ts.isBindingElement = isBindingElement; function isArrayLiteralExpression(node) { - return node.kind === 177; + return node.kind === 178; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 178; + return node.kind === 179; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 179; + return node.kind === 180; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 180; + return node.kind === 181; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 181; + return node.kind === 182; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 182; + return node.kind === 183; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 183; + return node.kind === 184; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 184; + return node.kind === 185; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 185; + return node.kind === 186; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 288) { + while (node.kind === 292) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 186; + return node.kind === 187; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 187; + return node.kind === 188; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 188; + return node.kind === 189; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 191; + return node.kind === 192; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 190; + return node.kind === 191; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 191; + return node.kind === 192; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 192; + return node.kind === 193; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 193; + return node.kind === 194; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 194; + return node.kind === 195; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 195; + return node.kind === 196; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 196; + return node.kind === 197; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 197; + return node.kind === 198; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 198; + return node.kind === 199; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 199; + return node.kind === 200; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 200; + return node.kind === 201; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 201; + return node.kind === 202; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 202; + return node.kind === 203; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 203; + return node.kind === 204; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 204; + return node.kind === 205; } ts.isMetaProperty = isMetaProperty; function isTemplateSpan(node) { - return node.kind === 205; + return node.kind === 206; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 206; + return node.kind === 207; } ts.isSemicolonClassElement = isSemicolonClassElement; function isBlock(node) { - return node.kind === 207; + return node.kind === 208; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 208; + return node.kind === 209; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 209; + return node.kind === 210; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 210; + return node.kind === 211; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 211; + return node.kind === 212; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 212; + return node.kind === 213; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 213; + return node.kind === 214; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 214; + return node.kind === 215; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 215; + return node.kind === 216; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 216; + return node.kind === 217; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 217; + return node.kind === 218; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 218; + return node.kind === 219; } ts.isBreakStatement = isBreakStatement; + function isBreakOrContinueStatement(node) { + return node.kind === 219 || node.kind === 218; + } + ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 219; + return node.kind === 220; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 220; + return node.kind === 221; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 221; + return node.kind === 222; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 222; + return node.kind === 223; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 223; + return node.kind === 224; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 224; + return node.kind === 225; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 225; + return node.kind === 226; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 226; + return node.kind === 227; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 227; + return node.kind === 228; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 228; + return node.kind === 229; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 229; + return node.kind === 230; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 230; + return node.kind === 231; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 231; + return node.kind === 232; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 232; + return node.kind === 233; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 233; + return node.kind === 234; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 234; + return node.kind === 235; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 235; + return node.kind === 236; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 236; + return node.kind === 237; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 237; + return node.kind === 238; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 238; + return node.kind === 239; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 239; + return node.kind === 240; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 240; + return node.kind === 241; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 241; + return node.kind === 242; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 242; + return node.kind === 243; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 243; + return node.kind === 244; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 244; + return node.kind === 245; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 245; + return node.kind === 246; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 246; + return node.kind === 247; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 247; + return node.kind === 248; } ts.isMissingDeclaration = isMissingDeclaration; function isExternalModuleReference(node) { - return node.kind === 248; + return node.kind === 249; } ts.isExternalModuleReference = isExternalModuleReference; function isJsxElement(node) { - return node.kind === 249; + return node.kind === 250; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 250; + return node.kind === 251; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 251; + return node.kind === 252; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 252; + return node.kind === 253; } ts.isJsxClosingElement = isJsxClosingElement; + function isJsxFragment(node) { + return node.kind === 254; + } + ts.isJsxFragment = isJsxFragment; + function isJsxOpeningFragment(node) { + return node.kind === 255; + } + ts.isJsxOpeningFragment = isJsxOpeningFragment; + function isJsxClosingFragment(node) { + return node.kind === 256; + } + ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 253; + return node.kind === 257; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 254; + return node.kind === 258; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 255; + return node.kind === 259; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 256; + return node.kind === 260; } ts.isJsxExpression = isJsxExpression; function isCaseClause(node) { - return node.kind === 257; + return node.kind === 261; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 258; + return node.kind === 262; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 259; + return node.kind === 263; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 260; + return node.kind === 264; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 261; + return node.kind === 265; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 262; + return node.kind === 266; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 263; + return node.kind === 267; } ts.isSpreadAssignment = isSpreadAssignment; function isEnumMember(node) { - return node.kind === 264; + return node.kind === 268; } ts.isEnumMember = isEnumMember; function isSourceFile(node) { - return node.kind === 265; + return node.kind === 269; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 266; + return node.kind === 270; } ts.isBundle = isBundle; function isJSDocTypeExpression(node) { - return node.kind === 267; + return node.kind === 271; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 268; + return node.kind === 272; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 269; + return node.kind === 273; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 270; + return node.kind === 274; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 271; + return node.kind === 275; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 272; + return node.kind === 276; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 273; + return node.kind === 277; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 274; + return node.kind === 278; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 275; + return node.kind === 279; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 277; + return node.kind === 282; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocParameterTag(node) { - return node.kind === 279; + return node.kind === 284; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 280; + return node.kind === 285; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 281; + return node.kind === 286; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 282; + return node.kind === 287; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 283; + return node.kind === 288; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 284; + return node.kind === 289; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 284 || node.kind === 279; + return node.kind === 289 || node.kind === 284; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 285; + return node.kind === 280; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 286; + return n.kind === 290; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -8580,11 +8187,11 @@ var ts; } ts.isNode = isNode; function isNodeKind(kind) { - return kind >= 143; + return kind >= 144; } ts.isNodeKind = isNodeKind; function isToken(n) { - return n.kind >= 0 && n.kind <= 142; + return n.kind >= 0 && n.kind <= 143; } ts.isToken = isToken; function isNodeArray(array) { @@ -8610,16 +8217,7 @@ var ts; } ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isStringTextContainingNode(node) { - switch (node.kind) { - case 9: - case 14: - case 15: - case 16: - case 13: - return true; - default: - return false; - } + return node.kind === 9 || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { @@ -8650,7 +8248,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 143 + return kind === 144 || kind === 71; } ts.isEntityName = isEntityName; @@ -8659,14 +8257,14 @@ var ts; return kind === 71 || kind === 9 || kind === 8 - || kind === 144; + || kind === 145; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 - || kind === 174 - || kind === 175; + || kind === 175 + || kind === 176; } ts.isBindingName = isBindingName; function isFunctionLike(node) { @@ -8679,13 +8277,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 228: - case 151: + case 229: case 152: case 153: case 154: - case 186: + case 155: case 187: + case 188: return true; default: return false; @@ -8693,13 +8291,13 @@ var ts; } function isFunctionLikeKind(kind) { switch (kind) { - case 150: - case 155: + case 151: case 156: case 157: - case 160: - case 273: + case 158: case 161: + case 277: + case 162: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -8712,47 +8310,47 @@ var ts; ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 + return kind === 153 + || kind === 150 + || kind === 152 || kind === 154 - || kind === 157 - || kind === 206 - || kind === 247; + || kind === 155 + || kind === 158 + || kind === 207 + || kind === 248; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); + return node && (node.kind === 230 || node.kind === 200); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); + return node && (node.kind === 154 || node.kind === 155); } ts.isAccessor = isAccessor; function isTypeElement(node) { var kind = node.kind; - return kind === 156 - || kind === 155 - || kind === 148 - || kind === 150 - || kind === 157 - || kind === 247; + return kind === 157 + || kind === 156 + || kind === 149 + || kind === 151 + || kind === 158 + || kind === 248; } ts.isTypeElement = isTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 261 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 + return kind === 265 + || kind === 266 + || kind === 267 + || kind === 152 || kind === 154 - || kind === 247; + || kind === 155 + || kind === 248; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) + return (kind >= 159 && kind <= 174) || kind === 119 || kind === 133 || kind === 134 @@ -8764,7 +8362,14 @@ var ts; || kind === 139 || kind === 95 || kind === 130 - || kind === 201; + || kind === 202 + || kind === 272 + || kind === 273 + || kind === 274 + || kind === 275 + || kind === 276 + || kind === 277 + || kind === 278; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -8772,8 +8377,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 160: case 161: + case 162: return true; } return false; @@ -8782,29 +8387,29 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 175 - || kind === 174; + return kind === 176 + || kind === 175; } return false; } ts.isBindingPattern = isBindingPattern; function isAssignmentPattern(node) { var kind = node.kind; - return kind === 177 - || kind === 178; + return kind === 178 + || kind === 179; } ts.isAssignmentPattern = isAssignmentPattern; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 176 - || kind === 200; + return kind === 177 + || kind === 201; } ts.isArrayBindingElement = isArrayBindingElement; function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 226: - case 146: - case 176: + case 227: + case 147: + case 177: return true; } return false; @@ -8817,8 +8422,8 @@ var ts; ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 174: - case 178: + case 175: + case 179: return true; } return false; @@ -8826,8 +8431,8 @@ var ts; ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 175: - case 177: + case 176: + case 178: return true; } return false; @@ -8835,18 +8440,18 @@ var ts; ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 179 - || kind === 143; + return kind === 180 + || kind === 144; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { + case 252: case 251: - case 250: - case 181: case 182: case 183: - case 147: + case 184: + case 148: return true; default: return false; @@ -8854,12 +8459,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 181 || node.kind === 182; + return node.kind === 182 || node.kind === 183; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 196 + return kind === 197 || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; @@ -8869,31 +8474,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 179: case 180: - case 182: case 181: - case 249: + case 183: + case 182: case 250: - case 183: - case 177: - case 185: + case 251: + case 254: + case 184: case 178: - case 199: case 186: + case 179: + case 200: + case 187: case 71: case 12: case 8: case 9: case 13: - case 196: + case 197: case 86: case 95: case 99: case 101: case 97: - case 203: case 204: + case 205: case 91: return true; default: @@ -8906,13 +8512,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 192: case 193: - case 188: + case 194: case 189: case 190: case 191: - case 184: + case 192: + case 185: return true; default: return isLeftHandSideExpressionKind(kind); @@ -8920,9 +8526,9 @@ var ts; } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 193: + case 194: return true; - case 192: + case 193: return expr.operator === 43 || expr.operator === 44; default: @@ -8936,15 +8542,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 195: - case 197: - case 187: - case 194: + case 196: case 198: - case 202: - case 200: - case 289: - case 288: + case 188: + case 195: + case 199: + case 203: + case 201: + case 293: + case 292: return true; default: return isUnaryExpressionKind(kind); @@ -8952,16 +8558,16 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 184 - || kind === 202; + return kind === 185 + || kind === 203; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 288; + return node.kind === 292; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 287; + return node.kind === 291; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -8971,20 +8577,20 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 214: case 215: case 216: - case 212: + case 217: case 213: + case 214: return true; - case 222: + case 223: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isForInOrOfStatement(node) { - return node.kind === 215 || node.kind === 216; + return node.kind === 216 || node.kind === 217; } ts.isForInOrOfStatement = isForInOrOfStatement; function isConciseBody(node) { @@ -9003,106 +8609,106 @@ var ts; ts.isForInitializer = isForInitializer; function isModuleBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233 + return kind === 235 + || kind === 234 || kind === 71; } ts.isModuleBody = isModuleBody; function isNamespaceBody(node) { var kind = node.kind; - return kind === 234 - || kind === 233; + return kind === 235 + || kind === 234; } ts.isNamespaceBody = isNamespaceBody; function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 - || kind === 233; + || kind === 234; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 241 - || kind === 240; + return kind === 242 + || kind === 241; } ts.isNamedImportBindings = isNamedImportBindings; function isModuleOrEnumDeclaration(node) { - return node.kind === 233 || node.kind === 232; + return node.kind === 234 || node.kind === 233; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 + return kind === 188 + || kind === 177 + || kind === 230 + || kind === 200 + || kind === 153 + || kind === 233 + || kind === 268 + || kind === 247 || kind === 229 - || kind === 199 + || kind === 187 + || kind === 154 + || kind === 240 + || kind === 238 + || kind === 243 + || kind === 231 + || kind === 257 || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 || kind === 151 + || kind === 234 + || kind === 237 + || kind === 241 + || kind === 147 + || kind === 265 || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 283; + || kind === 155 + || kind === 266 + || kind === 232 + || kind === 146 + || kind === 227 + || kind === 288; } function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 + return kind === 229 + || kind === 248 || kind === 230 || kind === 231 || kind === 232 || kind === 233 + || kind === 234 + || kind === 239 || kind === 238 - || kind === 237 + || kind === 245 || kind === 244 - || kind === 243 - || kind === 236; + || kind === 237; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 + return kind === 219 + || kind === 218 + || kind === 226 + || kind === 213 + || kind === 211 + || kind === 210 + || kind === 216 || kind === 217 - || kind === 225 + || kind === 215 || kind === 212 - || kind === 210 + || kind === 223 + || kind === 220 + || kind === 222 + || kind === 224 + || kind === 225 || kind === 209 - || kind === 215 - || kind === 216 || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 287 || kind === 291 - || kind === 290; + || kind === 295 + || kind === 294; } function isDeclaration(node) { - if (node.kind === 145) { - return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + if (node.kind === 146) { + return node.parent.kind !== 287 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -9123,10 +8729,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 207) + if (node.kind !== 208) return false; if (node.parent !== undefined) { - if (node.parent.kind === 224 || node.parent.kind === 260) { + if (node.parent.kind === 225 || node.parent.kind === 264) { return false; } } @@ -9134,8 +8740,8 @@ var ts; } function isModuleReference(node) { var kind = node.kind; - return kind === 248 - || kind === 143 + return kind === 249 + || kind === 144 || kind === 71; } ts.isModuleReference = isModuleReference; @@ -9143,53 +8749,62 @@ var ts; var kind = node.kind; return kind === 99 || kind === 71 - || kind === 179; + || kind === 180; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; + return kind === 250 + || kind === 260 + || kind === 251 + || kind === 10 + || kind === 254; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 253 - || kind === 255; + return kind === 257 + || kind === 259; } ts.isJsxAttributeLike = isJsxAttributeLike; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 - || kind === 256; + || kind === 260; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 251 - || kind === 250; + return kind === 252 + || kind === 251; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 257 - || kind === 258; + return kind === 261 + || kind === 262; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 285; + return node.kind >= 271 && node.kind <= 289; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 275 || isJSDocTag(node); + return node.kind === 279 || isJSDocTag(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 276 && node.kind <= 285; + return node.kind >= 281 && node.kind <= 289; } ts.isJSDocTag = isJSDocTag; + function isSetAccessor(node) { + return node.kind === 155; + } + ts.isSetAccessor = isSetAccessor; + function isGetAccessor(node) { + return node.kind === 154; + } + ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { return !!node.jsDoc && node.jsDoc.length > 0; } @@ -9201,6 +8816,10 @@ var ts; return token >= 71; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 29 || tokenIsIdentifierOrKeyword(token); + } + ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; var textToToken = ts.createMapFromTemplate({ "abstract": 117, "any": 119, @@ -9225,7 +8844,7 @@ var ts; "false": 86, "finally": 87, "for": 88, - "from": 140, + "from": 141, "function": 89, "get": 125, "if": 90, @@ -9250,7 +8869,7 @@ var ts; "public": 114, "readonly": 131, "require": 132, - "global": 141, + "global": 142, "return": 96, "set": 135, "static": 115, @@ -9265,6 +8884,7 @@ var ts; "type": 138, "typeof": 103, "undefined": 139, + "unique": 140, "var": 104, "void": 105, "while": 106, @@ -9272,7 +8892,7 @@ var ts; "yield": 116, "async": 120, "await": 121, - "of": 142, + "of": 143, "{": 17, "}": 18, "(": 19, @@ -9430,7 +9050,7 @@ var ts; } ts.getLineStarts = getLineStarts; function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position); + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); if (lineNumber < 0) { lineNumber = ~lineNumber - 1; ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); @@ -9785,10 +9405,7 @@ var ts; var tokenPos; var token; var tokenValue; - var precedingLineBreak; - var hasExtendedUnicodeEscape; - var tokenIsUnterminated; - var numericLiteralFlags; + var tokenFlags; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -9797,12 +9414,12 @@ var ts; getTokenPos: function () { return tokenPos; }, getTokenText: function () { return text.substring(tokenPos, pos); }, getTokenValue: function () { return tokenValue; }, - hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, - hasPrecedingLineBreak: function () { return precedingLineBreak; }, + hasExtendedUnicodeEscape: function () { return (tokenFlags & 8) !== 0; }, + hasPrecedingLineBreak: function () { return (tokenFlags & 1) !== 0; }, isIdentifier: function () { return token === 71 || token > 107; }, isReservedWord: function () { return token >= 72 && token <= 107; }, - isUnterminated: function () { return tokenIsUnterminated; }, - getNumericLiteralFlags: function () { return numericLiteralFlags; }, + isUnterminated: function () { return (tokenFlags & 4) !== 0; }, + getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, @@ -9839,7 +9456,7 @@ var ts; var end = pos; if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { pos++; - numericLiteralFlags = 2; + tokenFlags |= 16; if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; if (isDigit(text.charCodeAt(pos))) { @@ -9892,8 +9509,8 @@ var ts; } return value; } - function scanString(allowEscapes) { - if (allowEscapes === void 0) { allowEscapes = true; } + function scanString(jsxAttributeString) { + if (jsxAttributeString === void 0) { jsxAttributeString = false; } var quote = text.charCodeAt(pos); pos++; var result = ""; @@ -9901,7 +9518,7 @@ var ts; while (true) { if (pos >= end) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -9911,15 +9528,15 @@ var ts; pos++; break; } - if (ch === 92 && allowEscapes) { + if (ch === 92 && !jsxAttributeString) { result += text.substring(start, pos); result += scanEscapeSequence(); start = pos; continue; } - if (isLineBreak(ch)) { + if (isLineBreak(ch) && !jsxAttributeString) { result += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_string_literal); break; } @@ -9936,7 +9553,7 @@ var ts; while (true) { if (pos >= end) { contents += text.substring(start, pos); - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_template_literal); resultingToken = startedWithBacktick ? 13 : 16; break; @@ -10005,7 +9622,7 @@ var ts; return "\""; case 117: if (pos < end && text.charCodeAt(pos) === 123) { - hasExtendedUnicodeEscape = true; + tokenFlags |= 8; pos++; return scanExtendedUnicodeEscape(); } @@ -10139,10 +9756,7 @@ var ts; } function scan() { startPos = pos; - hasExtendedUnicodeEscape = false; - precedingLineBreak = false; - tokenIsUnterminated = false; - numericLiteralFlags = 0; + tokenFlags = 0; while (true) { tokenPos = pos; if (pos >= end) { @@ -10161,7 +9775,7 @@ var ts; switch (ch) { case 10: case 13: - precedingLineBreak = true; + tokenFlags |= 1; if (skipTrivia) { pos++; continue; @@ -10286,6 +9900,9 @@ var ts; } if (text.charCodeAt(pos + 1) === 42) { pos += 2; + if (text.charCodeAt(pos) === 42 && text.charCodeAt(pos + 1) !== 47) { + tokenFlags |= 2; + } var commentClosed = false; while (pos < end) { var ch_1 = text.charCodeAt(pos); @@ -10295,7 +9912,7 @@ var ts; break; } if (isLineBreak(ch_1)) { - precedingLineBreak = true; + tokenFlags |= 1; } pos++; } @@ -10306,7 +9923,9 @@ var ts; continue; } else { - tokenIsUnterminated = !commentClosed; + if (!commentClosed) { + tokenFlags |= 4; + } return token = 3; } } @@ -10324,7 +9943,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 8; + tokenFlags |= 64; return token = 8; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 || text.charCodeAt(pos + 1) === 98)) { @@ -10335,7 +9954,7 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 16; + tokenFlags |= 128; return token = 8; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 || text.charCodeAt(pos + 1) === 111)) { @@ -10346,12 +9965,12 @@ var ts; value = 0; } tokenValue = "" + value; - numericLiteralFlags = 32; + tokenFlags |= 256; return token = 8; } if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); - numericLiteralFlags = 4; + tokenFlags |= 32; return token = 8; } case 49: @@ -10501,7 +10120,7 @@ var ts; continue; } else if (isLineBreak(ch)) { - precedingLineBreak = true; + tokenFlags |= 1; pos++; continue; } @@ -10540,13 +10159,13 @@ var ts; var inCharacterClass = false; while (true) { if (p >= end) { - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } var ch = text.charCodeAt(p); if (isLineBreak(ch)) { - tokenIsUnterminated = true; + tokenFlags |= 4; error(ts.Diagnostics.Unterminated_regular_expression_literal); break; } @@ -10648,7 +10267,7 @@ var ts; switch (text.charCodeAt(pos)) { case 34: case 39: - tokenValue = scanString(false); + tokenValue = scanString(true); return token = 9; default: return scan(); @@ -10692,6 +10311,12 @@ var ts; case 93: pos++; return token = 22; + case 60: + pos++; + return token = 27; + case 62: + pos++; + return token = 29; case 61: pos++; return token = 58; @@ -10700,13 +10325,24 @@ var ts; return token = 26; case 46: pos++; + if (text.substr(tokenPos, pos + 2) === "...") { + pos += 2; + return token = 24; + } return token = 23; + case 33: + pos++; + return token = 51; + case 63: + pos++; + return token = 55; } - if (isIdentifierStart(ch, 5)) { + if (isIdentifierStart(ch, 6)) { pos++; - while (isIdentifierPart(text.charCodeAt(pos), 5) && pos < end) { + while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } + tokenValue = text.substring(tokenPos, pos); return token = 71; } else { @@ -10719,7 +10355,7 @@ var ts; var saveTokenPos = tokenPos; var saveToken = token; var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; + var saveTokenFlags = tokenFlags; var result = callback(); if (!result || isLookahead) { pos = savePos; @@ -10727,7 +10363,7 @@ var ts; tokenPos = saveTokenPos; token = saveToken; tokenValue = saveTokenValue; - precedingLineBreak = savePrecedingLineBreak; + tokenFlags = saveTokenFlags; } return result; } @@ -10737,10 +10373,8 @@ var ts; var saveStartPos = startPos; var saveTokenPos = tokenPos; var saveToken = token; - var savePrecedingLineBreak = precedingLineBreak; var saveTokenValue = tokenValue; - var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - var saveTokenIsUnterminated = tokenIsUnterminated; + var saveTokenFlags = tokenFlags; setText(text, start, length); var result = callback(); end = saveEnd; @@ -10748,10 +10382,8 @@ var ts; startPos = saveStartPos; tokenPos = saveTokenPos; token = saveToken; - precedingLineBreak = savePrecedingLineBreak; tokenValue = saveTokenValue; - hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; - tokenIsUnterminated = saveTokenIsUnterminated; + tokenFlags = saveTokenFlags; return result; } function lookAhead(callback) { @@ -10783,32 +10415,20 @@ var ts; startPos = textPos; tokenPos = textPos; token = 0; - precedingLineBreak = false; tokenValue = undefined; - hasExtendedUnicodeEscape = false; - tokenIsUnterminated = false; + tokenFlags = 0; } } ts.createScanner = createScanner; })(ts || (ts = {})); var ts; (function (ts) { - var SignatureFlags; - (function (SignatureFlags) { - SignatureFlags[SignatureFlags["None"] = 0] = "None"; - SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; - SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; - SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; - SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; - SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; - SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; - })(SignatureFlags || (SignatureFlags = {})); var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 265) { + if (kind === 269) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71) { @@ -10840,59 +10460,60 @@ var ts; } } function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 142) { + if (!node || node.kind <= 143) { return; } switch (node.kind) { - case 143: + case 144: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 145: + case 146: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 262: + case 266: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 263: + case 267: return visitNode(cbNode, node.expression); - case 146: + case 147: + case 150: case 149: - case 148: - case 261: - case 226: - case 176: + case 265: + case 227: + case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 160: case 161: - case 155: + case 162: case 156: case 157: + case 158: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 151: - case 150: case 152: + case 151: case 153: case 154: - case 186: - case 228: + case 155: case 187: + case 229: + case 188: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -10903,287 +10524,291 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 159: + case 160: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 158: + case 159: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 162: - return visitNode(cbNode, node.exprName); case 163: - return visitNodes(cbNode, cbNodes, node.members); + return visitNode(cbNode, node.exprName); case 164: - return visitNode(cbNode, node.elementType); + return visitNodes(cbNode, cbNodes, node.members); case 165: - return visitNodes(cbNode, cbNodes, node.elementTypes); + return visitNode(cbNode, node.elementType); case 166: + return visitNodes(cbNode, cbNodes, node.elementTypes); case 167: - return visitNodes(cbNode, cbNodes, node.types); case 168: - case 170: - return visitNode(cbNode, node.type); + return visitNodes(cbNode, cbNodes, node.types); + case 169: case 171: + return visitNode(cbNode, node.type); + case 172: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 172: + case 173: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 173: - return visitNode(cbNode, node.literal); case 174: + return visitNode(cbNode, node.literal); case 175: - return visitNodes(cbNode, cbNodes, node.elements); - case 177: + case 176: return visitNodes(cbNode, cbNodes, node.elements); case 178: - return visitNodes(cbNode, cbNodes, node.properties); + return visitNodes(cbNode, cbNodes, node.elements); case 179: + return visitNodes(cbNode, cbNodes, node.properties); + case 180: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 180: + case 181: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 181: case 182: + case 183: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 183: + case 184: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 184: + case 185: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.expression); - case 188: + case 186: return visitNode(cbNode, node.expression); case 189: return visitNode(cbNode, node.expression); case 190: return visitNode(cbNode, node.expression); - case 192: - return visitNode(cbNode, node.operand); - case 197: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 191: return visitNode(cbNode, node.expression); case 193: return visitNode(cbNode, node.operand); + case 198: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.expression); case 194: + return visitNode(cbNode, node.operand); + case 195: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 202: + case 203: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 203: - return visitNode(cbNode, node.expression); case 204: + return visitNode(cbNode, node.expression); + case 205: return visitNode(cbNode, node.name); - case 195: + case 196: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 198: + case 199: return visitNode(cbNode, node.expression); - case 207: - case 234: + case 208: + case 235: return visitNodes(cbNode, cbNodes, node.statements); - case 265: + case 269: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 208: + case 209: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 227: + case 228: return visitNodes(cbNode, cbNodes, node.declarations); - case 210: - return visitNode(cbNode, node.expression); case 211: + return visitNode(cbNode, node.expression); + case 212: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 212: + case 213: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 213: + case 214: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 214: + case 215: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 215: + case 216: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 216: + case 217: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 217: case 218: - return visitNode(cbNode, node.label); case 219: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.label); case 220: + return visitNode(cbNode, node.expression); + case 221: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221: + case 222: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 235: + case 236: return visitNodes(cbNode, cbNodes, node.clauses); - case 257: + case 261: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 258: + case 262: return visitNodes(cbNode, cbNodes, node.statements); - case 222: + case 223: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 223: - return visitNode(cbNode, node.expression); case 224: + return visitNode(cbNode, node.expression); + case 225: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 260: + case 264: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 147: + case 148: return visitNode(cbNode, node.expression); - case 229: - case 199: + case 230: + case 200: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 230: + case 231: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 231: + case 232: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 232: + case 233: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 264: + case 268: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 233: + case 234: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 237: + case 238: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 238: + case 239: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 239: + case 240: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 236: - return visitNode(cbNode, node.name); - case 240: + case 237: return visitNode(cbNode, node.name); case 241: - case 245: + return visitNode(cbNode, node.name); + case 242: + case 246: return visitNodes(cbNode, cbNodes, node.elements); - case 244: + case 245: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: + case 243: + case 247: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 243: + case 244: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 196: + case 197: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 205: + case 206: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: + case 145: return visitNode(cbNode, node.expression); - case 259: + case 263: return visitNodes(cbNode, cbNodes, node.types); - case 201: + case 202: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 248: + case 249: return visitNode(cbNode, node.expression); - case 247: + case 248: return visitNodes(cbNode, cbNodes, node.decorators); - case 289: + case 293: return visitNodes(cbNode, cbNodes, node.elements); - case 249: + case 250: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 250: + case 254: + return visitNode(cbNode, node.openingFragment) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingFragment); case 251: + case 252: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.attributes); - case 254: + case 258: return visitNodes(cbNode, cbNodes, node.properties); - case 253: + case 257: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 255: + case 259: return visitNode(cbNode, node.expression); - case 256: + case 260: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 252: + case 253: return visitNode(cbNode, node.tagName); - case 267: - return visitNode(cbNode, node.type); case 271: return visitNode(cbNode, node.type); - case 270: + case 275: + return visitNode(cbNode, node.type); + case 274: return visitNode(cbNode, node.type); - case 272: + case 276: return visitNode(cbNode, node.type); - case 273: + case 277: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 274: + case 278: return visitNode(cbNode, node.type); - case 275: - return visitNodes(cbNode, cbNodes, node.tags); case 279: + return visitNodes(cbNode, cbNodes, node.tags); case 284: + case 289: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -11192,17 +10817,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 280: - return visitNode(cbNode, node.typeExpression); - case 281: + case 285: return visitNode(cbNode, node.typeExpression); - case 277: + case 286: return visitNode(cbNode, node.typeExpression); case 282: + return visitNode(cbNode, node.class); + case 287: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 283: + case 288: if (node.typeExpression && - node.typeExpression.kind === 267) { + node.typeExpression.kind === 271) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -11210,7 +10835,7 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 285: + case 280: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -11218,7 +10843,7 @@ var ts; } } return; - case 288: + case 292: return visitNode(cbNode, node.expression); } } @@ -11264,7 +10889,7 @@ var ts; ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; var Parser; (function (Parser) { - var scanner = ts.createScanner(5, true); + var scanner = ts.createScanner(6, true); var disallowInAndDecoratorContext = 2048 | 8192; var NodeConstructor; var TokenConstructor; @@ -11300,7 +10925,7 @@ var ts; Parser.parseIsolatedEntityName = parseIsolatedEntityName; function parseJsonText(fileName, sourceText) { initializeState(sourceText, 2, undefined, 6); - sourceFile = createSourceFile(fileName, 2, 6); + sourceFile = createSourceFile(fileName, 2, 6, false); var result = sourceFile; nextToken(); if (token() === 1) { @@ -11334,7 +10959,16 @@ var ts; identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + switch (scriptKind) { + case 1: + case 2: + case 6: + contextFlags = 65536; + break; + default: + contextFlags = 0; + break; + } parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); @@ -11351,7 +10985,11 @@ var ts; sourceText = undefined; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + var isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 2097152; + } + sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; nextToken(); processReferenceComments(sourceFile); @@ -11374,13 +11012,14 @@ var ts; for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; + if (jsDoc) { + if (!node.jsDoc) { + node.jsDoc = [jsDoc]; + } + else { + node.jsDoc.push(jsDoc); + } } - node.jsDoc.push(jsDoc); } } return node; @@ -11408,15 +11047,15 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { + var sourceFile = new SourceFileConstructor(269, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.isDeclarationFile = isDeclarationFile; sourceFile.scriptKind = scriptKind; return sourceFile; } @@ -11630,12 +11269,17 @@ var ts; } function createNode(kind, pos) { nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); + var p = pos >= 0 ? pos : scanner.getStartPos(); + return ts.isNodeKind(kind) || kind === 0 ? new NodeConstructor(kind, p, p) : + kind === 71 ? new IdentifierConstructor(kind, p, p) : + new TokenConstructor(kind, p, p); + } + function createNodeWithJSDoc(kind) { + var node = createNode(kind); + if (scanner.getTokenFlags() & 2) { + addJSDocComment(node); } - return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return node; } function createNodeArray(elements, pos, end) { var length = elements.length; @@ -11662,7 +11306,7 @@ var ts; else { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); + var result = createNode(kind); if (kind === 71) { result.escapedText = ""; } @@ -11695,8 +11339,8 @@ var ts; function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage); } function isLiteralPropertyName() { return ts.tokenIsIdentifierOrKeyword(token()) || @@ -11718,7 +11362,7 @@ var ts; return parsePropertyNameWorker(true); } function parseComputedPropertyName() { - var node = createNode(144); + var node = createNode(145); parseExpected(21); node.expression = allowInAnd(parseExpression); parseExpected(22); @@ -11846,6 +11490,10 @@ var ts; nextToken(); return ts.tokenIsIdentifierOrKeyword(token()); } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } function isHeritageClauseExtendsOrImplementsKeyword() { if (token() === 108 || token() === 85) { @@ -11962,7 +11610,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.flags & 96256; + var nodeContextFlags = node.flags & 6387712; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -12011,14 +11659,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 152: - case 157: case 153: + case 158: case 154: - case 149: - case 206: + case 155: + case 150: + case 207: return true; - case 151: + case 152: var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 71 && methodDeclaration.name.originalKeywordKind === 123; @@ -12030,8 +11678,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 257: - case 258: + case 261: + case 262: return true; } } @@ -12040,65 +11688,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 228: + case 229: + case 209: case 208: - case 207: + case 212: case 211: - case 210: - case 223: + case 224: + case 220: + case 222: case 219: - case 221: case 218: + case 216: case 217: case 215: - case 216: case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: + case 221: + case 210: case 225: + case 223: + case 213: + case 226: + case 239: case 238: - case 237: + case 245: case 244: - case 243: - case 233: - case 229: + case 234: case 230: - case 232: case 231: + case 233: + case 232: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 264; + return node.kind === 268; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 156: - case 150: case 157: - case 148: - case 155: + case 151: + case 158: + case 149: + case 156: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { + if (node.kind !== 227) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 146) { + if (node.kind !== 147) { return false; } var parameter = node; @@ -12192,7 +11840,7 @@ var ts; return createMissingList(); } function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); var dotPos = scanner.getStartPos(); while (parseOptional(23)) { if (token() === 27) { @@ -12205,7 +11853,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(143, entity.pos); + var node = createNode(144, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -12220,7 +11868,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(196); + var template = createNode(197); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); var list = []; @@ -12232,7 +11880,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(205); + var span = createNode(206); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18) { @@ -12269,15 +11917,15 @@ var ts; node.isUnterminated = true; } if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + node.numericLiteralFlags = scanner.getTokenFlags() & 496; } nextToken(); finishNode(node); return node; } function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + var node = createNode(160); + node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27) { node.typeArguments = parseBracketedList(19, parseType, 27, 29); } @@ -12285,18 +11933,18 @@ var ts; } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(158, lhs.pos); + var node = createNode(159, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(169); + var node = createNode(170); nextToken(); return finishNode(node); } function parseJSDocAllType() { - var result = createNode(268); + var result = createNode(272); nextToken(); return finishNode(result); } @@ -12309,28 +11957,28 @@ var ts; token() === 29 || token() === 58 || token() === 49) { - var result = createNode(269, pos); + var result = createNode(273, pos); return finishNode(result); } else { - var result = createNode(270, pos); + var result = createNode(274, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNode(273); + var result = createNodeWithJSDoc(277); nextToken(); fillSignature(56, 4 | 32, result); - return addJSDocComment(finishNode(result)); + return finishNode(result); } - var node = createNode(159); + var node = createNode(160); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(146); + var parameter = createNode(147); if (token() === 99 || token() === 94) { parameter.name = parseIdentifierName(); parseExpected(56); @@ -12341,17 +11989,17 @@ var ts; function parseJSDocNodeWithType(kind) { var result = createNode(kind); nextToken(); - result.type = parseType(); + result.type = parseNonArrayType(); return finishNode(result); } function parseTypeQuery() { - var node = createNode(162); + var node = createNode(163); parseExpected(103); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(145); + var node = createNode(146); node.name = parseIdentifier(); if (parseOptional(85)) { if (isStartOfType() || !isStartOfExpression()) { @@ -12384,8 +12032,8 @@ var ts; token() === 57 || isStartOfType(true); } - function parseParameter(requireEqualsToken) { - var node = createNode(146); + function parseParameter() { + var node = createNodeWithJSDoc(147); if (token() === 99) { node.name = createIdentifier(true); node.type = parseParameterType(); @@ -12400,8 +12048,8 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseInitializer(true, requireEqualsToken); - return addJSDocComment(finishNode(node)); + node.initializer = parseInitializer(); + return finishNode(node); } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { @@ -12434,7 +12082,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -12451,19 +12099,16 @@ var ts; parseSemicolon(); } function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { + var node = createNodeWithJSDoc(kind); + if (kind === 157) { parseExpected(94); } fillSignature(56, 4, node); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); + return token() === 21 && lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); @@ -12491,39 +12136,29 @@ var ts; nextToken(); return token() === 56 || token() === 26 || token() === 22; } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseIndexSignatureDeclaration(node) { + node.kind = 158; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); + function parsePropertyOrMethodSignature(node) { + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, 4, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); + node.kind = 151; + fillSignature(56, 4, node); } else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); + node.kind = 149; + node.type = parseTypeAnnotation(); if (token() === 58) { - property.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); } + parseTypeMemberSemicolon(); + return finishNode(node); } function isTypeMemberStart() { if (token() === 19 || token() === 27) { @@ -12553,24 +12188,24 @@ var ts; } function parseTypeMember() { if (token() === 19 || token() === 27) { - return parseSignatureMember(155); + return parseSignatureMember(156); } if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(156); + return parseSignatureMember(157); } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0); + node.modifiers = parseModifiers(); if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + return parseIndexSignatureDeclaration(node); } - return parsePropertyOrMethodSignature(fullStart, modifiers); + return parsePropertyOrMethodSignature(node); } function nextTokenIsOpenParenOrLessThan() { nextToken(); return token() === 19 || token() === 27; } function parseTypeLiteral() { - var node = createNode(163); + var node = createNode(164); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -12593,14 +12228,14 @@ var ts; return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; } function parseMappedTypeParameter() { - var node = createNode(145); + var node = createNode(146); node.name = parseIdentifier(); parseExpected(92); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(172); + var node = createNode(173); parseExpected(17); node.readonlyToken = parseOptionalToken(131); parseExpected(21); @@ -12613,34 +12248,34 @@ var ts; return finishNode(node); } function parseTupleType() { - var node = createNode(165); + var node = createNode(166); node.elementTypes = parseBracketedList(20, parseType, 21, 22); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(168); + var node = createNode(169); parseExpected(19); node.type = parseType(); parseExpected(20); return finishNode(node); } function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { + var node = createNodeWithJSDoc(kind); + if (kind === 162) { parseExpected(94); } fillSignature(36, 4, node); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseKeywordAndNoDot() { var node = parseTokenNode(); return token() === 23 ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(173); + var node = createNode(174); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(192); + unaryMinusExpression = createNode(193); unaryMinusExpression.operator = 38; nextToken(); } @@ -12663,8 +12298,8 @@ var ts; case 119: case 136: case 133: - case 122: case 137: + case 122: case 139: case 130: case 134: @@ -12675,10 +12310,8 @@ var ts; return parseJSDocUnknownOrNullableType(); case 89: return parseJSDocFunctionType(); - case 24: - return parseJSDocNodeWithType(274); case 51: - return parseJSDocNodeWithType(271); + return parseJSDocNodeWithType(275); case 13: case 9: case 8: @@ -12718,6 +12351,7 @@ var ts; case 133: case 122: case 137: + case 140: case 105: case 139: case 95: @@ -12752,58 +12386,71 @@ var ts; nextToken(); return token() === 20 || isStartOfParameter() || isStartOfType(); } - function parseJSDocPostfixTypeOrHigher() { + function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); - var kind = getKind(token()); - if (!kind) - return type; - nextToken(); - var postfix = createNode(kind, type.pos); - postfix.type = type; - return finishNode(postfix); - function getKind(tokenKind) { - switch (tokenKind) { + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { case 58: - return contextFlags & 1048576 ? 272 : undefined; + if (!(contextFlags & 1048576)) { + return type; + } + type = createJSDocPostfixType(276, type); + break; case 51: - return 271; + type = createJSDocPostfixType(275, type); + break; case 55: - return 270; - } - } - } - function parseArrayTypeOrHigher() { - var type = parseJSDocPostfixTypeOrHigher(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); + type = createJSDocPostfixType(274, type); + break; + case 21: + parseExpected(21); + if (isStartOfType()) { + var node = createNode(172, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(165, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + break; + default: + return type; } } return type; } + function createJSDocPostfixType(kind, type) { + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + } function parseTypeOperator(operator) { - var node = createNode(170); + var node = createNode(171); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseTypeOperatorOrHigher() { - switch (token()) { + var operator = token(); + switch (operator) { case 127: - return parseTypeOperator(127); + case 140: + return parseTypeOperator(operator); + case 24: { + var result = createNode(278); + nextToken(); + result.type = parsePostfixTypeOrHigher(); + return finishNode(result); + } } - return parseArrayTypeOrHigher(); + return parsePostfixTypeOrHigher(); } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { parseOptional(operator); @@ -12820,10 +12467,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + return parseUnionOrIntersectionType(168, parseTypeOperatorOrHigher, 48); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + return parseUnionOrIntersectionType(167, parseIntersectionTypeOrHigher, 49); } function isStartOfFunctionType() { if (token() === 27) { @@ -12869,7 +12516,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); + var node = createNode(159, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -12890,10 +12537,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); + return parseFunctionOrConstructorType(161); } if (token() === 94) { - return parseFunctionOrConstructorType(161); + return parseFunctionOrConstructorType(162); } return parseUnionTypeOrHigher(); } @@ -12974,19 +12621,8 @@ var ts; } return expr; } - function parseInitializer(inParameter, requireEqualsToken) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - if (inParameter && requireEqualsToken) { - var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); - result.escapedText = "= not found"; - return result; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); + function parseInitializer() { + return parseOptional(58) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { if (isYieldExpression()) { @@ -13019,7 +12655,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(197); + var node = createNode(198); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 39 || isStartOfExpression())) { @@ -13035,13 +12671,13 @@ var ts; ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(187, asyncModifier.pos); + node = createNode(188, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(187, identifier.pos); + node = createNode(188, identifier.pos); } - var parameter = createNode(146, identifier.pos); + var parameter = createNode(147, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -13066,7 +12702,7 @@ var ts; arrowFunction.body = (lastToken === 36 || lastToken === 17) ? parseArrowFunctionExpressionBody(isAsync) : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); + return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { if (token() === 19 || token() === 27 || token() === 120) { @@ -13107,13 +12743,27 @@ var ts; if (second === 24) { return 1; } + if (ts.isModifierKind(second) && second !== 120 && lookAhead(nextTokenIsIdentifier)) { + return 1; + } if (!isIdentifier()) { return 0; } - if (nextToken() === 56) { - return 1; + switch (nextToken()) { + case 56: + return 1; + case 55: + nextToken(); + if (token() === 56 || token() === 26 || token() === 58 || token() === 20) { + return 1; + } + return 0; + case 26: + case 58: + case 20: + return 2; } - return 2; + return 0; } else { ts.Debug.assert(first === 27); @@ -13173,15 +12823,14 @@ var ts; return 0; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); + var node = createNodeWithJSDoc(188); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); if (!node.parameters) { return undefined; } - if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || - ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { + if (!allowAmbiguity && token() !== 36 && token() !== 17) { return undefined; } return node; @@ -13206,7 +12855,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(195, leftOperand.pos); + var node = createNode(196, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -13219,7 +12868,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 || t === 142; + return t === 92 || t === 143; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -13297,39 +12946,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); + var node = createNode(195, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(202, left.pos); + var node = createNode(203, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(192); + var node = createNode(193); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(188); + var node = createNode(189); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(189); + var node = createNode(190); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(190); + var node = createNode(191); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -13344,7 +12993,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(191); + var node = createNode(192); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -13360,7 +13009,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { + if (simpleUnaryExpression.kind === 185) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -13413,19 +13062,19 @@ var ts; } function parseUpdateExpression() { if (token() === 43 || token() === 44) { - var node = createNode(192); + var node = createNode(193); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + return parseJsxElementOrSelfClosingElementOrFragment(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); + var node = createNode(194, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -13453,7 +13102,7 @@ var ts; if (token() === 19 || token() === 23 || token() === 21) { return expression; } - var node = createNode(179, expression.pos); + var node = createNode(180, expression.pos); node.expression = expression; parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); @@ -13472,28 +13121,35 @@ var ts; return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); + if (opening.kind === 252) { + var node = createNode(250, opening.pos); node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); + node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } + else if (opening.kind === 255) { + var node = createNode(254, opening.pos); + node.openingFragment = opening; + node.children = parseJsxChildren(node.openingFragment); + node.closingFragment = parseJsxClosingFragment(inExpressionContext); + result = finishNode(node); + } else { - ts.Debug.assert(opening.kind === 250); + ts.Debug.assert(opening.kind === 251); result = opening; } if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); + var badNode = createNode(195, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -13505,7 +13161,7 @@ var ts; return result; } function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); + var node = createNode(10); node.containsOnlyWhiteSpaces = currentToken === 11; currentToken = scanner.scanJsxToken(); return finishNode(node); @@ -13518,11 +13174,11 @@ var ts; case 17: return parseJsxExpression(false); case 27: - return parseJsxElementOrSelfClosingElement(false); + return parseJsxElementOrSelfClosingElementOrFragment(false); } ts.Debug.fail("Unknown JSX child kind " + token()); } - function parseJsxChildren(openingTagName) { + function parseJsxChildren(openingTag) { var list = []; var listPos = getNodePos(); var saveParsingContext = parsingContext; @@ -13533,7 +13189,13 @@ var ts; break; } else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + var openingTagName = openingTag.tagName; + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + } break; } else if (token() === 7) { @@ -13548,18 +13210,23 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(254); + var jsxAttributes = createNode(258); jsxAttributes.properties = parseList(13, parseJsxAttribute); return finishNode(jsxAttributes); } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { var fullStart = scanner.getStartPos(); parseExpected(27); + if (token() === 29) { + parseExpected(29); + var node_1 = createNode(255, fullStart); + return finishNode(node_1); + } var tagName = parseJsxElementName(); var attributes = parseJsxAttributes(); var node; if (token() === 29) { - node = createNode(251, fullStart); + node = createNode(252, fullStart); scanJsxText(); } else { @@ -13571,7 +13238,7 @@ var ts; parseExpected(29, undefined, false); scanJsxText(); } - node = createNode(250, fullStart); + node = createNode(251, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -13582,7 +13249,7 @@ var ts; var expression = token() === 99 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -13590,7 +13257,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(256); + var node = createNode(260); parseExpected(17); if (token() !== 18) { node.dotDotDotToken = parseOptionalToken(24); @@ -13610,7 +13277,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(253); + var node = createNode(257); node.name = parseIdentifierName(); if (token() === 58) { switch (scanJsxAttributeValue()) { @@ -13625,7 +13292,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(255); + var node = createNode(259); parseExpected(17); parseExpected(24); node.expression = parseExpression(); @@ -13633,7 +13300,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); + var node = createNode(253); parseExpected(28); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -13645,8 +13312,24 @@ var ts; } return finishNode(node); } + function parseJsxClosingFragment(inExpressionContext) { + var node = createNode(256); + parseExpected(28); + if (ts.tokenIsIdentifierOrKeyword(token())) { + var unexpectedTagName = parseJsxElementName(); + parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + } + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } function parseTypeAssertion() { - var node = createNode(184); + var node = createNode(185); parseExpected(27); node.type = parseType(); parseExpected(29); @@ -13657,7 +13340,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23); if (dotToken) { - var propertyAccess = createNode(179, expression.pos); + var propertyAccess = createNode(180, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); @@ -13665,13 +13348,13 @@ var ts; } if (token() === 51 && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(203, expression.pos); + var nonNullExpression = createNode(204, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); + var indexedAccess = createNode(181, expression.pos); indexedAccess.expression = expression; if (token() !== 22) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -13685,7 +13368,7 @@ var ts; continue; } if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); + var tagExpression = createNode(184, expression.pos); tagExpression.tag = expression; tagExpression.template = token() === 13 ? parseLiteralNode() @@ -13704,7 +13387,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -13712,7 +13395,7 @@ var ts; continue; } else if (token() === 19) { - var callExpr = createNode(181, expression.pos); + var callExpr = createNode(182, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -13807,28 +13490,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(185); + var node = createNodeWithJSDoc(186); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseSpreadElement() { - var node = createNode(198); + var node = createNode(199); parseExpected(24); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : + token() === 26 ? createNode(201) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(177); + var node = createNode(178); parseExpected(21); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -13837,60 +13520,46 @@ var ts; parseExpected(22); return finishNode(node); } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + function parseObjectLiteralElement() { + var node = createNodeWithJSDoc(0); + if (parseOptionalToken(24)) { + node.kind = 267; + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(node, 154); } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + if (parseContextualModifier(135)) { + return parseAccessorDeclaration(node, 155); } var asteriskToken = parseOptionalToken(39); var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + return parseMethodDeclaration(node, asteriskToken); } var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; + node.kind = 266; var equalsToken = parseOptionalToken(58); if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + node.equalsToken = equalsToken; + node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; + node.kind = 265; parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); + node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } + return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(178); + var node = createNode(179); parseExpected(17); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -13904,7 +13573,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(186); + var node = createNodeWithJSDoc(187); node.modifiers = parseModifiers(); parseExpected(89); node.asteriskToken = parseOptionalToken(39); @@ -13920,7 +13589,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(true); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; @@ -13929,12 +13598,12 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(94); if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); + var node_2 = createNode(205, fullStart); + node_2.keywordToken = 94; + node_2.name = parseIdentifierName(); + return finishNode(node_2); } - var node = createNode(182, fullStart); + var node = createNode(183, fullStart); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); if (node.typeArguments || token() === 19) { @@ -13943,7 +13612,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); + var node = createNode(208); if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -13974,12 +13643,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(209); + var node = createNode(210); parseExpected(25); return finishNode(node); } function parseIfStatement() { - var node = createNode(211); + var node = createNode(212); parseExpected(90); parseExpected(19); node.expression = allowInAnd(parseExpression); @@ -13989,7 +13658,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(212); + var node = createNode(213); parseExpected(81); node.statement = parseStatement(); parseExpected(106); @@ -14000,7 +13669,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(213); + var node = createNode(214); parseExpected(106); parseExpected(19); node.expression = allowInAnd(parseExpression); @@ -14023,8 +13692,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); + if (awaitToken ? parseExpected(143) : parseOptional(143)) { + var forOfStatement = createNode(217, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -14032,14 +13701,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); + var forInStatement = createNode(216, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(214, pos); + var forStatement = createNode(215, pos); forStatement.initializer = initializer; parseExpected(25); if (token() !== 25 && token() !== 20) { @@ -14057,7 +13726,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); + parseExpected(kind === 219 ? 72 : 77); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -14065,7 +13734,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(219); + var node = createNode(220); parseExpected(96); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -14074,16 +13743,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(220); + var node = createNode(221); parseExpected(107); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - node.statement = parseStatement(); + node.statement = doInsideOfContext(4194304, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(257); + var node = createNode(261); parseExpected(73); node.expression = allowInAnd(parseExpression); parseExpected(56); @@ -14091,7 +13760,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(258); + var node = createNode(262); parseExpected(79); parseExpected(56); node.statements = parseList(3, parseStatement); @@ -14101,12 +13770,12 @@ var ts; return token() === 73 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(221); + var node = createNode(222); parseExpected(98); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); + var caseBlock = createNode(236); parseExpected(17); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(18); @@ -14114,14 +13783,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(223); + var node = createNode(224); parseExpected(100); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(224); + var node = createNode(225); parseExpected(102); node.tryBlock = parseBlock(false); node.catchClause = token() === 74 ? parseCatchClause() : undefined; @@ -14132,7 +13801,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(260); + var result = createNode(264); parseExpected(74); if (parseOptional(19)) { result.variableDeclaration = parseVariableDeclaration(); @@ -14145,26 +13814,25 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(225); + var node = createNode(226); parseExpected(78); parseSemicolon(); return finishNode(node); } function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); + var node = createNodeWithJSDoc(0); var expression = allowInAnd(parseExpression); if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); + node.kind = 223; + node.label = expression; + node.statement = parseStatement(); } else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; + node.kind = 211; + node.expression = expression; parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); } + return finishNode(node); } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); @@ -14210,7 +13878,7 @@ var ts; return false; } continue; - case 141: + case 142: nextToken(); return token() === 17 || token() === 71 || token() === 84; case 91: @@ -14272,7 +13940,7 @@ var ts; case 128: case 129: case 138: - case 141: + case 142: return true; case 114: case 112: @@ -14298,16 +13966,16 @@ var ts; case 17: return parseBlock(false); case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227)); case 110: if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + return parseVariableStatement(createNodeWithJSDoc(227)); } break; case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + return parseFunctionDeclaration(createNodeWithJSDoc(229)); case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + return parseClassDeclaration(createNodeWithJSDoc(230)); case 90: return parseIfStatement(); case 81: @@ -14317,9 +13985,9 @@ var ts; case 88: return parseForOrForInOrForOfStatement(); case 77: - return parseBreakOrContinueStatement(217); - case 72: return parseBreakOrContinueStatement(218); + case 72: + return parseBreakOrContinueStatement(219); case 96: return parseReturnStatement(); case 107: @@ -14352,7 +14020,7 @@ var ts; case 117: case 115: case 131: - case 141: + case 142: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -14360,49 +14028,64 @@ var ts; } return parseExpressionOrLabeledStatement(); } + function isDeclareModifier(modifier) { + return modifier.kind === 124; + } function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + if (ts.some(node.modifiers, isDeclareModifier)) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var m = _a[_i]; + m.flags |= 2097152; + } + return doInsideOfContext(2097152, function () { return parseDeclarationWorker(node); }); + } + else { + return parseDeclarationWorker(node); + } + } + function parseDeclarationWorker(node) { switch (token()) { case 104: case 110: case 76: - return parseVariableStatement(fullStart, decorators, modifiers); + return parseVariableStatement(node); case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); + return parseFunctionDeclaration(node); case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); + return parseClassDeclaration(node); case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); + return parseInterfaceDeclaration(node); case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + return parseTypeAliasDeclaration(node); case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: + return parseEnumDeclaration(node); + case 142: case 128: case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); + return parseModuleDeclaration(node); case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + return parseImportDeclarationOrImportEqualsDeclaration(node); case 84: nextToken(); switch (token()) { case 79: case 58: - return parseExportAssignment(fullStart, decorators, modifiers); + return parseExportAssignment(node); case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + return parseNamespaceExportDeclaration(node); default: - return parseExportDeclaration(fullStart, decorators, modifiers); + return parseExportDeclaration(node); } default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); + if (node.decorators || node.modifiers) { + var missing = createMissingNode(248, true, ts.Diagnostics.Declaration_expected); + missing.pos = node.pos; + missing.decorators = node.decorators; + missing.modifiers = node.modifiers; + return finishNode(missing); } } } @@ -14419,16 +14102,16 @@ var ts; } function parseArrayBindingElement() { if (token() === 26) { - return createNode(200); + return createNode(201); } - var node = createNode(176); + var node = createNode(177); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(176); + var node = createNode(177); node.dotDotDotToken = parseOptionalToken(24); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -14440,18 +14123,18 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseInitializer(false); + node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(174); + var node = createNode(175); parseExpected(17); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(18); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(175); + var node = createNode(176); parseExpected(21); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(22); @@ -14469,17 +14152,24 @@ var ts; } return parseIdentifier(); } - function parseVariableDeclaration() { - var node = createNode(226); + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration(true); + } + function parseVariableDeclaration(allowExclamation) { + var node = createNode(227); node.name = parseIdentifierOrPattern(); + if (allowExclamation && node.name.kind === 71 && + token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseNonParameterInitializer(); + node.initializer = parseInitializer(); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); + var node = createNode(228); switch (token()) { case 104: break; @@ -14493,13 +14183,13 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 143 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); + node.declarations = parseDelimitedList(8, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -14507,18 +14197,14 @@ var ts; function canFollowContextualOfKeyword() { return nextTokenIsIdentifier() && nextToken() === 20; } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseVariableStatement(node) { + node.kind = 209; node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseFunctionDeclaration(node) { + node.kind = 229; parseExpected(89); node.asteriskToken = parseOptionalToken(39); node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); @@ -14526,65 +14212,51 @@ var ts; var isAsync = ts.hasModifier(node, 256) ? 2 : 0; fillSignature(56, isGenerator | isAsync, node); node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; + function parseConstructorDeclaration(node) { + node.kind = 153; parseExpected(123); fillSignature(56, 0, node); node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; + function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { + node.kind = 152; + node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 : 0; - var isAsync = ts.hasModifier(method, 256) ? 2 : 0; - fillSignature(56, isGenerator | isAsync, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return finishNode(node); + } + function parsePropertyDeclaration(node) { + node.kind = 150; + if (!node.questionToken && token() === 51 && !scanner.hasPrecedingLineBreak()) { + node.exclamationToken = parseTokenNode(); + } + node.type = parseTypeAnnotation(); + node.initializer = ts.hasModifier(node, 32) + ? allowInAnd(parseInitializer) + : doOutsideOfContext(4096 | 2048, parseInitializer); parseSemicolon(); - return addJSDocComment(finishNode(property)); + return finishNode(node); } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + function parsePropertyOrMethodDeclaration(node) { var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); + node.name = parsePropertyName(); + node.questionToken = parseOptionalToken(55); if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected); } + return parsePropertyDeclaration(node); } - function parseNonParameterInitializer() { - return parseInitializer(false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseAccessorDeclaration(node, kind) { + node.kind = kind; node.name = parsePropertyName(); fillSignature(56, 0, node); node.body = parseFunctionBlockOrSemicolon(0); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function isClassMemberModifier(idToken) { switch (idToken) { @@ -14645,7 +14317,7 @@ var ts; if (!parseOptional(57)) { break; } - var decorator = createNode(147, decoratorStart); + var decorator = createNode(148, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -14686,46 +14358,46 @@ var ts; } function parseClassElement() { if (token() === 25) { - var result = createNode(206); + var result = createNode(207); nextToken(); return finishNode(result); } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; + var node = createNodeWithJSDoc(0); + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(true); + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(node, 154); + } + if (parseContextualModifier(135)) { + return parseAccessorDeclaration(node, 155); } if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); + return parseConstructorDeclaration(node); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + return parseIndexSignatureDeclaration(node); } if (ts.tokenIsIdentifierOrKeyword(token()) || token() === 9 || token() === 8 || token() === 39 || token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + return parsePropertyOrMethodDeclaration(node); } - if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + if (node.decorators || node.modifiers) { + node.name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(node); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0), 200); } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + function parseClassDeclaration(node) { + return parseClassDeclarationOrExpression(node, 230); } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseClassDeclarationOrExpression(node, kind) { + node.kind = kind; parseExpected(75); node.name = parseNameOfClassDeclarationOrExpression(); node.typeParameters = parseTypeParameters(); @@ -14737,7 +14409,7 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseNameOfClassDeclarationOrExpression() { return isIdentifier() && !isImplementsClause() @@ -14756,7 +14428,7 @@ var ts; function parseHeritageClause() { var tok = token(); if (tok === 85 || tok === 108) { - var node = createNode(259); + var node = createNode(263); node.token = tok; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -14765,52 +14437,49 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(201); + var node = createNode(202); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } + node.typeArguments = tryParseTypeArguments(); return finishNode(node); } + function tryParseTypeArguments() { + return token() === 27 + ? parseBracketedList(19, parseType, 27, 29) + : undefined; + } function isHeritageClause() { return token() === 85 || token() === 108; } function parseClassMembers() { return parseList(5, parseClassElement); } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseInterfaceDeclaration(node) { + node.kind = 231; parseExpected(109); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); node.heritageClauses = parseHeritageClauses(); node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseTypeAliasDeclaration(node) { + node.kind = 232; parseExpected(138); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(58); node.type = parseType(); parseSemicolon(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); + var node = createNodeWithJSDoc(268); node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); + node.initializer = allowInAnd(parseInitializer); + return finishNode(node); } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseEnumDeclaration(node) { + node.kind = 233; parseExpected(83); node.name = parseIdentifier(); if (parseExpected(17)) { @@ -14820,10 +14489,10 @@ var ts; else { node.members = createMissingList(); } - return addJSDocComment(finishNode(node)); + return finishNode(node); } function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); + var node = createNode(235); if (parseExpected(17)) { node.statements = parseList(1, parseStatement); parseExpected(18); @@ -14833,23 +14502,19 @@ var ts; } return finishNode(node); } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); + function parseModuleOrNamespaceDeclaration(node, flags) { + node.kind = 234; var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(createNode(0), 4 | namespaceFlag) : parseModuleBlock(); - return addJSDocComment(finishNode(node)); + return finishNode(node); } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { + function parseAmbientExternalModuleDeclaration(node) { + node.kind = 234; + if (token() === 142) { node.name = parseIdentifier(); node.flags |= 512; } @@ -14865,10 +14530,10 @@ var ts; } return finishNode(node); } - function parseModuleDeclaration(fullStart, decorators, modifiers) { + function parseModuleDeclaration(node) { var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + if (token() === 142) { + return parseAmbientExternalModuleDeclaration(node); } else if (parseOptional(129)) { flags |= 16; @@ -14876,10 +14541,10 @@ var ts; else { parseExpected(128); if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + return parseAmbientExternalModuleDeclaration(node); } } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + return parseModuleOrNamespaceDeclaration(node, flags); } function isExternalModuleReference() { return token() === 132 && @@ -14891,57 +14556,51 @@ var ts; function nextTokenIsSlash() { return nextToken() === 41; } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; + function parseNamespaceExportDeclaration(node) { + node.kind = 237; parseExpected(118); parseExpected(129); - exportDeclaration.name = parseIdentifier(); + node.name = parseIdentifier(); parseSemicolon(); - return finishNode(exportDeclaration); + return finishNode(node); } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + function parseImportDeclarationOrImportEqualsDeclaration(node) { parseExpected(91); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + if (token() !== 26 && token() !== 141) { + return parseImportEqualsDeclaration(node, identifier); } } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; + node.kind = 239; if (identifier || token() === 39 || token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); + node.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(141); } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); + node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); - return finishNode(importDeclaration); + return finishNode(node); } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; + function parseImportEqualsDeclaration(node, identifier) { + node.kind = 238; + node.name = identifier; parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); + node.moduleReference = parseModuleReference(); parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); + return finishNode(node); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); + var importClause = createNode(240, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(242); } return finishNode(importClause); } @@ -14951,7 +14610,7 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(248); + var node = createNode(249); parseExpected(132); parseExpected(19); node.expression = parseModuleSpecifier(); @@ -14969,7 +14628,7 @@ var ts; } } function parseNamespaceImport() { - var namespaceImport = createNode(240); + var namespaceImport = createNode(241); parseExpected(39); parseExpected(118); namespaceImport.name = parseIdentifier(); @@ -14977,14 +14636,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + node.elements = parseBracketedList(22, kind === 242 ? parseImportSpecifier : parseExportSpecifier, 17, 18); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); + return parseImportOrExportSpecifier(247); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); + return parseImportOrExportSpecifier(243); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -15003,33 +14662,29 @@ var ts; else { node.name = identifierName; } - if (kind === 242 && checkIdentifierIsKeyword) { + if (kind === 243 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportDeclaration(node) { + node.kind = 245; if (parseOptional(39)) { - parseExpected(140); + parseExpected(141); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); + node.exportClause = parseNamedImportsOrExports(246); + if (token() === 141 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(141); node.moduleSpecifier = parseModuleSpecifier(); } } parseSemicolon(); return finishNode(node); } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; + function parseExportAssignment(node) { + node.kind = 244; if (parseOptional(58)) { node.isExportEquals = true; } @@ -15105,7 +14760,7 @@ var ts; var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment); if (checkJsDirectiveMatchResult) { checkJsDirective = { - enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", true) === 0, + enabled: ts.equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"), end: range.end, pos: range.pos }; @@ -15121,52 +14776,19 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return ts.hasModifier(node, 1) - || node.kind === 237 && node.moduleReference.kind === 248 - || node.kind === 238 - || node.kind === 243 + || node.kind === 238 && node.moduleReference.kind === 249 + || node.kind === 239 || node.kind === 244 + || node.kind === 245 ? node : undefined; }); } - var ParsingContext; - (function (ParsingContext) { - ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; - ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; - ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; - ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; - ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; - ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; - ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; - ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; - ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; - ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; - ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; - ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; - ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; - ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes"; - ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; - ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; - ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; - })(ParsingContext || (ParsingContext = {})); - var Tristate; - (function (Tristate) { - Tristate[Tristate["False"] = 0] = "False"; - Tristate[Tristate["True"] = 1] = "True"; - Tristate[Tristate["Unknown"] = 2] = "Unknown"; - })(Tristate || (Tristate = {})); var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = createSourceFile("file.js", 5, 1); + initializeState(content, 6, undefined, 1); + sourceFile = createSourceFile("file.js", 6, 1, false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -15175,19 +14797,19 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression(requireBraces) { - var result = createNode(267, scanner.getTokenPos()); - if (!parseExpected(17) && requireBraces) { - return undefined; - } + function parseJSDocTypeExpression(mayOmitBraces) { + var result = createNode(271, scanner.getTokenPos()); + var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(1048576, parseType); - parseExpected(18); + if (!mayOmitBraces || hasBrace) { + parseExpected(18); + } fixupParentReferences(result); return finishNode(result); } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); + initializeState(content, 6, undefined, 1); sourceFile = { languageVariant: 0, text: content }; var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -15203,7 +14825,7 @@ var ts; if (comment) { comment.parent = parent; } - if (ts.isInJavaScriptFile(parent)) { + if (contextFlags & 65536) { if (!sourceFile.jsDocDiagnostics) { sourceFile.jsDocDiagnostics = []; } @@ -15216,17 +14838,6 @@ var ts; var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; - var JSDocState; - (function (JSDocState) { - JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine"; - JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk"; - JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments"; - })(JSDocState || (JSDocState = {})); - var PropertyLikeParse; - (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; - })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { var content = sourceText; start = start || 0; @@ -15345,7 +14956,7 @@ var ts; content.charCodeAt(start + 3) !== 42; } function createJSDocComment() { - var result = createNode(275, start); + var result = createNode(279, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -15369,6 +14980,7 @@ var ts; if (tagName) { switch (tagName.escapedText) { case "augments": + case "extends": tag = parseAugmentsTag(atToken, tagName); break; case "class": @@ -15461,7 +15073,7 @@ var ts; return comments; } function parseUnknownTag(atToken, tagName) { - var result = createNode(276, atToken.pos); + var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -15497,7 +15109,7 @@ var ts; switch (node.kind) { case 134: return true; - case 164: + case 165: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; @@ -15513,8 +15125,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(279, atToken.pos) : - createNode(284, atToken.pos); + createNode(284, atToken.pos) : + createNode(289, atToken.pos); var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -15530,7 +15142,7 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var typeLiteralExpression = createNode(271, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); @@ -15542,9 +15154,9 @@ var ts; children.push(child); } if (children) { - jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral = createNode(280, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 164) { + if (typeExpression.type.kind === 165) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -15553,35 +15165,55 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + if (ts.forEach(tags, function (t) { return t.kind === 285; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(280, atToken.pos); + var result = createNode(285, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + if (ts.forEach(tags, function (t) { return t.kind === 286; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(281, atToken.pos); + var result = createNode(286, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = parseJSDocTypeExpression(true); - var result = createNode(277, atToken.pos); + var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = typeExpression; + result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); } + function parseExpressionWithTypeArgumentsForAugments() { + var usedBrace = parseOptional(17); + var node = createNode(202); + node.expression = parsePropertyAccessEntityNameExpression(); + node.typeArguments = tryParseTypeArguments(); + var res = finishNode(node); + if (usedBrace) { + parseExpected(18); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + var node = parseJSDocIdentifierName(true); + while (parseOptional(23)) { + var prop = createNode(180, node.pos); + prop.expression = node; + prop.name = parseJSDocIdentifierName(); + node = finishNode(prop); + } + return node; + } function parseClassTag(atToken, tagName) { - var tag = createNode(278, atToken.pos); + var tag = createNode(283, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); @@ -15589,7 +15221,7 @@ var ts; function parseTypedefTag(atToken, tagName) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(283, atToken.pos); + var typedefTag = createNode(288, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); @@ -15612,9 +15244,9 @@ var ts; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(285, start_3); + jsdocTypeLiteral = createNode(280, start_3); } - if (child.kind === 281) { + if (child.kind === 286) { if (childTypeTag) { break; } @@ -15630,10 +15262,10 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 164) { + if (typeExpression && typeExpression.type.kind === 165) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); } @@ -15643,7 +15275,7 @@ var ts; var pos = scanner.getTokenPos(); var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); + var jsDocNamespaceNode = createNode(234, pos); jsDocNamespaceNode.flags |= flags; jsDocNamespaceNode.name = typeNameOrNamespaceName; jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); @@ -15676,7 +15308,7 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 279 && + if (child && child.kind === 284 && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } @@ -15704,7 +15336,7 @@ var ts; } function tryParseChildTag(target) { ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); + var atToken = createNode(57); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); @@ -15726,7 +15358,7 @@ var ts; return false; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + if (ts.forEach(tags, function (t) { return t.kind === 287; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; @@ -15738,7 +15370,7 @@ var ts; parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(145, name.pos); + var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -15750,7 +15382,7 @@ var ts; break; } } - var result = createNode(282, atToken.pos); + var result = createNode(287, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -16080,11 +15712,10 @@ var ts; } } } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + function isDeclarationFileName(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts"); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -16154,31 +15785,32 @@ var ts; name: "target", shortName: "t", type: ts.createMapFromTemplate({ - "es3": 0, - "es5": 1, - "es6": 2, - "es2015": 2, - "es2016": 3, - "es2017": 4, - "esnext": 5, + es3: 0, + es5: 1, + es6: 2, + es2015: 2, + es2016: 3, + es2017: 4, + es2018: 5, + esnext: 6, }), paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", shortName: "m", type: ts.createMapFromTemplate({ - "none": ts.ModuleKind.None, - "commonjs": ts.ModuleKind.CommonJS, - "amd": ts.ModuleKind.AMD, - "system": ts.ModuleKind.System, - "umd": ts.ModuleKind.UMD, - "es6": ts.ModuleKind.ES2015, - "es2015": ts.ModuleKind.ES2015, - "esnext": ts.ModuleKind.ESNext + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -16197,6 +15829,7 @@ var ts; "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", "dom": "lib.dom.d.ts", "dom.iterable": "lib.dom.iterable.d.ts", @@ -16216,6 +15849,7 @@ var ts; "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", + "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", }), }, @@ -16342,6 +15976,20 @@ var ts; category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, { name: "noImplicitThis", type: "boolean", @@ -16387,8 +16035,8 @@ var ts; { name: "moduleResolution", type: ts.createMapFromTemplate({ - "node": ts.ModuleResolutionKind.NodeJs, - "classic": ts.ModuleResolutionKind.Classic, + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, }), paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, @@ -16571,8 +16219,8 @@ var ts; { name: "newLine", type: ts.createMapFromTemplate({ - "crlf": 0, - "lf": 1 + crlf: 0, + lf: 1 }), paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Advanced_Options, @@ -16907,7 +16555,7 @@ var ts; } function readConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; function parseConfigFileTextToJson(fileName, jsonText) { @@ -16920,7 +16568,7 @@ var ts; ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function readJsonConfigFile(fileName, readFile) { var textOrDiagnostic = tryReadFile(fileName, readFile); - return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; function tryReadFile(fileName, readFile) { @@ -17004,7 +16652,7 @@ var ts; var result = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 261) { + if (element.kind !== 265) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -17061,9 +16709,9 @@ var ts; if (!isDoubleQuotedString(valueExpression)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); var text = valueExpression.text; - if (option && typeof option.type !== "string") { + if (option && !ts.isString(option.type)) { var customOption = option; if (!customOption.type.has(text.toLowerCase())) { errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); @@ -17073,7 +16721,13 @@ var ts; case 8: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 178: + case 193: + if (valueExpression.operator !== 38 || valueExpression.operand.kind !== 8) { + break; + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 179: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; if (option) { @@ -17083,7 +16737,7 @@ var ts; else { return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); } - case 177: + case 178: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -17101,13 +16755,13 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { return option.type === "list" ? "Array" : - typeof option.type === "string" ? option.type : "string"; + ts.isString(option.type) ? option.type : "string"; } function isCompilerOptionsValue(option, value) { if (option) { @@ -17116,7 +16770,7 @@ var ts; if (option.type === "list") { return ts.isArray(value); } - var expectedType = typeof option.type === "string" ? option.type : "string"; + var expectedType = ts.isString(option.type) ? option.type : "string"; return typeof value === expectedType; } } @@ -17277,12 +16931,13 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -17290,14 +16945,15 @@ var ts; raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec }; function getFileNames() { - var fileNames; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - fileNames = raw["files"]; - if (fileNames.length === 0) { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -17306,35 +16962,35 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } } - if (fileNames === undefined && includeSpecs === undefined) { + if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } return result; } @@ -17344,12 +17000,20 @@ var ts; } } } + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); @@ -17386,11 +17050,11 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { - if (typeof json.extends !== "string") { + if (!ts.isString(json.extends)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { @@ -17478,7 +17142,7 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } @@ -17502,7 +17166,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -17562,7 +17226,7 @@ var ts; if (optType === "list" && ts.isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors); } - else if (typeof optType !== "string") { + else if (!ts.isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); } return normalizeNonListOptionValue(opt, basePath, value); @@ -17576,13 +17240,13 @@ var ts; return undefined; if (option.type === "list") { var listOption_1 = option; - if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else if (typeof option.type !== "string") { - return option.type.get(typeof value === "string" ? value.toLowerCase() : value); + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); } return normalizeNonListOptionValue(option, basePath, value); } @@ -17618,28 +17282,36 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); + } + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); - if (include) { - include = validateSpecs(include, errors, false, jsonSourceFile, "include"); - } - if (exclude) { - exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); - } - var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); - if (fileNames) { - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } - if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -17655,9 +17327,11 @@ var ts; var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); return { fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + spec: spec }; } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter(function (spec) { var diag = specToDiagnostic(spec, allowTrailingRecursion); @@ -17861,7 +17535,7 @@ var ts; }); getTypingNamesFromSourceFileNames(fileNames); if (unresolvedImports) { - var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); addInferredTypings(module_1, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typingLocation, name) { @@ -17913,7 +17587,7 @@ var ts; if (!ts.hasJavaScriptFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); }); if (fromFileNames.length) { @@ -17935,15 +17609,15 @@ var ts; if (log) log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); var packageNames = []; - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; var normalizedFileName = ts.normalizePath(fileName); var baseFileName = ts.getBaseFileName(normalizedFileName); if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_2 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_2.config; + var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_1.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -17966,6 +17640,50 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + var maxPackageNameLength = 214; + function validatePackageName(packageName) { + if (!packageName) { + return 2; + } + if (packageName.length > maxPackageNameLength) { + return 3; + } + if (packageName.charCodeAt(0) === 46) { + return 4; + } + if (packageName.charCodeAt(0) === 95) { + return 5; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6; + } + return 0; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2: + return "Package name '" + typing + "' cannot be empty"; + case 3: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4: + return "Package name '" + typing + "' cannot start with '.'"; + case 5: + return "Package name '" + typing + "' cannot start with '_'"; + case 1: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0: + throw ts.Debug.fail(); + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; @@ -17974,6 +17692,8 @@ var ts; (function (server) { server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; server.EventInitializationFailed = "event::initializationFailed"; @@ -18044,7 +17764,7 @@ var ts; return; } var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { + if (!ts.isString(fileName)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); } @@ -18087,7 +17807,7 @@ var ts; return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; } var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -18416,8 +18136,8 @@ var ts; matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -18618,14 +18338,14 @@ var ts; var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; - return { packageJsonContent: packageJsonContent, packageId: packageId }; + return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } failedLookupLocations.push(packageJsonPath); - return { packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined }; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { @@ -18669,10 +18389,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var packageJsonContent; + var packageId; + var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); + if (packageInfo.found) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); + } + else { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + } + } var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); @@ -18684,6 +18414,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); } @@ -18692,7 +18423,7 @@ var ts; } function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); if (resolutionFromCache) { @@ -18726,23 +18457,30 @@ var ts; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); } } - return moduleName; + return packageName; } function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : withoutAtTypePrefix; } @@ -18772,7 +18510,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -18808,19 +18546,6 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } - 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 || (ts = {})); var ts; (function (ts) { @@ -18844,39 +18569,6 @@ var ts; return undefined; } } - var PackageNameValidationResult; - (function (PackageNameValidationResult) { - PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; - PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; - PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; - PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; - PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; - })(PackageNameValidationResult = typingsInstaller.PackageNameValidationResult || (typingsInstaller.PackageNameValidationResult = {})); - typingsInstaller.MaxPackageNameLength = 214; - function validatePackageName(packageName) { - if (!packageName) { - return PackageNameValidationResult.EmptyName; - } - if (packageName.length > typingsInstaller.MaxPackageNameLength) { - return PackageNameValidationResult.NameTooLong; - } - if (packageName.charCodeAt(0) === 46) { - return PackageNameValidationResult.NameStartsWithDot; - } - if (packageName.charCodeAt(0) === 95) { - return PackageNameValidationResult.NameStartsWithUnderscore; - } - if (/^@[^/]+\/[^/]+$/.test(packageName)) { - return PackageNameValidationResult.ScopedPackagesNotSupported; - } - if (encodeURIComponent(packageName) !== packageName) { - return PackageNameValidationResult.NameContainsNonURISafeCharacters; - } - return PackageNameValidationResult.Ok; - } - typingsInstaller.validatePackageName = validatePackageName; var TypingsInstaller = (function () { function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) { if (log === void 0) { log = nullLog; } @@ -18939,12 +18631,12 @@ var ts; if (this.log.isEnabled()) { this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult)); } - this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths)); this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); if (discoverTypingsResult.newTypingNames.length) { this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); } else { + this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths)); if (this.log.isEnabled()) { this.log.writeLine("No new typings were requested as a result of typings discovery"); } @@ -19023,8 +18715,8 @@ var ts; if (this.missingTypingsSet.get(typing) || this.packageNameToTypingLocation.get(typing)) { continue; } - var validationResult = validatePackageName(typing); - if (validationResult === PackageNameValidationResult.Ok) { + var validationResult = ts.JsTyping.validatePackageName(typing); + if (validationResult === 0) { if (this.typesRegistry.has(typing)) { result.push(typing); } @@ -19037,26 +18729,7 @@ var ts; else { this.missingTypingsSet.set(typing, true); if (this.log.isEnabled()) { - switch (validationResult) { - case PackageNameValidationResult.EmptyName: - this.log.writeLine("Package name '" + typing + "' cannot be empty"); - break; - case PackageNameValidationResult.NameTooLong: - this.log.writeLine("Package name '" + typing + "' should be less than " + typingsInstaller.MaxPackageNameLength + " characters"); - break; - case PackageNameValidationResult.NameStartsWithDot: - this.log.writeLine("Package name '" + typing + "' cannot start with '.'"); - break; - case PackageNameValidationResult.NameStartsWithUnderscore: - this.log.writeLine("Package name '" + typing + "' cannot start with '_'"); - break; - case PackageNameValidationResult.ScopedPackagesNotSupported: - this.log.writeLine("Package '" + typing + "' is scoped and currently is not supported"); - break; - case PackageNameValidationResult.NameContainsNonURISafeCharacters: - this.log.writeLine("Package name '" + typing + "' contains non URI safe characters"); - break; - } + this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing)); } } } @@ -19072,7 +18745,7 @@ var ts; this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one..."); } this.ensureDirectoryExists(directory, this.installTypingHost); - this.installTypingHost.writeFile(npmConfigPath, "{}"); + this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }'); } }; TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) { @@ -19083,8 +18756,9 @@ var ts; var filteredTypings = this.filterTypings(typingsToInstall); if (filteredTypings.length === 0) { if (this.log.isEnabled()) { - this.log.writeLine("All typings are known to be missing or invalid - no need to go any further"); + this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings"); } + this.sendResponse(this.createSetTypings(req, currentlyCachedTypings)); return; } this.ensurePackageDirectoryExists(cachePath); @@ -19160,8 +18834,8 @@ var ts; this.closeWatchers(projectName); var isInvoked = false; var watchers = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var file = files_2[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var file = files_1[_i]; var w = this.installTypingHost.watchFile(file, function (f) { if (_this.log.isEnabled()) { _this.log.writeLine("Got FS notification for " + f + ", handler is already invoked '" + isInvoked + "'"); @@ -19185,8 +18859,8 @@ var ts; kind: server.ActionSet }; }; - TypingsInstaller.prototype.installTypingsAsync = function (requestId, args, cwd, onRequestCompleted) { - this.pendingRunRequests.unshift({ requestId: requestId, args: args, cwd: cwd, onRequestCompleted: onRequestCompleted }); + TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) { + this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted }); this.executeWithThrottling(); }; TypingsInstaller.prototype.executeWithThrottling = function () { @@ -19194,7 +18868,7 @@ var ts; var _loop_4 = function () { this_1.inFlightRequestCount++; var request = this_1.pendingRunRequests.pop(); - this_1.installWorker(request.requestId, request.args, request.cwd, function (ok) { + this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) { _this.inFlightRequestCount--; request.onRequestCompleted(ok); _this.executeWithThrottling(); @@ -19268,36 +18942,36 @@ var ts; return ts.createMap(); } } - var TypesRegistryPackageName = "types-registry"; + var typesRegistryPackageName = "types-registry"; function getTypesRegistryFileLocation(globalTypingsCacheLocation) { - return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + TypesRegistryPackageName + "/index.json"); + return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json"); } var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, throttleLimit, log) { var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); - if (_this.npmPath.indexOf(" ") !== -1 && _this.npmPath[0] !== "\"") { + if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") { _this.npmPath = "\"" + _this.npmPath + "\""; } if (_this.log.isEnabled()) { _this.log.writeLine("Process id: " + process.pid); _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)"); } - (_this.execSync = require("child_process").execSync); + (_this.nodeExecSync = require("child_process").execSync); _this.ensurePackageDirectoryExists(globalTypingsCacheLocation); try { if (_this.log.isEnabled()) { - _this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package..."); + _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package..."); } - _this.execSync(_this.npmPath + " install --ignore-scripts " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" }); + _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName, { cwd: globalTypingsCacheLocation }); if (_this.log.isEnabled()) { - _this.log.writeLine("Updated " + TypesRegistryPackageName + " npm package"); + _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package"); } } catch (e) { if (_this.log.isEnabled()) { - _this.log.writeLine("Error updating " + TypesRegistryPackageName + " package: " + e.message); + _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message); } _this.delayedInitializationError = { kind: "event::initializationFailed", @@ -19320,43 +18994,85 @@ var ts; break; case "closeProject": _this.closeProject(req); + break; + case "typesRegistry": { + var typesRegistry_1 = {}; + _this.typesRegistry.forEach(function (value, key) { + typesRegistry_1[key] = value; + }); + var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 }; + _this.sendResponse(response); + break; + } + case "installPackage": { + var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath; + var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath; + if (cwd) { + _this.installWorker(-1, [packageName_1], cwd, function (success) { + var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + "."; + var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message }; + _this.sendResponse(response); + }); + } + else { + var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." }; + _this.sendResponse(response); + } + break; + } + default: + ts.Debug.assertNever(req); } }); }; NodeTypingsInstaller.prototype.sendResponse = function (response) { if (this.log.isEnabled()) { - this.log.writeLine("Sending response: " + JSON.stringify(response)); + this.log.writeLine("Sending response:\n " + JSON.stringify(response)); } process.send(response); if (this.log.isEnabled()) { this.log.writeLine("Response has been sent."); } }; - NodeTypingsInstaller.prototype.installWorker = function (requestId, args, cwd, onRequestCompleted) { + NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) { if (this.log.isEnabled()) { - this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(args) + "'."); + this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'."); } - var command = this.npmPath + " install --ignore-scripts " + args.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; + var command = this.npmPath + " install --ignore-scripts " + packageNames.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; var start = Date.now(); - var stdout; - var stderr; - var hasError = false; - try { - stdout = this.execSync(command, { cwd: cwd }); - } - catch (e) { - stdout = e.stdout; - stderr = e.stderr; - hasError = true; - } + var hasError = this.execSyncAndLog(command, { cwd: cwd }); if (this.log.isEnabled()) { - this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms" + ts.sys.newLine + "stdout: " + (stdout && stdout.toString()) + ts.sys.newLine + "stderr: " + (stderr && stderr.toString())); + this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms"); } onRequestCompleted(!hasError); }; + NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) { + if (this.log.isEnabled()) { + this.log.writeLine("Exec: " + command); + } + try { + var stdout = this.nodeExecSync(command, __assign({}, options, { encoding: "utf-8" })); + if (this.log.isEnabled()) { + this.log.writeLine(" Succeeded. stdout:" + indent(ts.sys.newLine, stdout)); + } + return false; + } + catch (error) { + var stdout = error.stdout, stderr = error.stderr; + this.log.writeLine(" Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + " stderr:" + indent(ts.sys.newLine, stderr)); + return true; + } + }; return NodeTypingsInstaller; }(typingsInstaller.TypingsInstaller)); typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller; + function getDirectoryOfPackageJson(fileName, host) { + return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) { + if (host.fileExists(ts.combinePaths(directory, "package.json"))) { + return directory; + } + }); + } var logFilePath = server.findArgument(server.Arguments.LogFile); var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); @@ -19376,8 +19092,9 @@ var ts; }); var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, 5, log); installer.listen(); + function indent(newline, str) { + return newline + " " + str.replace(/\r?\n/, newline + " "); + } })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); - -//# sourceMappingURL=typingsInstaller.js.map diff --git a/lib/watchGuard.js b/lib/watchGuard.js index 11a70cd8e94bd..4048f128878bc 100644 --- a/lib/watchGuard.js +++ b/lib/watchGuard.js @@ -23,6 +23,5 @@ try { var watcher = fs.watch(directoryName, { recursive: true }, function () { return ({}); }); watcher.close(); } -catch (_e) { -} +catch (_a) { } process.exit(0); diff --git a/lib/zh-CN/diagnosticMessages.generated.json b/lib/zh-CN/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..e7713b2cbd3be --- /dev/null +++ b/lib/zh-CN/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "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_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}”关键字。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "计算属性名中不允许逗号表达式。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "计算属性名无法从其包含的类型引用类型参数。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "类属性声明中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法重载中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "类型文本中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "环境上下文中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "接口中的计算属性名称必须引用必须引用类型为文本类型或“唯一符号”的表达式。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "计算属性名的类型必须为 \"string\"、\"number\"、\"symbol\" 或 \"any\"。", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "窗体“{0}”的计算属性名必须是 \"symbol\" 类型。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "只有使用字符串文本才能访问常数枚举成员。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "环境上下文中的 \"const\" 初始化表达式必须为字符串或数字参数。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "当构造函数的类扩展 \"null\" 时,它不能包含 \"super\" 调用。", + "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_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-style 模块中使用。", + "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\" 构造函数进行了声明或在 \"--lib\" 选项中包含了 \"ES2015\"。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "动态导入调用返回 \"Promise\"。请确保具有对 \"Promise\" 的声明或在 `--lib` 选项中包括 \"ES2015\"。", + "A_file_cannot_have_a_reference_to_itself_1006": "文件不能引用自身。", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "仅异步函数或异步生成器中允许 \"for-await-of\" 语句。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "返回“从不”的函数不能具有可访问的终结点。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "使用 \"new\" 关键字调用的函数不可具有“失效”的 \"this\" 类型。", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "其声明类型不为 \"void\" 或 \"any\" 的函数必须返回值。", + "A_generator_cannot_have_a_void_type_annotation_2505": "生成器不能具有 \"void\" 类型批注。", + "A_get_accessor_cannot_have_parameters_1054": "\"get\" 访问器不能具有参数。", + "A_get_accessor_must_return_a_value_2378": "\"get\" 访问器必须返回值。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "枚举声明中的成员初始化表达式不能引用在其后声明的成员(包括在其他枚举中定义的成员)。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 类必须具有单个 rest 参数为类型 \"any[]\" 的构造函数。", + "A_module_cannot_have_multiple_default_exports_2528": "一个模块不能具有多个默认导出。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空间声明必须位于与之合并的类或函数所在的相同文件内。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空间声明不能位于与之合并的类或函数前", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只允许在命名空间或模块中使用命名空间声明。", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只允许在函数或构造函数实现中使用参数初始化表达式。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "不能使用 rest 参数声明参数属性。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "只允许在构造函数实现中使用参数属性。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "不能使用绑定模式声明参数属性。", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "“扩展”选项中的路径必须为相对路径或根路径,但“{0}”不是。", + "A_promise_must_have_a_then_method_1059": "承诺必须具有 \"then\" 方法。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "类型为“唯一符号”的类的属性必须同时为“静态”和“只读”。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "类型为“唯一符号”的接口或类型文本的属性必须是“只读”", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必选参数不能位于可选参数后。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 元素不能包含绑定模式。", + "A_rest_element_cannot_have_an_initializer_1186": "rest 元素不能具有初始化表达式。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 元素必须在析构模式中位于最末。", + "A_rest_parameter_cannot_be_optional_1047": "rest 参数不能为可选参数。", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "\"set\" 访问器不能具有可选参数。", + "A_set_accessor_cannot_have_rest_parameter_1053": "\"set\" 访问器不能具有 rest 参数。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "\"set\" 访问器必须正好具有一个参数。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "\"set\" 访问器参数不能包含初始化表达式。", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "具有实现的签名不能使用字符串文本类型。", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "当类包含初始化的属性或参数属性时,\"super\" 调用必须是构造函数中的第一个语句。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "基于 \"this\" 的类型防护与基于参数的类型防护不兼容。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "\"this\" 类型仅在类或接口的非静态成员中可用。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "已在“{0}”中定义了 \"tsconfig.json\" 文件。", + "A_tuple_type_element_list_cannot_be_empty_1122": "元组类型元素列表不能为空。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "乘方表达式的左侧不允许出现类型断言表达式。请考虑用括号将表达式括起。", + "A_type_literal_property_cannot_have_an_initializer_1247": "类型文字数据不可具有初始化表达式。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "类型谓词无法引用 rest 参数。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "类型谓词无法在绑定模式中引用元素“{0}”。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "只允许在函数和方法的返回类型位置使用类型谓词。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "类型谓词的类型不可赋给其参数的类型。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "类型为“唯一符号”的变量必须是“常量”。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "只允许在生成器正文中使用 \"yield\" 表达式。", + "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": "已看到可访问性修饰符。", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "访问器仅在面向 ECMAScript 5 和更高版本时可用。", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。", + "Add_0_to_existing_import_declaration_from_1_90015": "将 {0} 从 {1} 添加到现有导入声明。", + "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名。", + "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用。", + "Add_this_to_unresolved_variable_90008": "向未解析的变量添加 \"this.\"。", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "添加 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_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。", + "Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。", + "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_abstract_accessor_cannot_have_an_implementation_1318": "抽象访问器不能有实现。", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "不能在环境上下文中声明访问器。", + "An_accessor_cannot_have_type_parameters_1094": "访问器不能具有类型参数。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "只允许在文件的顶层中使用环境模块声明。", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "算术操作数必须为类型 \"any\"、\"number\" 或枚举类型。", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 中的异步函数或方法需要 \"Promise\" 构造函数。确保对 \"Promise\" 构造函数进行了声明或在 \"--lib\" 选项中包含了 \"ES2015\"。", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "异步函数或方法必须具有有效的可等待返回类型。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "异步函数或方法必须返回 \"Promise\"。请确保具有对 \"Promise\" 的声明或在 `--lib` 选项中包括 \"ES2015\"。", + "An_async_iterator_must_have_a_next_method_2519": "异步迭代器必须具有 \"next()\" 方法。", + "An_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_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 之间。", + "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_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": "索引签名不能包含 rest 参数。", + "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_initializer_1020": "索引签名参数不能具有初始化表达式。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "接口只能扩展类或其他接口。", + "An_interface_property_cannot_have_an_initializer_1246": "接口函数不能具有初始化表达式。", + "An_iterator_must_have_a_next_method_2489": "迭代器必须具有 \"next()\" 方法。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "对象文字不能具有多个具有相同名称的 get/set 访问器。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "严格模式下,对象文字不能包含多个具有相同名称的属性。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "对象文字不能包含具有相同名称的属性和访问器。", + "An_object_member_cannot_be_declared_optional_1162": "对象成员无法声明为可选。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "重载签名无法声明为生成器。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "乘方表达式的左侧不允许存在具有“{0}”运算符的一元表达式。请考虑用括号将表达式括起。", + "Annotate_with_type_from_JSDoc_95009": "使用 JSDoc 中的类型批注", + "Annotate_with_types_from_JSDoc_95010": "使用 JSDoc 中的类型批注", + "Argument_expression_expected_1135": "应为参数表达式。", + "Argument_for_0_option_must_be_Colon_1_6046": "“{0}”选项的参数必须为 {1}。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "类型“{0}”的参数不能赋给类型“{1}”的参数。", + "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\" 修饰符,除非它们显示在已有的环境上下文中。", + "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}”不是类或接口类型。", + "Base_constructors_must_all_have_the_same_return_type_2510": "所有的基构造函数必须具有相同的返回类型。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "用于解析非绝对模块名的基目录。", + "Basic_Options_6172": "基本选项", + "Binary_digit_expected_1177": "需要二进制数字。", + "Binding_element_0_implicitly_has_an_1_type_7031": "绑定元素“{0}”隐式具有“{1}”类型。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "声明之前已使用的块范围变量“{0}”。", + "Call_decorator_expression_90028": "调用修饰器表达式。", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "缺少返回类型批注的调用签名隐式具有返回类型 \"any\"。", + "Call_target_does_not_contain_any_signatures_2346": "调用目标不包含任何签名。", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "无法访问“{0}.{1}”,因为“{0}”是类型,不是命名空间。是否要使用“{0}[\"{1}\"]”检索“{0}”中“{1}”属性的类型?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "不可将“{0}”构造函数类型分配给“{1}”构造函数类型。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "无法将抽象构造函数类型分配给非抽象构造函数类型。", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "无法分配到“{0}”,因为它是常数或只读属性。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "无法分配到“{0}”,因为它不是变量。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "无法扩大模块“{0}”,因为它解析为非模块实体。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "无法扩充具有值导出的模块“{0}”,因为它解析为一个非模块的实体。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "无法使用选项“{0}”来编译模块,除非 \"--module\" 标记为 \"amd\" 或 \"system\"。", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "提供 \"--isolatedModules\" 标志时无法编译命名空间。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "无法创建抽象类的实例。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "无法导出“{0}”。仅可从模块中导出本地声明。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "无法扩展类“{0}”。类构造函数标记为私有。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "无法扩展接口‘{0}’。您的意思是‘实施’吗?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "无法在指定目录找到 tsconfig.json 文件:“{0}”。", + "Cannot_find_global_type_0_2318": "找不到全局类型“{0}”。", + "Cannot_find_global_value_0_2468": "找不到全局值“{0}”。", + "Cannot_find_module_0_2307": "找不到模块“{0}”。", + "Cannot_find_name_0_2304": "找不到名称“{0}”。", + "Cannot_find_name_0_Did_you_mean_1_2552": "找不到名称“{0}”。你是否指的是“{1}”?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "找不到名称“{0}”。你的意思是实例成员“this.{0}”?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "找不到名称“{0}”。你的意思是静态成员“{1}.{0}”?", + "Cannot_find_namespace_0_2503": "找不到命名空间“{0}”。", + "Cannot_find_parameter_0_1225": "找不到参数“{0}”。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到输入文件的公共子目录路径。", + "Cannot_find_type_definition_file_for_0_2688": "找不到“{0}”的类型定义文件。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "无法导入类型声明文件。请考虑导入“{0}”,而不是“{1}”。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "无法在块范围声明“{1}”所在的范围内初始化外部范围变量“{0}”。", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "无法调用类型缺少调用签名的表达式。类型“{0}”没有兼容的调用签名。", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。", + "Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。", + "Cannot_redeclare_exported_variable_0_2323": "无法重新声明导出的变量“{0}”。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "无法在 catch 子句中重新声明标识符“{0}”。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "无法使用 JSX,除非提供了 \"--jsx\" 标志。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "当 \"--module\" 为 \"none\" 时无法使用导入、导出或模块扩大。", + "Cannot_use_namespace_0_as_a_type_2709": "不能将命名空间“{0}”用作类型。", + "Cannot_use_namespace_0_as_a_value_2708": "不能将命名空间“{0}”用作值。", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "其类型缺少调用或构造签名的表达式无法使用 \"new\"。", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "无法写入文件“{0}”,因为它会被多个输入文件覆盖。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "无法写入文件“{0}”,因为它会覆盖输入文件。", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 子句变量不能有类型批注。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 子句变量不能有初始化表达式。", + "Change_0_to_1_90014": "将“{0}”更改为“{1}”。", + "Change_extends_to_implements_90003": "将 \"extends\" 更改为 \"implements\"。", + "Change_spelling_to_0_90022": "将拼写更改为“{0}”。", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "检查“{0}”是否是“{1}”-“{2}”的最长匹配前缀。", + "Circular_definition_of_import_alias_0_2303": "导入别名“{0}”的循环定义。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "解析配置时检测到循环: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "类“{0}”将“{1}”定义为实例成员访问器,但扩展类“{2}”将其定义为实例成员函数。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "类“{0}”将“{1}”定义为实例成员函数,但扩展类“{2}”将其定义为实例成员访问器。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "类“{0}”将“{1}”定义为实例成员函数,但扩展类“{2}”将其定义为实例成员属性。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "类“{0}”将“{1}”定义为实例成员属性,但扩展类“{2}”将其定义为实例成员函数。", + "Class_0_incorrectly_extends_base_class_1_2415": "类“{0}”错误扩展基类“{1}”。", + "Class_0_incorrectly_implements_interface_1_2420": "类“{0}”错误实现接口“{1}”。", + "Class_0_used_before_its_declaration_2449": "类“{0}”用于其声明前。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "类声明不能有多个 \"@augments\" 或 \"@extends\" 标记。", + "Class_name_cannot_be_0_2414": "类名不能为“{0}”。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "类静态侧“{0}”错误扩展基类静态侧“{1}”。", + "Classes_can_only_extend_a_single_class_1174": "类只能扩展一个类。", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "包含抽象方法的类必须标记为抽象。", + "Command_line_Options_6171": "命令行选项", + "Compilation_complete_Watching_for_file_changes_6042": "编译完成。查看文件更改。", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。", + "Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。", + "Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "含字符串值成员的枚举中不允许使用计算值。", + "Concatenate_and_emit_output_to_single_file_6001": "连接输出并将其发出到单个文件。", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "“{1}”和“{2}”处找到的“{0}”的定义具有冲突。考虑安装此库的特定版本以解决冲突。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "缺少返回类型批注的构造签名隐式具有返回类型 \"any\"。", + "Constructor_implementation_is_missing_2390": "缺少构造函数实现。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "类“{0}”的构造函数是私有的,仅可在类声明中访问。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "类“{0}”的构造函数是受保护的,仅可在类声明中访问。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。", + "Convert_function_0_to_class_95002": "将函数“{0}”转换为类", + "Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类", + "Convert_to_default_import_95013": "转换为默认导入", + "Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "无法找到模块“{0}”的声明文件。“{1}”隐式拥有 \"any\" 类型。", + "Could_not_write_file_0_Colon_1_5033": "无法写入文件“{0}”: {1}。", + "DIRECTORY_6038": "目录", + "Declaration_expected_1146": "应为声明。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "声明名称与内置全局标识符“{0}”冲突。", + "Declaration_or_statement_expected_1128": "应为声明或语句。", + "Declare_method_0_90023": "声明方法“{0}”。", + "Declare_property_0_90016": "声明属性“{0}”。", + "Declare_static_method_0_90024": "声明静态方法“{0}”。", + "Declare_static_property_0_90027": "声明静态属性 \"{0}\"。", + "Decorators_are_not_valid_here_1206": "修饰器在此处无效。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "不能向多个同名的 get/set 访问器应用修饰器。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模块的默认导出具有或正在使用专用名称“{0}”。", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[已弃用] 请改用 \"--jsxFactory\"。已 \"react\" JSX 发出设为目标时,请指定要为 createElement 调用的对象", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[已弃用] 请改用 \"--outFile\"。连接并发出到单个文件的输出", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[已弃用] 请改用 \"--skipLibCheck\"。请跳过默认库声明文件的类型检查。", + "Digit_expected_1124": "应为数字。", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "目录“{0}”不存在,正在跳过该目录中的所有查找。", + "Disable_checking_for_this_file_90018": "禁用检查此文件。", + "Disable_size_limitations_on_JavaScript_projects_6162": "禁用对 JavaScript 项目的大小限制。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "禁止严格检查函数类型中的通用签名。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "不允许对同一文件采用大小不一致的引用。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "请勿将三斜杠引用或导入的模块添加到已编译文件列表中。", + "Do_not_emit_comments_to_output_6009": "请勿将注释发出到输出。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "请勿对具有 \"@internal\" 注释的代码发出声明。", + "Do_not_emit_outputs_6010": "请勿发出输出。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "如果报告了任何错误,请不要发出输出。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "不要在模块输出中发出 \"use strict\" 指令。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "请勿清除生成代码中的常数枚举声明。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "请勿在已编译输出中生成自定义帮助程序函数,例如 \"__extends\"。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "请勿包括默认库文件(lib.d.ts)。", + "Do_not_report_errors_on_unreachable_code_6077": "不报告有关不可访问的代码的错误。", + "Do_not_report_errors_on_unused_labels_6074": "不报告有关未使用的标签的错误。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "不要解析 symlink 的真实路径。", + "Do_not_truncate_error_messages_6165": "请勿删除错误消息。", + "Duplicate_declaration_0_2718": "重复声明“{0}”。", + "Duplicate_function_implementation_2393": "函数实现重复。", + "Duplicate_identifier_0_2300": "标识符“{0}”重复。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "标识符“{0}”重复。编译器在模块的顶层范围中保留名称“{1}”。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "标识符“{0}”重复。编译器在包含异步函数的模块的顶层范围中保留名称“{1}”。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "标识符“{0}”重复。编译器使用“{1}”声明来支持异步函数。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "标识符 \"arguments\" 重复。编译器使用 \"arguments\" 初始化 rest 参数。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "标识符 \"_newTarget\" 重复。编译器使用变量声明 \"_newTarget\" 来捕获 \"new.target\" 元属性引用。", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "标识符 \"_super\" 重复。编译器使用 \"_super\" 获取基类引用。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "标识符 \"_this\" 重复。编译器使用变量声明 \"_this\" 来捕获 \"this\" 引用。", + "Duplicate_label_0_1114": "标签“{0}”重复。", + "Duplicate_number_index_signature_2375": "数字索引签名重复。", + "Duplicate_string_index_signature_2374": "字符串索引签名重复。", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "面向 ECMAScript 2015 模块时,不能使用动态导入。", + "Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "动态导入必须具有一个说明符作为参数。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "元素隐式具有 \"any\" 类型,因为索引表达式的类型不为 \"number\"。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "元素隐式具有 \"any\" 类型,因为类型“{0}”没有索引签名。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "在输出文件的开头发出一个 UTF-8 字节顺序标记(BOM)。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "发出包含源映射而非包含单独文件的单个文件。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "在单个文件内发出源以及源映射;需要设置 \"--inlineSourceMap\" 或 \"--sourceMap\"。", + "Enable_all_strict_type_checking_options_6180": "启用所有严格类型检查选项。", + "Enable_strict_checking_of_function_types_6186": "对函数类型启用严格检查。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。", + "Enable_strict_null_checks_6113": "启用严格的 NULL 检查。", + "Enable_tracing_of_the_name_resolution_process_6085": "启用名称解析过程的跟踪。", + "Enables_experimental_support_for_ES7_async_functions_6068": "对 ES7 异步函数启用实验支持。", + "Enables_experimental_support_for_ES7_decorators_6065": "对 ES7 修饰器启用实验支持。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "对发出修饰器的类型元数据启用实验支持。", + "Enum_0_used_before_its_declaration_2450": "枚举“{0}”用于其声明前。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "枚举声明必须全为常数或非常数。", + "Enum_member_expected_1132": "应为枚举成员。", + "Enum_member_must_have_initializer_1061": "枚举成员必须具有初始化表达式。", + "Enum_name_cannot_be_0_2431": "枚举名不能为“{0}”。", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "枚举类型“{0}”包含具有不是文本的初始值设定项的成员。", + "Examples_Colon_0_6026": "示例: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "与类型“{0}”和“{1}”相比,堆栈深度过高。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "应为 {0}-{1} 类型参数;请为这些参数添加 \"@extends\" 标记。", + "Expected_0_arguments_but_got_1_2554": "应有 {0} 个参数,但获得 {1} 个。", + "Expected_0_arguments_but_got_1_or_more_2556": "应有 {0} 个参数,但获得的数量大于等于 {1}。", + "Expected_0_type_arguments_but_got_1_2558": "应有 {0} 个类型参数,但获得 {1} 个。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "应为 {0} 类型参数;请为这些参数添加 \"@extends\" 标记。", + "Expected_at_least_0_arguments_but_got_1_2555": "应有至少 {0} 个参数,但获得 {1} 个。", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "应有至少 {0} 个参数,但获得的数量大于等于 {1}。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "“{0}”预期的相应 JSX 结束标记。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "预期的 JSX 片段的相应结束标记。", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "\"package.json\" 中“{0}”字段的类型应为 \"string\",但实际为“{1}”。", + "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_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}”不是一个模块。请与包作者联系或更新包定义。", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "导出的外部包键入文件不能包含三斜线引用。请与包作者联系或更新包定义。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "导出的类型别名“{0}”已经或正在使用专用名称“{1}”。", + "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": "模块扩大中不允许导出和导出分配。", + "Expression_expected_1109": "应为表达式。", + "Expression_or_comma_expected_1137": "应为表达式或逗号。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "表达式解析为 \"_super\",编译器使用 \"_super\" 获取基类引用。", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "表达式解析为编译器用于支持异步函数的变量声明“{0}”。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "表达式解析为编辑器用于捕获 \"new.target\" 元属性引用的变量声明 \"_newTarget\"。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "表达式解析为编译器用于捕获 \"this\" 引用的变量声明 \"_this\"。", + "Extract_constant_95006": "提取常数", + "Extract_function_95005": "提取函数", + "Extract_symbol_95003": "提取符号", + "Extract_to_0_in_1_95004": "提取到 {1} 中的 {0}", + "Extract_to_0_in_1_scope_95008": "提取到 {1} 范围中的 {0}", + "Extract_to_0_in_enclosing_scope_95007": "提取到封闭范围中的 {0}", + "FILE_6035": "文件", + "FILE_OR_DIRECTORY_6040": "文件或目录", + "Failed_to_parse_file_0_Colon_1_5014": "未能分析文件“{0}”: {1}。", + "Fallthrough_case_in_switch_7029": "switch 语句中的 Fallthrough 情况。", + "File_0_does_not_exist_6096": "文件“{0}”不存在。", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "文件“{0}”存在 - 将其用作名称解析结果。", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "不支持文件“{0}”的扩展名。唯一支持的扩展名为 {1}。", + "File_0_is_not_a_module_2306": "文件“{0}”不是模块。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "文件“{0}”不在 \"rootDir\"“{1}”下。\"rootDir\" 应包含所有源文件。", + "File_0_not_found_6053": "找不到文件“{0}”。", + "File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "文件名“{0}”仅在大小写方面与包含的文件名“{1}”不同。", + "File_name_0_has_a_1_extension_stripping_it_6132": "文件名“{0}”的扩展名为“{1}”,请去除它。", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "文件规范不能包含出现在递归目录通配符(\"*\"): “{0}”后的父目录(\"..\")。", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "文件规范不能包含多个递归目录通配符(\"**\"):“{0}”。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "文件规范不能以递归目录通配符结尾(\"**\"):“{0}”。", + "Found_package_json_at_0_6099": "在“{0}”处找到了 \"package.json\"。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。类定义自动处于严格模式。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。模块自动处于严格模式。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "缺少返回类型批注的函数表达式隐式具有“{0}”返回类型。", + "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_overload_must_be_static_2387": "函数重载必须为静态。", + "Function_overload_must_not_be_static_2388": "函数重载不能为静态。", + "Generates_corresponding_d_ts_file_6002": "生成相应的 \".d.ts\" 文件。", + "Generates_corresponding_map_file_6043": "生成相应的 \".map\" 文件。", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "生成器隐式具有类型“{0}”,因为它不生成任何值。请考虑提供一个返回类型。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "不允许在环境上下文中使用生成器。", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "仅当面向 ECMAScript 2015 或更高版本时,生成器才可用。", + "Generic_type_0_requires_1_type_argument_s_2314": "泛型类型“{0}”需要 {1} 个类型参数。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "泛型类型“{0}”需要介于 {1} 和 {2} 类型参数之间。", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "泛型类型实例化过深,且可能无限。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Getter 和 Setter 访问器在可见性上不一致。", + "Global_module_exports_may_only_appear_at_top_level_1316": "全局模块导出仅可出现在顶层级别中。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "全局模块导出仅可出现声明文件中。", + "Global_module_exports_may_only_appear_in_module_files_1314": "全局模块导出仅可出现模块文件中。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "全局类型“{0}”必须为类或接口类型。", + "Global_type_0_must_have_1_type_parameter_s_2317": "全局类型“{0}”必须具有 {1} 个类型参数。", + "Hexadecimal_digit_expected_1125": "应为十六进制数字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "应为标识符。“{0}”在严格模式下是保留字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "应为标识符。“{0}”在严格模式下是保留字。类定义自动处于严格模式。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "应为标识符。“{0}”是严格模式下的保留字。模块自动处于严格模式。", + "Identifier_expected_1003": "应为标识符。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "应为标识符。转换 ECMAScript 模块时,\"__esModule\" 保留为导出标记。", + "Ignore_this_error_message_90019": "忽略此错误信息。", + "Implement_inherited_abstract_class_90007": "实现继承的抽象类。", + "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_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": "命名空间中的导入声明不能引用模块。", + "Import_emit_helpers_from_tslib_6139": "从 \"tslib\" 导入发出帮助程序。", + "Import_name_cannot_be_0_2438": "导入名称不能为“{0}”。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "环境模块声明中的导入或导出声明不能通过相对模块名引用模块。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "模块扩大中不允许导入。请考虑将它们移动到封闭的外部模块。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在环境枚举声明中,成员初始化表达式必须是常数表达式。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在包含多个声明的枚举中,只有一个声明可以省略其第一个枚举元素的初始化表达式。", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 \"const\" 枚举声明中,成员初始化表达式必须是常数表达式。", + "Index_signature_in_type_0_only_permits_reading_2542": "类型“{0}”中的索引签名仅允许读取。", + "Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。", + "Index_signatures_are_incompatible_2330": "索引签名不兼容。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合并声明“{0}”中的单独声明必须全为导出或全为局部声明。", + "Infer_parameter_types_from_usage_95012": "从用法中推断出参数类型。", + "Infer_type_of_0_from_usage_95011": "从用法中推断出“{0}”的类型。", + "Initialize_property_0_in_the_constructor_90020": "初始化构造函数中的属性“{0}”。", + "Initialize_static_property_0_90021": "初始化静态属性“{0}”。", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "实例成员变量“{0}”的初始化表达式不能引用构造函数中声明的标识符“{1}”。", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "参数“{0}”的初始化表达式不能引用在它之后声明的标识符“{1}”。", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始化表达式没有为此绑定元素提供此任何值,且该绑定元素没有默认值。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "不允许在环境上下文中使用初始化表达式。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "初始化 TypeScript 项目并创建 tsconfig.json 文件。", + "Insert_command_line_options_and_files_from_a_file_6030": "从文件插入命令行选项和文件。", + "Install_0_95014": "安装“{0}”", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "接口“{0}”不能同时扩展类型“{1}”和“{2}”。", + "Interface_0_incorrectly_extends_interface_1_2430": "接口“{0}”错误扩展接口“{1}”。", + "Interface_declaration_cannot_have_implements_clause_1176": "接口声明不能有 \"implements\" 子句。", + "Interface_name_cannot_be_0_2427": "接口名称不能为“{0}”。", + "Invalid_character_1127": "无效的字符。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "扩大中的模块名称无效。模块“{0}”解析到位于“{1}”处的非类型化模块,其无法扩大。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "扩大中的模块名无效,找不到模块“{0}”。", + "Invalid_reference_directive_syntax_1084": "\"reference\" 指令语法无效。", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "“{0}”的使用无效。类定义自动处于严格模式。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "“{0}”的使用无效。模块自动处于严格模式。", + "Invalid_use_of_0_in_strict_mode_1100": "严格模式下“{0}”的使用无效。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "\"jsxFactory\" 的值无效。“{0}”不是有效的标识符或限定名称。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "\"--reactNamespace\" 的值无效。“{0}”不是有效的标识符。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" 不匹配 \"extends {2}\" 子句。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" 未附加到类。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc \"...\" 可能仅出现在签名的最后一个参数中。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc \"@param\" 标记具有名称 \"{0}\",但不存在具有该名称的参数。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc \"@typedef\" 标记应具有类型注释,或其后跟有 \"@property\" 或 \"@member\" 标记。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 类型只能在文档注释内部使用。", + "JSX_attribute_expected_17003": "需要 JSX 属性。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "只能为 JSX 属性分配非空“表达式”。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 元素“{0}”没有相应的结束标记。", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 元素属性类型“{0}”可能不是联合类型。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 元素类不支持特性,因为它不具有“{0}”属性。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "JSX 元素隐式具有类型 \"any\",因为不存在接口 \"JSX.{0}\"。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "JSX 元素隐式具有类型 \"any\",因为不存在全局类型 \"JSX.Element\"。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 元素类型“{0}”不具有任何构造签名或调用签名。", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 元素类型“{0}”不是 JSX 元素的构造函数。", + "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_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。", + "Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。", + "KIND_6034": "种类", + "LOCATION_6037": "位置", + "Language_service_is_disabled_9004": "语言服务已禁用。", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "逗号运算符的左侧未使用,没有任何副作用。", + "Line_break_not_permitted_here_1142": "不允许在此处换行。", + "Line_terminator_not_permitted_before_arrow_1200": "箭头前不允许有行终止符。", + "List_of_folders_to_include_type_definitions_from_6161": "包含类型定义来源的文件夹列表。", + "List_of_language_service_plugins_6181": "语言服务插件列表。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "根文件夹列表,其组合内容表示在运行时的项目结构。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "正在从根目录“{1}”加载“{0}”,候选位置“{2}”。", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "正在从 \"node_modules\" 文件夹加载模块“{0}”,目标文件类型“{1}”。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "正在将模块作为文件/文件夹进行加载,候选模块位置“{0}”,目标文件类型“{1}”。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "区域设置必须采用 <语言> 或 <语言>-<区域> 形式。例如“{0}”或“{1}”。", + "Longest_matching_prefix_for_0_is_1_6108": "“{0}”的最长匹配前缀为“{1}”。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "正在在 \"node_modules\" 文件夹中查找,初始位置“{0}”。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "在构造函数中,使 \"super()\" 调用第一个语句。", + "Member_0_implicitly_has_an_1_type_7008": "成员“{0}”隐式包含类型“{1}”。", + "Merge_conflict_marker_encountered_1185": "遇到合并冲突标记。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合并声明“{0}”不能包含默认导出声明。请考虑改为添加一个独立的“导出默认 {0}”声明。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "元属性“{0}”只能在函数声明、函数表达式或构造函数的主体中使用。", + "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": "修饰符不能出现在此处。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模块 {0} 已导出一个名为“{1}”的成员。请考虑重新显式导出以解决歧义。", + "Module_0_has_no_default_export_1192": "模块“{0}”没有默认导出。", + "Module_0_has_no_exported_member_1_2305": "模块“{0}”没有导出的成员“{1}”。", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "模块“{0}”被具有相同名称的局部声明隐藏。", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "模块“{0}”解析为非模块实体,且不能使用此构造导入。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "模块“{0}”使用 \"export =\" 且无法与 \"export *\" 一起使用。", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "模块“{0}”解析为“{1}”中声明的环境模块,因为未修改此文件。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "模块“{0}”解析为文件“{1}”中本地声明的环境模块。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "模块“{0}”已解析为“{1}”,但尚未设置 \"--jsx\"。", + "Module_Resolution_Options_6174": "模块分辨率选项", + "Module_name_0_matched_pattern_1_6092": "模块名“{0}”,匹配的模式“{1}”。", + "Module_name_0_was_not_resolved_6090": "======== 未解析模块名“{0}”。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模块名“{0}”已成功解析为“{1}”。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模块解析类型,正在使用“{0}”。", + "Module_resolution_using_rootDirs_has_failed_6111": "使用 \"rootDirs\" 的模块解析失败。", + "Multiple_constructor_implementations_are_not_allowed_2392": "不允许存在多个构造函数实现。", + "NEWLINE_6061": "换行符", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "“{1}”和“{2}”类型的命名属性“{0}”不完全相同。", + "Namespace_0_has_no_exported_member_1_2694": "命名空间“{0}”没有已导出的成员“{1}”。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "没有任何基构造函数具有指定数量的类型参数。", + "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}”不会实现继承自“{2}”类的抽象成员“{1}”。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象类表达式不会实现继承自“{1}”类的抽象成员“{0}”。", + "Not_all_code_paths_return_a_value_7030": "并非所有代码路径都返回值。", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "数字索引类型“{0}”不能赋给字符串索引类型“{1}”。", + "Object_is_possibly_null_2531": "对象可能为 \"null\"。", + "Object_is_possibly_null_or_undefined_2533": "对象可能为 \"null\" 或“未定义”。", + "Object_is_possibly_undefined_2532": "对象可能为“未定义”。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "对象文字可以只指定已知属性,并且“{0}”不在类型“{1}”中。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "对象文字只能指定已知的属性,但“{0}”中不存在类型“{1}”。是否要写入 {2}?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "对象文字的属性“{0}”隐式含有“{1}”类型。", + "Octal_digit_expected_1178": "需要八进制数字。", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "八进制文本类型必须使用 ES2015 语法。请使用语法“{0}”。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "枚举成员初始值设定项中不允许有八进制文本。请使用语法“{0}”。", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "严格模式下不允许使用八进制文本。", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "当面向 ECMAScript 5 及更高版本时,不能使用八进制文本。请使用语法“{0}”。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "\"for...in\" 语句中只允许单个变量声明。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "\"for...of\" 语句中只允许单个变量声明。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "使用 \"new\" 关键字只能调用 void 函数。", + "Only_ambient_modules_can_use_quoted_names_1035": "仅环境模块可使用带引号的名称。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} 旁仅支持 \"amd\" 和 \"system\" 模块。", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "类 \"extends\" 子句当前仅支持具有可选类型参数的标识符/限定名称。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "通过 \"super\" 关键字只能访问基类的公共方法和受保护方法。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "运算符“{0}”不能应用于类型“{1}”和“{2}”。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "仅可在 \"tsconfig.json\" 文件中指定选项“{0}”。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "仅当提供了选项 \"--inlineSourceMap\" 或选项 \"--sourceMap\" 时,才能使用选项“{0}”。", + "Option_0_cannot_be_specified_with_option_1_5053": "选项“{0}”不能与选项“{1}”同时指定。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "无法在不指定选项“{1}”的情况下指定选项“{0}”。", + "Option_0_should_have_array_of_strings_as_a_value_6103": "选项“{0}”应将字符串数组作为一个值。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。", + "Options_Colon_6027": "选项:", + "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "重载签名与函数实现不兼容。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "重载签名必须均导出或均不导出。", + "Overload_signatures_must_all_be_optional_or_required_2386": "重载签名必须全部为可选签名或必需签名。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "重载签名必须全部是公共签名、私有签名或受保护签名。", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "参数“{0}”的初始化表达式中不能引用该参数自身。", + "Parameter_0_implicitly_has_an_1_type_7006": "参数“{0}”隐式具有“{1}”类型。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "参数“{0}”和参数“{1}”的位置不一样。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "导出接口中的调用签名的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "导出接口中的调用签名的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "导出类中的构造函数的参数“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "导出类中的构造函数的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "导出类中的构造函数的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "导出接口中的构造函数签名的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "导出接口中的构造函数签名的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "导出函数的参数“{0}”具有或正在使用外部模块 {2} 中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "导出函数的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "导出函数的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "来自导出接口的索引签名的参数“{0}”具有或正在使用来自私有模块“{2}”的名称“{1}”。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "来自导出接口的索引签名的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "导出接口中的方法的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "导出接口中的方法的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "导出类中的公共方法的参数“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "导出类中的公共方法的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "导出类中的公共方法的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "导出类中的公共静态方法的参数“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "导出类中的公共静态方法的参数“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "导出类中的公共静态方法的参数“{0}”具有或正在使用专用名称“{1}”。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "参数不能包含问号和初始化表达式。", + "Parameter_declaration_expected_1138": "应为参数声明。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "导出类中的公共 setter“{0}”的参数类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "导出类中的公共 setter“{0}”的参数类型具有或正在使用专用名称“{1}”。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "导出类中的公共静态 setter“{0}”的参数类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "导出类中的公共静态 setter“{0}”的参数类型具有或正在使用专用名称“{1}”。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "以严格模式进行分析,并为每个源文件发出 \"use strict\" 指令。", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "模式“{0}”最多只可具有一个 \"*\" 字符。", + "Prefix_0_with_an_underscore_90025": "带下划线的前缀“{0}”。", + "Print_names_of_files_part_of_the_compilation_6155": "属于编译一部分的文件的打印名称。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。", + "Print_the_compiler_s_version_6019": "打印编译器的版本。", + "Print_this_message_6017": "打印此消息。", + "Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。", + "Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "属性“{0}”在类型“{1}”上不存在。你是否指的是“{2}”?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "属性“{0}”的声明发生冲突,并且在类型“{1}”中不可访问此属性。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "属性“{0}”没有初始化表达式,且未在构造函数中明确赋值。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "属性“{0}”隐式具有类型 \"any\",因为其 get 访问器缺少返回类型批注。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "属性“{0}”隐式具有类型 \"any\",因为其 set 访问器缺少参数类型批注。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "类型“{1}”中的属性“{0}”不可分配给类型“{2}”。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "已声明属性“{0}”,但从未读取其值。", + "Property_0_is_incompatible_with_index_signature_2530": "属性“{0}”与索引签名不兼容。", + "Property_0_is_missing_in_type_1_2324": "类型“{1}”中缺少属性“{0}”。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "属性“{0}”在类型“{1}”中为可选,但在类型“{2}”中为必选。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "属性“{0}”为私有属性,只能在类“{1}”中访问。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "属性“{0}”在类型“{1}”中是私有属性,但在类型“{2}”中不是。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "属性“{0}”受保护,只能通过类“{1}”的实例访问。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "属性“{0}”受保护,只能在类“{1}”及其子类中访问。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "属性“{0}”受保护,但类型“{1}”并不是从“{2}”派生的类。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "属性“{0}”在类型“{1}”中受保护,但在类型“{2}”中为公共属性。", + "Property_0_is_used_before_being_assigned_2565": "在赋值前使用了属性“{0}”。", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 展开特性的“{0}”属性不能分配给目标属性。", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "导出类表达式的属性“{0}”可能不是私密或受保护的属性。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "导出接口的属性“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "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_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\"、对象文字或数组文本。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "以 \"ES5\" 或 \"ES3\" 设为目标时,对 \"for-of\"、传播和析构中的可迭代项提供完全支持。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "导出类的公共方法“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "导出类的公共方法“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "导出类的公共方法“{0}”具有或正在使用专用名称“{1}”。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "导出类的公共属性“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "导出类的公共属性“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "导出类的公共属性“{0}”具有或正在使用专用名称“{1}”。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "导出类的公共静态方法“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "导出类的公共静态方法“{0}”具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "导出类的公共静态方法“{0}”具有或正在使用专用名称“{1}”。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "导出类的公共静态属性“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "导出类的公共静态属性“{0}”具有或正在使用外部模块“{2}”中的名称“{1}”。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "导出类的公共静态属性“{0}”具有或正在使用专用名称“{1}”。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。", + "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", + "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明。", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。", + "Report_errors_in_js_files_8019": ".js 文件中的报表出错。", + "Report_errors_on_unused_locals_6134": "报告未使用的局部变量上的错误。", + "Report_errors_on_unused_parameters_6135": "报告未使用的参数上的错误。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "所需的类型参数可能不遵循可选类型参数。", + "Resolution_for_module_0_was_found_in_cache_6147": "在缓存中找到了模块“{0}”的解析。", + "Resolving_from_node_modules_folder_6118": "正在从 node_modules 文件夹解析...", + "Resolving_module_0_from_1_6086": "======== 正在从“{1}”解析模块“{0}”。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在相对于基 URL“{1}”-“{2}”解析模块名“{0}”。", + "Resolving_real_path_for_0_result_1_6130": "正在解析“{0}”的真实路径,结果为“{1}”。", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 正在解析类型引用指令“{0}”,包含文件“{1}”,根目录“{2}”。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 正在解析类型引用指令“{0}”,包含文件“{1}”,未设置根目录。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 正在解析类型引用指令“{0}”,未设置包含文件,根目录“{1}”。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 正在解析类型引用指令“{0}”,未设置包含文件,未设置根目录。========", + "Resolving_using_primary_search_paths_6117": "正在使用主搜索路径解析...", + "Resolving_with_primary_search_path_0_6121": "正在使用主搜索路径“{0}”解析。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest 参数“{0}”隐式具有 \"any[]\" 类型。", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 类型只能从对象类型创建。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "导出接口中的调用签名的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "导出接口中的调用签名的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "导出接口中的构造函数签名的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "导出接口中的构造函数签名的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "构造函数签名的返回类型必须可赋给类的实例类型。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "导出函数的返回类型具有或正在使用外部模块“{1}”中的名称“{0}”,但不能为其命名。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "导出函数的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "导出函数的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "导出接口中的索引签名的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "导出接口中的索引签名的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "导出接口中的方法的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "导出接口中的方法的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "导出类中的公共 getter“{0}”的返回类型具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "导出类中的公共 getter“{0}”的返回类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "导出类中的公共 getter“{0}”的返回类型具有或正在使用专用名称“{1}”。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "导出类中的公共方法的返回类型具有或正在使用外部模块“{1}”中的名称“{0}”,但不能为其命名。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "导出类中的公共方法的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "导出类中的公共方法的返回类型具有或正在使用专用名称“{0}”。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "导出类中的公共静态 getter“{0}”的返回类型具有或正在使用外部模块“{2}”中的名称“{1}”,但不能为其命名。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "导出类中的公共静态 getter“{0}”的返回类型具有或正在使用私有模块“{2}”中的名称“{1}”。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "导出类中的公共静态 getter“{0}”的返回类型具有或正在使用专用名称“{1}”。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "导出类中的公共静态方法的返回类型具有或正在使用外部模块“{1}”中的名称“{0}”,但不能为其命名。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "导出类中的公共静态方法的返回类型具有或正在使用私有模块“{1}”中的名称“{0}”。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "导出类中的公共静态方法的返回类型具有或正在使用专用名称“{0}”。", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "重用源自“{0}”的模块解析,因为解析在旧程序中未更改。", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "对文件“{1}”重用旧程序中模块 “{0}”的解析。", + "Rewrite_as_the_indexed_access_type_0_90026": "重写为索引访问类型“{0}”。", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "无法确定根目录,正在跳过主搜索路径。", + "STRATEGY_6039": "策略", + "Scoped_package_detected_looking_in_0_6182": "检测到范围包,请在“{0}”中查看", + "Setters_cannot_return_a_value_2408": "Setter 不能返回值。", + "Show_all_compiler_options_6169": "显示所有编译器选项。", + "Show_diagnostic_information_6149": "显示诊断信息。", + "Show_verbose_diagnostic_information_6150": "显示详细的诊断信息。", + "Signature_0_must_be_a_type_predicate_1224": "签名“{0}”必须为类型谓词。", + "Skip_type_checking_of_declaration_files_6012": "跳过声明文件的类型检查。", + "Source_Map_Options_6175": "源映射选项", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "指定的重载签名不可分配给任何非专用化签名。", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "动态导入的说明符不能是扩散元素。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "指定 ECMAScript 目标版本: \"ES3\"(默认)、\"ES5\"、\"ES2015\"、\"ES2016\"、\"ES2017\" 或 \"ESNEXT\"。", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "指定 JSX 代码生成: \"preserve\"、\"react-native\" 或 \"react\"。", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "指定要在编译中包括的库文件: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "指定模块代码生成: \"none\"、\"commonjs\"、\"amd\"、\"system\"、\"umd\"、\"es2015\"或 \"ESNext\"。", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "指定模块解析策略: \"node\" (Node.js)或 \"classic\" (TypeScript pre-1.6)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "指定在设定 \"react\" JSX 发出目标时要使用的 JSX 工厂函数,例如 \"react.createElement\" 或 \"h\"。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "指定发出文件时要使用的行序列结尾: \"CRLF\" (dos)或 \"LF\" (unix)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "指定调试调试程序应将 TypeScript 文件放置到的位置而不是源位置。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "指定调试程序应将映射文件放置到的位置而不是生成的位置。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定输入文件的根目录。与 --outDir 一起用于控制输出目录结构。", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "仅当面向 ECMAScript 5 和更高版本时,\"new\" 表达式中的展开运算符才可用。", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 类型只能从对象类型创建。", + "Statement_expected_1129": "应为语句。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "不允许在环境上下文中使用语句。", + "Static_members_cannot_reference_class_type_parameters_2302": "静态成员不能引用类类型参数。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "静态属性“{0}”与构造函数“{1}”的内置属性函数“{0}”冲突。", + "Strict_Type_Checking_Options_6173": "严格类型检查选项", + "String_literal_expected_1141": "应为字符串文本。", + "String_literal_with_double_quotes_expected_1327": "应为带双引号的字符串文字。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用颜色和上下文风格化错误和消息(实验)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "后续变量声明必须属于同一类型。变量“{0}”必须属于类型“{1}”,但此处却为类型“{2}”。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "模式“{1}”的替换“{0}”类型不正确,应为 \"string\",实际为“{2}”。", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "模式“{1}”中的替换“{0}”最多只可具有一个 \"*\" 字符。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "模式“{0}”的替代应为数组。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "模式“{0}”的替换模式不应为空数组。", + "Successfully_created_a_tsconfig_json_file_6071": "已成功创建 tsconfig.json 文件。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "不允许在构造函数外部或在构造函数内的嵌套函数中进行 Super 调用。", + "Suppress_excess_property_checks_for_object_literals_6072": "取消对象文字的多余属性检查。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "抑制缺少索引签名的索引对象的 noImplicitAny 错误。", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "\"Symbol\" 引用不是指全局符号构造函数对象。", + "Syntax_Colon_0_6023": "语法: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "“{0}”运算符不能应用于类型 \"symbol\"。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "“{0}”运算符不允许用于布尔类型。请考虑改用“{1}”。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "\"Object\" 类型可分配给极少数其他类型。是否想要改用“任意”类型?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "ES3 和 ES5 中的箭头函数不能引用 \"arguments\" 对象。请考虑使用标准函数表达式。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "ES3 和 ES5 中的异步函数或方法不能引用“参数”对象。请考虑使用标准函数或方法。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "\"if\" 语句的正文不能为空语句。", + "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_files_list_in_config_file_0_is_empty_18002": "配置文件“{0}”中的 \"files\" 列表为空。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "承诺的 \"then\" 方法的第一个参数必须是回调。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "\"for...in\" 语句的左侧不能使用类型批注。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "\"for...in\" 语句的左侧必须是变量或属性访问。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "\"for...in\" 语句的左侧必须是 \"string\" 或 \"any\" 类型。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "\"for...of\" 语句的左侧不能使用类型批注。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "\"for...of\" 语句的左侧必须是变量或属性访问。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "算术运算左侧必须是 \"any\"、\"number\" 或枚举类型。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "赋值表达式的左侧必须是变量或属性访问。", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "\"in\" 表达式左侧的类型必须为 \"any\"、\"string\"、\"number\" 或 \"symbol\"。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "\"instanceof\" 表达式左侧必须是 \"any\" 类型、对象类型或类型参数。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "向用户显示消息时所用的区域设置(例如,\"en-us\")", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "用于搜索 node_modules 和加载 JavaScript 文件的最大依赖项深度。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "删除运算符的操作数不能是只读属性。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "删除运算符的操作数必须是属性引用。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "递增或递减运算符的操作数必须是变量或属性访问。", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 元素构造函数的返回类型必须返回对象类型。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "参数修饰器函数的返回类型必须为 \"void\" 或 \"any\"。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "属性修饰器函数的返回类型必须为 \"void\" 或 \"any\"。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "异步函数的返回类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。 ", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "异步函数或方法的返回类型必须为全局 Promise 类型。", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "\"for...in\" 语句右侧必须是 \"any\" 类型、对象类型或类型参数。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "算术运算右侧必须是 \"any\"、\"number\" 或枚举类型。", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "\"in\" 表达式的右侧必须是 \"any\" 类型、对象类型或类型参数。", + "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": "对象 rest 分配的目标必须是变量或属性访问。", + "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}”的类型实参。可以考虑显式指定类型实参。", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "异步迭代器的 \"next()\" 方法返回的类型必须是具有 \"value\" 属性的类型的承诺。", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "迭代器的 \"next()\" 方法返回的类型必须具有 \"value\" 属性。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "\"for...in\" 语句的变量声明不能有初始化表达式。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "\"for...of\" 语句的变量声明不能有初始化表达式。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "不支持 \"with\" 语句。\"with\" 程序块中的所有符号都将具有类型 \"any\"。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此语法需要一个导入的帮助程序,但找不到模块“{0}”。", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "此语法需要一个名为“{1}”的导入帮助程序,但模块“{0}”没有导出的成员“{1}”。", + "Trailing_comma_not_allowed_1009": "不允许使用尾随逗号。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "将每个文件转换为单独的模块(类似 \"ts.transpileModule\")。", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "尝试 \"npm install @types/{0}\" (如果存在),或者添加一个包含“声明模块‘{0}’”的新声明文件(.d.ts);", + "Trying_other_entries_in_rootDirs_6110": "正在尝试 \"rootDirs\" 中的其他条目。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "正在尝试替换“{0}”,候选模块位置:“{1}”。", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "不能将长度为“{1}”的元组类型“{0}”分配给长度为“{2}”的元组。", + "Type_0_cannot_be_converted_to_type_1_2352": "类型“{0}”不可转换为类型“{1}”。", + "Type_0_cannot_be_used_as_an_index_type_2538": "类型“{0}”不能作为索引类型使用。", + "Type_0_cannot_be_used_to_index_type_1_2536": "类型“{0}”无法用于索引类型“{1}”。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "类型“{0}”不满足约束“{1}”。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "类型“{0}”没有匹配的类型“{1}”的索引签名。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "类型“{0}”与类型“{1}”不具有相同的属性。", + "Type_0_has_no_property_1_2460": "类型“{0}”不具有属性“{1}”。", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "类型“{0}”不具有属性“{1}”和字符串索引签名。", + "Type_0_is_not_a_constructor_function_type_2507": "类型“{0}”不是构造函数类型。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "类型“{0}”不是 ES5/ES3 中的有效异步函数返回类型,因为其未引用与 Promise 相符的构造函数值。", + "Type_0_is_not_an_array_type_2461": "类型“{0}”不是数组类型。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "类型“{0}”不是数组类型或字符串类型。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "类型“{0}”不是数组类型或字符串类型,或者没有返回迭代器的 \"[Symbol.iterator]()\" 方法。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "类型“{0}”不是数组类型,或者没有返回迭代器的 \"[Symbol.iterator]()\" 方法。", + "Type_0_is_not_assignable_to_type_1_2322": "不能将类型“{0}”分配给类型“{1}”。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "类型“{0}”无法分配给类型“{1}”。存在具有此名称的两种不同类型,但它们是不相关的。", + "Type_0_is_not_comparable_to_type_1_2678": "类型“{0}”不可与类型“{1}”进行比较。", + "Type_0_is_not_generic_2315": "类型“{0}”不是泛型类型。", + "Type_0_provides_no_match_for_the_signature_1_2658": "类型“{0}”提供的内容与签名“{1}”不匹配。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "类型“{0}”以递归方式将自身引用为基类。", + "Type_alias_0_circularly_references_itself_2456": "类型别名“{0}”循环引用自身。", + "Type_alias_name_cannot_be_0_2457": "类型别名不能为“{0}”。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "类型批注不能出现在构造函数声明中。", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "候选类型参数“{1}”不是有效的类型参数,因为它不是候选“{0}”的超类型。", + "Type_argument_expected_1140": "应为类型参数。", + "Type_argument_list_cannot_be_empty_1099": "类型参数列表不能为空。", + "Type_declaration_files_to_be_included_in_compilation_6124": "要包含在编译中类型声明文件。", + "Type_expected_1110": "应为类型。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "类型在其自身的 \"then\" 方法的 fulfillment 回调中被直接或间接引用。", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "类型必须具有返回异步迭代器的 \"[Symbol.asyncIterator]()\" 方法。", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "类型必须具有返回迭代器的 \"[Symbol.iterator]()\" 方法。", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "\"await\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "\"yield*\" 操作数的迭代元素的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "异步生成器中 \"yield\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", + "Type_parameter_0_has_a_circular_constraint_2313": "类型参数“{0}”具有循环约束。", + "Type_parameter_0_has_a_circular_default_2716": "类型参数“{0}”具有循环默认值。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "导出接口中的调用签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "导出接口中的构造函数签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "导出类的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "导出函数的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "导出接口的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "已导出类型别名的类型参数“{0}”具有或正使用专用名称“{1}”。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "导出接口中的方法的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "导出类中的公共方法的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "导出类中的公共静态方法的类型参数“{0}”具有或正在使用专用名称“{1}”。", + "Type_parameter_declaration_expected_1139": "应为类型参数声明。", + "Type_parameter_list_cannot_be_empty_1098": "类型参数列表不能为空。", + "Type_parameter_name_cannot_be_0_2368": "类型参数名称不能为“{0}”。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "类型参数不能出现在构造函数声明中。", + "Type_predicate_0_is_not_assignable_to_1_1226": "类型谓词“{0}”不可分配给“{1}”。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 未解析类型引用指令“{0}”。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 类型引用指令“{0}”已成功解析为“{1}”,主要: {2}。========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "类型具有私有属性“{0}”的单独声明。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "参数“{0}”和“{1}” 的类型不兼容。", + "Types_of_property_0_are_incompatible_2326": "属性“{0}”的类型不兼容。", + "Unable_to_open_file_0_6050": "无法打开文件“{0}”。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "作为表达式调用时,无法解析类修饰器的签名。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "作为表达式调用时,无法解析方法修饰器的签名。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "作为表达式调用时,无法解析参数修饰器的签名。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "作为表达式调用时,无法解析属性修饰器的签名。", + "Unexpected_end_of_text_1126": "文本意外结束。", + "Unexpected_token_1012": "意外的标记。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "意外的标记。应为构造函数、方法、访问器或属性。", + "Unexpected_token_expected_1179": "意外标记。应为 \"{\"。", + "Unknown_compiler_option_0_5023": "未知的编译器选项“{0}”。", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "未知的 \"excludes\" 选项。你的意思是 \"exclude\"?", + "Unknown_type_acquisition_option_0_17010": "未知类型获取选项“{0}”。", + "Unreachable_code_detected_7027": "检测到无法访问的代码。", + "Unsupported_locale_0_6049": "区域设置“{0}”不受支持。", + "Unterminated_Unicode_escape_sequence_1199": "未终止的 Unicode 转义序列。", + "Unterminated_quoted_string_in_response_file_0_6045": "响应文件“{0}”中引号不配对。", + "Unterminated_regular_expression_literal_1161": "未终止的正则表达式文本。", + "Unterminated_string_literal_1002": "未终止的字符串文本。", + "Unterminated_template_literal_1160": "未终止的模板文本。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "非类型化函数调用不能接受类型参数。", + "Unused_label_7028": "未使用的标签。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", + "VERSION_6036": "版本", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "类型“{0}”的值没有与类型“{1}”相同的属性。你是想调用它吗?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "类型“{0}”的值不可调用。是否希望包括 \"new\"?", + "Variable_0_implicitly_has_an_1_type_7005": "变量“{0}”隐式具有“{1}”类型。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "变量“{0}”在某些无法确定其类型的位置处隐式具有类型“{1}”。", + "Variable_0_is_used_before_being_assigned_2454": "在赋值前使用了变量“{0}”。", + "Variable_declaration_expected_1134": "应为变量声明。", + "Variable_declaration_list_cannot_be_empty_1123": "变量声明列表不能为空。", + "Version_0_6029": "版本 {0}", + "Watch_input_files_6005": "监视输入文件。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "不能重命名标准 TypeScript 库中定义的元素。", + "You_cannot_rename_this_element_8000": "无法重命名此元素。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "“{0}”收到的参数过少,无法在此处充当修饰器。你是要先调用它,然后再写入 \"@{0}()\" 吗?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "“{0}”被指定了两次。将覆盖名为“{0}”的特性。", + "_0_can_only_be_used_in_a_ts_file_8009": "“{0}”只能在 .ts 文件中使用。", + "_0_expected_1005": "应为“{0}”。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "由于“{0}'”不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "“{0}”隐式具有类型 \"any\",因为它不具有类型批注,且在其自身的初始化表达式中得到直接或间接引用。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "“{0}”是基元,但“{1}”是包装器对象。如可能首选使用“{0}”。", + "_0_is_declared_but_its_value_is_never_read_6133": "已声明“{0}”,但从未读取其值。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "“{0}”不是关键字“{1}”的有效元属性。是否是指“{2}”?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "“{0}”在其自身的基表达式中得到直接或间接引用。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "“{0}”在其自身的类型批注中得到直接或间接引用。", + "_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_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\" 修饰符仅可出现在类、方法或属性声明中。", + "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": "\"=\" 只可在重构赋值内部的对象文字属性中使用。", + "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\" 枚举仅可在属性、索引访问表达式、导入声明的右侧或导出分配中使用。", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "在严格模式下,无法对标识符调用 \"delete\"。", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" 只能在 .ts 文件中使用。", + "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" 只能在 .ts 文件中使用。", + "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}”。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "导出接口“{0}”的 \"extends\" 子句具有或正在使用专用名称“{1}”。", + "file_6025": "文件", + "get_and_set_accessor_must_have_the_same_this_type_2682": "\"get\" 和 \"set\" 访问器必须拥有相同的 \"this\" 类型。", + "get_and_set_accessor_must_have_the_same_type_2380": "\"get\" 和 \"set\" 访问器必须属于同一类型。", + "implements_clause_already_seen_1175": "已看到 \"implements\" 子句。", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "\"implements clauses\" 只能在 .ts 文件中使用。", + "import_can_only_be_used_in_a_ts_file_8002": "\"import ... =\" 只能在 .ts 文件中使用。", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "\"interface declarations\" 只能在 .ts 文件中使用。", + "let_declarations_can_only_be_declared_inside_a_block_1157": "\"let\" 声明只能在块的内部声明。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "\"let\" 不能用作 \"let\" 或 \"const\" 声明中的名称。", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "\"module declarations\" 只能在 .ts 文件中使用。", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "\"new T[]\" 不能用于创建数组。请改用 \"new Array()\"。", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "其目标缺少构造签名的 \"new\" 表达式隐式具有 \"any\" 类型。", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "\"non-null assertions\" 只能在 .ts 文件中使用。", + "options_6024": "选项", + "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 文件中使用。", + "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\" 仅可出现在属性声明或索引签名中。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。", + "super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "不能在计算属性名中引用 \"super\"。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "不能在构造函数参数中引用 \"super\"。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "\"target\" 选项为 \"ES2015\" 或更高版本时,仅对象文字表达式的成员中允许 \"super\"。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "访问派生类构造函数中的 \"super\" 属性前,必须调用 \"super\"。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "访问派生类的构造函数中的 \"this\" 前,必须调用 \"super\"。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "\"super\" 的后面必须是参数列表或成员访问。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "只有构造函数、成员函数或派生类的成员访问器中才允许 \"super\" 属性访问。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "不能在计算属性名中引用 \"this\"。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "不能在模块或命名空间体中引用 \"this\"。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "不能在静态属性初始化表达式中引用 \"this\"。", + "this_cannot_be_referenced_in_constructor_arguments_2333": "不能在构造函数参数中引用 \"this\"。", + "this_cannot_be_referenced_in_current_location_2332": "不能在当前位置引用 \"this\"。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "\"this\" 隐式具有类型 \"any\",因为它没有类型注释。", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "\"type aliases\" 只能在 .ts 文件中使用。", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "\"type arguments\" 只能在 .ts 文件中使用。", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" 只能在 .ts 文件中使用。", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" 只能在 .ts 文件中使用。", + "types_can_only_be_used_in_a_ts_file_8010": "\"types\" 只能在 .ts 文件中使用。", + "unique_symbol_types_are_not_allowed_here_1335": "此处不允许“唯一符号”类型。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "“唯一符号”类型仅可在变量语句中的变量上使用。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "不可在具有绑定名称的变量声明中使用“唯一符号”类型。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "不允许在异步函数块中使用 \"with\" 语句。", + "with_statements_are_not_allowed_in_strict_mode_1101": "严格模式下不允许使用 \"with\" 语句。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "不能在参数初始化表达式中使用 \"yield\" 表达式。" +} \ No newline at end of file diff --git a/lib/zh-TW/diagnosticMessages.generated.json b/lib/zh-TW/diagnosticMessages.generated.json new file mode 100644 index 0000000000000..39a6a077fbf49 --- /dev/null +++ b/lib/zh-TW/diagnosticMessages.generated.json @@ -0,0 +1,972 @@ +{ + "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_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}' 關鍵字。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "計算的屬性名稱中不可有逗點運算式。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算的屬性名稱不得參考其包含類型中的型別參數。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "類別屬性宣告中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法多載中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型別常值中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境內容中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "介面中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算的屬性名稱必須是 'string'、'number'、'symbol' 或 'any' 類型。", + "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "格式為 '{0}' 之計算的屬性名稱必須是 'symbol' 類型。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "若要存取常數列舉成員,必須透過字串常值。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "環境內容中的 'const' 初始設定式必須為字串或數字常值。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "當建構函式的類別擴充為 'null' 時,不得包含 'super' 呼叫。", + "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_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_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' 建構函式的宣告,或在 `--lib` 選項中納入 'ES2015'。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "動態匯入呼叫傳回 'Promise'。請確認您有 'Promise' 的宣告,或在 `--lib` 選項中納入 'ES2015'。", + "A_file_cannot_have_a_reference_to_itself_1006": "檔案不得參考自己。", + "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "只在非同步函式或非同步產生器中才允許 'for-await-of' 陳述式。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "會傳回 'never' 的功能不得具有可聯繫的端點。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "透過 'new' 關鍵字呼叫的函式不能含有為 'viod' 的 'this' 類型。", + "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355": "若函式的宣告類型既不是 'void' 也不是 'any',則必須傳回值。", + "A_generator_cannot_have_a_void_type_annotation_2505": "產生器不得有 'void' 類型註釋。", + "A_get_accessor_cannot_have_parameters_1054": "'get' 存取子不得有參數。", + "A_get_accessor_must_return_a_value_2378": "'get' 存取子必須傳回值。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "列舉宣告中的成員初始設定式,不得參考在它之後宣告的成員,包括在其他列舉中所定義的成員。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 類別必須具備建構函式,且該建構函式必須指定一個類型為 'any[]' 的 rest 參數。", + "A_module_cannot_have_multiple_default_exports_2528": "一個模組不得有多個預設匯出。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空間宣告的所在檔案位置,不得與其要合併的類別或函式不同。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空間宣告的位置不得先於其要合併的類別或函式。", + "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只有命名空間或模組才允許命名空間宣告。", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只有函式或建構函式實作才可使用參數初始設定式。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "無法使用剩餘參數宣告參數屬性。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "建構函式實作中只可有一個參數屬性。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "無法使用繫結模式宣告參數屬性。", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "[擴充] 選項中的路徑必須為相對或根路徑,但 '{0}' 並不是。", + "A_promise_must_have_a_then_method_1059": "Promise 必須有 'then' 方法。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型別為 'unique symbol' 型別的類別屬性必須同時為 'static' 與 'readonly'。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型別為 'unique symbol' 型別的介面或型別常值屬性必須是 'readonly'。", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必要參數不得接在選擇性參數之後。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "剩餘項目不得包含繫結模式。", + "A_rest_element_cannot_have_an_initializer_1186": "剩餘項目不得有初始設定式。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Rest 項目必須保持在解構模式。", + "A_rest_parameter_cannot_be_optional_1047": "剩餘參數不得為選擇性參數。", + "A_rest_parameter_cannot_have_an_initializer_1048": "剩餘參數不得有初始設定式。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "剩餘參數必須是參數清單中的最後一個參數。", + "A_rest_parameter_must_be_of_an_array_type_2370": "剩餘參數必須為陣列類型。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 陳述式只可在函式主體內使用。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列由重新對應匯入到 'baseUrl' 之相對查詢位置的項目。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 存取子不得有傳回型別註解。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' 存取子不得有選擇性參數。", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' 存取子不得有剩餘參數。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' 存取子只可有一個參數。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' 存取子參數不得有初始設定式。", + "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381": "包含實作的簽章不得使用字串常值類型。", + "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376": "當類別包含已初始化的屬性或參數屬性時,'super' 呼叫必須是建構函式中的第一個陳述式。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "以 'this' 為基礎的類型成立條件,和以參數為基礎的類型成立條件不相容。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 類型只適用於類別或介面的非靜態成員。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 檔案已定義於: '{0}'。", + "A_tuple_type_element_list_cannot_be_empty_1122": "元組類型項目清單不得為空白。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "乘冪運算式左邊不允許類型宣告運算式。請考慮以括弧括住運算式。", + "A_type_literal_property_cannot_have_an_initializer_1247": "類型常值屬性不得有初始設定式。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "型別述詞不得參考剩餘參數。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "型別述詞不得參考繫結模式的項目 '{0}'。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "只有函式及方法的傳回型別位置才允許型別述詞。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "類型述詞的類型必須可指派給其參數的類型。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型別為 'unique symbol' 型別的變數必須是 'const'。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "只有產生器主體才允許 'yield' 運算式。", + "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": "已有存取範圍修飾詞。", + "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_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章。", + "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫。", + "Add_this_to_unresolved_variable_90008": "將 'this.' 新增到未經解析的變數。", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "新增 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_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。", + "Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。", + "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_abstract_accessor_cannot_have_an_implementation_1318": "抽象存取子無法實作。", + "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "不得在環境內容中宣告存取子", + "An_accessor_cannot_have_type_parameters_1094": "存取子不得有類型參數。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "環境模組宣告只可出現在檔案的最上層。", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "算術運算元必須是 'any'、'number' 或列舉類型。", + "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 中的非同步函式或方法需要 'Promise' 建構函式。請確認您有 'Promise' 建構函式的宣告,或在 `--lib` 選項中納入 'ES2015'。", + "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同步函式或方法必須包含有效可等候的傳回型別。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同步函式或方法必須傳回 'Promise'。請確定您有 'Promise' 的宣告或將 'ES2015' 納入您的 '-lib' 選項。", + "An_async_iterator_must_have_a_next_method_2519": "非同步迭代器必須有 'next()' 方法。", + "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_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 (不含) 之間。", + "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_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_initializer_1020": "索引簽章參數不得有初始設定式。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引簽章參數必須有類型註釋。", + "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引簽章參數類型必須是 'string' 或 'number'。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "介面只能擴充具有選擇性型別引數的識別碼/限定名稱。", + "An_interface_may_only_extend_a_class_or_another_interface_2312": "每個介面只可擴充一個類別或另一個介面。", + "An_interface_property_cannot_have_an_initializer_1246": "介面屬性不得有初始設定式。", + "An_iterator_must_have_a_next_method_2489": "迭代器必須要有 'next()' 方法。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "物件常值不得有多個同名的 get/set 存取子。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117": "在 strict 模式中,物件常值不得有多個同名的屬性。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "物件常值不得有同名的屬性與存取子。", + "An_object_member_cannot_be_declared_optional_1162": "不得將物件成員宣告為選擇性。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "不可將多載簽章宣告為產生器。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "乘冪運算式左邊不允許具 '{0}' 運算子的一元運算式。請考慮以括弧括住運算式。", + "Annotate_with_type_from_JSDoc_95009": "為來自 JSDoc 的類型標註", + "Annotate_with_types_from_JSDoc_95010": "為來自 JSDoc 的類型標註", + "Argument_expression_expected_1135": "必須是引數運算式。", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 選項的引數必須是: {1}。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "類型 '{0}' 的引數不可指派給類型 '{1}' 的參數。", + "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' 修飾詞。", + "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}' 不是類別或介面類型。", + "Base_constructors_must_all_have_the_same_return_type_2510": "基底建構函式的傳回型別必須全部相同。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "要解析非絕對模組名稱的基底目錄。", + "Basic_Options_6172": "基本選項", + "Binary_digit_expected_1177": "必須是二進位數字。", + "Binding_element_0_implicitly_has_an_1_type_7031": "繫結元素 '{0}' 隱含擁有 '{1}' 類型。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "已在其宣告之前使用區塊範圍變數 '{0}'。", + "Call_decorator_expression_90028": "呼叫裝飾項目運算式。", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "缺少傳回型別註解的呼叫簽章隱含了 'any' 傳回型別。", + "Call_target_does_not_contain_any_signatures_2346": "呼叫目標未包含任何特徵標記。", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "因為 '{0}' 是類型而非命名空間,所以無法存取 '{0}.{1}'。您要在 '{0}' 中使用 '{0}[\"{1}\"]' 擷取屬性 '{1}' 的類型嗎?", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "無法將 '{0}' 建構函式類型指派至 '{1}' 建構函式類型。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "無法將抽象建構函式類型指派給非抽象建構函式類型。", + "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540": "無法指派至 '{0}',因為它是常數或唯讀屬性。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "無法指派至 '{0}',因為它不是變數。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "因為模組 '{0}' 會解析為非模組實體,所以無法加以增強。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "無法使用值匯出擴充模組 '{0}',因為其會解析為非模組實體。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "除非 '--module' 旗標為 'amd' 或 'system',否則無法使用選項 '{0}' 編譯模組。", + "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208": "提供 '--isolatedModules' 旗標時,無法編譯命名空間。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "無法建立抽象類別的執行個體。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "無法匯出 '{0}'。只有區域宣告可以從模組匯出。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "無法延伸類別 '{0}'。類別建構函式已標記為私用。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "無法擴充介面 '{0}',您意指「實作」嗎?", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "在指定的目錄 '{0}' 中找不到 tsconfig.json 檔案。", + "Cannot_find_global_type_0_2318": "找不到全域類型 '{0}'。", + "Cannot_find_global_value_0_2468": "找不到全域值 '{0}'。", + "Cannot_find_module_0_2307": "找不到模組 '{0}'。", + "Cannot_find_name_0_2304": "找不到名稱 '{0}'。", + "Cannot_find_name_0_Did_you_mean_1_2552": "找不到名稱 '{0}'。您指的是 '{1}' 嗎?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "找不到名稱 '{0}'。您要找的是此執行個體成員 'this.{0}' 嗎?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "找不到名稱 '{0}'。您要找的是此靜態成員 '{1}.{0}' 嗎?", + "Cannot_find_namespace_0_2503": "找不到命名空間 '{0}'。", + "Cannot_find_parameter_0_1225": "找不到參數 '{0}'。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到輸入檔案的一般子目錄路徑。", + "Cannot_find_type_definition_file_for_0_2688": "找不到 '{0}' 的類型定義檔案。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "無法匯入型別宣告檔案。請考慮匯入 '{0}' 而不是 '{1}'。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "無法初始化區塊範圍宣告 '{1}' 之同一範圍中的外部範圍變數 '{0}'。", + "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "無法叫用類型缺少呼叫簽章的運算式。類型 '{0}' 不含相容的呼叫簽章。", + "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。", + "Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。", + "Cannot_redeclare_exported_variable_0_2323": "無法重新宣告匯出的變數 '{0}'。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "無法在 Catch 子句中重新宣告識別碼 '{0}'。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "除非有提供 '--jsx' 旗標,否則無法使用 JSX。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "當 '--module' 為 'none' 時,無法使用匯入、匯出或模組增強指定。", + "Cannot_use_namespace_0_as_a_type_2709": "不得使用命名空間 '{0}' 作為類型。", + "Cannot_use_namespace_0_as_a_value_2708": "不得使用命名空間 '{0}' 作為值。", + "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351": "類型缺少呼叫或建構簽章的運算式,不得與 'new' 一起使用。", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "無法寫入檔案 '{0}',原因是其會由多個輸入檔覆寫。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "無法寫入檔案 '{0}',原因是其會覆寫輸入檔。", + "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 子句變數不得有類型註釋。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 子句變數不得有初始設定式。", + "Change_0_to_1_90014": "將 '{0}' 變更為 '{1}'。", + "Change_extends_to_implements_90003": "將 'extends' 變更為 'implements'。", + "Change_spelling_to_0_90022": "將拼字變更為 '{0}'。", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "檢查 '{0}' 是否為 '{1}' - '{2}' 的最長相符前置詞。", + "Circular_definition_of_import_alias_0_2303": "匯入別名 '{0}' 的循環定義。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "解析組態時偵測到循環性: {0}", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "類別 '{0}' 已定義執行個體成員存取子 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員函式。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "類別 '{0}' 已定義執行個體成員函式 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員存取子。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "類別 '{0}' 已定義執行個體成員函式 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員屬性。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "類別 '{0}' 已定義執行個體成員屬性 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員函式。", + "Class_0_incorrectly_extends_base_class_1_2415": "類別 '{0}' 不正確地擴充基底類別 '{1}'。", + "Class_0_incorrectly_implements_interface_1_2420": "類別 '{0}' 不正確地實作介面 '{1}'。", + "Class_0_used_before_its_declaration_2449": "類別 '{0}' 的位置在其宣告之前。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "類別宣告只可有一個 '@augments' 或 '@extends' 標記。", + "Class_name_cannot_be_0_2414": "類別名稱不得為 '{0}'。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "類別靜態端 '{0}' 不正確地擴充基底類別靜態端 '{1}'。", + "Classes_can_only_extend_a_single_class_1174": "類別只能擴充一個類別。", + "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "包含抽象方法的類別必須標記為抽象。", + "Command_line_Options_6171": "命令列選項", + "Compilation_complete_Watching_for_file_changes_6042": "編譯完成。正在等候檔案變更。", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。", + "Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。", + "Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "具有字串值成員的列舉中不允許計算值。", + "Concatenate_and_emit_output_to_single_file_6001": "串連並發出輸出至單一檔案。", + "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "在 '{1}' 和 '{2}' 找到衝突的 '{0}' 定義。請考慮安裝此程式庫的特定版本以解決衝突。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "缺少傳回型別註解的建構簽章,隱含有 'any' 傳回型別。", + "Constructor_implementation_is_missing_2390": "缺少建構函式實作。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "類別 '{0}' 的建構函式為私用,並且只能在類別宣告內存取。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "類別 '{0}' 的建構函式受到保護,並且只能在類別宣告內存取。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "衍生類別的建構函式必須包含 'super' 呼叫。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。", + "Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別", + "Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別", + "Convert_to_default_import_95013": "轉換為預設匯入", + "Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "找不到模組 '{0}' 的宣告檔案。'{1}' 隱含具有 'any' 類型。", + "Could_not_write_file_0_Colon_1_5033": "無法編寫檔案 '{0}': {1}。", + "DIRECTORY_6038": "目錄", + "Declaration_expected_1146": "必須是宣告。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣告名稱與內建全域識別碼 '{0}' 衝突。", + "Declaration_or_statement_expected_1128": "必須是宣告或陳述式。", + "Declare_method_0_90023": "宣告方法 '{0}'。", + "Declare_property_0_90016": "宣告屬性 '{0}'。", + "Declare_static_method_0_90024": "宣告靜態方法 '{0}'。", + "Declare_static_property_0_90027": "宣告靜態屬性 '{0}'。", + "Decorators_are_not_valid_here_1206": "裝飾項目在此處無效。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "無法將裝飾項目套用至多個同名的 get/set 存取子。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模組的預設匯出具有或正在使用私用名稱 '{0}'。", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[即將淘汰] 請改用 '--jsxFactory'。當目標為 'react' JSX 發出時,為 createElement 指定所叫用的物件", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[即將淘汰] 請改用 '--outFile'。 串連輸出並將其發出到單一檔案", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[即將淘汰] 請改用 '--skipLibCheck'。跳過預設程式庫宣告檔案的類型檢查。", + "Digit_expected_1124": "必須是數字。", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "目錄 '{0}' 不存在,將會跳過其中所有查閱。", + "Disable_checking_for_this_file_90018": "停用此檔案的檢查。", + "Disable_size_limitations_on_JavaScript_projects_6162": "停用 JavaScript 專案的大小限制。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "停用函式類型中一般簽章的 Strict 檢查。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "不允許相同檔案大小寫不一致的參考。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "不要在編譯後的檔案清單中新增三道斜線的參考或匯入的模組。", + "Do_not_emit_comments_to_output_6009": "請勿將註解發出到輸出。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "請勿發出包含 '@internal' 註釋的程式碼宣告。", + "Do_not_emit_outputs_6010": "請勿發出輸出。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "如果回報了任何錯誤,即不發出輸出。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "請勿在模組輸出中發出 'use strict' 指示詞。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "請勿清除產生之程式碼中的 const 列舉宣告。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "不要在編譯後的輸出中產生自訂的協助程式函式,例如 '__extends'。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "不要包含預設程式庫檔案 (lib.d.ts)。", + "Do_not_report_errors_on_unreachable_code_6077": "請勿回報無法執行到之程式碼的錯誤。", + "Do_not_report_errors_on_unused_labels_6074": "請勿回報未使用之標籤的錯誤。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "請勿解析符號連結的真實路徑。", + "Do_not_truncate_error_messages_6165": "不要截斷錯誤訊息。", + "Duplicate_declaration_0_2718": "重複宣告 '{0}'。", + "Duplicate_function_implementation_2393": "函式實作重複。", + "Duplicate_identifier_0_2300": "識別碼 '{0}' 重複。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "識別碼 '{0}' 重複。編譯器會將名稱 '{1}' 保留在模組的最上層範圍中。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "識別碼 '{0}' 重複。編譯器會將名稱 '{1}' 保留在含有非同步函式模組的最上層範圍中。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "識別碼 '{0}' 重複。編譯器會使用宣告 '{1}' 支援非同步函式。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "識別碼 'arguments'' 重複。編譯器會使用 'arguments' 來初始化剩餘參數。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "識別碼 '_newTarget' 重複。編譯器使用變數宣告 '_newTarget' 擷取 'new.target' 中繼屬性參考。", + "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401": "識別碼 '_super' 重複。編譯器會使用 '_super' 來擷取基底類別參考。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "識別碼 '_this' 重複。編譯器會使用變數宣告 '_this' 來擷取 'this' 參考。", + "Duplicate_label_0_1114": "標籤 '{0}' 重複。", + "Duplicate_number_index_signature_2375": "數字索引簽章重複。", + "Duplicate_string_index_signature_2374": "字串索引簽章重複。", + "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "以 ECMAScript 2015 模組為目標時,無法使用動態匯入。", + "Dynamic_import_cannot_have_type_arguments_1326": "動態匯入不能有型別引數", + "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動態匯入必須有一個指定名稱作為引數。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動態匯入的指定名稱必須屬於類型 'string',但這裡的類型為 '{0}'。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "因為索引運算式不屬於類型 'number',所以元素具有隱含 'any' 類型。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "元素隱含地擁有 'any' 類型,因為類型 '{0}' 不具索引簽章。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "在輸出檔的開頭發出 UTF-8 位元組順序標記 (BOM)。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "發出單一檔案包含來源對應,而不要使用個別的檔案。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "使用單一檔案發出來源與來源對應。必須設定 '--inlineSourceMap' 或 '--sourceMap'。", + "Enable_all_strict_type_checking_options_6180": "啟用所有 Strict 類型檢查選項。", + "Enable_strict_checking_of_function_types_6186": "啟用嚴格檢查函式類型。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。", + "Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。", + "Enable_tracing_of_the_name_resolution_process_6085": "啟用名稱解析流程的追蹤。", + "Enables_experimental_support_for_ES7_async_functions_6068": "啟用 ES7 非同步函式的實驗支援。", + "Enables_experimental_support_for_ES7_decorators_6065": "啟用 ES7 裝飾項目的實驗支援。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "啟用實驗支援以發出裝飾項目類型的中繼資料。", + "Enum_0_used_before_its_declaration_2450": "列舉 '{0}' 的位置在其宣告之前。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "列舉宣告必須都是 const 或非 const。", + "Enum_member_expected_1132": "必須是列舉成員。", + "Enum_member_must_have_initializer_1061": "列舉成員必須有初始設定式。", + "Enum_name_cannot_be_0_2431": "列舉名稱不得為 '{0}'。", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "列舉類型 '{0}' 有初始設定式非常值的成員。", + "Examples_Colon_0_6026": "範例: {0}", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "比較類型 '{0}' 與 '{1}' 的堆疊深度過深。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "必須是 {0}-{1} 型別引數; 請提供有 '@ extends' 標記的這類型引數。", + "Expected_0_arguments_but_got_1_2554": "應有 {0} 個引數,但得到 {1} 個。", + "Expected_0_arguments_but_got_1_or_more_2556": "應有 {0} 個引數,但得到 {1} 個或更多。", + "Expected_0_type_arguments_but_got_1_2558": "應有 {0} 個型別引數,但得到 {1} 個。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "必須是 {0} 型別引數; 請提供有 '@ extends' 標記的這類引數。", + "Expected_at_least_0_arguments_but_got_1_2555": "至少應有 {0} 個引數,但得到 {1} 個。", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "應有至少 {0} 個引數,但得到 {1} 個或更多。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' 需要對應的 JSX 結尾標記。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX 片段必須有對應的結尾標記。", + "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "在 'package.json' 中 '{0}' 欄位的類型必須為 'string',但得到 '{1}'。", + "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_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}' 不是模組。請連絡封裝作者以更新封裝定義。", + "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "匯出的外部封裝類型檔案不得包含三斜線的參考。請連絡封裝作者以更新封裝定義。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "匯出的類型別名 '{0}' 具有或使用私用名稱 '{1}'。", + "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": "模組增強指定中不允許匯出及匯出指派。", + "Expression_expected_1109": "必須是運算式。", + "Expression_or_comma_expected_1137": "必須是運算式或逗號。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "運算式會解析成 '_super',而編譯器會使用其來擷取基底類別參考。", + "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "運算式會解析成變數宣告 '{0}',而編譯器會使用此宣告支援非同步函式。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "運算式解析成編譯器用來擷取 'new.target' 中繼屬性參考的變數宣告 '_newTarget'。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "運算式會解析成變數宣告 '_this',而編譯器會使用此宣告來擷取 'this' 參考 。", + "Extract_constant_95006": "解壓縮常數", + "Extract_function_95005": "解壓縮函式", + "Extract_symbol_95003": "解壓縮符號", + "Extract_to_0_in_1_95004": "解壓縮至 {1} 中的 {0}", + "Extract_to_0_in_1_scope_95008": "解壓縮至 {1} 範圍中的 {0}", + "Extract_to_0_in_enclosing_scope_95007": "解壓縮至封閉式範圍中的 {0}", + "FILE_6035": "檔案", + "FILE_OR_DIRECTORY_6040": "檔案或目錄", + "Failed_to_parse_file_0_Colon_1_5014": "無法剖析檔案 '{0}': {1}。", + "Fallthrough_case_in_switch_7029": "參數中的 fallthrough 案例。", + "File_0_does_not_exist_6096": "檔案 '{0}' 不存在。", + "File_0_exist_use_it_as_a_name_resolution_result_6097": "檔案 '{0}' 存在 - 將其作為名稱解析結果使用。", + "File_0_has_an_unsupported_extension_so_skipping_it_6081": "因為不支援檔案 '{0}' 的副檔名,所以將其跳過。", + "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "檔案 '{0}' 的附檔名不受支援。僅支援副檔名 {1}。", + "File_0_is_not_a_module_2306": "檔案 '{0}' 不是模組。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "檔案 '{0}' 不在 'rootDir' '{1}' 之下。'rootDir' 必須包含所有原始程式檔。", + "File_0_not_found_6053": "找不到檔案 '{0}'。", + "File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "檔案名稱 '{0}' 與包含的檔案名稱 '{1}' 只差在大小寫。", + "File_name_0_has_a_1_extension_stripping_it_6132": "檔案名稱 '{0}' 的副檔名為 '{1}'。正予以移除。", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "檔案規格不得包含出現在遞迴目錄萬用字元 ('**') 之後的父目錄 ('..'): '{0}'。", + "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "檔案規格不能包含多個遞迴目錄萬用字元 ('**'): '{0}'。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "檔案規格不能以遞迴目錄萬用字元 ('**') 結尾: '{0}'。", + "Found_package_json_at_0_6099": "在 '{0}' 找到 'package.json'。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。類別定義會自動進入 strict 模式。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。模組會自動進入 strict 模式。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "缺少傳回型別註解的函式運算式隱含了 '{0}' 傳回型別。", + "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_overload_must_be_static_2387": "函式多載必須為靜態。", + "Function_overload_must_not_be_static_2388": "函式多載不可為靜態。", + "Generates_corresponding_d_ts_file_6002": "產生對應的 '.d.ts' 檔案。", + "Generates_corresponding_map_file_6043": "產生對應的 '.map' 檔案。", + "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "產生器因為沒有產生任何值,所以隱含有類型 '{0}'。請考慮提供傳回型別。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "環境內容中不允許產生器。", + "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "只有在目標為 ECMAScript 2015 或更高版本時,才可使用產生器。", + "Generic_type_0_requires_1_type_argument_s_2314": "泛型類型 '{0}' 需要 {1} 個型別引數。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "泛型型別 '{0}' 需要介於 {1} 和 {2} 之間的型別引數。", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "泛型類型具現化的深度過深,而且可能是無限深。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "getter 和 setter 存取子的可視性不符。", + "Global_module_exports_may_only_appear_at_top_level_1316": "全域模組匯出只能顯示在最上層。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "全域模組匯出只能顯示在宣告檔案中。", + "Global_module_exports_may_only_appear_in_module_files_1314": "全域模組匯出只能顯示在模組檔案中。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "全域類型 '{0}' 必須是類別或介面類型。", + "Global_type_0_must_have_1_type_parameter_s_2317": "全域類型 '{0}' 必須要有 {1} 個型別參數。", + "Hexadecimal_digit_expected_1125": "必須適十六進位數字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "必須是識別碼。'{0}' 在 strict 模式中為保留字。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "必須是識別碼。'{0}' 是 strict 模式中的保留字。類別定義會自動採用 strict 模式。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "需要識別碼。'{0}' 是 strict 模式中的保留字。模組會自動採用 strict 模式。", + "Identifier_expected_1003": "必須是識別碼。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "必須有識別碼。'__esModule' 已保留為轉換 ECMAScript 模組時匯出的標記。", + "Ignore_this_error_message_90019": "忽略此錯誤訊息。", + "Implement_inherited_abstract_class_90007": "實作已繼承的抽象類別。", + "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_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": "命名空間中的匯入宣告不得參考模組。", + "Import_emit_helpers_from_tslib_6139": "從 'tslib' 匯入發出協助程式。", + "Import_name_cannot_be_0_2438": "匯入名稱不得為 '{0}'。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "環境模組宣告中的匯入或匯出宣告,不得透過相對模組名稱參考模組。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "模組增強指定中不允許匯入。請考慮將其移至封入外部模組。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在環境列舉宣告中,成員初始設定式必須是常數運算式。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在具有多個宣告的列舉中,只有一個宣告可以在其第一個列舉項目中省略初始設定式。", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 'const' 列舉宣告中,成員初始設定式必須是常數運算式。", + "Index_signature_in_type_0_only_permits_reading_2542": "類型 '{0}' 中的索引簽章只允許讀取。", + "Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。", + "Index_signatures_are_incompatible_2330": "索引簽章不相容。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合併宣告 '{0}' 中的個別宣告必須全部匯出或全在本機上。", + "Infer_parameter_types_from_usage_95012": "從用法推斷參數類型。", + "Infer_type_of_0_from_usage_95011": "從用法推斷 '{0}' 的類型。", + "Initialize_property_0_in_the_constructor_90020": "初始化建構函式中的屬性 '{0}'。", + "Initialize_static_property_0_90021": "初始化靜態屬性 '{0}'。", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "執行個體成員變數 '{0}' 的初始設定式不得參考建構函式中所宣告的識別碼 '{1}'。", + "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "參數 '{0}' 的初始設定式不得參考在其之後宣告的識別碼 '{1}'。", + "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始設定式未提供任何值給這個繫結項目,且該繫結項目沒有預設值。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "環境內容中不得有初始設定式。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "初始化 TypeScript 專案並建立 tsconfig.json 檔案。", + "Insert_command_line_options_and_files_from_a_file_6030": "從檔案插入命令列選項與檔案。", + "Install_0_95014": "安裝 '{0}'", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "介面 '{0}' 不能同時擴充類型 '{1}' 和 '{2}'。", + "Interface_0_incorrectly_extends_interface_1_2430": "介面 '{0}' 不正確地擴充介面 '{1}'。", + "Interface_declaration_cannot_have_implements_clause_1176": "介面宣告不能有 'implements' 子句。", + "Interface_name_cannot_be_0_2427": "介面名稱不得為 '{0}'。", + "Invalid_character_1127": "無效的字元。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "增強中的模組名稱無效。模組 '{0}' 於 '{1}' 解析至不具類型的模組,其無法擴增。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "增強指定中的模組名稱無效,找不到模組 '{0}'。", + "Invalid_reference_directive_syntax_1084": "無效的 'reference' 指示詞語法。", + "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210": "不當使用 '{0}'。類別定義會自動採用 strict 模式。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' 的用法無效。模組會自動採用 strict 模式。", + "Invalid_use_of_0_in_strict_mode_1100": "在 strict 模式中使用 '{0}' 無效。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' 的值無效。'{0}' 不是有效的識別碼或限定名稱。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' 的值無效。'{0}' 不是有效的識別碼。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' 不符合 'extends {2}' 子句。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc ''@{0}' 未連結到類別。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' 只能出現在特徵標記的最後一個參數中。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 標記的名稱為 '{0}',但沒有為該名稱的參數。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 標記應具有類型註解,或者其後接著 '@property' 或 '@member' 標記。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 類型只能在文件註解中使用。", + "JSX_attribute_expected_17003": "必須是 JSX 屬性。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "只能將非空白的 'expression' 指派給 JSX 屬性。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 元素 '{0}' 沒有對應的結尾標記。", + "JSX_element_attributes_type_0_may_not_be_a_union_type_2600": "JSX 元素的屬性類型 '{0}' 不得為等位型別。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "因為 JSX 項目類別沒有 '{0}' 屬性 (property),所以不支援屬性 (attribute)。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "因為沒有介面 'JSX.{0}',表示 JSX 項目隱含了類型 'any'。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "因為全域類型 'JSX.Element' 不存在,所以 JSX 項目隱含有類型 'any'。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 項目類型 '{0}' 沒有任何建構或呼叫簽章。", + "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605": "JSX 項目類型 '{0}' 不是 JSX 項目的建構函式。", + "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_jsxFactory_17016": "使用 --jsxFactory 時,不支援 JSX 片段", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 擴張子系必須為陣列類型。", + "Jump_target_cannot_cross_function_boundary_1107": "跳躍目標不得跨越函式界限。", + "KIND_6034": "類型", + "LOCATION_6037": "位置", + "Language_service_is_disabled_9004": "已停用語言服務。", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "逗號運算子左側未使用,而且沒有任何不良影響。", + "Line_break_not_permitted_here_1142": "這裡不可使用分行符號。", + "Line_terminator_not_permitted_before_arrow_1200": "箭號前不得有行結束字元。", + "List_of_folders_to_include_type_definitions_from_6161": "要包含之類型定義所屬資料夾的清單。", + "List_of_language_service_plugins_6181": "語言服務外掛程式清單。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "資料夾的清單。這些資料夾內所含的合併內容代表了專案在執行階段時的結果。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "正在從根目錄 '{1}',候選位置 '{2}' 載入 '{0}'。", + "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "正在從 'node_modules' 資料夾載入模組 '{0}',目標檔案類型 '{1}'。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "正在將模組載入為檔案/資料夾,候選模組位置 '{0}',目標檔案類型 '{1}'。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "地區設定的格式必須是 <語言> 或 <語言>-<國家/地區>。例如 '{0}' 或 '{1}'。", + "Longest_matching_prefix_for_0_is_1_6108": "符合 '{0}' 的前置詞最長為 '{1}'。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "目前正在 'node_modules' 資料夾中查詢,初始位置為 '{0}'。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "使 'super()' 呼叫成為建構函式中的第一個陳述式。", + "Member_0_implicitly_has_an_1_type_7008": "成員 '{0}' 隱含了 '{1}' 類型。", + "Merge_conflict_marker_encountered_1185": "偵測到合併衝突標記。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合併宣告 '{0}' 不得包含預設匯出宣告。請考慮改為加入獨立型 'export default {0}' 宣告。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "只有函式宣告、函式運算式或建構函式的主體中允許中繼屬性 '{0}'。", + "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": "此處不得出現修飾詞。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模組 {0} 已匯出名為 '{1}' 的成員。請考慮明確重新匯出項目以解決模稜兩可的情形。", + "Module_0_has_no_default_export_1192": "模組 '{0}' 沒有預設匯出。", + "Module_0_has_no_exported_member_1_2305": "模組 '{0}' 沒有匯出的成員 '{1}'。", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "同名的區域宣告隱藏了模組 '{0}'。", + "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "模組 '{0}' 會解析成非模組實體,且不可使用這個建構加以匯入。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "模組 '{0}' 使用 'export =',因而無法以 'export *' 的方式使用。", + "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "此檔案未修改,因此模組 '{0}' 已解析為在 '{1}' 中所宣告的環境模組。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "模組 '{0}' 在檔案 '{1}' 中已解析為本機宣告的環境模組。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "模組 '{0}' 已解析為 '{1}',但未設定 '--jsx'。", + "Module_Resolution_Options_6174": "模組解析選項", + "Module_name_0_matched_pattern_1_6092": "模組名稱 '{0}',符合的模式 '{1}'。", + "Module_name_0_was_not_resolved_6090": "======== 模組名稱 '{0}' 未解析。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。", + "Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。", + "Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。", + "NEWLINE_6061": "新行", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "類型 '{1}' 及 '{2}' 的具名屬性 '{0}' 不一致。", + "Namespace_0_has_no_exported_member_1_2694": "命名空間 '{0}' 沒有匯出的成員 '{1}'。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "沒有任何基底建構函式具有指定的類型引數數量。", + "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}' 未實作從類別 '{2}' 繼承而來的抽象成員 '{1}'。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象類別運算式未實作從類別 '{1}' 繼承而來的抽象成員 '{0}'。", + "Not_all_code_paths_return_a_value_7030": "部分程式碼路徑並未傳回值。", + "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "數值索引類型 '{0}' 不可指派給字串索引類型 '{1}'。", + "Object_is_possibly_null_2531": "物件可能為「null」。", + "Object_is_possibly_null_or_undefined_2533": "物件可能為「null」或「未定義」。", + "Object_is_possibly_undefined_2532": "物件可能為「未定義」。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "物件常值只可指定已知的屬性,且類型 '{1}' 中沒有 '{0}'。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "物件常值只會指定已知的屬性,但類型 '{1}' 中沒有 '{0}'。您是否想要寫入 '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "物件常值的屬性 '{0}' 隱含了 '{1}' 類型。", + "Octal_digit_expected_1178": "必須是八進位數字。", + "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "八進位的常值類型必須使用 ES2015 語法。請使用語法 '{0}'。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "列舉成員初始設定式中不允許八進位常值。請使用語法 '{0}'。", + "Octal_literals_are_not_allowed_in_strict_mode_1121": "strict 模式中不允許八進位常值。", + "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "當目標為 ECMAScript 5 及更高版本時,不可使用八進位的常值。請使用語法 '{0}'。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 陳述式中只可包含一個變數宣告。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 陳述式只能包含一個變數宣告。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "只有 void 函式可以使用 'new' 關鍵字進行呼叫。", + "Only_ambient_modules_can_use_quoted_names_1035": "只有環境模組可以使用括以引號的名稱。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "只有 'amd' 與 'system' 模組連同受支援 --{0}。", + "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "類別 'extends' 子句中,目前只支援具有選擇性型別引數的識別碼/限定名稱。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "只有基底類別之公開且受保護的方法,才可透過 'super' 關鍵字存取。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "無法將運算子 '{0}' 套用至類型 '{1}' 和 '{2}'。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_6064": "只能在 'tsconfig.json' 檔案中指定選項 '{0}'。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "只有在已提供選項 '--inlineSourceMap' 或選項 '--sourceMap' 時,才可使用選項 '{0}'。", + "Option_0_cannot_be_specified_with_option_1_5053": "不得同時指定選項 '{0}' 與選項 '{1}'。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "必須指定選項 '{1}' 才可指定選項 '{0}'。", + "Option_0_should_have_array_of_strings_as_a_value_6103": "選項 '{0}' 應以字串陣列作為值。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "只有在提供選項 '--module' 或是 'target' 為 'ES2015' 或更高項目時,才可使用選項 'isolatedModules'。", + "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "必須指定 '--baseUrl' 選項才能使用選項 'paths'。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "在命令列上,'project' 選項不得與原始程式檔並用。", + "Options_Colon_6027": "選項:", + "Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。", + "Overload_signature_is_not_compatible_with_function_implementation_2394": "多載簽章與函式實作不相容。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "多載簽章必須全部匯出或不匯出。", + "Overload_signatures_must_all_be_optional_or_required_2386": "多載簽章都必須是選擇性或必要簽章。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "多載簽章必須是公用、私用或受保護。", + "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "無法在參數 '{0}' 的初始設定式中參考此參數。", + "Parameter_0_implicitly_has_an_1_type_7006": "參數 '{0}' 隱含了 '{1}' 類型。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "參數 '{0}' 與參數 '{1}' 不在同一個位置。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "匯出介面之呼叫簽章的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "匯出介面之呼叫簽章的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "匯出類別中建構函式的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "匯出類別中建構函式的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "匯出類別中建構函式的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "匯出介面中建構函式簽章的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "匯出介面中建構函式簽章的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "匯出函式的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "匯出函式的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "匯出函式的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "匯出介面的索引簽章參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "匯出介面的索引簽章參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "匯出介面中方法的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "匯出介面中方法的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "匯出類別中公用方法的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "匯出類別中公用方法的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "匯出類別中公用方法的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "匯出類別中公用靜態方法的參數 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "匯出類別中公用靜態方法的參數 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "匯出類別中公用靜態方法的參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "參數不得有問號及初始設定式。", + "Parameter_declaration_expected_1138": "必須是參數宣告。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "匯出類別中公用 setter '{0}' 的參數類型具有或是正在使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "匯出類別中公用 setter '{0}' 的參數類型具有或正在使用私用名稱 '{1}'。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "匯出類別中公用靜態 setter '{0}' 的參數類型具有或正在使用私用模組 '{2}' 中的名稱 '{1}'。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "匯出類別中公用靜態 setter '{0}' 的參數類型具有或正在使用私用名稱 '{1}'。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "在 strict 模式中進行剖析,並為每個來源檔案發出 \"use strict\"。", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "模式 '{0}' 最多只可有一個 '*' 字元。", + "Prefix_0_with_an_underscore_90025": "有底線的前置詞 '{0}'。", + "Print_names_of_files_part_of_the_compilation_6155": "列印編譯時檔案部分的名稱。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。", + "Print_the_compiler_s_version_6019": "列印編譯器的版本。", + "Print_this_message_6017": "列印這則訊息。", + "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 沒有屬性 '{0}'。", + "Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "類型 '{1}' 沒有屬性 '{0}'。您指的是 '{2}' 嗎?", + "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "屬性 '{0}' 有衝突的宣告,在類型 '{1}' 中無法存取。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "屬性 '{0}' 沒有初始設定式,且未在建構函式中明確指派。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "因為屬性 '{0}' 的 get 存取子沒有傳回類型註釋,致使該屬性意味著類型 'any'。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "因為屬性 '{0}' 的 set 存取子沒有參數類型註釋,致使該屬性意味著類型 'any'。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "不得將類型 '{1}' 的屬性 '{0}' 指派給類型 '{2}'。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "屬性 '{0}' 已宣告但從未讀取其值。", + "Property_0_is_incompatible_with_index_signature_2530": "屬性 '{0}' 和索引簽章不相容。", + "Property_0_is_missing_in_type_1_2324": "類型 '{1}' 遺漏屬性 '{0}'。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "在類型 '{1}' 中,'{0}' 是選擇性屬性,但在類型 '{2}' 中則為必要屬性。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' 是私用屬性,只可從類別 '{1}' 中存取。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "在類型 '{1}' 中,'{0}' 是私用屬性,但在類型 '{2}' 中不是。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446": "'{0}' 是受保護屬性,只能透過類別 '{1}' 的執行個體進行存取。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' 是受保護屬性,只可從類別 '{1}' 及其子類別中存取。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' 是受保護屬性,但類型 '{1}' 不是衍生自 '{2}' 的類別。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "在類型 '{1}' 中,'{0}' 是受保護屬性,但在類型 '{2}' 中是公用屬性。", + "Property_0_is_used_before_being_assigned_2565": "屬性 '{0}' 已在指派之前使用。", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 擴張屬性 (Attribute) 的屬性 (Property) '{0}' 不可指派給目標屬性 (Property)。", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "匯出之類別運算式的屬性 '{0}' 可能為私人或受保護。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "匯出介面的屬性 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "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_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'、物件常值或陣列常值。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "當目標為 'ES5' 或 'ES3' 時,為 'for-of'、擴張及解構提供完整的支援。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "匯出類別的公用方法 '{0}' 具有或使用外部模組 {2} 的名稱 '{1}',但無法命名。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "匯出類別的公用方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "匯出類別的公用方法 '{0}' 具有或使用私用名稱 '{1}'。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "匯出類別的公用屬性 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "匯出類別的公用屬性 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "匯出類別的公用屬性 '{0}' 具有或使用私用名稱 '{1}'。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "匯出類別的公用靜態方法 '{0}' 具有或使用外部模組 {2} 的名稱 '{1}',但無法命名。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "匯出類別的公用靜態方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "匯出類別的公用靜態方法 '{0}' 具有或使用私用名稱 '{1}'。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "匯出類別的公用靜態屬性 '{0}' 具有或使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "匯出類別的公用靜態屬性 '{0}' 具有或使用私用模組 '{2}' 中的名稱 '{1}'。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "匯出類別的公用靜態屬性 '{0}' 具有或使用私用名稱 '{1}'。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。", + "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", + "Remove_declaration_for_Colon_0_90004": "移除 {0} 的宣告。", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。", + "Report_errors_in_js_files_8019": "報告 .js 檔案中的錯誤。", + "Report_errors_on_unused_locals_6134": "回報未使用之區域變數的錯誤。", + "Report_errors_on_unused_parameters_6135": "回報未使用之參數的錯誤。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必要型別參數可能未遵循選擇性型別參數。", + "Resolution_for_module_0_was_found_in_cache_6147": "於快取找到模組 '{0}' 的解析。", + "Resolving_from_node_modules_folder_6118": "正在從 node_modules 資料夾解析...", + "Resolving_module_0_from_1_6086": "======== 正在從 '{1}' 解析模組 '{0}'。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在解析與基底 URL '{1}' 相對的模組名稱 '{0}' - '{2}'。", + "Resolving_real_path_for_0_result_1_6130": "正在解析 '{0}' 的真實路徑,結果 '{1}'。", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 正在解析類型參考指示詞 '{0}',包含檔案 '{1}',根目錄 '{2}'。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 正在解析類型參考指示詞 '{0}',包含檔案 '{1}',未設定根目錄。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 正在解析類型參考指示詞 '{0}',未設定包含檔案,根目錄 '{1}'。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 正在解析類型參考指示詞 '{0}',未設定包含檔案,未設定根目錄。 ========", + "Resolving_using_primary_search_paths_6117": "正在使用主要搜尋路徑進行解析...", + "Resolving_with_primary_search_path_0_6121": "正在解析主要搜尋路徑 '{0}'。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "剩餘參數 '{0}' 隱含了 'any[]' 類型。", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest 類型只能從物件類型建立。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "匯出介面中呼叫簽章的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "匯出介面中呼叫簽章的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "匯出介面中建構函式簽章的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "匯出介面中建構函式簽章的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "建構函式簽章的傳回類型必須能夠指派給類別的執行個體類型。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "匯出函式的傳回型別具有或使用外部模組 {1} 中的名稱 '{0}',但無法命名。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "匯出函式的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "匯出函式的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "匯出介面中索引簽章的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "匯出介面中索引簽章的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "匯出介面中方法的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "匯出介面中方法的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "匯出類別中公用 getter '{0}' 的傳回型別具有或正在使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "匯出類別中公用 getter '{0}' 的傳回型別具有或正在使用私用模組 {2} 中的名稱 '{1}'。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "匯出類別中公用 getter '{0}' 的傳回型別具有或正在使用私用名稱 '{1}'。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "匯出類別中公用方法的傳回型別具有或使用外部模組 {1} 中的名稱 '{0}',但無法命名。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "匯出類別中公用方法的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "匯出類別中公用方法的傳回型別具有或使用私用名稱 '{0}'。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "匯出類別中公用靜態 getter '{0}' 的傳回型別具有或正在使用外部模組 {2} 中的名稱 '{1}',但無法命名。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "匯出類別中公用靜態 getter '{0}' 的傳回型別具有或正在使用私用模組 '{2}' 中的名稱 '{1}'。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "匯出類別中公用靜態 getter '{0}' 的傳回型別具有或正在使用私用名稱 '{1}'。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "匯出類別中公用靜態方法的傳回型別具有或使用外部模組 {1} 中的名稱 '{0}',但無法命名。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "匯出類別中公用靜態方法的傳回型別具有或使用私用模組 '{1}' 中的名稱 '{0}'。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "匯出類別中公用靜態方法的傳回型別具有或使用私用名稱 '{0}'。", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "因為舊程式中的解決方案並無任何變更,所以會重複使用 '{0}' 中的模組解決方案。", + "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "對檔案 '{1}' 重複用舊程式中模組 '{0}' 的解決方案。", + "Rewrite_as_the_indexed_access_type_0_90026": "重寫為索引存取類型 '{0}'。", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "無法判斷根目錄,將略過主要搜尋路徑。", + "STRATEGY_6039": "策略", + "Scoped_package_detected_looking_in_0_6182": "偵測到範圍套件,正於 '{0}' 尋找", + "Setters_cannot_return_a_value_2408": "setter 無法傳回值。", + "Show_all_compiler_options_6169": "顯示所有的編譯器選項。", + "Show_diagnostic_information_6149": "顯示診斷資訊。", + "Show_verbose_diagnostic_information_6150": "顯示詳細診斷資訊。", + "Signature_0_must_be_a_type_predicate_1224": "簽章 '{0}' 必須是型別述詞。", + "Skip_type_checking_of_declaration_files_6012": "跳過宣告檔案的類型檢查。", + "Source_Map_Options_6175": "來源對應選項", + "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "特製化的多載簽章不可指派給任何非特製化的簽章。", + "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "動態匯入的指定名稱不能是展開元素。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "指定 ECMAScript 目標版本: 'ES3' (預設)、'ES5'、'ES2015'、'ES2016'、'ES2017' 或 'ESNEXT'。", + "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "指定 JSX 程式碼產生: 'preserve'、'react-native' 或 'react'。", + "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "指定編譯內要包含的程式庫檔: ", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "指定模組程式碼產生: 'none'、'commonjs'、'amd'、'system'、'umd'、'es2015' 或 'ESNext'。", + "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "指定模組解決方案策略: 'node' (Node.js) 或 'classic' (TypeScript 1.6 前)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "請指定要在以 'react' JSX 發出為目標時使用的 JSX factory 函式。例如 'React.createElement' 或 'h'。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "指定發出檔案時要用的行尾順序: 'CRLF' (DOS) 或 'LF' (UNIX)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "指定偵錯工具尋找 TypeScript 檔案的位置,而非原始檔位置。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "指定偵錯工具尋找對應檔的位置,而非產生的位置。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定輸入檔案的根目錄。用以控制具有 --outDir 的輸出目錄結構。", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "只有當目標為 ECMAScript 5 及更高版本時,才可使用 'new' 運算式中的擴張運算子。", + "Spread_types_may_only_be_created_from_object_types_2698": "Spread 類型只能從物件類型建立。", + "Statement_expected_1129": "必須是陳述式。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "環境內容中不得有陳述式。", + "Static_members_cannot_reference_class_type_parameters_2302": "靜態成員不得參考類別類型參數。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "靜態屬性 '{0}' 與建構函式 '{1}' 的內建屬性 'Function.{0}' 相衝突。", + "Strict_Type_Checking_Options_6173": "Strict 類型檢查選項", + "String_literal_expected_1141": "必須是字串常值。", + "String_literal_with_double_quotes_expected_1327": "應有具雙引號的字串常值。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用色彩及內容設計錯誤與訊息的風格 (實驗)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後續的變數宣告必須具有相同的類型。變數 '{0}' 的類型必須是 '{1}' 但卻是 '{2}'。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "模式 '{1}' 的替代 '{0}' 類型不正確,必須為 'string',但得到 '{2}'。", + "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "模式 '{1}' 中的替代 '{0}' 最多只可有一個 '*' 字元。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "模式 '{0}' 的替代應為陣列。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "模式 '{0}' 的替代項目不應為空陣列。", + "Successfully_created_a_tsconfig_json_file_6071": "已成功建立 tsconfig.json 檔案。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "建構函式外部或建構函式內的巢狀函式中不允許 super 呼叫。", + "Suppress_excess_property_checks_for_object_literals_6072": "不對物件常值進行多餘的屬性檢查。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "針對缺少索引簽章的索引物件隱藏 noImplicitAny 錯誤。", + "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "'Symbol' 參考不是參考全域 Symbol 建構函式物件。", + "Syntax_Colon_0_6023": "語法: {0}", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "無法將 '{0}' 運算子套用至類型 'symbol'。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "布林類型不允許有 '{0}' 運算子。請考慮改用 '{1}'。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 類型可指派給極少數的其他類型。要改用 'any' 類型嗎?", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "無法在 ES3 和 ES5 的箭號函式中參考 'arguments' 物件。請考慮使用標準函式運算式。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "在 ES3 與 ES5 的非同步函式或方法中,無法參考 'arguments' 物件。請考慮使用標準函式或方法。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' 陳述式的主體不能是空白陳述式。", + "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_files_list_in_config_file_0_is_empty_18002": "設定檔 '{0}' 中的 'files' 清單是空的。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 陳述式左側不得使用類型註釋。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' 陳述式的左邊必須是變數或屬性存取。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' 陳述式的左側必須是類型 'string' 或 'any'。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' 陳述式的左側不得使用類型註釋。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' 陳述式的左邊必須是變數或屬性存取。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "算術運算的左側必須是類型 'any'、'number' 或列舉類型。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "指派運算式的左邊必須是變數或屬性存取。", + "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' 運算式的左側必須是 'any'、'string'、'number' 或 'symbol' 類型。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 運算式左側必須是類型 'any'、物件類型或型別參數。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "對使用者顯示訊息時所使用的地區設定 (例如 'zh-tw')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "在 node_modules 及載入 JavaScript 檔案下搜尋時的最大相依性深度。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "刪除運算子的運算元不得為唯讀屬性。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "刪除運算子的運算元必須是屬性參考。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "遞增或遞減運算子的運算元必須是變數或屬性存取。", + "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601": "JSX 項目建構函式的傳回型別必須傳回物件類型。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "參數裝飾項目函式的傳回型別必須是 'void' 或 'any'。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "屬性裝飾項目函式的傳回型別必須是 'void' 或 'any'。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "非同步函式的傳回型別必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "非同步函式或方法的傳回類型必須為全域 Promise 類型。", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "'for...in' 陳述式的右側必須是類型 'any'、物件類型或型別參數。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "算術運算的右側必須是 'any'、'number' 或列舉類型。", + "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 運算式的右側必須是類型 'any'、物件類型或型別參數。", + "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_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}' 的型別引數。請考慮明確地指定型別引數。", + "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "非同步迭代器的 'next()' 方法傳回的類型,對具有 'value' 屬性的類型必須為 Promise。", + "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "迭代器之 'next()' 方法傳回的類型必須具有 'value' 屬性。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' 陳述式的變數宣告不得有初始設定式。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' 陳述式的變數宣告不得有初始設定式。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "不支援 'with' 陳述式。'with' 區塊中的所有符號都會有類型 'any'。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此語法需要已匯入的協助程式,但找不到模組 '{0}'。", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "此語法需要名為 '{1}' 的已匯入協助程式,但模組 '{0}' 沒有匯出的成員 '{1}'。", + "Trailing_comma_not_allowed_1009": "尾端不得為逗號。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "以個別模組的形式轉換每個檔案的語言 (類似於 'ts.transpileModule')。", + "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "如有 'npm install @types/{0}',請試用,否則請新增內含 'declare module '{0}';' 的宣告 (.d.ts) 檔案", + "Trying_other_entries_in_rootDirs_6110": "正在嘗試 'rootDirs' 中的其他項目。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "正在嘗試替代 '{0}',候選模組位置: '{1}'。", + "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493": "無法將長度為 '{1}' 的元組類型 '{0}' 指派給長度為 '{2}' 的元組。", + "Type_0_cannot_be_converted_to_type_1_2352": "類型 '{0}' 無法轉換為類型 '{1}'。", + "Type_0_cannot_be_used_as_an_index_type_2538": "類型 '{0}' 無法作為索引類型。", + "Type_0_cannot_be_used_to_index_type_1_2536": "類型 '{0}' 無法用來為類型 '{1}' 編制索引。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "類型 '{0}' 不符合條件約束 '{1}'。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "類型 '{0}' 沒有與類型 '{1}' 相符的索引簽章。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "類型 '{0}' 與類型 '{1}' 沒有任何共通的屬性。", + "Type_0_has_no_property_1_2460": "類型 '{0}' 沒有屬性 '{1}'。", + "Type_0_has_no_property_1_and_no_string_index_signature_2459": "類型 '{0}' 沒有屬性 '{1}',也沒有字串索引簽章。", + "Type_0_is_not_a_constructor_function_type_2507": "類型 '{0}' 不是建構函式類型。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "類型 '{0}' 不是 ES5/ES3 中的有效非同步函式傳回型別,因為它不是指與 Promise 相容的建構函式值。", + "Type_0_is_not_an_array_type_2461": "類型 '{0}' 不是陣列類型。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "類型 '{0}' 不是陣列類型或字串類型。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "類型 '{0}' 不是陣列類型或字串類型,或沒有會傳回迭代器的 '[Symbol.iterator]()' 方法。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "類型 '{0}' 不是陣列類型,或沒有會傳回迭代器的 '[Symbol.iterator]()' 方法。", + "Type_0_is_not_assignable_to_type_1_2322": "類型 '{0}' 不可指派給類型 '{1}'。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "無法將類型 '{0}' 指派給類型 '{1}'。有兩種使用此名稱的不同類型存在,但彼此並不相關。", + "Type_0_is_not_comparable_to_type_1_2678": "類型 '{0}' 無法和類型 '{1}' 比較。", + "Type_0_is_not_generic_2315": "'{0}' 不是泛型類型。", + "Type_0_provides_no_match_for_the_signature_1_2658": "類型 '{0}' 沒有符合特徵標記 '{1}' 的項目。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "類型 '{0}' 將自己當做基底類型遞迴參考。", + "Type_alias_0_circularly_references_itself_2456": "類型別名 '{0}' 會循環參考自己。", + "Type_alias_name_cannot_be_0_2457": "類型別名不得為 '{0}'。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "建構函式宣告不得有類型註釋。", + "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455": "因為型別引數候選項 '{1}' 不是候選項 '{0}' 的超級類型,所以不是有效的型別引數。", + "Type_argument_expected_1140": "必須是型別引數。", + "Type_argument_list_cannot_be_empty_1099": "型別引數清單不得為空白。", + "Type_declaration_files_to_be_included_in_compilation_6124": "要包含在編譯內的類型宣告檔案。", + "Type_expected_1110": "必須是類型。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "類型在其本身 'then' 方法的完成回撥中直接或間接受到參考。", + "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "類型必須有會傳回非同步迭代器的 '[Symbol.asyncIterator]()' 方法。", + "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "類型必須有傳回迭代器的 '[Symbol.iterator]()' 方法。", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' 運算元的反覆項目類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同步產生器中的 'yield' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", + "Type_parameter_0_has_a_circular_constraint_2313": "類型參數 '{0}' 具有循環條件約束。", + "Type_parameter_0_has_a_circular_default_2716": "型別參數 '{0}' 包含循環的預設值。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "匯出介面中呼叫簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "匯出介面中建構函式簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "匯出類別的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "匯出函式的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "匯出介面的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "匯出類型別名的型別參數 '{0}' 具有或正在使用私人名稱 '{1}'。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "匯出介面中方法的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "匯出類別中公用方法的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "匯出類別中公用靜態方法的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", + "Type_parameter_declaration_expected_1139": "必須是型別參數宣告。", + "Type_parameter_list_cannot_be_empty_1098": "型別參數清單不得為空白。", + "Type_parameter_name_cannot_be_0_2368": "型別參數名稱不得為 '{0}'。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "建構函式宣告不得有類型參數。", + "Type_predicate_0_is_not_assignable_to_1_1226": "型別述詞 '{0}' 不可指派給 '{1}'。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 類型參考指示詞 '{0}' 未解析。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 類型參考指示詞 '{0}' 已成功解析為 '{1}',主要: {2}。========", + "Types_have_separate_declarations_of_a_private_property_0_2442": "類型具有私用屬性 '{0}' 的個別宣告。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "參數 '{0}' 和 '{1}' 的類型不相容。", + "Types_of_property_0_are_incompatible_2326": "屬性 '{0}' 的類型不相容。", + "Unable_to_open_file_0_6050": "無法開啟檔案 '{0}'。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "無法解析以運算式形式呼叫之類別裝飾項目的簽章。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "無法解析以運算式形式呼叫之方法裝飾項目的簽章。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "無法解析以運算式形式呼叫之參數裝飾項目的簽章。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "無法解析以運算式形式呼叫之屬性裝飾項目的簽章。", + "Unexpected_end_of_text_1126": "未預期的文字結尾。", + "Unexpected_token_1012": "未預期的語彙基元。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "未預期的語彙基元。必須是建構函式、方法、存取子或屬性。", + "Unexpected_token_expected_1179": "未預期的語彙基元。必須是 '{'。", + "Unknown_compiler_option_0_5023": "不明的編譯器選項 '{0}'。", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "選項 'excludes' 未知。您是指 'exclude' 嗎?", + "Unknown_type_acquisition_option_0_17010": "未知的類型取得選項 '{0}'。", + "Unreachable_code_detected_7027": "偵測到無法執行到的程式碼。", + "Unsupported_locale_0_6049": "不支援的地區設定 '{0}'。", + "Unterminated_Unicode_escape_sequence_1199": "未結束的 Unicode 逸出序列。", + "Unterminated_quoted_string_in_response_file_0_6045": "回應檔 '{0}' 中有未結束的括號字串。", + "Unterminated_regular_expression_literal_1161": "未結束的規則運算式常值。", + "Unterminated_string_literal_1002": "未結束的字串常值。", + "Unterminated_template_literal_1160": "未結束的樣板常值。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "不具類型的函式呼叫無法接受類型引數。", + "Unused_label_7028": "未使用的標籤。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "只有在 ECMAScript 5 及更高版本中,才可在 'for...of' 陳述式中使用字串。", + "VERSION_6036": "版本", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "類型為 '{0}' 的值與類型 '{1}' 沒有任何共通的屬性。確定要呼叫嗎?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "無法呼叫類型 '{0}' 的值。您要包含 'new' 嗎?", + "Variable_0_implicitly_has_an_1_type_7005": "變數 '{0}' 隱含有 '{1}' 類型。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "變數 '{0}' 在某些其類型無法判斷的位置隱含地擁有類型 '{1}'。", + "Variable_0_is_used_before_being_assigned_2454": "變數 '{0}' 已在指派之前使用。", + "Variable_declaration_expected_1134": "必須是變數宣告。", + "Variable_declaration_list_cannot_be_empty_1123": "變數宣告清單不得為空白。", + "Version_0_6029": "版本 {0}", + "Watch_input_files_6005": "監看輸入檔案。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "您無法重新命名標準 TypeScript 程式庫中所定義的項目。", + "You_cannot_rename_this_element_8000": "您無法重新命名這個項目。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' 在此只接受極少數的引數用為裝飾項目。要先呼叫此項目,然後再寫入 '@{0}()' 嗎?", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' 指定了兩次。將會覆寫名為 '{0}' 的屬性。", + "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' 只可用於 .ts 檔案中。", + "_0_expected_1005": "必須是 '{0}'。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' 因為沒有傳回型別註解,且在其中一個傳回運算式中直接或間接參考了自己,所以隱含了傳回型別 'any'。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' 因為沒有類型註釋,且在其本身的初始設定式中直接或間接參考了自己,所以隱含有類型 'any'。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' 為基元,但 '{1}' 為包裝函式物件。建議盡可能使用 '{0}'。", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' 已宣告但從未讀取其值。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' 對關鍵字 '{1}' 而言不是有效的中繼屬性。您是指 '{2}' 嗎?", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' 在其本身的基底運算式中直接或間接受到參考。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' 在其本身的類型註釋中直接或間接受到參考。", + "_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_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' 修飾詞只能出現在類別宣告、方法宣告或屬性宣告。", + "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": "'=' 僅能在解構指派內的物件常值屬性中使用。", + "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' 列舉只可用於屬性或索引存取運算式中,或者用於匯入宣告或匯出指派的右側 。", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "不得在 strict 模式中對識別碼呼叫 'delete'。", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' 只可用於 .ts 檔案中。", + "export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。", + "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}'。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "匯出介面 '{0}' 的 'extends' 子句具有或使用私用名稱 '{1}'。", + "file_6025": "檔案", + "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' 和 'set' 存取子必須有相同的 'this' 類型。", + "get_and_set_accessor_must_have_the_same_type_2380": "get' 和 'set' 存取子的類型必須相同。", + "implements_clause_already_seen_1175": "已經有 'implements' 子句。", + "implements_clauses_can_only_be_used_in_a_ts_file_8005": "'implements clauses' 只可用於 .ts 檔案中。", + "import_can_only_be_used_in_a_ts_file_8002": "'import ... =' 只可用於 .ts 檔案中。", + "interface_declarations_can_only_be_used_in_a_ts_file_8006": "'interface declarations' 只可用於 .ts 檔案中。", + "let_declarations_can_only_be_declared_inside_a_block_1157": "只能在區塊內宣告 'let' 宣告。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' 或 'const' 宣告中不得使用 'let' 作為名稱。", + "module_declarations_can_only_be_used_in_a_ts_file_8007": "'module declarations' 只可用於 .ts 檔案中。", + "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150": "new T[]' 不能用來建立陣列。請改用 'new Array()'。", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "目標缺少建構簽章的 'new' 運算式隱含了 'any' 類型。", + "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "'non-null assertions' 只可用於 .ts 檔案中。", + "options_6024": "選項", + "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 檔案中。", + "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' 修飾詞只能出現在屬性宣告或索引簽章。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。", + "super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "只有在衍生類別或物件常值運算式的成員中才可參考 'super'。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "計算的屬性名稱中不得參考 'super'。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "建構函式引數中不得參考 'super'。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "當選項 'target' 為 'ES2015' 或更高時,只有在物件常值運算式的成員中才允許 'super'。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "必須先呼叫 'super' 才能存取衍生類別建構函式中 'super' 的屬性。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "必須先呼叫 'super' 才能存取衍生類別中建構函式的 'this'。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' 之後必須接引數清單或成員存取。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "只有在建構函式、成員函式或衍生類別的成員存取子中,才能存取 'super' 屬性。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "計算的屬性名稱中不得參考 'this'。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "模組或命名空間主體中不得參考 'this'。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "靜態屬性初始設定式中不得參考 'this'。", + "this_cannot_be_referenced_in_constructor_arguments_2333": "建構函式引數中不得參考 'this'。", + "this_cannot_be_referenced_in_current_location_2332": "目前的位置中不得參考 'this'。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "因為 'this' 沒有型別註解,所以隱含具有類型 'any'。", + "type_aliases_can_only_be_used_in_a_ts_file_8008": "'type aliases' 只可用於 .ts 檔案中。", + "type_arguments_can_only_be_used_in_a_ts_file_8011": "'type arguments' 只可用於 .ts 檔案中。", + "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' 只可用於 .ts 檔案中。", + "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' 只可用於 .ts 檔案中。", + "types_can_only_be_used_in_a_ts_file_8010": "'types' 只可用於 .ts 檔案中。", + "unique_symbol_types_are_not_allowed_here_1335": "這裡不允許 'unique symbol' 型別。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "只有變數陳述式中的變數允許 'unique symbol' 型別。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 型別無法用在具有繫結名稱的變數宣告上。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "非同步函式區塊中不允許 'with' 陳述式。", + "with_statements_are_not_allowed_in_strict_mode_1101": "不得在 strict 模式中使用 'with' 陳述式。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 運算式不得用於參數初始設定式。" +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 6c44ab023b9aa..736551168ae6f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,13 +4,30 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@browserify/acorn5-object-spread": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@browserify/acorn5-object-spread/-/acorn5-object-spread-5.0.1.tgz", + "integrity": "sha512-sFCUPzgeEjdq3rinwy4TFXtak2YZdhqpj6MdNusxkdTFr9TXAUEYK4YQSamR8Joqt/yii1drgl5hk8q/AtJDKA==", + "dev": true, + "requires": { + "acorn": "5.3.0" + }, + "dependencies": { + "acorn": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz", + "integrity": "sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==", + "dev": true + } + } + }, "@gulp-sourcemaps/identity-map": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@gulp-sourcemaps/identity-map/-/identity-map-1.0.1.tgz", "integrity": "sha1-z6I7xYQPkQTOMqZedNt+epdLvuE=", "dev": true, "requires": { - "acorn": "5.1.2", + "acorn": "5.3.0", "css": "2.2.1", "normalize-path": "2.1.1", "source-map": "0.5.7", @@ -18,9 +35,9 @@ }, "dependencies": { "acorn": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.1.2.tgz", - "integrity": "sha512-o96FZLJBPY1lvTuJylGA9Bk3t/GKPPJG8H0ydQQl01crzwJgspa4AEIq/pVTXigmK0PHVQhiAtn8WMBLL9D2WA==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz", + "integrity": "sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==", "dev": true } } @@ -42,25 +59,19 @@ "dev": true, "requires": { "@types/insert-module-globals": "7.0.0", - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/chai": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.0.4.tgz", - "integrity": "sha512-cvU0HomQ7/aGDQJZsbtJXqBQ7w4J4TqLB0Z/h8mKrpRjfeZEvTbygkfJEb7fWdmwpIeDeFmIVwAEqS0OYuUv3Q==", - "dev": true - }, - "@types/colors": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@types/colors/-/colors-1.1.3.tgz", - "integrity": "sha1-VBOwp6GxbdGL4OP9V9L+7Mgcx3Y=", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.1.0.tgz", + "integrity": "sha512-OuYBlXWHYthxIudMXMeQr92f6D97YoT9CUYCRb0BEP4OavC95jNcczjjr4Ob3H5E1IqlWqwj+leUZPSeth27Qw==", "dev": true }, "@types/convert-source-map": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@types/convert-source-map/-/convert-source-map-1.5.0.tgz", - "integrity": "sha512-4OHKJEw70U59CN24TLRxU3W+B/9GPp0P6g+eNIsObZLAIqw6NTEBorkjIpei4xsvUCx+YzFwUtt4MBZbfSLvbQ==", + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@types/convert-source-map/-/convert-source-map-1.5.1.tgz", + "integrity": "sha512-laiDIXqqthjJlyAMYAXOtN3N8+UlbM+KvZi4BaY5ZOekmVkBs/UxfK5O0HWeJVG2eW8F+Mu2ww13fTX+kY1FlQ==", "dev": true }, "@types/del": { @@ -69,66 +80,73 @@ "integrity": "sha512-18mSs54BvzV8+TTQxt0ancig6tsuPZySnhp3cQkWFFDmDMavU4pmWwR+bHHqRBWODYqpzIzVkqKLuk/fP6yypQ==", "dev": true, "requires": { - "@types/glob": "5.0.33" + "@types/glob": "5.0.34" } }, + "@types/events": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-1.1.0.tgz", + "integrity": "sha512-y3bR98mzYOo0pAZuiLari+cQyiKk3UXRuT45h1RjhfeCzqkjaVsfZJNaxdgtk7/3tzOm1ozLTqEqMP3VbI48jw==", + "dev": true + }, "@types/glob": { - "version": "5.0.33", - "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.33.tgz", - "integrity": "sha512-BcD4yyWz+qmCggaYMSFF0Xn7GkO6tgwm3Fh9Gxk/kQmEU3Z7flQTnVlMyKBUNvXXNTCCyjqK4XT4/2hLd1gQ2A==", + "version": "5.0.34", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-5.0.34.tgz", + "integrity": "sha512-sUvpieq+HsWTLdkeOI8Mi8u22Ag3AoGuM3sv+XMP1bKtbaIAHpEA2f52K2mz6vK5PVhTa3bFyRZLZMqTxOo2Cw==", "dev": true, "requires": { - "@types/minimatch": "3.0.1", - "@types/node": "8.0.46" + "@types/events": "1.1.0", + "@types/minimatch": "3.0.3", + "@types/node": "8.5.5" } }, "@types/gulp": { - "version": "3.8.33", - "resolved": "https://registry.npmjs.org/@types/gulp/-/gulp-3.8.33.tgz", - "integrity": "sha512-3UpA2pkKO40cNPe/8bxMQFWSASR9Jx67JfN9Z2Cf6ogfDMwXgEHm2XjKmuLYEtrp1IHYApOWlYMLYNgtTJgSAw==", + "version": "3.8.36", + "resolved": "https://registry.npmjs.org/@types/gulp/-/gulp-3.8.36.tgz", + "integrity": "sha512-u6/zWPzYRNPAtvyFJ3/RSXjmBaBM1dVs5kW22/jU6J786ZGLfSndhLoNOpFI6FGQvqTA+QzFHjSMhpkAN+wxcQ==", "dev": true, "requires": { - "@types/node": "8.0.46", - "@types/orchestrator": "0.3.0", - "@types/vinyl": "2.0.1" + "@types/node": "8.5.5", + "@types/orchestrator": "0.3.2", + "@types/vinyl": "2.0.2" } }, "@types/gulp-concat": { - "version": "0.0.31", - "resolved": "https://registry.npmjs.org/@types/gulp-concat/-/gulp-concat-0.0.31.tgz", - "integrity": "sha512-F14zRcKn15HC59RXRlHpcxj79WoLjkJBJBPfN0NBZOgkRCfDZYVu8rs0Y/CH4CJGUbbc/nHczD2LmepDS+ARaA==", + "version": "0.0.32", + "resolved": "https://registry.npmjs.org/@types/gulp-concat/-/gulp-concat-0.0.32.tgz", + "integrity": "sha512-CUCFADlITzzBfBa2bdGzhKtvBr4eFh+evb+4igVbvPoO5RyPfHifmyQlZl6lM7q19+OKncRlFXDU7B4X9Ayo2g==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/gulp-help": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/@types/gulp-help/-/gulp-help-0.0.33.tgz", - "integrity": "sha1-ZejGUSQQkiVTf6OQA8S6UfT9GsU=", + "version": "0.0.34", + "resolved": "https://registry.npmjs.org/@types/gulp-help/-/gulp-help-0.0.34.tgz", + "integrity": "sha512-MkW7psZznxxJg2MBk2P2qHE+T8jEZVFz3FG/qGjUYazkyJt7hBJWx5Nuewmay5RVNtUvSWPrdZLr/WTXY3T/6A==", "dev": true, "requires": { - "@types/gulp": "3.8.33", - "@types/node": "8.0.46", - "@types/orchestrator": "0.3.0" + "@types/gulp": "3.8.36", + "@types/node": "8.5.5", + "@types/orchestrator": "0.3.2" } }, "@types/gulp-newer": { - "version": "0.0.30", - "resolved": "https://registry.npmjs.org/@types/gulp-newer/-/gulp-newer-0.0.30.tgz", - "integrity": "sha1-bqn7oVsFdr5CTpl31IlCAEZKFR4=", + "version": "0.0.31", + "resolved": "https://registry.npmjs.org/@types/gulp-newer/-/gulp-newer-0.0.31.tgz", + "integrity": "sha512-e7J/Zv5Wd7CC0WpuA2syWVitgwrkG0u221e41w7r07XUR6hMH6kHPkq9tUrusHkbeW8QbuLbis5fODOwQCyggQ==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/gulp-sourcemaps": { - "version": "0.0.31", - "resolved": "https://registry.npmjs.org/@types/gulp-sourcemaps/-/gulp-sourcemaps-0.0.31.tgz", - "integrity": "sha512-kJD1byVNx+sdQlaBzZpSGeFH/4l99TXTY4XSGW+aRk27eOnVyk6VknXJpsb1Jk5E4ThKxZ8GYy6ais7MtprK1w==", + "version": "0.0.32", + "resolved": "https://registry.npmjs.org/@types/gulp-sourcemaps/-/gulp-sourcemaps-0.0.32.tgz", + "integrity": "sha512-+7BAmptW2bxyJnJcCEuie7vLoop3FwWgCdBMzyv7MYXED/HeNMeQuX7uPCkp4vfU1TTu4CYFH0IckNPvo0VePA==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/insert-module-globals": { @@ -137,22 +155,22 @@ "integrity": "sha512-zudCJPwluh1VUDB6Gl/OQdRp+fYy3+47huJB/JMQubMS2p+sH18MCVK4WUz3FqaWLB12yh5ELxVR/+tqwlm/qA==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/merge2": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@types/merge2/-/merge2-1.1.2.tgz", - "integrity": "sha512-Xy54xPmFQ8oAx0S3ku46i/zXE4dvfxl5M8n4p2M62IwxPau8IpobiRtL4jkrUzX6Kgeyb34BHOh0i70SDjKHeA==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@types/merge2/-/merge2-1.1.4.tgz", + "integrity": "sha512-GjaXY4OultxbaOOk7lCLO7xvEcFpdjExC605YmfI6X29vhHKpJfMWKCDZd3x+BITrZaXKg97DgV/SdGVSwdzxA==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/minimatch": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.1.tgz", - "integrity": "sha512-rUO/jz10KRSyA9SHoCWQ8WX9BICyj5jZYu1/ucKEJKb4KzLZCKMURdYbadP157Q6Zl1x0vHsrU+Z/O0XlhYQDw==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", "dev": true }, "@types/minimist": { @@ -162,85 +180,99 @@ "dev": true }, "@types/mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/@types/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha512-XA4vNO6GCBz8Smq0hqSRo4yRWMqr4FPQrWjhJt6nKskzly4/p87SfuJMFYGRyYb6jo2WNIQU2FDBsY5r1BibUA==", + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/@types/mkdirp/-/mkdirp-0.5.2.tgz", + "integrity": "sha512-U5icWpv7YnZYGsN4/cmh3WD2onMY0aJIiTE6+51TwJCttdHvtCYmkBNOobHlXwrJRL0nkH9jH4kD+1FAdMN4Tg==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/mocha": { - "version": "2.2.43", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-2.2.43.tgz", - "integrity": "sha512-xNlAmH+lRJdUMXClMTI9Y0pRqIojdxfm7DHsIxoB2iTzu3fnPmSMEN8SsSx0cdwV36d02PWCWaDUoZPDSln+xw==", + "version": "2.2.46", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-2.2.46.tgz", + "integrity": "sha512-fwTTP5QLf4xHMkv7ovcKvmlLWX3GrxCa5DRQDOilVyYGCp+arZTAQJCy7/4GKezzYJjfWMpB/Cy4e8nrc9XioA==", "dev": true }, "@types/node": { - "version": "8.0.46", - "resolved": "https://registry.npmjs.org/@types/node/-/node-8.0.46.tgz", - "integrity": "sha512-rRkP4kb5JYIfAoRKaDbcdPZBcTNOgzSApyzhPN9e6rhViSJAWQGlSXIX5gc75iR02jikhpzy3usu31wMHllfFw==", + "version": "8.5.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-8.5.5.tgz", + "integrity": "sha512-JRnfoh0Ll4ElmIXKxbUfcOodkGvcNHljct6mO1X9hE/mlrMzAx0hYCLAD7sgT53YAY1HdlpzUcV0CkmDqUqTuA==", "dev": true }, "@types/orchestrator": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@types/orchestrator/-/orchestrator-0.3.0.tgz", - "integrity": "sha1-v4ShaZyTMNT+ic2BJj6PwJ+zKXg=", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@types/orchestrator/-/orchestrator-0.3.2.tgz", + "integrity": "sha512-cKB4yTX0wGaRCSkdHDX2fkGQbMAA8UOshC2U7DQky1CE5o+5q2iQQ8VkbPbE/88uaTtsusvBPMcCX7dgmjxBhQ==", "dev": true, "requires": { - "@types/node": "8.0.46", - "@types/q": "0.0.37" - }, - "dependencies": { - "@types/q": { - "version": "0.0.37", - "resolved": "https://registry.npmjs.org/@types/q/-/q-0.0.37.tgz", - "integrity": "sha512-vjFGX1zMTMz/kUp3xgfJcxMVLkMWVMrdlyc0RwVyve1y9jxwqNaT8wTcv6M51ylq2a/zn5lm8g7qPSoIS4uvZQ==", - "dev": true - } + "@types/node": "8.5.5", + "@types/q": "1.0.6" } }, "@types/q": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/q/-/q-1.0.5.tgz", - "integrity": "sha512-sudQPADzmQjXYS1fS2TxbWA/N/vbbfaO4Y7luPaAEyRWZVXC8jHwKV8KgNDbT7IHQaONNZWy9BYsodxY7IyDXQ==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/q/-/q-1.0.6.tgz", + "integrity": "sha512-LSx7jkcXoXWB+kkfwG5zc9Okbgn51BrjLMtKwbmnqfQlCGttTnTxvDVwQanHxkK6CLKb9yEfxQ1ID6pqDpeURw==", "dev": true }, "@types/run-sequence": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/run-sequence/-/run-sequence-0.0.29.tgz", - "integrity": "sha1-atD3ODE24TklMi5p/EHbd7MLIHU=", + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/@types/run-sequence/-/run-sequence-0.0.30.tgz", + "integrity": "sha512-XwGr1b4yCGUILKeBkzmeWcxmGHQ0vFFFpA6D6y1yLO6gKmYorF+PHqdU5KG+nWt38OvtrkDptmrSmlHX/XtpLw==", "dev": true, "requires": { - "@types/gulp": "3.8.33", - "@types/node": "8.0.46" + "@types/gulp": "3.8.36", + "@types/node": "8.5.5" } }, + "@types/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-FKjsOVbC6B7bdSB5CuzyHCkK69I=", + "dev": true + }, + "@types/strip-json-comments": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/@types/strip-json-comments/-/strip-json-comments-0.0.30.tgz", + "integrity": "sha512-7NQmHra/JILCd1QqpSzl8+mJRc8ZHz3uDm8YV1Ks9IhK0epEiTw8aIErbvH9PI+6XbqhyIQy3462nEsn7UVzjQ==", + "dev": true + }, "@types/through2": { "version": "2.0.33", "resolved": "https://registry.npmjs.org/@types/through2/-/through2-2.0.33.tgz", "integrity": "sha1-H/LoihAN+1sUDnu5h5HxGUQA0TE=", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/vinyl": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@types/vinyl/-/vinyl-2.0.1.tgz", - "integrity": "sha512-Joudabfn2ZofU2usW04y8OLmN75u7ZQkW0MCT3AnoBf5oUBp5iQ3Pgfz9+y1RdWkzhCPZo9/wBJ7FMWW2JrY0g==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@types/vinyl/-/vinyl-2.0.2.tgz", + "integrity": "sha512-2iYpNuOl98SrLPBZfEN9Mh2JCJ2EI9HU35SfgBEb51DcmaHkhp8cKMblYeBqMQiwXMgAD3W60DbQ4i/UdLiXhw==", "dev": true, "requires": { - "@types/node": "8.0.46" + "@types/node": "8.5.5" } }, "@types/xml2js": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.0.tgz", - "integrity": "sha512-3gw0UqFMq7PsfMDwsawD0/L48soXfzOEh0NSAWVO99IZXnhx9LD3nOldHIpGYzZBsrS9NV2vaRFvEdWe+UweXQ==", + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.2.tgz", + "integrity": "sha512-8aKUBSj3oGcnuiBmDLm3BIk09RYg01mz9HlQ2u4aS17oJ25DxjQrEUVGFSBVNOfM45pQW4OjcBPplq6r/exJdA==", + "dev": true, + "requires": { + "@types/node": "8.5.5" + } + }, + "JSONStream": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.2.tgz", + "integrity": "sha1-wQI3G27Dp887hHygDCC7D85Mbeo=", "dev": true, "requires": { - "@types/node": "8.0.46" + "jsonparse": "1.3.1", + "through": "2.3.8" } }, "abbrev": { @@ -264,6 +296,17 @@ "kind-of": "3.2.2", "longest": "1.0.1", "repeat-string": "1.6.1" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } } }, "amdefine": { @@ -272,6 +315,33 @@ "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", "dev": true }, + "ansi-cyan": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", + "integrity": "sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, + "ansi-gray": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-gray/-/ansi-gray-0.1.1.tgz", + "integrity": "sha1-KWLPVOyXksSFEKPetSRDaGHvclE=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, + "ansi-red": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-red/-/ansi-red-0.1.1.tgz", + "integrity": "sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", @@ -279,9 +349,18 @@ "dev": true }, "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", + "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", + "dev": true, + "requires": { + "color-convert": "1.9.1" + } + }, + "ansi-wrap": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/ansi-wrap/-/ansi-wrap-0.1.0.tgz", + "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", "dev": true }, "archy": { @@ -300,13 +379,10 @@ } }, "arr-diff": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", - "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", - "dev": true, - "requires": { - "arr-flatten": "1.1.0" - } + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true }, "arr-flatten": { "version": "1.1.0", @@ -314,6 +390,12 @@ "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", "dev": true }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, "array-differ": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", @@ -332,12 +414,6 @@ "integrity": "sha1-fajPLiZijtcygDWB/SH2fKzS7uw=", "dev": true }, - "array-find-index": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", - "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", - "dev": true - }, "array-map": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/array-map/-/array-map-0.0.0.tgz", @@ -351,9 +427,9 @@ "dev": true }, "array-slice": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.0.0.tgz", - "integrity": "sha1-5zA08A3MH0CHYAj9IP6ud71LfC8=", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.1.0.tgz", + "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==", "dev": true }, "array-union": { @@ -372,9 +448,9 @@ "dev": true }, "array-unique": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", - "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, "arrify": { @@ -384,9 +460,9 @@ "dev": true }, "asn1.js": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.9.1.tgz", - "integrity": "sha1-SLokC0WpKA6UdImQull9IWYX/UA=", + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.9.2.tgz", + "integrity": "sha512-b/OsSjvWEo8Pi8H0zsDd2P6Uqo2TK2pH8gNLSJtNLM2Db0v2QaAZ0pBQJXVjAn4gBuugeVDr7s63ZogpUIwWDg==", "dev": true, "requires": { "bn.js": "4.11.8", @@ -404,9 +480,15 @@ } }, "assertion-error": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.0.2.tgz", - "integrity": "sha1-E8pRXYYgbaC6xm6DTdOX2HWBCUw=", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", "dev": true }, "astw": { @@ -425,9 +507,9 @@ "dev": true }, "atob": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/atob/-/atob-1.1.3.tgz", - "integrity": "sha1-lfE2KbEsOlGl0hWr3OKqnzL4B3M=", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.0.3.tgz", + "integrity": "sha1-GcenYEc3dEaPILLS0DNyrX1Mv10=", "dev": true }, "babel-code-frame": { @@ -439,6 +521,33 @@ "chalk": "1.1.3", "esutils": "2.0.2", "js-tokens": "3.0.2" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } } }, "balanced-match": { @@ -447,6 +556,21 @@ "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", "dev": true }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "1.0.1", + "class-utils": "0.3.5", + "component-emitter": "1.2.1", + "define-property": "1.0.0", + "isobject": "3.0.1", + "mixin-deep": "1.3.0", + "pascalcase": "0.1.1" + } + }, "base64-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.2.1.tgz", @@ -476,14 +600,22 @@ } }, "braces": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", - "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.0.tgz", + "integrity": "sha512-P4O8UQRdGiMLWSizsApmXVQDBS6KCt7dSexgLKBmH5Hr1CZq7vsnscFh8oR1sP1ab1Zj0uCHCEzZeV6SfUf3rA==", "dev": true, "requires": { - "expand-range": "1.8.2", - "preserve": "0.2.0", - "repeat-element": "1.1.2" + "arr-flatten": "1.1.0", + "array-unique": "0.3.2", + "define-property": "1.0.0", + "extend-shallow": "2.0.1", + "fill-range": "4.0.0", + "isobject": "3.0.1", + "repeat-element": "1.1.2", + "snapdragon": "0.8.1", + "snapdragon-node": "2.1.1", + "split-string": "3.1.0", + "to-regex": "3.0.1" } }, "brorand": { @@ -498,9 +630,9 @@ "integrity": "sha1-+GzWzvT1MAyOY+B6TVEvZfv/RTE=", "dev": true, "requires": { + "JSONStream": "1.3.2", "combine-source-map": "0.7.2", "defined": "1.0.0", - "JSONStream": "1.3.1", "through2": "2.0.3", "umd": "3.0.1" } @@ -521,11 +653,12 @@ "dev": true }, "browserify": { - "version": "14.5.0", - "resolved": "https://registry.npmjs.org/browserify/-/browserify-14.5.0.tgz", - "integrity": "sha512-gKfOsNQv/toWz+60nSPfYzuwSEdzvV2WdxrVPUbPD/qui44rAkB3t3muNtmmGYHqrG56FGwX9SUEQmzNLAeS7g==", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/browserify/-/browserify-15.0.0.tgz", + "integrity": "sha512-dERxjzl4yacUzaB4XVVXDFFHARzDr6tLRhjqpE/NJUv0SkS3QVmZKiYTiKEQZhQ2HygCL02FUzSS5r3sY/SlTg==", "dev": true, "requires": { + "JSONStream": "1.3.2", "assert": "1.4.1", "browser-pack": "6.0.2", "browser-resolve": "1.11.2", @@ -535,7 +668,7 @@ "concat-stream": "1.5.2", "console-browserify": "1.1.0", "constants-browserify": "1.0.0", - "crypto-browserify": "3.11.1", + "crypto-browserify": "3.12.0", "defined": "1.0.0", "deps-sort": "2.0.0", "domain-browser": "1.1.7", @@ -547,9 +680,8 @@ "https-browserify": "1.0.0", "inherits": "2.0.3", "insert-module-globals": "7.0.1", - "JSONStream": "1.3.1", "labeled-stream-splicer": "2.0.0", - "module-deps": "4.1.1", + "module-deps": "5.0.1", "os-browserify": "0.3.0", "parents": "1.0.1", "path-browserify": "0.0.0", @@ -573,35 +705,12 @@ "util": "0.10.3", "vm-browserify": "0.0.4", "xtend": "4.0.1" - }, - "dependencies": { - "browserify-zlib": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", - "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", - "dev": true, - "requires": { - "pako": "1.0.6" - } - }, - "os-browserify": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", - "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", - "dev": true - }, - "pako": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.6.tgz", - "integrity": "sha512-lQe48YPsMJAig+yngZ87Lus+NF+3mtu7DVOBu6b/gHO1YpKwIj5AWjZ/TOS7i46HD/UixzWb1zeWDZfGZ3iYcg==", - "dev": true - } } }, "browserify-aes": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.8.tgz", - "integrity": "sha512-WYCMOT/PtGTlpOKFht0YJFYcPy6pLCR98CtWfzK13zoynLlBMvAdEMSRGmgnJCw2M2j/5qxBkinZQFobieM8dQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.1.1.tgz", + "integrity": "sha512-UGnTYAnB2a3YuYKIRy1/4FB2HdM866E0qC46JXvVTYKlBlZlnvfpSfY6OKfXZAkv70eJ2a1SqzpAo5CRhZGDFg==", "dev": true, "requires": { "buffer-xor": "1.0.3", @@ -618,7 +727,7 @@ "integrity": "sha1-mYgkSHS/XtTijalWZtzWasj8Njo=", "dev": true, "requires": { - "browserify-aes": "1.0.8", + "browserify-aes": "1.1.1", "browserify-des": "1.0.0", "evp_bytestokey": "1.0.3" } @@ -659,6 +768,15 @@ "parse-asn1": "5.1.0" } }, + "browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "dev": true, + "requires": { + "pako": "1.0.6" + } + }, "buffer": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.0.8.tgz", @@ -693,6 +811,23 @@ "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=", "dev": true }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "1.0.0", + "component-emitter": "1.2.1", + "get-value": "2.0.6", + "has-value": "1.0.0", + "isobject": "3.0.1", + "set-value": "2.0.0", + "to-object-path": "0.3.0", + "union-value": "1.0.0", + "unset-value": "1.0.0" + } + }, "cached-path-relative": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cached-path-relative/-/cached-path-relative-1.0.1.tgz", @@ -700,20 +835,11 @@ "dev": true }, "camelcase": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", - "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", - "dev": true - }, - "camelcase-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", - "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", "dev": true, - "requires": { - "camelcase": "2.1.1", - "map-obj": "1.0.1" - } + "optional": true }, "center-align": { "version": "0.1.3", @@ -724,6 +850,15 @@ "requires": { "align-text": "0.1.4", "lazy-cache": "1.0.4" + }, + "dependencies": { + "lazy-cache": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", + "dev": true, + "optional": true + } } }, "chai": { @@ -732,25 +867,23 @@ "integrity": "sha1-D2RYS6ZC8PKs4oBiefTwbKI61zw=", "dev": true, "requires": { - "assertion-error": "1.0.2", + "assertion-error": "1.1.0", "check-error": "1.0.2", "deep-eql": "3.0.1", "get-func-name": "2.0.0", "pathval": "1.1.0", - "type-detect": "4.0.3" + "type-detect": "4.0.5" } }, "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.0.tgz", + "integrity": "sha512-Az5zJR2CBujap2rqXGaJKaPHyJ0IrUimvYNX+ncCy8PJP4ltOGTrHUIo097ZaL2zMeKYpiCdqDvS6zdrTFok3Q==", "dev": true, "requires": { - "ansi-styles": "2.2.1", + "ansi-styles": "3.2.0", "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" + "supports-color": "4.5.0" } }, "check-error": { @@ -769,6 +902,87 @@ "safe-buffer": "5.1.1" } }, + "class-utils": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.5.tgz", + "integrity": "sha1-F+eTEDdQ+WJ7IXbqNM/RtWWQPIA=", + "dev": true, + "requires": { + "arr-union": "3.1.0", + "define-property": "0.2.5", + "isobject": "3.0.1", + "lazy-cache": "2.0.2", + "static-extend": "0.1.2" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, "cliui": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", @@ -791,9 +1005,9 @@ } }, "clone": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz", - "integrity": "sha1-Jgt6meux7f4kdTgXX3gyQ8sZ0Uk=", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.3.tgz", + "integrity": "sha1-KY1+IjFmD0DAA8LtMUDezz9TCF8=", "dev": true }, "clone-buffer": { @@ -819,10 +1033,20 @@ "through2": "2.0.3" } }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "1.0.0", + "object-visit": "1.0.1" + } + }, "color-convert": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.0.tgz", - "integrity": "sha1-Gsz5fdc5uYO/mU1W/sj5WFNkG3o=", + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.1.tgz", + "integrity": "sha512-mjGanIiwQJskCC18rPR6OmrZ6fm2Lc7PeGFYwCmy5J34wC6F1PzdGL6xeMfmgicfYcNLGuVFA3WzXtIDCQSZxQ==", "dev": true, "requires": { "color-name": "1.1.3" @@ -834,10 +1058,10 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, - "colors": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", - "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", + "color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", "dev": true }, "combine-source-map": { @@ -866,6 +1090,12 @@ "integrity": "sha512-b0553uYA5YAEGgyYIGYROzKQ7X5RAqedkfjiZxwi0kL1g3bOaBNNZfYkzt/CL0umgD5wc9Jec2FbB98CjkMRvQ==", "dev": true }, + "component-emitter": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", + "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", + "dev": true + }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -930,9 +1160,15 @@ "dev": true }, "convert-source-map": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.0.tgz", - "integrity": "sha1-ms1whRxtXf3ZPZKC5e35SgP/RrU=", + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", + "integrity": "sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=", + "dev": true + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", "dev": true }, "core-util-is": { @@ -978,9 +1214,9 @@ } }, "crypto-browserify": { - "version": "3.11.1", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.11.1.tgz", - "integrity": "sha512-Na7ZlwCOqoaW5RwUK1WpXws2kv8mNhWdTlzob0UXulk6G9BDbyiJaGTYBIX61Ozn9l1EPPJpICZb4DaOpT9NlQ==", + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", "dev": true, "requires": { "browserify-cipher": "1.0.0", @@ -992,7 +1228,8 @@ "inherits": "2.0.3", "pbkdf2": "3.0.14", "public-encrypt": "4.0.0", - "randombytes": "2.0.5" + "randombytes": "2.0.5", + "randomfill": "1.0.3" } }, "css": { @@ -1007,6 +1244,12 @@ "urix": "0.1.0" }, "dependencies": { + "atob": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/atob/-/atob-1.1.3.tgz", + "integrity": "sha1-lfE2KbEsOlGl0hWr3OKqnzL4B3M=", + "dev": true + }, "source-map": { "version": "0.1.43", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz", @@ -1015,25 +1258,34 @@ "requires": { "amdefine": "1.0.1" } + }, + "source-map-resolve": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.3.1.tgz", + "integrity": "sha1-YQ9hIqRFuN1RU1oqcbeD38Ekh2E=", + "dev": true, + "requires": { + "atob": "1.1.3", + "resolve-url": "0.2.1", + "source-map-url": "0.3.0", + "urix": "0.1.0" + } + }, + "source-map-url": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.3.0.tgz", + "integrity": "sha1-fsrxO1e80J2opAxdJp2zN5nUqvk=", + "dev": true } } }, - "currently-unhandled": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", - "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", - "dev": true, - "requires": { - "array-find-index": "1.0.2" - } - }, "d": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", "dev": true, "requires": { - "es5-ext": "0.10.31" + "es5-ext": "0.10.37" } }, "date-now": { @@ -1049,30 +1301,48 @@ "dev": true }, "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "requires": { "ms": "2.0.0" } }, "debug-fabulous": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/debug-fabulous/-/debug-fabulous-0.2.1.tgz", - "integrity": "sha512-u0TV6HcfLsZ03xLBhdhSViQMldaiQ2o+8/nSILaXkuNSWvxkx66vYJUAam0Eu7gAilJRX/69J4kKdqajQPaPyw==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/debug-fabulous/-/debug-fabulous-1.0.0.tgz", + "integrity": "sha512-dsd50qQ1atDeurcxL7XOjPp4nZCGZzWIONDujDXzl1atSyC3hMbZD+v6440etw+Vt0Pr8ce4TQzHfX3KZM05Mw==", "dev": true, "requires": { "debug": "3.1.0", "memoizee": "0.4.11", "object-assign": "4.1.1" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + } } }, "decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true + "dev": true, + "optional": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true }, "deep-eql": { "version": "3.0.1", @@ -1080,7 +1350,7 @@ "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", "dev": true, "requires": { - "type-detect": "4.0.3" + "type-detect": "4.0.5" } }, "deep-is": { @@ -1095,7 +1365,16 @@ "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", "dev": true, "requires": { - "clone": "1.0.2" + "clone": "1.0.3" + } + }, + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "1.0.2" } }, "defined": { @@ -1130,7 +1409,7 @@ "integrity": "sha1-CRckkC6EZYJg65EHSMzNGvbiH7U=", "dev": true, "requires": { - "JSONStream": "1.3.1", + "JSONStream": "1.3.2", "shasum": "1.0.2", "subarg": "1.0.0", "through2": "2.0.3" @@ -1147,13 +1426,10 @@ } }, "detect-file": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-0.1.0.tgz", - "integrity": "sha1-STXe39lIhkjgBrASlWbpOGcR6mM=", - "dev": true, - "requires": { - "fs-exists-sync": "0.1.0" - } + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", + "dev": true }, "detect-newline": { "version": "2.1.0", @@ -1162,13 +1438,22 @@ "dev": true }, "detective": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/detective/-/detective-4.5.0.tgz", - "integrity": "sha1-blqMaybmx6JUsca210kNmOyR7dE=", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/detective/-/detective-5.0.2.tgz", + "integrity": "sha512-NUsLoezj4wb9o7vpxS9F3L5vcO87ceyRBcl48op06YFNwkyIEY997JpSCA5lDlDuDc6JxOtaL5qfK3muoWxpMA==", "dev": true, "requires": { - "acorn": "4.0.13", + "@browserify/acorn5-object-spread": "5.0.1", + "acorn": "5.3.0", "defined": "1.0.0" + }, + "dependencies": { + "acorn": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz", + "integrity": "sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==", + "dev": true + } } }, "diff": { @@ -1261,33 +1546,24 @@ } } }, - "error-ex": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.1.tgz", - "integrity": "sha1-+FWobOYa3E6GIcPNoh56dhLDqNw=", - "dev": true, - "requires": { - "is-arrayish": "0.2.1" - } - }, "es5-ext": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.31.tgz", - "integrity": "sha1-e7k4yVp/G59ygJLcCcQe3MOY7v4=", + "version": "0.10.37", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.37.tgz", + "integrity": "sha1-DudB0Ui4AGm6J9AgOTdWryV978M=", "dev": true, "requires": { - "es6-iterator": "2.0.1", + "es6-iterator": "2.0.3", "es6-symbol": "3.1.1" } }, "es6-iterator": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.1.tgz", - "integrity": "sha1-jjGcnwRTv1ddN0lAplWSDlnKVRI=", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { "d": "1.0.0", - "es5-ext": "0.10.31", + "es5-ext": "0.10.37", "es6-symbol": "3.1.1" } }, @@ -1304,7 +1580,7 @@ "dev": true, "requires": { "d": "1.0.0", - "es5-ext": "0.10.31" + "es5-ext": "0.10.37" } }, "es6-weak-map": { @@ -1314,8 +1590,8 @@ "dev": true, "requires": { "d": "1.0.0", - "es5-ext": "0.10.31", - "es6-iterator": "2.0.1", + "es5-ext": "0.10.37", + "es6-iterator": "2.0.3", "es6-symbol": "3.1.1" } }, @@ -1375,7 +1651,7 @@ "dev": true, "requires": { "d": "1.0.0", - "es5-ext": "0.10.31" + "es5-ext": "0.10.37" } }, "events": { @@ -1395,12 +1671,86 @@ } }, "expand-brackets": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", - "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", - "dev": true, - "requires": { - "is-posix-bracket": "0.1.1" + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "2.6.9", + "define-property": "0.2.5", + "extend-shallow": "2.0.1", + "posix-character-classes": "0.1.1", + "regex-not": "1.0.0", + "snapdragon": "0.8.1", + "to-regex": "3.0.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } } }, "expand-range": { @@ -1410,15 +1760,57 @@ "dev": true, "requires": { "fill-range": "2.2.3" + }, + "dependencies": { + "fill-range": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.3.tgz", + "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", + "dev": true, + "requires": { + "is-number": "2.1.0", + "isobject": "2.1.0", + "randomatic": "1.1.7", + "repeat-element": "1.1.2", + "repeat-string": "1.6.1" + } + }, + "is-number": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", + "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + } + }, + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } } }, "expand-tilde": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-1.2.2.tgz", - "integrity": "sha1-C4HrqJflo9MdHD0QL48BRB5VlEk=", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", "dev": true, "requires": { - "os-homedir": "1.0.2" + "homedir-polyfill": "1.0.1" } }, "extend": { @@ -1437,21 +1829,29 @@ } }, "extglob": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", - "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.3.tgz", + "integrity": "sha512-AyptZexgu7qppEPq59DtN/XJGZDrLcVxSHai+4hdgMMS9EpF4GBvygcWWApno8lL9qSjVpYt7Raao28qzJX1ww==", "dev": true, "requires": { - "is-extglob": "1.0.0" + "array-unique": "0.3.2", + "define-property": "1.0.0", + "expand-brackets": "2.1.4", + "extend-shallow": "2.0.1", + "fragment-cache": "0.2.1", + "regex-not": "1.0.0", + "snapdragon": "0.8.1", + "to-regex": "3.0.1" } }, "fancy-log": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.0.tgz", - "integrity": "sha1-Rb4X0Cu5kX1gzP/UmVyZnmyMmUg=", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.2.tgz", + "integrity": "sha1-9BEl49hPLn2JpD0G2VjI94vha+E=", "dev": true, "requires": { - "chalk": "1.1.3", + "ansi-gray": "0.1.1", + "color-support": "1.1.3", "time-stamp": "1.1.0" } }, @@ -1486,16 +1886,15 @@ "dev": true }, "fill-range": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.3.tgz", - "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", "dev": true, "requires": { - "is-number": "2.1.0", - "isobject": "2.1.0", - "randomatic": "1.1.7", - "repeat-element": "1.1.2", - "repeat-string": "1.6.1" + "extend-shallow": "2.0.1", + "is-number": "3.0.0", + "repeat-string": "1.6.1", + "to-regex-range": "2.1.1" } }, "find-index": { @@ -1504,26 +1903,16 @@ "integrity": "sha1-Z101iyyjiS15Whq0cjL4tuLg3eQ=", "dev": true }, - "find-up": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", - "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", - "dev": true, - "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" - } - }, "findup-sync": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.4.3.tgz", - "integrity": "sha1-QAQ5Kee8YK3wt/SCfExudaDeyhI=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", + "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", "dev": true, "requires": { - "detect-file": "0.1.0", - "is-glob": "2.0.1", - "micromatch": "2.3.11", - "resolve-dir": "0.1.1" + "detect-file": "1.0.0", + "is-glob": "3.1.0", + "micromatch": "3.1.5", + "resolve-dir": "1.0.1" } }, "fined": { @@ -1536,18 +1925,7 @@ "is-plain-object": "2.0.4", "object.defaults": "1.1.0", "object.pick": "1.3.0", - "parse-filepath": "1.0.1" - }, - "dependencies": { - "expand-tilde": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", - "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", - "dev": true, - "requires": { - "homedir-polyfill": "1.0.1" - } - } + "parse-filepath": "1.0.2" } }, "first-chunk-stream": { @@ -1557,9 +1935,9 @@ "dev": true }, "flagged-respawn": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-0.3.2.tgz", - "integrity": "sha1-/xke3c1wiKZ1smEP/8l2vpuAdLU=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-1.0.0.tgz", + "integrity": "sha1-Tnmumy6zi/hrO7Vr8+ClaqX8q9c=", "dev": true }, "for-in": { @@ -1569,19 +1947,22 @@ "dev": true }, "for-own": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", - "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", "dev": true, "requires": { "for-in": "1.0.2" } }, - "fs-exists-sync": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/fs-exists-sync/-/fs-exists-sync-0.1.0.tgz", - "integrity": "sha1-mC1ok6+RjnLQjeyehnP/K1qNat0=", - "dev": true + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "0.2.2" + } }, "fs.realpath": { "version": "1.0.0", @@ -1610,10 +1991,10 @@ "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", "dev": true }, - "get-stdin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", - "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", "dev": true }, "glob": { @@ -1638,15 +2019,42 @@ "requires": { "glob-parent": "2.0.0", "is-glob": "2.0.1" + }, + "dependencies": { + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "dev": true, + "requires": { + "is-glob": "2.0.1" + } + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "1.0.0" + } + } } }, "glob-parent": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", - "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { - "is-glob": "2.0.1" + "is-glob": "3.1.0", + "path-dirname": "1.0.2" } }, "glob-stream": { @@ -1739,24 +2147,26 @@ } }, "global-modules": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-0.2.3.tgz", - "integrity": "sha1-6lo77ULG1s6ZWk+KEmm12uIjgo0=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", "dev": true, "requires": { - "global-prefix": "0.1.5", - "is-windows": "0.2.0" + "global-prefix": "1.0.2", + "is-windows": "1.0.1", + "resolve-dir": "1.0.1" } }, "global-prefix": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-0.1.5.tgz", - "integrity": "sha1-jTvGuNo8qBEqFg2NSW/wRiv+948=", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", "dev": true, "requires": { + "expand-tilde": "2.0.2", "homedir-polyfill": "1.0.1", - "ini": "1.3.4", - "is-windows": "0.2.0", + "ini": "1.3.5", + "is-windows": "1.0.1", "which": "1.3.0" } }, @@ -1842,7 +2252,7 @@ "integrity": "sha1-dhPHeKGv6mLyXGMKCG1/Osu92Bg=", "dev": true, "requires": { - "natives": "1.1.0" + "natives": "1.1.1" } }, "growl": { @@ -1861,8 +2271,8 @@ "chalk": "1.1.3", "deprecated": "0.0.1", "gulp-util": "3.0.8", - "interpret": "1.0.4", - "liftoff": "2.3.0", + "interpret": "1.1.0", + "liftoff": "2.5.0", "minimist": "1.2.0", "orchestrator": "0.3.8", "pretty-hrtime": "1.0.3", @@ -1870,309 +2280,121 @@ "tildify": "1.2.0", "v8flags": "2.1.1", "vinyl-fs": "0.3.14" - } - }, - "gulp-clone": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/gulp-clone/-/gulp-clone-1.0.0.tgz", - "integrity": "sha1-mubGVr2cTzae6AXu9WV4a8gQBbA=", - "dev": true, - "requires": { - "gulp-util": "2.2.20", - "through2": "0.4.2" }, "dependencies": { - "ansi-regex": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-0.2.1.tgz", - "integrity": "sha1-DY6UaWej2BQ/k+JOKYUl/BsiNfk=", - "dev": true - }, "ansi-styles": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-1.1.0.tgz", - "integrity": "sha1-6uy/Zs1waIJ2Cy9GkVgrj1XXp94=", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", "dev": true }, "chalk": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-0.5.1.tgz", - "integrity": "sha1-Zjs6ZItotV0EaQ1JFnqoN4WPIXQ=", + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", "dev": true, "requires": { - "ansi-styles": "1.1.0", + "ansi-styles": "2.2.1", "escape-string-regexp": "1.0.5", - "has-ansi": "0.1.0", - "strip-ansi": "0.3.0", - "supports-color": "0.2.0" + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" } }, - "dateformat": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz", - "integrity": "sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk=", - "dev": true, - "requires": { - "get-stdin": "4.0.1", - "meow": "3.7.0" - } + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "gulp-clone": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/gulp-clone/-/gulp-clone-1.1.1.tgz", + "integrity": "sha512-+9z6YKyup0pxL1nD9Hw5WjC29d280dsGkegagzt4xKAOvroyzZlA8Bs9MYs2WSSFIDqmcftMUVN/oentgBv69A==", + "dev": true, + "requires": { + "chai": "4.1.2", + "mocha": "4.1.0", + "plugin-error": "0.1.2", + "through2": "2.0.3" + } + }, + "gulp-concat": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.1.tgz", + "integrity": "sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M=", + "dev": true, + "requires": { + "concat-with-sourcemaps": "1.0.4", + "through2": "2.0.3", + "vinyl": "2.1.0" + } + }, + "gulp-help": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/gulp-help/-/gulp-help-1.6.1.tgz", + "integrity": "sha1-Jh2xhuGDl/7z9qLCLpwxW/qIrgw=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "object-assign": "3.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true }, - "gulp-util": { - "version": "2.2.20", - "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-2.2.20.tgz", - "integrity": "sha1-1xRuVyiRC9jwR6awseVJvCLb1kw=", + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", "dev": true, "requires": { - "chalk": "0.5.1", - "dateformat": "1.0.12", - "lodash._reinterpolate": "2.4.1", - "lodash.template": "2.4.1", - "minimist": "0.2.0", - "multipipe": "0.1.2", - "through2": "0.5.1", - "vinyl": "0.2.3" - }, - "dependencies": { - "through2": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.5.1.tgz", - "integrity": "sha1-390BLrnHAOIyP9M084rGIqs3Lac=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "xtend": "3.0.0" - } - } + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" } }, - "has-ansi": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-0.1.0.tgz", - "integrity": "sha1-hPJlqujA5qiKEtcCKJS3VoiUxi4=", - "dev": true, - "requires": { - "ansi-regex": "0.2.1" - } + "object-assign": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", + "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", + "dev": true }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "gulp-insert": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/gulp-insert/-/gulp-insert-0.5.0.tgz", + "integrity": "sha1-MjE/E+SiPPWsylzl8MCAkjx3hgI=", + "dev": true, + "requires": { + "readable-stream": "1.1.14", + "streamqueue": "0.0.6" + }, + "dependencies": { "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", "dev": true }, - "lodash._reinterpolate": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-2.4.1.tgz", - "integrity": "sha1-TxInqlqHEfxjL1sHofRgequLMiI=", - "dev": true - }, - "lodash.escape": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-2.4.1.tgz", - "integrity": "sha1-LOEsXghNsKV92l5dHu659dF1o7Q=", - "dev": true, - "requires": { - "lodash._escapehtmlchar": "2.4.1", - "lodash._reunescapedhtml": "2.4.1", - "lodash.keys": "2.4.1" - } - }, - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - }, - "lodash.template": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-2.4.1.tgz", - "integrity": "sha1-nmEQB+32KRKal0qzxIuBez4c8g0=", - "dev": true, - "requires": { - "lodash._escapestringchar": "2.4.1", - "lodash._reinterpolate": "2.4.1", - "lodash.defaults": "2.4.1", - "lodash.escape": "2.4.1", - "lodash.keys": "2.4.1", - "lodash.templatesettings": "2.4.1", - "lodash.values": "2.4.1" - } - }, - "lodash.templatesettings": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-2.4.1.tgz", - "integrity": "sha1-6nbHXRHrhtTb6JqDiTu4YZKaxpk=", - "dev": true, - "requires": { - "lodash._reinterpolate": "2.4.1", - "lodash.escape": "2.4.1" - } - }, - "minimist": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.2.0.tgz", - "integrity": "sha1-Tf/lJdriuGTGbC4jxicdev3s784=", - "dev": true - }, - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - }, - "strip-ansi": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-0.3.0.tgz", - "integrity": "sha1-JfSOoiynkYfzF0pNuHWTR7sSYiA=", - "dev": true, - "requires": { - "ansi-regex": "0.2.1" - } - }, - "supports-color": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-0.2.0.tgz", - "integrity": "sha1-2S3iaU6z9nMjlz1649i1W0wiGQo=", - "dev": true - }, - "through2": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.4.2.tgz", - "integrity": "sha1-2/WGYDEVHsg1K7bE22SiKSqEC5s=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "xtend": "2.1.2" - }, - "dependencies": { - "xtend": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.1.2.tgz", - "integrity": "sha1-bv7MKk2tjmlixJAbM3znuoe10os=", - "dev": true, - "requires": { - "object-keys": "0.4.0" - } - } - } - }, - "vinyl": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.2.3.tgz", - "integrity": "sha1-vKk4IJWC7FpJrVOKAPofEl5RMlI=", - "dev": true, - "requires": { - "clone-stats": "0.0.1" - } - }, - "xtend": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz", - "integrity": "sha1-XM50B7r2Qsunvs2laBEcST9ZZlo=", - "dev": true - } - } - }, - "gulp-concat": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.1.tgz", - "integrity": "sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M=", - "dev": true, - "requires": { - "concat-with-sourcemaps": "1.0.4", - "through2": "2.0.3", - "vinyl": "2.1.0" - }, - "dependencies": { - "clone": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", - "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", - "dev": true - }, - "clone-stats": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", - "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", - "dev": true - }, - "replace-ext": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", - "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=", - "dev": true - }, - "vinyl": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.1.0.tgz", - "integrity": "sha1-Ah+cLPlR1rk5lDyJ617lrdT9kkw=", - "dev": true, - "requires": { - "clone": "2.1.1", - "clone-buffer": "1.0.0", - "clone-stats": "1.0.0", - "cloneable-readable": "1.0.0", - "remove-trailing-separator": "1.1.0", - "replace-ext": "1.0.0" - } - } - } - }, - "gulp-help": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/gulp-help/-/gulp-help-1.6.1.tgz", - "integrity": "sha1-Jh2xhuGDl/7z9qLCLpwxW/qIrgw=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "object-assign": "3.0.0" - }, - "dependencies": { - "object-assign": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", - "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", - "dev": true - } - } - }, - "gulp-insert": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/gulp-insert/-/gulp-insert-0.5.0.tgz", - "integrity": "sha1-MjE/E+SiPPWsylzl8MCAkjx3hgI=", - "dev": true, - "requires": { - "readable-stream": "1.1.14", - "streamqueue": "0.0.6" - }, - "dependencies": { - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", "dev": true, "requires": { "core-util-is": "1.0.2", @@ -2190,59 +2412,53 @@ } }, "gulp-newer": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/gulp-newer/-/gulp-newer-1.3.0.tgz", - "integrity": "sha1-1Q7Ky7gi7aSStXMkpshaB/2aVcE=", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/gulp-newer/-/gulp-newer-1.4.0.tgz", + "integrity": "sha512-h79fGO55S/P9eAADbLAP9aTtVYpLSR1ONj08VPaSdVVNVYhTS8p1CO1TW7kEMu+hC+sytmCqcUr5LesvZEtDoQ==", "dev": true, "requires": { "glob": "7.1.2", - "gulp-util": "3.0.8", - "kew": "0.7.0" + "kew": "0.7.0", + "plugin-error": "0.1.2" } }, "gulp-sourcemaps": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/gulp-sourcemaps/-/gulp-sourcemaps-2.6.1.tgz", - "integrity": "sha512-1qHCI3hdmsMdq/SUotxwUh/L8YzlI6J9zQ5ifNOtx4Y6KV5y5sGuORv1KZzWhuKtz/mXNh5xLESUtwC4EndCjA==", + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/gulp-sourcemaps/-/gulp-sourcemaps-2.6.3.tgz", + "integrity": "sha1-EbAz91n5CeCl8Vt730esKcxU76Q=", "dev": true, "requires": { "@gulp-sourcemaps/identity-map": "1.0.1", "@gulp-sourcemaps/map-sources": "1.0.0", - "acorn": "4.0.13", - "convert-source-map": "1.5.0", + "acorn": "5.3.0", + "convert-source-map": "1.5.1", "css": "2.2.1", - "debug-fabulous": "0.2.1", + "debug-fabulous": "1.0.0", "detect-newline": "2.1.0", "graceful-fs": "4.1.11", "source-map": "0.5.7", "strip-bom-string": "1.0.0", - "through2": "2.0.3", - "vinyl": "1.2.0" + "through2": "2.0.3" }, "dependencies": { + "acorn": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz", + "integrity": "sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==", + "dev": true + }, "graceful-fs": { "version": "4.1.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", "dev": true - }, - "vinyl": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-1.2.0.tgz", - "integrity": "sha1-XIgDbPVl5d8FVYv8kR+GVt8hiIQ=", - "dev": true, - "requires": { - "clone": "1.0.2", - "clone-stats": "0.0.1", - "replace-ext": "0.0.1" - } } } }, "gulp-typescript": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/gulp-typescript/-/gulp-typescript-3.2.2.tgz", - "integrity": "sha1-t+Xh08s193LlPmBAJmAYJuK+d/w=", + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/gulp-typescript/-/gulp-typescript-3.2.3.tgz", + "integrity": "sha512-Np2sJXgtDUwIAoMtlJ9uXsVmpu1FWXlKZw164hLuo56uJa7qo5W2KZ0yAYiYH/HUsaz5L0O2toMOcLIokpFCPg==", "dev": true, "requires": { "gulp-util": "3.0.8", @@ -2251,6 +2467,50 @@ "vinyl-fs": "2.4.4" }, "dependencies": { + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "dev": true, + "requires": { + "arr-flatten": "1.1.0" + } + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "dev": true, + "requires": { + "expand-range": "1.8.2", + "preserve": "0.2.0", + "repeat-element": "1.1.2" + } + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "dev": true, + "requires": { + "is-posix-bracket": "0.1.1" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "dev": true, + "requires": { + "is-extglob": "1.0.0" + } + }, "glob": { "version": "5.0.15", "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", @@ -2264,16 +2524,6 @@ "path-is-absolute": "1.0.1" } }, - "glob-parent": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", - "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", - "dev": true, - "requires": { - "is-glob": "3.1.0", - "path-dirname": "1.0.2" - } - }, "glob-stream": { "version": "5.3.5", "resolved": "https://registry.npmjs.org/glob-stream/-/glob-stream-5.3.5.tgz", @@ -2326,7 +2576,7 @@ "integrity": "sha1-uG/zSdgBzrVuHZ59x7vLS33uYAw=", "dev": true, "requires": { - "convert-source-map": "1.5.0", + "convert-source-map": "1.5.1", "graceful-fs": "4.1.11", "strip-bom": "2.0.0", "through2": "2.0.3", @@ -2334,18 +2584,18 @@ } }, "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", "dev": true }, "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", "dev": true, "requires": { - "is-extglob": "2.1.1" + "is-extglob": "1.0.0" } }, "isarray": { @@ -2363,6 +2613,36 @@ "jsonify": "0.0.0" } }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "dev": true, + "requires": { + "arr-diff": "2.0.0", + "array-unique": "0.2.1", + "braces": "1.8.5", + "expand-brackets": "0.1.5", + "extglob": "0.3.2", + "filename-regex": "2.0.1", + "is-extglob": "1.0.0", + "is-glob": "2.0.1", + "kind-of": "3.2.2", + "normalize-path": "2.1.1", + "object.omit": "2.0.1", + "parse-glob": "3.0.4", + "regex-cache": "0.4.4" + } + }, "ordered-read-streams": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-0.3.0.tgz", @@ -2404,7 +2684,7 @@ "integrity": "sha1-XIgDbPVl5d8FVYv8kR+GVt8hiIQ=", "dev": true, "requires": { - "clone": "1.0.2", + "clone": "1.0.3", "clone-stats": "0.0.1", "replace-ext": "0.0.1" } @@ -2447,7 +2727,7 @@ "beeper": "1.1.1", "chalk": "1.1.3", "dateformat": "2.2.0", - "fancy-log": "1.3.0", + "fancy-log": "1.3.2", "gulplog": "1.0.0", "has-gulplog": "0.1.0", "lodash._reescape": "3.0.0", @@ -2462,11 +2742,47 @@ "vinyl": "0.5.3" }, "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, "object-assign": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", "dev": true + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "vinyl": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", + "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", + "dev": true, + "requires": { + "clone": "1.0.3", + "clone-stats": "0.0.1", + "replace-ext": "0.0.1" + } } } }, @@ -2480,9 +2796,9 @@ } }, "handlebars": { - "version": "4.0.10", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.0.10.tgz", - "integrity": "sha1-PTDHGLCaPZbyPqTMH0A8TTup/08=", + "version": "4.0.11", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.0.11.tgz", + "integrity": "sha1-Ywo13+ApS8KB7a5v/F0yn8eYLcw=", "dev": true, "requires": { "async": "1.5.2", @@ -2527,9 +2843,9 @@ "dev": true }, "has-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", - "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", + "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", "dev": true }, "has-gulplog": { @@ -2541,6 +2857,38 @@ "sparkles": "1.0.0" } }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "2.0.6", + "has-values": "1.0.0", + "isobject": "3.0.1" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "3.0.0", + "kind-of": "4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, "hash-base": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-2.0.2.tgz", @@ -2586,12 +2934,6 @@ "parse-passwd": "1.0.0" } }, - "hosted-git-info": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.5.0.tgz", - "integrity": "sha512-pNgbURSuab90KbTqvRPsseaTxOJCZBD0a7t+haSN33piP9cCM4l0CqdzAif2hUqm716UovKB2ROmiabGAKVXyg==", - "dev": true - }, "htmlescape": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/htmlescape/-/htmlescape-1.1.1.tgz", @@ -2610,15 +2952,6 @@ "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=", "dev": true }, - "indent-string": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", - "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", - "dev": true, - "requires": { - "repeating": "2.0.1" - } - }, "indexof": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", @@ -2642,9 +2975,9 @@ "dev": true }, "ini": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", - "integrity": "sha1-BTfLedr1m1mhpRff9wbIbsA5Fi4=", + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", "dev": true }, "inline-source-map": { @@ -2662,10 +2995,10 @@ "integrity": "sha1-wDv04BywhtW15azorQr+eInWOMM=", "dev": true, "requires": { + "JSONStream": "1.3.2", "combine-source-map": "0.7.2", "concat-stream": "1.5.2", - "is-buffer": "1.1.5", - "JSONStream": "1.3.1", + "is-buffer": "1.1.6", "lexical-scope": "1.2.0", "process": "0.11.10", "through2": "2.0.3", @@ -2673,40 +3006,54 @@ } }, "interpret": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.0.4.tgz", - "integrity": "sha1-ggzdWIuGj/sZGoCVBtbJyPISsbA=", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", + "integrity": "sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=", "dev": true }, "is-absolute": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-0.2.6.tgz", - "integrity": "sha1-IN5p89uULvLYe5wto28XIjWxtes=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", "dev": true, "requires": { - "is-relative": "0.2.1", - "is-windows": "0.2.0" + "is-relative": "1.0.0", + "is-windows": "1.0.1" } }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "6.0.2" + } }, "is-buffer": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.5.tgz", - "integrity": "sha1-Hzsm72E7IUuIy8ojzGwB2Hlh7sw=", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", "dev": true }, - "is-builtin-module": { + "is-data-descriptor": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", - "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "6.0.2" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { - "builtin-modules": "1.1.1" + "is-accessor-descriptor": "1.0.0", + "is-data-descriptor": "1.0.0", + "kind-of": "6.0.2" } }, "is-dotfile": { @@ -2731,36 +3078,47 @@ "dev": true }, "is-extglob": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", "dev": true }, - "is-finite": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", - "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { - "number-is-nan": "1.0.1" + "is-extglob": "2.1.1" } }, - "is-glob": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", - "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { - "is-extglob": "1.0.0" + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } } }, - "is-number": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", - "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", + "is-odd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-odd/-/is-odd-1.0.0.tgz", + "integrity": "sha1-O4qTLrAos3dcObsJ6RdnrM22kIg=", "dev": true, "requires": { - "kind-of": "3.2.2" + "is-number": "3.0.0" } }, "is-path-cwd": { @@ -2775,13 +3133,13 @@ "integrity": "sha1-ZHdYK4IU1gI0YJRWcAO+ip6sBNw=", "dev": true, "requires": { - "is-path-inside": "1.0.0" + "is-path-inside": "1.0.1" } }, "is-path-inside": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.0.tgz", - "integrity": "sha1-/AbloWg/vaE95mev9xe7wQpI838=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", "dev": true, "requires": { "path-is-inside": "1.0.2" @@ -2794,14 +3152,6 @@ "dev": true, "requires": { "isobject": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } } }, "is-posix-bracket": { @@ -2823,12 +3173,12 @@ "dev": true }, "is-relative": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-0.2.1.tgz", - "integrity": "sha1-0n9MfVFtF1+2ENuEu+7yPDvJeqU=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", "dev": true, "requires": { - "is-unc-path": "0.1.2" + "is-unc-path": "1.0.0" } }, "is-stream": { @@ -2838,9 +3188,9 @@ "dev": true }, "is-unc-path": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-0.1.2.tgz", - "integrity": "sha1-arBTpyVzwQJQ/0FqOBTDUXivObk=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", "dev": true, "requires": { "unc-path-regex": "0.1.2" @@ -2859,9 +3209,9 @@ "dev": true }, "is-windows": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-0.2.0.tgz", - "integrity": "sha1-3hqm1j6indJIc3tp8f+LgALSEIw=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.1.tgz", + "integrity": "sha1-MQ23D3QtJZoWo2kgK1GvhCMzENk=", "dev": true }, "isarray": { @@ -2877,13 +3227,10 @@ "dev": true }, "isobject": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "dev": true, - "requires": { - "isarray": "1.0.0" - } + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true }, "istanbul": { "version": "0.4.5", @@ -2896,7 +3243,7 @@ "escodegen": "1.8.1", "esprima": "2.7.3", "glob": "5.0.15", - "handlebars": "4.0.10", + "handlebars": "4.0.11", "js-yaml": "3.10.0", "mkdirp": "0.5.1", "nopt": "3.0.6", @@ -2920,6 +3267,12 @@ "path-is-absolute": "1.0.1" } }, + "has-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "dev": true + }, "supports-color": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz", @@ -3020,16 +3373,6 @@ "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", "dev": true }, - "JSONStream": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.1.tgz", - "integrity": "sha1-cH92HgHa6eFvG8+TcDt4xwlmV5o=", - "dev": true, - "requires": { - "jsonparse": "1.3.1", - "through": "2.3.8" - } - }, "kew": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/kew/-/kew-0.7.0.tgz", @@ -3037,13 +3380,10 @@ "dev": true }, "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.5" - } + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true }, "labeled-stream-splicer": { "version": "2.0.0", @@ -3065,11 +3405,13 @@ } }, "lazy-cache": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", - "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-2.0.2.tgz", + "integrity": "sha1-uRkKT5EzVGlIQIWfio9whNiCImQ=", "dev": true, - "optional": true + "requires": { + "set-getter": "0.1.0" + } }, "lazystream": { "version": "1.0.0", @@ -3100,58 +3442,21 @@ } }, "liftoff": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-2.3.0.tgz", - "integrity": "sha1-qY8v9nGD2Lp8+soQVIvX/wVQs4U=", + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-2.5.0.tgz", + "integrity": "sha1-IAkpG7Mc6oYbvxCnwVooyvdcMew=", "dev": true, "requires": { "extend": "3.0.1", - "findup-sync": "0.4.3", + "findup-sync": "2.0.0", "fined": "1.1.0", - "flagged-respawn": "0.3.2", - "lodash.isplainobject": "4.0.6", - "lodash.isstring": "4.0.1", - "lodash.mapvalues": "4.6.0", + "flagged-respawn": "1.0.0", + "is-plain-object": "2.0.4", + "object.map": "1.0.1", "rechoir": "0.6.2", "resolve": "1.1.7" } }, - "load-json-file": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", - "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", - "dev": true, - "requires": { - "graceful-fs": "4.1.11", - "parse-json": "2.2.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "strip-bom": "2.0.0" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", - "dev": true - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", - "dev": true, - "requires": { - "is-utf8": "0.2.1" - } - } - } - }, "lodash": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/lodash/-/lodash-1.0.2.tgz", @@ -3176,51 +3481,18 @@ "integrity": "sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=", "dev": true }, - "lodash._escapehtmlchar": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._escapehtmlchar/-/lodash._escapehtmlchar-2.4.1.tgz", - "integrity": "sha1-32fDu2t+jh6DGrSL+geVuSr+iZ0=", - "dev": true, - "requires": { - "lodash._htmlescapes": "2.4.1" - } - }, - "lodash._escapestringchar": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._escapestringchar/-/lodash._escapestringchar-2.4.1.tgz", - "integrity": "sha1-7P4iYYoq3lC/7qQ5N+Ud9m8O23I=", - "dev": true - }, "lodash._getnative": { "version": "3.9.1", "resolved": "https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz", "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", "dev": true }, - "lodash._htmlescapes": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._htmlescapes/-/lodash._htmlescapes-2.4.1.tgz", - "integrity": "sha1-MtFL8IRLbeb4tioFG09nwii2JMs=", - "dev": true - }, "lodash._isiterateecall": { "version": "3.0.9", "resolved": "https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", "dev": true }, - "lodash._isnative": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._isnative/-/lodash._isnative-2.4.1.tgz", - "integrity": "sha1-PqZAS3hKe+g2x7V1gOHN95sUgyw=", - "dev": true - }, - "lodash._objecttypes": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._objecttypes/-/lodash._objecttypes-2.4.1.tgz", - "integrity": "sha1-fAt/admKH3ZSn4kLDNsbTf7BHBE=", - "dev": true - }, "lodash._reescape": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz", @@ -3239,67 +3511,12 @@ "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", "dev": true }, - "lodash._reunescapedhtml": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._reunescapedhtml/-/lodash._reunescapedhtml-2.4.1.tgz", - "integrity": "sha1-dHxPxAED6zu4oJduVx96JlnpO6c=", - "dev": true, - "requires": { - "lodash._htmlescapes": "2.4.1", - "lodash.keys": "2.4.1" - }, - "dependencies": { - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - } - } - }, - "lodash._root": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", - "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", - "dev": true - }, - "lodash._shimkeys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._shimkeys/-/lodash._shimkeys-2.4.1.tgz", - "integrity": "sha1-bpzJZm/wgfC1psl4uD4kLmlJ0gM=", - "dev": true, - "requires": { - "lodash._objecttypes": "2.4.1" - } - }, - "lodash.defaults": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-2.4.1.tgz", - "integrity": "sha1-p+iIXwXmiFEUS24SqPNngCa8TFQ=", - "dev": true, - "requires": { - "lodash._objecttypes": "2.4.1", - "lodash.keys": "2.4.1" - }, - "dependencies": { - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - } - } - }, + "lodash._root": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", + "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", + "dev": true + }, "lodash.escape": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-3.2.0.tgz", @@ -3327,27 +3544,6 @@ "integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA=", "dev": true }, - "lodash.isobject": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.isobject/-/lodash.isobject-2.4.1.tgz", - "integrity": "sha1-Wi5H/mmVPx7mMafrof5k0tBlWPU=", - "dev": true, - "requires": { - "lodash._objecttypes": "2.4.1" - } - }, - "lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=", - "dev": true - }, - "lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=", - "dev": true - }, "lodash.keys": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz", @@ -3359,12 +3555,6 @@ "lodash.isarray": "3.0.4" } }, - "lodash.mapvalues": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.mapvalues/-/lodash.mapvalues-4.6.0.tgz", - "integrity": "sha1-G6+lAF3p3W9PJmaMMMo3IwzJaJw=", - "dev": true - }, "lodash.memoize": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", @@ -3404,44 +3594,12 @@ "lodash.escape": "3.2.0" } }, - "lodash.values": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.values/-/lodash.values-2.4.1.tgz", - "integrity": "sha1-q/UUQ2s8twUAFieXjLzzCxKA7qQ=", - "dev": true, - "requires": { - "lodash.keys": "2.4.1" - }, - "dependencies": { - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - } - } - }, "longest": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", "dev": true }, - "loud-rejection": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", - "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", - "dev": true, - "requires": { - "currently-unhandled": "0.4.1", - "signal-exit": "3.0.2" - } - }, "lru-cache": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", @@ -3454,26 +3612,49 @@ "integrity": "sha1-Jzi9nw089PhEkMVzbEhpmsYyzaM=", "dev": true, "requires": { - "es5-ext": "0.10.31" + "es5-ext": "0.10.37" } }, "make-error": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.0.tgz", - "integrity": "sha1-Uq06M5zPEM5itAQLcI/nByRLi5Y=", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.2.tgz", + "integrity": "sha512-l9ra35l5VWLF24y75Tg8XgfGLX0ueRhph118WKM6H5denx4bB5QF59+4UAm9oJ2qsPQZas/CQUDdtDdfvYHBdQ==", "dev": true }, + "make-iterator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/make-iterator/-/make-iterator-1.0.0.tgz", + "integrity": "sha1-V7713IXSOSO6I3ZzJNjo+PPZaUs=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, "map-cache": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", "dev": true }, - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", - "dev": true + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "1.0.1" + } }, "md5.js": { "version": "1.3.4", @@ -3504,7 +3685,7 @@ "dev": true, "requires": { "d": "1.0.0", - "es5-ext": "0.10.31", + "es5-ext": "0.10.37", "es6-weak-map": "2.0.2", "event-emitter": "0.3.5", "is-promise": "2.1.0", @@ -3513,24 +3694,6 @@ "timers-ext": "0.1.2" } }, - "meow": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", - "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", - "dev": true, - "requires": { - "camelcase-keys": "2.1.0", - "decamelize": "1.2.0", - "loud-rejection": "1.6.0", - "map-obj": "1.0.1", - "minimist": "1.2.0", - "normalize-package-data": "2.4.0", - "object-assign": "4.1.1", - "read-pkg-up": "1.0.1", - "redent": "1.0.0", - "trim-newlines": "1.0.0" - } - }, "merge-stream": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-1.0.1.tgz", @@ -3547,24 +3710,24 @@ "dev": true }, "micromatch": { - "version": "2.3.11", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", - "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", - "dev": true, - "requires": { - "arr-diff": "2.0.0", - "array-unique": "0.2.1", - "braces": "1.8.5", - "expand-brackets": "0.1.5", - "extglob": "0.3.2", - "filename-regex": "2.0.1", - "is-extglob": "1.0.0", - "is-glob": "2.0.1", - "kind-of": "3.2.2", - "normalize-path": "2.1.1", - "object.omit": "2.0.1", - "parse-glob": "3.0.4", - "regex-cache": "0.4.4" + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.5.tgz", + "integrity": "sha512-ykttrLPQrz1PUJcXjwsTUjGoPJ64StIGNE2lGVD1c9CuguJ+L7/navsE8IcDNndOoCMvYV0qc/exfVbMHkUhvA==", + "dev": true, + "requires": { + "arr-diff": "4.0.0", + "array-unique": "0.3.2", + "braces": "2.3.0", + "define-property": "1.0.0", + "extend-shallow": "2.0.1", + "extglob": "2.0.3", + "fragment-cache": "0.2.1", + "kind-of": "6.0.2", + "nanomatch": "1.2.7", + "object.pick": "1.3.0", + "regex-not": "1.0.0", + "snapdragon": "0.8.1", + "to-regex": "3.0.1" } }, "miller-rabin": { @@ -3604,6 +3767,27 @@ "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", "dev": true }, + "mixin-deep": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.0.tgz", + "integrity": "sha512-dgaCvoh6i1nosAUBKb0l0pfJ78K8+S9fluyIR2YvAeUD/QuMahnFnF3xYty5eYXMjhGSsB0DsW6A0uAZyetoAg==", + "dev": true, + "requires": { + "for-in": "1.0.2", + "is-extendable": "1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "2.0.4" + } + } + } + }, "mkdirp": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", @@ -3622,9 +3806,9 @@ } }, "mocha": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-4.0.1.tgz", - "integrity": "sha512-evDmhkoA+cBNiQQQdSKZa2b9+W2mpLoj50367lhy+Klnx9OV8XlCIhigUnn1gaTFLQCa0kdNhEGDr0hCXOQFDw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-4.1.0.tgz", + "integrity": "sha512-0RVnjg1HJsXY2YFDoTNzcc1NKhYuXKRrBAG2gDygmJJA136Cs2QlRliZG1mA0ap7cuaT30mw16luAeln+4RiNA==", "dev": true, "requires": { "browser-stdout": "1.3.0", @@ -3639,11 +3823,14 @@ "supports-color": "4.4.0" }, "dependencies": { - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", - "dev": true + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } }, "supports-color": { "version": "4.4.0", @@ -3663,19 +3850,19 @@ "dev": true }, "module-deps": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/module-deps/-/module-deps-4.1.1.tgz", - "integrity": "sha1-IyFYM/HaE/1gbMuAh7RIUty4If0=", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/module-deps/-/module-deps-5.0.1.tgz", + "integrity": "sha512-sigq/hm/L+Z5IGi1DDl0x2ptkw7S86aFh213QhPLD8v9Opv90IHzKIuWJrRa5bJ77DVKHco2CfIEuThcT/vDJA==", "dev": true, "requires": { + "JSONStream": "1.3.2", "browser-resolve": "1.11.2", "cached-path-relative": "1.0.1", - "concat-stream": "1.5.2", + "concat-stream": "1.6.0", "defined": "1.0.0", - "detective": "4.5.0", + "detective": "5.0.2", "duplexer2": "0.1.4", "inherits": "2.0.3", - "JSONStream": "1.3.1", "parents": "1.0.1", "readable-stream": "2.3.3", "resolve": "1.1.7", @@ -3683,6 +3870,19 @@ "subarg": "1.0.0", "through2": "2.0.3", "xtend": "4.0.1" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.0.tgz", + "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", + "dev": true, + "requires": { + "inherits": "2.0.3", + "readable-stream": "2.3.3", + "typedarray": "0.0.6" + } + } } }, "ms": { @@ -3735,10 +3935,37 @@ } } }, + "nanomatch": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.7.tgz", + "integrity": "sha512-/5ldsnyurvEw7wNpxLFgjVvBLMta43niEYOy0CJ4ntcYSbx6bugRUTQeFb4BR/WanEL1o3aQgHuVLHQaB6tOqg==", + "dev": true, + "requires": { + "arr-diff": "4.0.0", + "array-unique": "0.3.2", + "define-property": "1.0.0", + "extend-shallow": "2.0.1", + "fragment-cache": "0.2.1", + "is-odd": "1.0.0", + "kind-of": "5.1.0", + "object.pick": "1.3.0", + "regex-not": "1.0.0", + "snapdragon": "0.8.1", + "to-regex": "3.0.1" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, "natives": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/natives/-/natives-1.1.0.tgz", - "integrity": "sha1-6f+EFBimsux6SV6TmYT3jxY+bjE=", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/natives/-/natives-1.1.1.tgz", + "integrity": "sha512-8eRaxn8u/4wN8tGkhlc2cgwwvOLMLUMUn4IYTexMgWd+LyUDfeXVkk2ygQR0hvIHbJQXgHujia3ieUUDwNGkEA==", "dev": true }, "next-tick": { @@ -3756,18 +3983,6 @@ "abbrev": "1.0.9" } }, - "normalize-package-data": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.4.0.tgz", - "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", - "dev": true, - "requires": { - "hosted-git-info": "2.5.0", - "is-builtin-module": "1.0.0", - "semver": "4.3.6", - "validate-npm-package-license": "3.0.1" - } - }, "normalize-path": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", @@ -3777,23 +3992,88 @@ "remove-trailing-separator": "1.1.0" } }, - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - }, "object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", "dev": true }, - "object-keys": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.4.0.tgz", - "integrity": "sha1-KKaq50KN0sOpLz2V8hM13SBOAzY=", - "dev": true + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "0.1.1", + "define-property": "0.2.5", + "kind-of": "3.2.2" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "3.0.1" + } }, "object.defaults": { "version": "1.1.0", @@ -3802,26 +4082,19 @@ "dev": true, "requires": { "array-each": "1.0.1", - "array-slice": "1.0.0", + "array-slice": "1.1.0", "for-own": "1.0.0", "isobject": "3.0.1" - }, - "dependencies": { - "for-own": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", - "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", - "dev": true, - "requires": { - "for-in": "1.0.2" - } - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } + } + }, + "object.map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object.map/-/object.map-1.0.1.tgz", + "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", + "dev": true, + "requires": { + "for-own": "1.0.0", + "make-iterator": "1.0.0" } }, "object.omit": { @@ -3832,6 +4105,17 @@ "requires": { "for-own": "0.1.5", "is-extendable": "0.1.1" + }, + "dependencies": { + "for-own": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", + "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "dev": true, + "requires": { + "for-in": "1.0.2" + } + } } }, "object.pick": { @@ -3841,14 +4125,6 @@ "dev": true, "requires": { "isobject": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } } }, "once": { @@ -3915,6 +4191,12 @@ "integrity": "sha1-/VZamvjrRHO6abbtijQ1LLVS8SY=", "dev": true }, + "os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", + "dev": true + }, "os-homedir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", @@ -3927,6 +4209,12 @@ "integrity": "sha512-r6zKACMNhjPJMTl8KcFH4li//gkrXWfbD6feV8l6doRHlzljFWGJ2AP6iKaCJXyZmAUMOPtvbW7EXkbWO/pLEA==", "dev": true }, + "pako": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.6.tgz", + "integrity": "sha512-lQe48YPsMJAig+yngZ87Lus+NF+3mtu7DVOBu6b/gHO1YpKwIj5AWjZ/TOS7i46HD/UixzWb1zeWDZfGZ3iYcg==", + "dev": true + }, "parents": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parents/-/parents-1.0.1.tgz", @@ -3942,20 +4230,20 @@ "integrity": "sha1-N8T5t+06tlx0gXtfJICTf7+XxxI=", "dev": true, "requires": { - "asn1.js": "4.9.1", - "browserify-aes": "1.0.8", + "asn1.js": "4.9.2", + "browserify-aes": "1.1.1", "create-hash": "1.1.3", "evp_bytestokey": "1.0.3", "pbkdf2": "3.0.14" } }, "parse-filepath": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.1.tgz", - "integrity": "sha1-FZ1hVdQ5BNFsEO9piRHaHpGWm3M=", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", + "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", "dev": true, "requires": { - "is-absolute": "0.2.6", + "is-absolute": "1.0.0", "map-cache": "0.2.2", "path-root": "0.1.1" } @@ -3970,15 +4258,23 @@ "is-dotfile": "1.0.3", "is-extglob": "1.0.0", "is-glob": "2.0.1" - } - }, - "parse-json": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", - "dev": true, - "requires": { - "error-ex": "1.3.1" + }, + "dependencies": { + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "1.0.0" + } + } } }, "parse-passwd": { @@ -3987,6 +4283,12 @@ "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", "dev": true }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, "path-browserify": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", @@ -3999,15 +4301,6 @@ "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", "dev": true }, - "path-exists": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", - "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", - "dev": true, - "requires": { - "pinkie-promise": "2.0.1" - } - }, "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", @@ -4035,43 +4328,18 @@ "path-root": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", - "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", - "dev": true, - "requires": { - "path-root-regex": "0.1.2" - } - }, - "path-root-regex": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", - "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", - "dev": true - }, - "path-type": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", - "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", - "dev": true, - "requires": { - "graceful-fs": "4.1.11", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", - "dev": true - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - } + "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", + "dev": true, + "requires": { + "path-root-regex": "0.1.2" } }, + "path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", + "dev": true + }, "pathval": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz", @@ -4112,6 +4380,64 @@ "pinkie": "2.0.4" } }, + "plugin-error": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-0.1.2.tgz", + "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", + "dev": true, + "requires": { + "ansi-cyan": "0.1.1", + "ansi-red": "0.1.1", + "arr-diff": "1.1.0", + "arr-union": "2.1.0", + "extend-shallow": "1.1.4" + }, + "dependencies": { + "arr-diff": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-1.1.0.tgz", + "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", + "dev": true, + "requires": { + "arr-flatten": "1.1.0", + "array-slice": "0.2.3" + } + }, + "arr-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-2.1.0.tgz", + "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", + "dev": true + }, + "array-slice": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", + "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", + "dev": true + }, + "extend-shallow": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-1.1.4.tgz", + "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", + "dev": true, + "requires": { + "kind-of": "1.1.0" + } + }, + "kind-of": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz", + "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", + "dev": true + } + } + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, "prelude-ls": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", @@ -4189,33 +4515,13 @@ "kind-of": "4.0.0" }, "dependencies": { - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.5" - } - } - } - }, "kind-of": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", "dev": true, "requires": { - "is-buffer": "1.1.5" + "is-buffer": "1.1.6" } } } @@ -4229,6 +4535,16 @@ "safe-buffer": "5.1.1" } }, + "randomfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.3.tgz", + "integrity": "sha512-YL6GrhrWoic0Eq8rXVbMptH7dAxCs0J+mh5Y0euNekPPYaxEmdVGim6GdoxoRzKW2yJoU8tueifS7mYxvcFDEQ==", + "dev": true, + "requires": { + "randombytes": "2.0.5", + "safe-buffer": "5.1.1" + } + }, "read-only-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/read-only-stream/-/read-only-stream-2.0.0.tgz", @@ -4238,27 +4554,6 @@ "readable-stream": "2.3.3" } }, - "read-pkg": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", - "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", - "dev": true, - "requires": { - "load-json-file": "1.1.0", - "normalize-package-data": "2.4.0", - "path-type": "1.1.0" - } - }, - "read-pkg-up": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", - "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", - "dev": true, - "requires": { - "find-up": "1.1.2", - "read-pkg": "1.1.0" - } - }, "readable-stream": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", @@ -4283,16 +4578,6 @@ "resolve": "1.1.7" } }, - "redent": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", - "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", - "dev": true, - "requires": { - "indent-string": "2.1.0", - "strip-indent": "1.0.1" - } - }, "regex-cache": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", @@ -4302,6 +4587,15 @@ "is-equal-shallow": "0.1.3" } }, + "regex-not": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.0.tgz", + "integrity": "sha1-Qvg+OXcWIt+CawKvF2Ul1qXxV/k=", + "dev": true, + "requires": { + "extend-shallow": "2.0.1" + } + }, "remove-trailing-separator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", @@ -4320,15 +4614,6 @@ "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", "dev": true }, - "repeating": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", - "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", - "dev": true, - "requires": { - "is-finite": "1.0.2" - } - }, "replace-ext": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", @@ -4342,13 +4627,13 @@ "dev": true }, "resolve-dir": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-0.1.1.tgz", - "integrity": "sha1-shklmlYC+sXFxJatiUpujMQwJh4=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", "dev": true, "requires": { - "expand-tilde": "1.2.2", - "global-modules": "0.2.3" + "expand-tilde": "2.0.2", + "global-modules": "1.0.0" } }, "resolve-url": { @@ -4387,13 +4672,41 @@ } }, "run-sequence": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/run-sequence/-/run-sequence-2.2.0.tgz", - "integrity": "sha512-xW5DmUwdvoyYQUMPKN8UW7TZSFs7AxtT59xo1m5y91jHbvwGlGgOmdV1Yw5P68fkjf3aHUZ4G1o1mZCtNe0qtw==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/run-sequence/-/run-sequence-2.2.1.tgz", + "integrity": "sha512-qkzZnQWMZjcKbh3CNly2srtrkaO/2H/SI5f2eliMCapdRD3UhMrwjfOAZJAnZ2H8Ju4aBzFZkBGXUqFs9V0yxw==", "dev": true, "requires": { "chalk": "1.1.3", - "gulp-util": "3.0.8" + "fancy-log": "1.3.2", + "plugin-error": "0.1.2" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } } }, "safe-buffer": { @@ -4440,6 +4753,27 @@ "integrity": "sha1-kM/xnQLgcCf9dn9erT57ldHnOAw=", "dev": true }, + "set-getter": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/set-getter/-/set-getter-0.1.0.tgz", + "integrity": "sha1-12nBgsnVpR9AkUXy+6guXoboA3Y=", + "dev": true, + "requires": { + "to-object-path": "0.3.0" + } + }, + "set-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", + "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "dev": true, + "requires": { + "extend-shallow": "2.0.1", + "is-extendable": "0.1.1", + "is-plain-object": "2.0.4", + "split-string": "3.1.0" + } + }, "sha.js": { "version": "2.4.9", "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.9.tgz", @@ -4478,11 +4812,120 @@ "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", "dev": true }, - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", - "dev": true + "snapdragon": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.1.tgz", + "integrity": "sha1-4StUh/re0+PeoKyR6UAL91tAE3A=", + "dev": true, + "requires": { + "base": "0.11.2", + "debug": "2.6.9", + "define-property": "0.2.5", + "extend-shallow": "2.0.1", + "map-cache": "0.2.2", + "source-map": "0.5.7", + "source-map-resolve": "0.5.1", + "use": "2.0.2" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "dev": true, + "requires": { + "define-property": "1.0.0", + "isobject": "3.0.1", + "snapdragon-util": "3.0.1" + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } }, "sorcery": { "version": "0.10.0", @@ -4503,30 +4946,39 @@ "dev": true }, "source-map-resolve": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.3.1.tgz", - "integrity": "sha1-YQ9hIqRFuN1RU1oqcbeD38Ekh2E=", + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.1.tgz", + "integrity": "sha512-0KW2wvzfxm8NCTb30z0LMNyPqWCdDGE2viwzUaucqJdkTRXtZiSY3I+2A6nVAjmdOy0I4gU8DwnVVGsk9jvP2A==", "dev": true, "requires": { - "atob": "1.1.3", + "atob": "2.0.3", + "decode-uri-component": "0.2.0", "resolve-url": "0.2.1", - "source-map-url": "0.3.0", + "source-map-url": "0.4.0", "urix": "0.1.0" } }, "source-map-support": { - "version": "0.4.18", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", - "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.0.tgz", + "integrity": "sha512-vUoN3I7fHQe0R/SJLKRdKYuEdRGogsviXFkHHo17AWaTGv17VLnxw+CFXvqy+y4ORZ3doWLQcxRYfwKrsd/H7Q==", "dev": true, "requires": { - "source-map": "0.5.7" + "source-map": "0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } } }, "source-map-url": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.3.0.tgz", - "integrity": "sha1-fsrxO1e80J2opAxdJp2zN5nUqvk=", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", "dev": true }, "sourcemap-codec": { @@ -4544,33 +4996,120 @@ "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", "dev": true }, - "spdx-correct": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-1.0.2.tgz", - "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "3.0.2" + }, + "dependencies": { + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "1.0.0", + "is-extendable": "1.0.1" + } + }, + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "2.0.4" + } + } + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", "dev": true, "requires": { - "spdx-license-ids": "1.2.2" + "define-property": "0.2.5", + "object-copy": "0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } } }, - "spdx-expression-parse": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz", - "integrity": "sha1-m98vIOH0DtRH++JzJmGR/O1RYmw=", - "dev": true - }, - "spdx-license-ids": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz", - "integrity": "sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc=", - "dev": true - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - }, "stream-browserify": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", @@ -4716,15 +5255,6 @@ "integrity": "sha1-5SEekiQ2n7uB1jOi8ABE3IztrZI=", "dev": true }, - "strip-indent": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", - "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", - "dev": true, - "requires": { - "get-stdin": "4.0.1" - } - }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -4741,10 +5271,13 @@ } }, "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", + "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", + "dev": true, + "requires": { + "has-flag": "2.0.0" + } }, "syntax-error": { "version": "1.3.0", @@ -4811,7 +5344,7 @@ "integrity": "sha1-YcxHp2wavTGV8UUn+XjViulMUgQ=", "dev": true, "requires": { - "es5-ext": "0.10.31", + "es5-ext": "0.10.37", "next-tick": "1.0.0" } }, @@ -4830,71 +5363,139 @@ "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", "dev": true }, - "travis-fold": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/travis-fold/-/travis-fold-0.1.2.tgz", - "integrity": "sha1-/sAF+dyqJZo/lFnOWmkGq6TFRdo=", - "dev": true - }, - "trim-newlines": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", - "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", - "dev": true + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } }, - "ts-node": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-3.3.0.tgz", - "integrity": "sha1-wTxqMCTjC+EYDdUwOPwgkonUv2k=", + "to-regex": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.1.tgz", + "integrity": "sha1-FTWL7kosg712N3uh3ASdDxiDeq4=", "dev": true, "requires": { - "arrify": "1.0.1", - "chalk": "2.2.0", - "diff": "3.3.1", - "make-error": "1.3.0", - "minimist": "1.2.0", - "mkdirp": "0.5.1", - "source-map-support": "0.4.18", - "tsconfig": "6.0.0", - "v8flags": "3.0.1", - "yn": "2.0.0" + "define-property": "0.2.5", + "extend-shallow": "2.0.1", + "regex-not": "1.0.0" }, "dependencies": { - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "color-convert": "1.9.0" + "is-descriptor": "0.1.6" } }, - "chalk": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.2.0.tgz", - "integrity": "sha512-0BMM/2hG3ZaoPfR6F+h/oWpZtsh3b/s62TjSM6MGCJWEbJDN1acqCXvyhhZsDSVFklpebUoQ5O1kKC7lOzrn9g==", + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "4.5.0" + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } } }, - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", - "dev": true + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } }, - "supports-color": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", - "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", "dev": true, "requires": { - "has-flag": "2.0.0" + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" } }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "3.0.0", + "repeat-string": "1.6.1" + } + }, + "travis-fold": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/travis-fold/-/travis-fold-0.1.2.tgz", + "integrity": "sha1-/sAF+dyqJZo/lFnOWmkGq6TFRdo=", + "dev": true + }, + "ts-node": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-4.1.0.tgz", + "integrity": "sha512-xcZH12oVg9PShKhy3UHyDmuDLV3y7iKwX25aMVPt1SIXSuAfWkFiGPEkg+th8R4YKW/QCxDoW7lJdb15lx6QWg==", + "dev": true, + "requires": { + "arrify": "1.0.1", + "chalk": "2.3.0", + "diff": "3.3.1", + "make-error": "1.3.2", + "minimist": "1.2.0", + "mkdirp": "0.5.1", + "source-map-support": "0.5.0", + "tsconfig": "7.0.0", + "v8flags": "3.0.1", + "yn": "2.0.0" + }, + "dependencies": { "v8flags": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-3.0.1.tgz", @@ -4907,11 +5508,13 @@ } }, "tsconfig": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-6.0.0.tgz", - "integrity": "sha1-aw6DdgA9evGGT434+J3QBZ/80DI=", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-7.0.0.tgz", + "integrity": "sha512-vZXmzPrL+EmC4T/4rVlT2jNVMWCi/O4DIiSj3UHg1OE5kCKbk4mfrXc6dZksLgRM/TZlKnousKH9bbTazUWRRw==", "dev": true, "requires": { + "@types/strip-bom": "3.0.0", + "@types/strip-json-comments": "0.0.30", "strip-bom": "3.0.0", "strip-json-comments": "2.0.1" }, @@ -4925,9 +5528,9 @@ } }, "tslib": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.8.0.tgz", - "integrity": "sha512-ymKWWZJST0/CkgduC2qkzjMOWr4bouhuURNXCn/inEX0L57BnRG6FhX76o7FOnsjHazCjfU2LKeSrlS2sIKQJg==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.8.1.tgz", + "integrity": "sha1-aUavLR1lGnsYY7Ux1uWvpBqkTqw=", "dev": true }, "tslint": { @@ -4938,47 +5541,21 @@ "requires": { "babel-code-frame": "6.26.0", "builtin-modules": "1.1.1", - "chalk": "2.2.0", + "chalk": "2.3.0", "commander": "2.11.0", "diff": "3.3.1", "glob": "7.1.2", "minimatch": "3.0.4", - "resolve": "1.4.0", + "resolve": "1.5.0", "semver": "5.4.1", - "tslib": "1.8.0", - "tsutils": "2.12.1" + "tslib": "1.8.1", + "tsutils": "2.16.0" }, "dependencies": { - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", - "dev": true, - "requires": { - "color-convert": "1.9.0" - } - }, - "chalk": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.2.0.tgz", - "integrity": "sha512-0BMM/2hG3ZaoPfR6F+h/oWpZtsh3b/s62TjSM6MGCJWEbJDN1acqCXvyhhZsDSVFklpebUoQ5O1kKC7lOzrn9g==", - "dev": true, - "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "4.5.0" - } - }, - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", - "dev": true - }, "resolve": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.4.0.tgz", - "integrity": "sha512-aW7sVKPufyHqOmyyLzg/J+8606v5nevBgaliIlV7nUpVMsDnoBGV/cbSLNjZAg9q0Cfd/+easKVKQ8vOu8fn1Q==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.5.0.tgz", + "integrity": "sha512-hgoSGrc3pjzAPHNBg+KnFcK2HwlHTs/YrAGUr6qgTVUZmXv1UEXXl0bZNBKMA9fud6lRYFdPGz0xXxycPzmmiw==", "dev": true, "requires": { "path-parse": "1.0.5" @@ -4989,25 +5566,16 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", "integrity": "sha512-WfG/X9+oATh81XtllIo/I8gOiY9EXRdv1cQdyykeXK17YcUW3EXUAi2To4pcH6nZtJPr7ZOpM5OMyWJZm+8Rsg==", "dev": true - }, - "supports-color": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", - "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", - "dev": true, - "requires": { - "has-flag": "2.0.0" - } } } }, "tsutils": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.12.1.tgz", - "integrity": "sha1-9Nlc4zkciXHkblTEzw7bCiHdWyQ=", + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.16.0.tgz", + "integrity": "sha512-9Ier/60O7OZRNPiw+or5QAtAY4kQA+WDiO/r6xOYATEyefH9bdfvTRLCxrYnFhQlZfET2vYXKfpr3Vw2BiArZw==", "dev": true, "requires": { - "tslib": "1.8.0" + "tslib": "1.8.1" } }, "tty-browserify": { @@ -5026,9 +5594,9 @@ } }, "type-detect": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.3.tgz", - "integrity": "sha1-Dj8mcLRAmbC0bChNE2p+9Jx0wuo=", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.5.tgz", + "integrity": "sha512-N9IvkQslUGYGC24RkJk1ba99foK6TkwC2FHAEBlQFBP0RxQZS8ZpJuAZcwiY/w9ZJHFQb1aOXBI60OdxhTrwEQ==", "dev": true }, "typedarray": { @@ -5038,9 +5606,9 @@ "dev": true }, "typescript": { - "version": "2.7.0-dev.20171020", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.7.0-dev.20171020.tgz", - "integrity": "sha512-Sy1F2YVw7nj2pcMP2bE6YK5dviaY2WRJb12t27EUiW4wkD8GiaZ0sgNBdTKRcvTNFJ8KXjwnl+Ysi5+J5BlcHw==", + "version": "2.7.0-dev.20180108", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.7.0-dev.20180108.tgz", + "integrity": "sha512-ZlggGsch8Y2d0LqAlCYGRzm/gdm2bqSpb4rdthY+YvpPsQqFixT0tU8sgjeRibMXW9hbS2Hz6kibS8L2oUKWfQ==", "dev": true }, "uglify-js": { @@ -5074,12 +5642,78 @@ "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", "dev": true }, + "union-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", + "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "dev": true, + "requires": { + "arr-union": "3.1.0", + "get-value": "2.0.6", + "is-extendable": "0.1.1", + "set-value": "0.4.3" + }, + "dependencies": { + "set-value": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", + "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", + "dev": true, + "requires": { + "extend-shallow": "2.0.1", + "is-extendable": "0.1.1", + "is-plain-object": "2.0.4", + "to-object-path": "0.3.0" + } + } + } + }, "unique-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unique-stream/-/unique-stream-1.0.0.tgz", "integrity": "sha1-1ZpKdUJ0R9mqbJHnAmP40mpLEEs=", "dev": true }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "0.3.1", + "isobject": "3.0.1" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "2.0.6", + "has-values": "0.1.4", + "isobject": "2.1.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, "urix": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", @@ -5104,6 +5738,85 @@ } } }, + "use": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/use/-/use-2.0.2.tgz", + "integrity": "sha1-riig1y+TvyJCKhii43mZMRLeyOg=", + "dev": true, + "requires": { + "define-property": "0.2.5", + "isobject": "3.0.1", + "lazy-cache": "2.0.2" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, "user-home": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz", @@ -5154,25 +5867,38 @@ "integrity": "sha1-G5BKWWCfsyjvB4E4Qgk09rhnCaY=", "dev": true }, - "validate-npm-package-license": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz", - "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", - "dev": true, - "requires": { - "spdx-correct": "1.0.2", - "spdx-expression-parse": "1.0.4" - } - }, "vinyl": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", - "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.1.0.tgz", + "integrity": "sha1-Ah+cLPlR1rk5lDyJ617lrdT9kkw=", "dev": true, "requires": { - "clone": "1.0.2", - "clone-stats": "0.0.1", - "replace-ext": "0.0.1" + "clone": "2.1.1", + "clone-buffer": "1.0.0", + "clone-stats": "1.0.0", + "cloneable-readable": "1.0.0", + "remove-trailing-separator": "1.1.0", + "replace-ext": "1.0.0" + }, + "dependencies": { + "clone": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.1.tgz", + "integrity": "sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=", + "dev": true + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "replace-ext": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", + "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=", + "dev": true + } } }, "vinyl-fs": { @@ -5319,15 +6045,6 @@ "cliui": "2.1.0", "decamelize": "1.2.0", "window-size": "0.1.0" - }, - "dependencies": { - "camelcase": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", - "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", - "dev": true, - "optional": true - } } }, "yn": { diff --git a/package.json b/package.json index e329db05d85a2..fb089b6491811 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,6 @@ "devDependencies": { "@types/browserify": "latest", "@types/chai": "latest", - "@types/colors": "latest", "@types/convert-source-map": "latest", "@types/del": "latest", "@types/glob": "latest", @@ -45,7 +44,7 @@ "@types/minimist": "latest", "@types/mkdirp": "latest", "@types/mocha": "latest", - "@types/node": "latest", + "@types/node": "8.5.5", "@types/q": "latest", "@types/run-sequence": "latest", "@types/through2": "latest", @@ -80,7 +79,7 @@ "ts-node": "latest", "tslint": "latest", "vinyl": "latest", - "colors": "latest", + "chalk": "latest", "typescript": "next" }, "scripts": { diff --git a/scripts/tslint/formatters/autolinkableStylishFormatter.ts b/scripts/tslint/formatters/autolinkableStylishFormatter.ts index 6a02ec24f059c..23e01bc8587e1 100644 --- a/scripts/tslint/formatters/autolinkableStylishFormatter.ts +++ b/scripts/tslint/formatters/autolinkableStylishFormatter.ts @@ -1,5 +1,5 @@ import * as Lint from "tslint"; -import * as colors from "colors"; +import chalk from "chalk"; import { sep } from "path"; function groupBy(array: ReadonlyArray | undefined, getGroupId: (elem: T, index: number) => number | string): T[][] { if (!array) { @@ -52,7 +52,7 @@ function getLink(failure: Lint.RuleFailure, color: boolean): string { if (path.indexOf("/") === -1 && path.indexOf("\\") === -1) { path = `.${sep}${path}`; } - return `${color ? (sev === "WARNING" ? colors.blue(sev) : colors.red(sev)) : sev}: ${path}:${lineAndCharacter.line + 1}:${lineAndCharacter.character + 1}`; + return `${color ? (sev === "WARNING" ? chalk.blue(sev) : chalk.red(sev)) : sev}: ${path}:${lineAndCharacter.line + 1}:${lineAndCharacter.character + 1}`; } function getLinkMaxSize(failures: Lint.RuleFailure[]): number { @@ -91,7 +91,7 @@ export class Formatter extends Lint.Formatters.AbstractFormatter { const nameMaxSize = getNameMaxSize(group); return ` ${currentFile} -${group.map(f => `${pad(getLink(f, /*color*/ true), getLink(f, /*color*/ false).length, linkMaxSize)} ${colors.grey(pad(f.getRuleName(), f.getRuleName().length, nameMaxSize))} ${colors.yellow(f.getFailure())}`).join("\n")}`; +${group.map(f => `${pad(getLink(f, /*color*/ true), getLink(f, /*color*/ false).length, linkMaxSize)} ${chalk.grey(pad(f.getRuleName(), f.getRuleName().length, nameMaxSize))} ${chalk.yellow(f.getFailure())}`).join("\n")}`; }).join("\n"); } } \ No newline at end of file diff --git a/scripts/tslint/rules/noDoubleSpaceRule.ts b/scripts/tslint/rules/noDoubleSpaceRule.ts new file mode 100644 index 0000000000000..34ab470ebced3 --- /dev/null +++ b/scripts/tslint/rules/noDoubleSpaceRule.ts @@ -0,0 +1,54 @@ +import * as Lint from "tslint/lib"; +import * as ts from "typescript"; + +export class Rule extends Lint.Rules.AbstractRule { + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithFunction(sourceFile, walk); + } +} + +function walk(ctx: Lint.WalkContext): void { + const { sourceFile } = ctx; + const lines = sourceFile.text.split("\n"); + const strings = getLiterals(sourceFile); + lines.forEach((line, idx) => { + // Skip indentation. + const firstNonSpace = /\S/.exec(line); + if (firstNonSpace === null) { + return; + } + // Allow common uses of double spaces + // * To align `=` or `!=` signs + // * To align comments at the end of lines + // * To indent inside a comment + // * To use two spaces after a period + // * To include aligned `->` in a comment + const rgx = /[^/*. ] [^-!/= ]/g; + rgx.lastIndex = firstNonSpace.index; + const doubleSpace = rgx.exec(line); + // Also allow to align comments after `@param` + if (doubleSpace !== null && !line.includes("@param")) { + const pos = lines.slice(0, idx).reduce((len, line) => len + 1 + line.length, 0) + doubleSpace.index; + if (!strings.some(s => s.getStart() <= pos && s.end > pos)) { + ctx.addFailureAt(pos + 1, 2, "Use only one space."); + } + } + }); +} + +function getLiterals(sourceFile: ts.SourceFile): ReadonlyArray { + const out: ts.Node[] = []; + sourceFile.forEachChild(function cb(node) { + switch (node.kind) { + case ts.SyntaxKind.StringLiteral: + case ts.SyntaxKind.TemplateHead: + case ts.SyntaxKind.TemplateMiddle: + case ts.SyntaxKind.TemplateTail: + case ts.SyntaxKind.NoSubstitutionTemplateLiteral: + case ts.SyntaxKind.RegularExpressionLiteral: + out.push(node); + } + node.forEachChild(cb); + }); + return out; +} diff --git a/scripts/tslint/rules/typeOperatorSpacingRule.ts b/scripts/tslint/rules/typeOperatorSpacingRule.ts index d7da2e6b5e881..82dccfe0eace5 100644 --- a/scripts/tslint/rules/typeOperatorSpacingRule.ts +++ b/scripts/tslint/rules/typeOperatorSpacingRule.ts @@ -2,7 +2,7 @@ import * as Lint from "tslint/lib"; import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = "The '|' and '&' operators must be surrounded by single spaces"; + public static FAILURE_STRING = "The '|' and '&' operators must be surrounded by spaces"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithFunction(sourceFile, walk); @@ -11,26 +11,20 @@ export class Rule extends Lint.Rules.AbstractRule { function walk(ctx: Lint.WalkContext): void { const { sourceFile } = ctx; - ts.forEachChild(sourceFile, recur); - function recur(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.UnionType || node.kind === ts.SyntaxKind.IntersectionType) { - check((node as ts.UnionOrIntersectionTypeNode).types); + sourceFile.forEachChild(function cb(node: ts.Node): void { + if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) { + check(node); } - ts.forEachChild(node, recur); - } + node.forEachChild(cb); + }); - function check(types: ReadonlyArray): void { - let expectedStart = types[0].end + 2; // space, | or & - for (let i = 1; i < types.length; i++) { - const currentType = types[i]; - if (expectedStart !== currentType.pos || currentType.getLeadingTriviaWidth() !== 1) { - const previousTypeEndPos = sourceFile.getLineAndCharacterOfPosition(types[i - 1].end); - const currentTypeStartPos = sourceFile.getLineAndCharacterOfPosition(currentType.pos); - if (previousTypeEndPos.line === currentTypeStartPos.line) { - ctx.addFailureAtNode(currentType, Rule.FAILURE_STRING); - } + function check(node: ts.UnionTypeNode | ts.IntersectionTypeNode): void { + const list = node.getChildren().find(child => child.kind === ts.SyntaxKind.SyntaxList)!; + for (const child of list.getChildren()) { + if ((child.kind === ts.SyntaxKind.BarToken || child.kind === ts.SyntaxKind.AmpersandToken) + && (/\S/.test(sourceFile.text[child.getStart(sourceFile) - 1]) || /\S/.test(sourceFile.text[child.end]))) { + ctx.addFailureAtNode(child, Rule.FAILURE_STRING); } - expectedStart = currentType.end + 2; } } } diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 1f53c3bef5451..4e4b4f127053c 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -303,7 +303,7 @@ namespace ts { // without names can only come from JSDocFunctionTypes. Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType); const functionType = node.parent; - const index = indexOf(functionType.parameters, node); + const index = functionType.parameters.indexOf(node as ParameterDeclaration); return "arg" + index as __String; case SyntaxKind.JSDocTypedefTag: const name = getNameOfJSDocTypedef(node as JSDocTypedefTag); @@ -746,7 +746,11 @@ namespace ts { } function isNarrowingTypeofOperands(expr1: Expression, expr2: Expression) { - return expr1.kind === SyntaxKind.TypeOfExpression && isNarrowableOperand((expr1).expression) && expr2.kind === SyntaxKind.StringLiteral; + return expr1.kind === SyntaxKind.TypeOfExpression && isNarrowableOperand((expr1).expression) && (expr2.kind === SyntaxKind.StringLiteral || expr2.kind === SyntaxKind.NoSubstitutionTemplateLiteral); + } + + function isNarrowableInOperands(left: Expression, right: Expression) { + return (left.kind === SyntaxKind.StringLiteral || left.kind === SyntaxKind.NoSubstitutionTemplateLiteral) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr: BinaryExpression) { @@ -761,6 +765,8 @@ namespace ts { isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case SyntaxKind.InstanceOfKeyword: return isNarrowableOperand(expr.left); + case SyntaxKind.InKeyword: + return isNarrowableInOperands(expr.left, expr.right); case SyntaxKind.CommaToken: return isNarrowingExpression(expr.right); } @@ -1627,7 +1633,7 @@ namespace ts { // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); @@ -2404,7 +2410,7 @@ namespace ts { if (!isPrototypeProperty && (!targetSymbol || !(targetSymbol.flags & SymbolFlags.Namespace)) && isLegalPosition) { Debug.assert(isIdentifier(propertyAccess.expression)); const identifier = propertyAccess.expression as Identifier; - const flags = SymbolFlags.Module | SymbolFlags.JSContainer; + const flags = SymbolFlags.Module | SymbolFlags.JSContainer; const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.JSContainer; if (targetSymbol) { addDeclarationToSymbol(symbol, identifier, flags); @@ -2511,7 +2517,7 @@ namespace ts { } if (isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, "__" + indexOf(node.parent.parameters, node) as __String); + bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, "__" + node.parent.parameters.indexOf(node) as __String); } else { declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 34ca1bdf0e90a..7e44a9608f0ca 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -468,9 +468,9 @@ namespace ts { } function getReferencedByPaths(referencedFilePath: Path) { - return mapDefinedIter(references.entries(), ([filePath, referencesInFile]) => + return arrayFrom(mapDefinedIterator(references.entries(), ([filePath, referencesInFile]) => referencesInFile.has(referencedFilePath) ? filePath as Path : undefined - ); + )); } function getFilesAffectedByUpdatedShape(program: Program, sourceFile: SourceFile): ReadonlyArray { @@ -504,7 +504,7 @@ namespace ts { } // Return array of values that needs emit - return flatMapIter(seenFileNamesMap.values(), value => value); + return arrayFrom(mapDefinedIterator(seenFileNamesMap.values(), value => value)); } } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 990dd1ce14fa9..16bfd7fa7e253 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -171,6 +171,7 @@ namespace ts { node = getParseTreeNode(node, isExpression); return node ? getContextualType(node) : undefined; }, + isContextSensitive, getFullyQualifiedName, getResolvedSignature: (node, candidatesOutArray, theArgumentCount) => { node = getParseTreeNode(node, isCallLikeExpression); @@ -185,7 +186,11 @@ namespace ts { }, isValidPropertyAccess: (node, propertyName) => { node = getParseTreeNode(node, isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, escapeLeadingUnderscores(propertyName)) : false; + return !!node && isValidPropertyAccess(node, escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: (node, type, property) => { + node = getParseTreeNode(node, isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); }, getSignatureFromDeclaration: declaration => { declaration = getParseTreeNode(declaration, isFunctionLike); @@ -210,7 +215,18 @@ namespace ts { getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule, - getSymbolWalker: createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: createGetSymbolWalker( + getRestTypeOfSignature, + getTypePredicateOfSignature, + getReturnTypeOfSignature, + getBaseTypes, + resolveStructuredTypeMembers, + getTypeOfSymbol, + getResolvedSymbol, + getIndexTypeOfStructuredType, + getConstraintFromTypeParameter, + getFirstIdentifier, + ), getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: node => { node = getParseTreeNode(node, isJsxOpeningLikeElement); @@ -256,6 +272,8 @@ namespace ts { return resolveName(location, escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: () => unescapeLeadingUnderscores(getJsxNamespace()), + getAccessibleSymbolChain, + resolveExternalModuleSymbol, }; const tupleTypes: GenericType[] = []; @@ -311,15 +329,18 @@ namespace ts { markerSubType.constraint = markerSuperType; const markerOtherType = createType(TypeFlags.TypeParameter); - const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + const noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + + const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*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 enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); const jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); const globals = createSymbolTable(); + const reverseMappedCache = createMap(); let ambientModulesCache: Symbol[] | undefined; /** * List of every ambient module with a "*" wildcard. @@ -515,6 +536,7 @@ namespace ts { Normal = 0, // Normal type checking SkipContextSensitive = 1, // Skip context sensitive function expressions Inferential = 2, // Inferential typing + Contextual = 3, // Normal type checking informed by a contextual type, therefore not cacheable } const enum CallbackCheck { @@ -763,10 +785,6 @@ namespace ts { return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } - function getObjectFlags(type: Type): ObjectFlags { - return type.flags & TypeFlags.Object ? (type).objectFlags : 0; - } - function isGlobalSourceFile(node: Node) { return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); } @@ -828,7 +846,7 @@ namespace ts { return true; } const sourceFiles = host.getSourceFiles(); - return indexOf(sourceFiles, declarationFile) <= indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { @@ -936,7 +954,7 @@ namespace ts { isUse: boolean, excludeGlobals = false, suggestedNameNotFoundMessage?: DiagnosticMessage): Symbol { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper( @@ -1012,7 +1030,7 @@ namespace ts { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. - if (result = moduleExports.get("default" as __String)) { + if (result = moduleExports.get(InternalSymbolName.Default)) { const localSymbol = getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { break loop; @@ -1171,7 +1189,7 @@ namespace ts { } break; } - if (location.kind !== SyntaxKind.Block) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; @@ -1179,7 +1197,7 @@ namespace ts { } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -1205,7 +1223,7 @@ namespace ts { !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { let suggestion: string | undefined; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); @@ -1264,6 +1282,20 @@ namespace ts { return result; } + function isNonBlockLocation({ kind }: Node): boolean { + switch (kind) { + case SyntaxKind.Block: + case SyntaxKind.ModuleBlock: + case SyntaxKind.SwitchStatement: + case SyntaxKind.CaseBlock: + case SyntaxKind.CaseClause: + case SyntaxKind.DefaultClause: + return false; + default: + return true; + } + } + function diagnosticName(nameArg: __String | Identifier) { return isString(nameArg) ? unescapeLeadingUnderscores(nameArg as __String) : declarationNameToString(nameArg as Identifier); } @@ -1457,6 +1489,43 @@ namespace ts { return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol: Symbol, name: __String, dontResolveAlias: boolean) { + const exportValue = moduleSymbol.exports.get(InternalSymbolName.ExportEquals); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + + function canHaveSyntheticDefault(file: SourceFile | undefined, moduleSymbol: Symbol, dontResolveAlias: boolean) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, InternalSymbolName.Default, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } + function getTargetOfImportClause(node: ImportClause, dontResolveAlias: boolean): Symbol { const moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); @@ -1466,16 +1535,16 @@ namespace ts { exportDefaultSymbol = moduleSymbol; } else { - const exportValue = moduleSymbol.exports.get("export=" as __String); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default" as __String) - : resolveSymbol(moduleSymbol.exports.get("default" as __String), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, InternalSymbolName.Default, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + const file = find(moduleSymbol.declarations, isSourceFile); + const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -1558,7 +1627,7 @@ namespace ts { symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); let symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === InternalSymbolName.Default) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } const symbol = symbolFromModule && symbolFromVariable ? @@ -1875,8 +1944,40 @@ namespace ts { // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol: Symbol, moduleReferenceExpression: Expression, dontResolveAlias: boolean): Symbol { const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable))) { - error(moduleReferenceExpression, Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable))) { + error(moduleReferenceExpression, Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + const referenceParent = moduleReferenceExpression.parent; + if ( + (isImportDeclaration(referenceParent) && getNamespaceDeclarationNode(referenceParent)) || + isImportCall(referenceParent) + ) { + const type = getTypeOfSymbol(symbol); + let sigs = getSignaturesOfStructuredType(type, SignatureKind.Call); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, SignatureKind.Construct); + } + if (sigs && sigs.length) { + const moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + const result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = cloneMap(symbol.members); + if (symbol.exports) result.exports = cloneMap(symbol.exports); + const resolvedModuleType = resolveStructuredTypeMembers(moduleType as StructuredType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -1945,7 +2046,7 @@ namespace ts { function extendExportSymbols(target: SymbolTable, source: SymbolTable | undefined, lookupTable?: ExportCollisionTrackerTable, exportNode?: ExportDeclaration) { if (!source) return; source.forEach((sourceSymbol, id) => { - if (id === "default") return; + if (id === InternalSymbolName.Default) return; const targetSymbol = target.get(id); if (!targetSymbol) { @@ -2210,7 +2311,8 @@ namespace ts { // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified - const accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + const candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -2847,7 +2949,10 @@ namespace ts { typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String, context)); + const indexInfo = resolvedType.objectFlags & ObjectFlags.ReverseMapped ? + createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : + resolvedType.stringIndexInfo; + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, IndexKind.String, context)); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number, context)); @@ -2859,7 +2964,7 @@ namespace ts { } for (const propertySymbol of properties) { - const propertyType = getTypeOfSymbol(propertySymbol); + const propertyType = getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped ? anyType : getTypeOfSymbol(propertySymbol); const saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; const propertyName = symbolToName(propertySymbol, context, SymbolFlags.Value, /*expectsIdentifier*/ true); @@ -2933,8 +3038,8 @@ namespace ts { parameters.unshift(thisParameter); } let returnTypeNode: TypeNode; - if (signature.typePredicate) { - const typePredicate = signature.typePredicate; + const typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? setEmitFlags(createIdentifier((typePredicate).parameterName), EmitFlags.NoAsciiEscaping) : createThisTypeNode(); @@ -3215,7 +3320,7 @@ namespace ts { * ensuring that any names written with literals use element accesses. */ function appendPropertyOrElementAccessForSymbol(symbol: Symbol, writer: SymbolWriter): void { - const symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); + const symbolName = symbol.escapedName === InternalSymbolName.Default ? InternalSymbolName.Default : getNameOfSymbolAsWritten(symbol); const firstChar = symbolName.charCodeAt(0); const needsElementAccess = !isIdentifierStart(firstChar, languageVersion); @@ -3668,7 +3773,10 @@ namespace ts { writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, IndexKind.String, enclosingDeclaration, globalFlags, symbolStack); + const stringIndexInfo = resolved.objectFlags & ObjectFlags.ReverseMapped && resolved.stringIndexInfo ? + createIndexInfo(anyType, resolved.stringIndexInfo.isReadonly, resolved.stringIndexInfo.declaration) : + resolved.stringIndexInfo; + buildIndexSignatureDisplay(stringIndexInfo, writer, IndexKind.String, enclosingDeclaration, globalFlags, symbolStack); buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, IndexKind.Number, enclosingDeclaration, globalFlags, symbolStack); for (const p of resolved.properties) { if (globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) { @@ -3679,7 +3787,7 @@ namespace ts { writer.reportPrivateInBaseOfClassExpression(symbolName(p)); } } - const t = getTypeOfSymbol(p); + const t = getCheckFlags(p) & CheckFlags.ReverseMapped ? anyType : getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { const signatures = getSignaturesOfType(t, SignatureKind.Call); for (const signature of signatures) { @@ -3894,8 +4002,9 @@ namespace ts { } writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + const typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); @@ -3944,7 +4053,12 @@ namespace ts { writePunctuation(writer, SyntaxKind.CloseBracketToken); writePunctuation(writer, SyntaxKind.ColonToken); writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + if (info.type) { + buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + } + else { + writeKeyword(writer, SyntaxKind.AnyKeyword); + } writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -4203,7 +4317,7 @@ namespace ts { // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. - function getTypeForBindingElementParent(node: VariableLikeDeclaration) { + function getTypeForBindingElementParent(node: BindingElementGrandparent) { const symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } @@ -4310,7 +4424,7 @@ namespace ts { } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - const propName = "" + indexOf(pattern.elements, declaration); + const propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName as __String) : elementType; @@ -4331,7 +4445,7 @@ namespace ts { type = getTypeWithFacts(type, TypeFacts.NEUndefined); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], UnionReduction.Subtype) : type; } @@ -4358,15 +4472,15 @@ namespace ts { } // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, includeOptionality: boolean): Type { + function getTypeForVariableLikeDeclaration(declaration: ParameterDeclaration | PropertyDeclaration | PropertySignature | VariableDeclaration | BindingElement, includeOptionality: boolean): Type { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === SyntaxKind.ForInStatement) { + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForInStatement) { const indexType = getIndexType(checkNonNullExpression((declaration.parent.parent).expression)); return indexType.flags & (TypeFlags.TypeParameter | TypeFlags.Index) ? indexType : stringType; } - if (declaration.parent.parent.kind === SyntaxKind.ForOfStatement) { + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForOfStatement) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -4379,11 +4493,11 @@ namespace ts { return getTypeForBindingElement(declaration); } + const isOptional = !isBindingElement(declaration) && !isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; // Use type from type annotation if one is present - const typeNode = getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - const declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); + const declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); } if ((noImplicitAny || isInJavaScriptFile(declaration)) && @@ -4427,14 +4541,14 @@ namespace ts { type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { const type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } if (isJsxAttribute(declaration)) { @@ -4443,11 +4557,6 @@ namespace ts { return trueType; } - // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === SyntaxKind.ShorthandPropertyAssignment) { - return checkIdentifier(declaration.name); - } - // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); @@ -4499,7 +4608,7 @@ namespace ts { } } - const type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + const type = jsDocType || getUnionType(types, UnionReduction.Subtype); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } @@ -4592,7 +4701,7 @@ namespace ts { // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. - function getWidenedTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, reportErrors?: boolean): Type { + function getWidenedTypeForVariableLikeDeclaration(declaration: ParameterDeclaration | PropertyDeclaration | PropertySignature | VariableDeclaration | BindingElement, reportErrors?: boolean): Type { let type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); if (type) { if (reportErrors) { @@ -4600,21 +4709,15 @@ namespace ts { } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & TypeFlags.UniqueESSymbol && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & TypeFlags.UniqueESSymbol && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } - // During a normal type check we'll never get to here with a property assignment (the check of the containing - // object literal uses a different path). We exclude widening only so that language services and type verification - // tools see the actual type. - if (declaration.kind === SyntaxKind.PropertyAssignment) { - return type; - } return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any - type = declaration.dotDotDotToken ? anyArrayType : anyType; + type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && noImplicitAny) { @@ -4631,6 +4734,13 @@ namespace ts { return isPrivateWithinAmbient(memberDeclaration); } + function tryGetTypeFromEffectiveTypeNode(declaration: Declaration) { + const typeNode = getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function getTypeOfVariableOrParameterOrProperty(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { @@ -4665,8 +4775,39 @@ namespace ts { declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } + else if (isJSDocPropertyTag(declaration) + || isPropertyAccessExpression(declaration) + || isIdentifier(declaration) + || (isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration)) + || isMethodSignature(declaration)) { + + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, CheckMode.Normal); + } + else if (isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, CheckMode.Normal); + } + else if (isParameter(declaration) + || isPropertyDeclaration(declaration) + || isPropertySignature(declaration) + || isVariableDeclaration(declaration) + || isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + Debug.fail("Unhandled declaration kind! " + (ts as any).SyntaxKind[declaration.kind]); } if (!popTypeResolution()) { @@ -4854,6 +4995,9 @@ namespace ts { if (getCheckFlags(symbol) & CheckFlags.Instantiated) { return getTypeOfInstantiatedSymbol(symbol); } + if (getCheckFlags(symbol) & CheckFlags.ReverseMapped) { + return getTypeOfReverseMappedSymbol(symbol as ReverseMappedSymbol); + } if (symbol.flags & (SymbolFlags.Variable | SymbolFlags.Property)) { return getTypeOfVariableOrParameterOrProperty(symbol); } @@ -5082,11 +5226,11 @@ namespace ts { return type.resolvedBaseTypes; } - function resolveBaseTypesOfClass(type: InterfaceType): void { - type.resolvedBaseTypes = emptyArray; + function resolveBaseTypesOfClass(type: InterfaceType) { + type.resolvedBaseTypes = resolvingEmptyArray; const baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.Any))) { - return; + return type.resolvedBaseTypes = emptyArray; } const baseTypeNode = getBaseTypeNodeOfClass(type); const typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -5109,24 +5253,31 @@ namespace ts { const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; + return type.resolvedBaseTypes = emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === unknownType) { - return; + return type.resolvedBaseTypes = emptyArray; } if (!isValidBaseType(baseType)) { error(baseTypeNode.expression, Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; + return type.resolvedBaseTypes = emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); - return; + return type.resolvedBaseTypes = emptyArray; + } + if (type.resolvedBaseTypes === resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + (type as Type as ResolvedType).members = undefined; } - type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type: Type): boolean { @@ -5332,7 +5483,7 @@ namespace ts { } } if (memberTypeList.length) { - const enumType = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + const enumType = getUnionType(memberTypeList, UnionReduction.Literal, symbol, /*aliasTypeArguments*/ undefined); if (enumType.flags & TypeFlags.Union) { enumType.flags |= TypeFlags.EnumLiteral; enumType.symbol = symbol; @@ -5438,7 +5589,7 @@ namespace ts { */ function isThislessVariableLikeDeclaration(node: VariableLikeDeclaration): boolean { const typeNode = getEffectiveTypeAnnotationNode(node); - return typeNode ? isThislessType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !hasInitializer(node); } /** @@ -5761,6 +5912,7 @@ namespace ts { if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = createSymbolTable(source.declaredProperties); } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); const thisArgument = lastOrUndefined(typeArguments); for (const baseType of baseTypes) { const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; @@ -5790,15 +5942,24 @@ namespace ts { resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisParameter: Symbol | undefined, parameters: Symbol[], - resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasLiteralTypes: boolean): Signature { + function createSignature( + declaration: SignatureDeclaration, + typeParameters: TypeParameter[], + thisParameter: Symbol | undefined, + parameters: Symbol[], + resolvedReturnType: Type | undefined, + resolvedTypePredicate: TypePredicate | undefined, + minArgumentCount: number, + hasRestParameter: boolean, + hasLiteralTypes: boolean, + ): Signature { const sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; + sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasLiteralTypes = hasLiteralTypes; @@ -5806,15 +5967,15 @@ namespace ts { } function cloneSignature(sig: Signature): Signature { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, - sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType: InterfaceType): Signature[] { const baseConstructorType = getBaseConstructorTypeOfClass(classType); const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } const baseTypeNode = getBaseTypeNodeOfClass(classType); const isJavaScript = isInJavaScriptFile(baseTypeNode); @@ -5824,7 +5985,7 @@ namespace ts { for (const baseSig of baseSignatures) { const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); const typeParamCount = length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -5884,13 +6045,13 @@ namespace ts { let s = signature; // Union the result types when more than one signature matches if (unionSignatures.length > 1) { - s = cloneSignature(signature); + let thisParameter = signature.thisParameter; if (forEach(unionSignatures, sig => sig.thisParameter)) { - const thisType = getUnionType(map(unionSignatures, sig => getTypeOfSymbol(sig.thisParameter) || anyType), /*subtypeReduction*/ true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + const thisType = getUnionType(map(unionSignatures, sig => sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType), UnionReduction.Subtype); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; + s = cloneSignature(signature); + s.thisParameter = thisParameter; s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); @@ -5912,7 +6073,7 @@ namespace ts { indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, UnionReduction.Subtype), isAnyReadonly); } function resolveUnionTypeMembers(type: UnionType) { @@ -6014,6 +6175,7 @@ namespace ts { if (symbol.exports) { members = getExportsOfSymbol(symbol); } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, undefined, undefined); if (symbol.flags & SymbolFlags.Class) { const classType = getDeclaredTypeOfClassOrInterface(symbol); const baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -6046,6 +6208,23 @@ namespace ts { } } + function resolveReverseMappedTypeMembers(type: ReverseMappedType) { + const indexInfo = getIndexInfoOfType(type.source, IndexKind.String); + const readonlyMask = type.mappedType.declaration.readonlyToken ? false : true; + const optionalMask = type.mappedType.declaration.questionToken ? 0 : SymbolFlags.Optional; + const stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + const members = createSymbolTable(); + for (const prop of getPropertiesOfType(type.source)) { + const checkFlags = CheckFlags.ReverseMapped | (readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0); + const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.escapedName, checkFlags) as ReverseMappedSymbol; + inferredProp.declarations = prop.declarations; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); + } + /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type: MappedType) { const members: SymbolTable = createSymbolTable(); @@ -6185,6 +6364,9 @@ namespace ts { else if ((type).objectFlags & ObjectFlags.ClassOrInterface) { resolveClassOrInterfaceMembers(type); } + else if ((type).objectFlags & ObjectFlags.ReverseMapped) { + resolveReverseMappedTypeMembers(type as ReverseMappedType); + } else if ((type).objectFlags & ObjectFlags.Anonymous) { resolveAnonymousTypeMembers(type); } @@ -6441,14 +6623,13 @@ namespace ts { function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: __String): Symbol { let props: Symbol[]; - const types = containingType.types; const isUnion = containingType.flags & TypeFlags.Union; const excludeModifiers = isUnion ? ModifierFlags.NonPublicAccessibilityModifier : 0; // Flags we want to propagate to the result if they exist in all source symbols let commonFlags = isUnion ? SymbolFlags.None : SymbolFlags.Optional; let syntheticFlag = CheckFlags.SyntheticMethod; let checkFlags = 0; - for (const current of types) { + for (const current of containingType.types) { const type = getApparentType(current); if (type !== unknownType) { const prop = getPropertyOfType(type, name); @@ -6601,7 +6782,7 @@ namespace ts { } } if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); + return getUnionType(propTypes, UnionReduction.Subtype); } } return undefined; @@ -6665,7 +6846,7 @@ namespace ts { if (node.initializer) { const signatureDeclaration = node.parent; const signature = getSignatureFromDeclaration(signatureDeclaration); - const parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + const parameterIndex = signatureDeclaration.parameters.indexOf(node); Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -6673,7 +6854,7 @@ namespace ts { if (iife) { return !node.type && !node.dotDotDotToken && - indexOf((node.parent as SignatureDeclaration).parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; @@ -6681,22 +6862,26 @@ namespace ts { function createTypePredicateFromTypePredicateNode(node: TypePredicateNode): IdentifierTypePredicate | ThisTypePredicate { const { parameterName } = node; + const type = getTypeFromTypeNode(node.type); if (parameterName.kind === SyntaxKind.Identifier) { - return { - kind: TypePredicateKind.Identifier, - parameterName: parameterName ? parameterName.escapedText : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex((node.parent as SignatureDeclaration).parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - } as IdentifierTypePredicate; + return createIdentifierTypePredicate( + parameterName && parameterName.escapedText as string, // TODO: GH#18217 + parameterName && getTypePredicateParameterIndex((node.parent as SignatureDeclaration).parameters, parameterName), + type); } else { - return { - kind: TypePredicateKind.This, - type: getTypeFromTypeNode(node.type) - }; + return createThisTypePredicate(type); } } + function createIdentifierTypePredicate(parameterName: string | undefined, parameterIndex: number | undefined, type: Type): IdentifierTypePredicate { + return { kind: TypePredicateKind.Identifier, parameterName, parameterIndex, type }; + } + + function createThisTypePredicate(type: Type): ThisTypePredicate { + return { kind: TypePredicateKind.This, type }; + } + /** * Gets the minimum number of type arguments needed to satisfy all non-optional type * parameters. @@ -6725,7 +6910,7 @@ namespace ts { const numTypeParameters = length(typeParameters); if (numTypeParameters) { const numTypeArguments = length(typeArguments); - if ((isJavaScriptImplicitAny || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { if (!typeArguments) { typeArguments = []; } @@ -6744,6 +6929,7 @@ namespace ts { } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); } + typeArguments.length = typeParameters.length; } } return typeArguments; @@ -6811,11 +6997,8 @@ namespace ts { : undefined; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); const returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - const typePredicate = declaration.type && declaration.type.kind === SyntaxKind.TypePredicate ? - createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode) : - undefined; const hasRestLikeParameter = hasRestParameter(declaration) || isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -6952,6 +7135,30 @@ namespace ts { } } + function signatureHasTypePredicate(signature: Signature): boolean { + return getTypePredicateOfSignature(signature) !== undefined; + } + + function getTypePredicateOfSignature(signature: Signature): TypePredicate | undefined { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + const targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + const declaration = signature.declaration; + signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === SyntaxKind.TypePredicate ? + createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode) : + noTypePredicate; + } + Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } + function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { @@ -6962,7 +7169,7 @@ namespace ts { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + type = getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype); } else { type = getReturnTypeFromBody(signature.declaration); @@ -7215,12 +7422,15 @@ namespace ts { : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; const typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); - return unknownType; + if (!isJs) { + // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) + return unknownType; + } } // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJsImplicitAny)); + const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -7801,7 +8011,7 @@ namespace ts { // expression constructs such as array literals and the || and ?: operators). Named types can // circularly reference themselves and therefore cannot be subtype reduced during their declaration. // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types: Type[], subtypeReduction?: boolean, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { + function getUnionType(types: Type[], unionReduction: UnionReduction = UnionReduction.Literal, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { if (types.length === 0) { return neverType; } @@ -7813,11 +8023,15 @@ namespace ts { if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsLiteralOrUniqueESSymbol) { - removeRedundantLiteralTypes(typeSet); + switch (unionReduction) { + case UnionReduction.Literal: + if (typeSet.containsLiteralOrUniqueESSymbol) { + removeRedundantLiteralTypes(typeSet); + } + break; + case UnionReduction.Subtype: + removeSubtypes(typeSet); + break; } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : @@ -7827,6 +8041,42 @@ namespace ts { return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + function getUnionTypePredicate(signatures: ReadonlyArray): TypePredicate { + let first: TypePredicate | undefined; + const types: Type[] = []; + for (const sig of signatures) { + const pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + const unionType = getUnionType(types); + return isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + + function typePredicateKindsMatch(a: TypePredicate, b: TypePredicate): boolean { + return isIdentifierTypePredicate(a) + ? isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !isIdentifierTypePredicate(b); + } + // This function assumes the constituent type list is sorted and deduplicated. function getUnionTypeFromSortedList(types: Type[], aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { if (types.length === 0) { @@ -7857,7 +8107,7 @@ namespace ts { function getTypeFromUnionTypeNode(node: UnionTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), UnionReduction.Literal, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; @@ -7932,7 +8182,7 @@ namespace ts { // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. const unionType = typeSet[unionIndex]; return getUnionType(map(unionType.types, t => getIntersectionType(replaceElement(typeSet, unionIndex, t))), - /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + UnionReduction.Literal, aliasSymbol, aliasTypeArguments); } const id = getTypeListId(typeSet); let type = intersectionTypes.get(id); @@ -7965,7 +8215,7 @@ namespace ts { } function getLiteralTypeFromPropertyName(prop: Symbol) { - return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || startsWith(prop.escapedName as string, "__@") ? + return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || isKnownSymbol(prop) ? neverType : getLiteralType(symbolName(prop)); } @@ -8020,6 +8270,7 @@ namespace ts { const prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === SyntaxKind.ThisKeyword); if (isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -8243,10 +8494,7 @@ namespace ts { if (right.flags & TypeFlags.Union) { return mapType(right, t => getSpreadType(left, t, symbol, propagatedFlags)); } - if (right.flags & TypeFlags.NonPrimitive) { - return nonPrimitiveType; - } - if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.EnumLike)) { + if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive)) { return left; } @@ -8307,8 +8555,7 @@ namespace ts { emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= propagatedFlags; - spread.flags |= TypeFlags.FreshLiteral | TypeFlags.ContainsObjectLiteral; + spread.flags |= propagatedFlags | TypeFlags.ContainsObjectLiteral; (spread as ObjectType).objectFlags |= (ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread); return spread; } @@ -8549,7 +8796,7 @@ namespace ts { * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters: TypeParameter[], index: number): TypeMapper { - return t => indexOf(typeParameters, t) >= index ? emptyObjectType : t; + return t => typeParameters.indexOf(t) >= index ? emptyObjectType : t; } function isInferenceContext(mapper: TypeMapper): mapper is InferenceContext { @@ -8577,7 +8824,7 @@ namespace ts { return result; } - function cloneTypePredicate(predicate: TypePredicate, mapper: TypeMapper): ThisTypePredicate | IdentifierTypePredicate { + function instantiateTypePredicate(predicate: TypePredicate, mapper: TypeMapper): ThisTypePredicate | IdentifierTypePredicate { if (isIdentifierTypePredicate(predicate)) { return { kind: TypePredicateKind.Identifier, @@ -8596,7 +8843,6 @@ namespace ts { function instantiateSignature(signature: Signature, mapper: TypeMapper, eraseTypeParameters?: boolean): Signature { let freshTypeParameters: TypeParameter[]; - let freshTypePredicate: TypePredicate; if (signature.typeParameters && !eraseTypeParameters) { // First create a fresh set of type parameters, then include a mapping from the old to the // new type parameters in the mapper function. Finally store this mapper in the new type @@ -8607,15 +8853,17 @@ namespace ts { tp.mapper = mapper; } } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. const result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - freshTypePredicate, - signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, + signature.minArgumentCount, + signature.hasRestParameter, + signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -8770,7 +9018,7 @@ namespace ts { } } if (type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Primitive)) { - return getUnionType(instantiateTypes((type).types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return getUnionType(instantiateTypes((type).types, mapper), UnionReduction.Literal, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (type.flags & TypeFlags.Intersection) { return getIntersectionType(instantiateTypes((type).types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); @@ -8925,7 +9173,7 @@ namespace ts { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeAssignableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: DiagnosticMessageChain): boolean { + function checkTypeAssignableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined): boolean { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } @@ -8933,7 +9181,7 @@ namespace ts { * This is *not* a bi-directional relationship. * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. */ - function checkTypeComparableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: DiagnosticMessageChain): boolean { + function checkTypeComparableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined): boolean { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } @@ -9009,7 +9257,7 @@ namespace ts { // with respect to T. const sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); const targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); - const callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + const callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & TypeFlags.Nullable) === (getFalsyFlags(targetType) & TypeFlags.Nullable); const related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? CallbackCheck.Strict : CallbackCheck.Bivariant, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -9033,11 +9281,13 @@ namespace ts { const sourceReturnType = getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + const targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + const sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } - else if (isIdentifierTypePredicate(target.typePredicate)) { + else if (isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { errorReporter(Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } @@ -9245,6 +9495,10 @@ namespace ts { return false; } + function isIgnoredJsxProperty(source: Type, sourceProp: Symbol, targetMemberType: Type | undefined) { + return source.flags & TypeFlags.JsxAttributes && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } + /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -9261,7 +9515,7 @@ namespace ts { relation: Map, errorNode: Node, headMessage?: DiagnosticMessage, - containingMessageChain?: DiagnosticMessageChain): boolean { + containingMessageChain?: () => DiagnosticMessageChain | undefined): boolean { let errorInfo: DiagnosticMessageChain; let maybeKeys: string[]; @@ -9281,11 +9535,25 @@ namespace ts { } else if (errorInfo) { if (containingMessageChain) { - errorInfo = concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + const chain = containingMessageChain(); + if (chain) { + errorInfo = concatenateDiagnosticMessageChains(chain, errorInfo); + } } diagnostics.add(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + const links = getSymbolLinks(source.symbol); + if (links.originatingImport && !isImportCall(links.originatingImport)) { + const helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(createDiagnosticForNode(links.originatingImport, Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== Ternary.False; function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { @@ -9491,7 +9759,7 @@ namespace ts { } if (target.flags & TypeFlags.Union) { const discriminantType = findMatchingDiscriminantType(source, target as UnionType); - if (discriminantType) { + if (discriminantType) { // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminantType, reportErrors); } @@ -9973,6 +10241,9 @@ namespace ts { if (!(targetProp.flags & SymbolFlags.Prototype)) { const sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & ModifierFlags.Private || targetPropFlags & ModifierFlags.Private) { @@ -10197,6 +10468,9 @@ namespace ts { function eachPropertyRelatedTo(source: Type, target: Type, kind: IndexKind, reportErrors: boolean): Ternary { let result = Ternary.True; for (const prop of getPropertiesOfObjectType(source)) { + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } if (kind === IndexKind.String || isNumericLiteralName(prop.escapedName)) { const related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -10379,7 +10653,7 @@ namespace ts { let result = "" + type.target.id; for (const t of type.typeArguments) { if (isUnconstrainedTypeParameter(t)) { - let index = indexOf(typeParameters, t); + let index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -10456,20 +10730,6 @@ namespace ts { !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? undefined : checkClass; } - // Return true if the given type is the constructor type for an abstract class - function isAbstractConstructorType(type: Type) { - if (getObjectFlags(type) & ObjectFlags.Anonymous) { - const symbol = type.symbol; - if (symbol && symbol.flags & SymbolFlags.Class) { - const declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && hasModifier(declaration, ModifierFlags.Abstract)) { - return true; - } - } - } - return false; - } - // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely @@ -10596,11 +10856,20 @@ namespace ts { result &= related; } if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + const sourceTypePredicate = getTypePredicateOfSignature(source); + const targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } return result; } + function compareTypePredicatesIdentical(source: TypePredicate | undefined, target: TypePredicate | undefined, compareTypes: (s: Type, t: Type) => Ternary): Ternary { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? Ternary.False : compareTypes(source.type, target.type); + } + function isRestParameterIndex(signature: Signature, parameterIndex: number) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } @@ -10635,7 +10904,7 @@ namespace ts { const primaryTypes = filter(types, t => !(t.flags & TypeFlags.Nullable)); return primaryTypes.length ? getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & TypeFlags.Nullable) : - getUnionType(types, /*subtypeReduction*/ true); + getUnionType(types, UnionReduction.Subtype); } // Return the leftmost type for which no type to the right is a subtype. @@ -10698,7 +10967,7 @@ namespace ts { } function getWidenedLiteralLikeTypeForContextualType(type: Type, contextualType: Type) { - if (!isLiteralLikeContextualType(contextualType)) { + if (!isLiteralOfContextualType(type, contextualType)) { type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); } return type; @@ -10926,7 +11195,7 @@ namespace ts { // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). - return getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType)); + return getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? UnionReduction.Subtype : UnionReduction.Literal); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference((type).target, sameMap((type).typeArguments, getWidenedType)); @@ -11140,41 +11409,44 @@ namespace ts { * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ function inferTypeForHomomorphicMappedType(source: Type, target: MappedType): Type { + const key = source.id + "," + target.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + const type = createReverseMappedType(source, target); + reverseMappedCache.set(key, type); + return type; + } + + function createReverseMappedType(source: Type, target: MappedType) { const properties = getPropertiesOfType(source); - let indexInfo = getIndexInfoOfType(source, IndexKind.String); - if (properties.length === 0 && !indexInfo) { + if (properties.length === 0 && !getIndexInfoOfType(source, IndexKind.String)) { return undefined; } - const typeParameter = getIndexedAccessType((getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target)); - const inference = createInferenceInfo(typeParameter); - const inferences = [inference]; - const templateType = getTemplateTypeFromMappedType(target); - const readonlyMask = target.declaration.readonlyToken ? false : true; - const optionalMask = target.declaration.questionToken ? 0 : SymbolFlags.Optional; - const members = createSymbolTable(); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. for (const prop of properties) { - const propType = getTypeOfSymbol(prop); - // If any property contains context sensitive functions that have been skipped, the source type - // is incomplete and we can't infer a meaningful input type. - if (propType.flags & TypeFlags.ContainsAnyFunctionType) { + if (getTypeOfSymbol(prop).flags & TypeFlags.ContainsAnyFunctionType) { return undefined; } - const checkFlags = readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0; - const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.escapedName, checkFlags); - inferredProp.declarations = prop.declarations; - inferredProp.type = inferTargetType(propType); - members.set(prop.escapedName, inferredProp); } - if (indexInfo) { - indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); + const reversed = createObjectType(ObjectFlags.ReverseMapped | ObjectFlags.Anonymous, /*symbol*/ undefined) as ReverseMappedType; + reversed.source = source; + reversed.mappedType = target; + return reversed; + } - function inferTargetType(sourceType: Type): Type { - inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType); - return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; - } + function getTypeOfReverseMappedSymbol(symbol: ReverseMappedSymbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + } + + function inferReverseMappedType(sourceType: Type, target: MappedType): Type { + const typeParameter = getIndexedAccessType((getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target)); + const templateType = getTemplateTypeFromMappedType(target); + const inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return inference.candidates ? getUnionType(inference.candidates, UnionReduction.Subtype) : emptyObjectType; } function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean) { @@ -11278,7 +11550,7 @@ namespace ts { return; } } - else if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { + if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments const sourceTypes = (source).typeArguments || emptyArray; const targetTypes = (target).typeArguments || emptyArray; @@ -11459,8 +11731,10 @@ namespace ts { function inferFromSignature(source: Signature, target: Signature) { forEachMatchingParameterType(source, target, inferFromContravariantTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); + const sourceTypePredicate = getTypePredicateOfSignature(source); + const targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -11524,7 +11798,7 @@ namespace ts { if (candidates.length > 1) { const objectLiterals = filter(candidates, isObjectLiteralType); if (objectLiterals.length) { - const objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + const objectLiteralsType = getWidenedType(getUnionType(objectLiterals, UnionReduction.Subtype)); return concatenate(filter(candidates, t => !isObjectLiteralType(t)), [objectLiteralsType]); } } @@ -11551,7 +11825,7 @@ namespace ts { // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. const unwidenedType = inference.priority & InferencePriority.Contravariant ? getCommonSubtype(baseCandidates) : - context.flags & InferenceFlags.InferUnionTypes || inference.priority & InferencePriority.ReturnType ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : + context.flags & InferenceFlags.InferUnionTypes || inference.priority & InferencePriority.ReturnType ? getUnionType(baseCandidates, UnionReduction.Subtype) : getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); } @@ -11656,7 +11930,7 @@ namespace ts { const container = (node as BindingElement).parent.parent; const key = container.kind === SyntaxKind.BindingElement ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); const text = getBindingElementNameText(node as BindingElement); - const result = key && text && (key + "." + text); + const result = key && text && (key + "." + text); return result; } return undefined; @@ -11950,7 +12224,7 @@ namespace ts { } function getAssignedTypeOfArrayLiteralElement(node: ArrayLiteralExpression, element: Expression): Type { - return getTypeOfDestructuredArrayElement(getAssignedType(node), indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node: SpreadElement): Type { @@ -11994,7 +12268,7 @@ namespace ts { const type = pattern.kind === SyntaxKind.ObjectBindingPattern ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -12126,7 +12400,7 @@ namespace ts { // Apply a mapping function to a type and return the resulting type. If the source type // is a union type, the mapping function is applied to each constituent type and a union // of the resulting types is returned. - function mapType(type: Type, mapper: (t: Type) => Type): Type { + function mapType(type: Type, mapper: (t: Type) => Type, noReductions?: boolean): Type { if (!(type.flags & TypeFlags.Union)) { return mapper(type); } @@ -12147,7 +12421,7 @@ namespace ts { } } } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; + return mappedTypes ? getUnionType(mappedTypes, noReductions ? UnionReduction.None : UnionReduction.Literal) : mappedType; } function extractTypesOfKind(type: Type, kind: TypeFlags) { @@ -12206,7 +12480,7 @@ namespace ts { return elementType.flags & TypeFlags.Never ? autoArrayType : createArrayType(elementType.flags & TypeFlags.Union ? - getUnionType((elementType).types, /*subtypeReduction*/ true) : + getUnionType((elementType).types, UnionReduction.Subtype) : elementType); } @@ -12239,7 +12513,7 @@ namespace ts { // At flow control branch or loop junctions, if the type along every antecedent code path // is an evolving array type, we construct a combined evolving array type. Otherwise we // finalize all evolving array types. - function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: boolean) { + function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: UnionReduction) { return isEvolvingArrayTypeList(types) ? getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) : getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); @@ -12276,10 +12550,7 @@ namespace ts { const funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { const apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - return !!forEach(callSignatures, sig => sig.typePredicate); - } + return apparentType !== unknownType && some(getSignaturesOfType(apparentType, SignatureKind.Call), signatureHasTypePredicate); } } return false; @@ -12534,7 +12805,7 @@ namespace ts { seenIncomplete = true; } } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? UnionReduction.Subtype : UnionReduction.Literal), seenIncomplete); } function getTypeAtFlowLoopLabel(flow: FlowLabel): FlowType { @@ -12563,7 +12834,7 @@ namespace ts { // path that leads to the top. for (let i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], UnionReduction.Literal), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -12582,7 +12853,7 @@ namespace ts { firstAntecedentType = flowType; } const type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. const cached = cache.get(key); @@ -12605,7 +12876,7 @@ namespace ts { } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? UnionReduction.Subtype : UnionReduction.Literal); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } @@ -12640,6 +12911,25 @@ namespace ts { return type; } + function isTypePresencePossible(type: Type, propName: __String, assumeTrue: boolean) { + if (getIndexInfoOfType(type, IndexKind.String)) { + return true; + } + const prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & SymbolFlags.Optional ? true : assumeTrue; + } + return !assumeTrue; + } + + function narrowByInKeyword(type: Type, literal: LiteralExpression, assumeTrue: boolean) { + if ((type.flags & (TypeFlags.Union | TypeFlags.Object)) || (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType)) { + const propName = escapeLeadingUnderscores(literal.text); + return filterType(type, t => isTypePresencePossible(t, propName, assumeTrue)); + } + return type; + } + function narrowTypeByBinaryExpression(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { switch (expr.operatorToken.kind) { case SyntaxKind.EqualsToken: @@ -12651,10 +12941,10 @@ namespace ts { const operator = expr.operatorToken.kind; const left = getReferenceCandidate(expr.left); const right = getReferenceCandidate(expr.right); - if (left.kind === SyntaxKind.TypeOfExpression && right.kind === SyntaxKind.StringLiteral) { + if (left.kind === SyntaxKind.TypeOfExpression && (right.kind === SyntaxKind.StringLiteral || right.kind === SyntaxKind.NoSubstitutionTemplateLiteral)) { return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right.kind === SyntaxKind.TypeOfExpression && left.kind === SyntaxKind.StringLiteral) { + if (right.kind === SyntaxKind.TypeOfExpression && (left.kind === SyntaxKind.StringLiteral || left.kind === SyntaxKind.NoSubstitutionTemplateLiteral)) { return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } if (isMatchingReference(reference, left)) { @@ -12675,6 +12965,12 @@ namespace ts { break; case SyntaxKind.InstanceOfKeyword: return narrowTypeByInstanceof(type, expr, assumeTrue); + case SyntaxKind.InKeyword: + const target = getReferenceCandidate(expr.right); + if ((expr.left.kind === SyntaxKind.StringLiteral || expr.left.kind === SyntaxKind.NoSubstitutionTemplateLiteral) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; case SyntaxKind.CommaToken: return narrowType(type, expr.right, assumeTrue); } @@ -12763,7 +13059,7 @@ namespace ts { const discriminantType = getUnionType(clauseTypes); const caseType = discriminantType.flags & TypeFlags.Never ? neverType : - replacePrimitivesWithLiterals(filterType(type, t => isTypeComparableTo(discriminantType, t)), discriminantType); + replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -12852,7 +13148,7 @@ namespace ts { return type; } const signature = getResolvedSignature(callExpression); - const predicate = signature.typePredicate; + const predicate = getTypePredicateOfSignature(signature); if (!predicate) { return type; } @@ -13016,6 +13312,12 @@ namespace ts { return type; } + function markAliasReferenced(symbol: Symbol, location: Node) { + if (isNonLocalAlias(symbol, /*excludes*/ SymbolFlags.Value) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -13044,9 +13346,9 @@ namespace ts { } // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. - if (isNonLocalAlias(symbol, /*excludes*/ SymbolFlags.Value) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -13134,6 +13436,7 @@ namespace ts { const declarationContainer = getControlFlowContainer(declaration); let flowContainer = getControlFlowContainer(node); const isOuterVariable = flowContainer !== declarationContainer; + const isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -13145,7 +13448,7 @@ namespace ts { // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - const assumeInitialized = isParameter || isAlias || isOuterVariable || + const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0 || isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || @@ -13264,7 +13567,7 @@ namespace ts { } } - function findFirstSuperCall(n: Node): Node { + function findFirstSuperCall(n: Node): SuperCall | undefined { if (isSuperCall(n)) { return n; } @@ -13280,12 +13583,12 @@ namespace ts { * * @param constructor constructor-function to look for super statement */ - function getSuperCallInConstructor(constructor: ConstructorDeclaration): ExpressionStatement { + function getSuperCallInConstructor(constructor: ConstructorDeclaration): SuperCall | undefined { const links = getNodeLinks(constructor); // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result if (links.hasSuperCall === undefined) { - links.superCall = findFirstSuperCall(constructor.body); + links.superCall = findFirstSuperCall(constructor.body); links.hasSuperCall = links.superCall ? true : false; } return links.superCall; @@ -13720,7 +14023,7 @@ namespace ts { if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { const iife = getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - const indexOfParameter = indexOf(func.parameters, parameter); + const indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { const restTypes: Type[] = []; for (let i = indexOfParameter; i < iife.arguments.length; i++) { @@ -13741,7 +14044,7 @@ namespace ts { if (contextualSignature) { const funcHasRestParameters = hasRestParameter(func); const len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - let indexOfParameter = indexOf(func.parameters, parameter); + let indexOfParameter = func.parameters.indexOf(parameter); if (getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -13772,7 +14075,7 @@ namespace ts { // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node: Expression): Type { const declaration = node.parent; - if (node === declaration.initializer) { + if (hasInitializer(declaration) && node === declaration.initializer) { const typeNode = getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -13788,7 +14091,7 @@ namespace ts { } if (isBindingPattern(declaration.parent)) { const parentDeclaration = declaration.parent.parent; - const name = declaration.propertyName || declaration.name; + const name = (declaration as BindingElement).propertyName || (declaration as BindingElement).name; if (parentDeclaration.kind !== SyntaxKind.BindingElement) { const parentTypeNode = getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !isBindingPattern(name)) { @@ -13872,7 +14175,7 @@ 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 { const args = getEffectiveCallArguments(callTarget); - const argIndex = indexOf(args, arg); + const argIndex = args.indexOf(arg); if (argIndex >= 0) { // 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. @@ -13933,11 +14236,11 @@ namespace ts { return mapType(type, t => { const prop = t.flags & TypeFlags.StructuredType ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; - }); + }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type: Type, kind: IndexKind) { - return mapType(type, t => getIndexTypeOfStructuredType(t, kind)); + return mapType(type, t => getIndexTypeOfStructuredType(t, kind), /*noReductions*/ true); } // Return true if the given contextual type is a tuple-like type @@ -14119,9 +14422,9 @@ namespace ts { return getContextualTypeForReturnExpression(node); case SyntaxKind.YieldExpression: return getContextualTypeForYieldOperand(parent); - case SyntaxKind.CallExpression: + case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node); case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: return getTypeFromTypeNode((parent).type); @@ -14247,8 +14550,6 @@ namespace ts { let result: Signature; if (signatureList) { result = cloneSignature(signatureList[0]); - // Clear resolved return type we possibly got from cloneSignature - result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; @@ -14326,7 +14627,7 @@ namespace ts { if (patternElement.kind !== SyntaxKind.OmittedExpression) { error(patternElement, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -14336,7 +14637,7 @@ namespace ts { } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : + getUnionType(elementTypes, UnionReduction.Subtype) : strictNullChecks ? implicitNeverType : undefinedWideningType); } @@ -14415,7 +14716,7 @@ namespace ts { propTypes.push(getTypeOfSymbol(properties[i])); } } - const unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + const unionType = propTypes.length ? getUnionType(propTypes, UnionReduction.Subtype) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } @@ -14427,7 +14728,7 @@ namespace ts { let propertiesTable = createSymbolTable(); let propertiesArray: Symbol[] = []; let spread: Type = emptyObjectType; - let propagatedFlags: TypeFlags = 0; + let propagatedFlags: TypeFlags = TypeFlags.FreshLiteral; const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -14614,14 +14915,14 @@ namespace ts { type.flags & TypeFlags.UnionOrIntersection && !forEach((type).types, t => !isValidSpreadType(t))); } - function checkJsxSelfClosingElement(node: JsxSelfClosingElement): Type { - checkJsxOpeningLikeElementOrOpeningFragment(node); + function checkJsxSelfClosingElement(node: JsxSelfClosingElement, checkMode: CheckMode): Type { + checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); return getJsxGlobalElementType() || anyType; } - function checkJsxElement(node: JsxElement): Type { + function checkJsxElement(node: JsxElement, checkMode: CheckMode): Type { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { @@ -14634,8 +14935,8 @@ namespace ts { return getJsxGlobalElementType() || anyType; } - function checkJsxFragment(node: JsxFragment): Type { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + function checkJsxFragment(node: JsxFragment, checkMode: CheckMode): Type { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); if (compilerOptions.jsx === JsxEmit.React && compilerOptions.jsxFactory) { error(node, Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); @@ -14668,6 +14969,12 @@ namespace ts { } } + function checkJsxAttribute(node: JsxAttribute, checkMode?: CheckMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } + /** * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. * @@ -14677,11 +14984,10 @@ namespace ts { * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, * which also calls getSpreadType. */ - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement: JsxOpeningLikeElement, filter?: (symbol: Symbol) => boolean, checkMode?: CheckMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode) { const attributes = openingLikeElement.attributes; let attributesTable = createSymbolTable(); let spread: Type = emptyObjectType; - let attributesArray: Symbol[] = []; let hasSpreadAnyType = false; let typeToIntersect: Type; let explicitlySpecifyChildrenAttribute = false; @@ -14690,9 +14996,7 @@ namespace ts { for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { - const exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; // is sugar for + const exprType = checkJsxAttribute(attributeDecl, checkMode); const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; @@ -14703,24 +15007,22 @@ namespace ts { attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - attributesArray.push(attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - attributesArray = []; + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, TypeFlags.JsxAttributes); attributesTable = createSymbolTable(); } - const exprType = checkExpression(attributeDecl.expression); + const exprType = checkExpressionCached(attributeDecl.expression, checkMode); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, TypeFlags.JsxAttributes); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -14729,18 +15031,8 @@ namespace ts { } if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - } - attributesArray = getPropertiesOfType(spread); - } - - attributesTable = createSymbolTable(); - for (const attr of attributesArray) { - if (!filter || filter(attr)) { - attributesTable.set(attr.escapedName, attr); - } + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, TypeFlags.JsxAttributes); } } @@ -14758,30 +15050,30 @@ namespace ts { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process const childrenPropSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + createArrayType(getUnionType(childrenTypes)); + const childPropMap = createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, TypeFlags.JsxAttributes); + } } if (hasSpreadAnyType) { return anyType; } - - const attributeType = createJsxAttributesType(attributes.symbol, attributesTable); - return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : - typeToIntersect ? typeToIntersect : attributeType; + return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ - function createJsxAttributesType(symbol: Symbol, attributesTable: UnderscoreEscapedMap) { - const result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + function createJsxAttributesType() { + const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral; result.objectFlags |= ObjectFlags.ObjectLiteral; return result; @@ -14810,8 +15102,8 @@ namespace ts { * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) * @param node a JSXAttributes to be resolved of its type */ - function checkJsxAttributes(node: JsxAttributes, checkMode?: CheckMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent as JsxOpeningLikeElement, /*filter*/ undefined, checkMode); + function checkJsxAttributes(node: JsxAttributes, checkMode: CheckMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent as JsxOpeningLikeElement, checkMode); } function getJsxType(name: __String) { @@ -14867,7 +15159,7 @@ namespace ts { * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node: JsxOpeningLikeElement, valueType: Type) { + function getJsxElementInstanceType(node: JsxOpeningLikeElement, valueType: Type, sourceAttributesType: Type) { Debug.assert(!(valueType.flags & TypeFlags.Union)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -14890,7 +15182,8 @@ namespace ts { for (const signature of signatures) { if (signature.typeParameters) { const isJavascript = isInJavaScriptFile(node); - const typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); + const inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? InferenceFlags.AnyDefault : 0); + const typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { @@ -14898,7 +15191,7 @@ namespace ts { } } - return getUnionType(map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(map(instantiatedSignatures, getReturnTypeOfSignature), UnionReduction.Subtype); } /** @@ -15075,6 +15368,7 @@ namespace ts { * * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) * @return attributes type if able to resolve the type of node @@ -15083,14 +15377,15 @@ namespace ts { */ function resolveCustomJsxElementAttributesType(openingLikeElement: JsxOpeningLikeElement, shouldIncludeAllStatelessAttributesType: boolean, - elementType: Type = checkExpression(openingLikeElement.tagName), + sourceAttributesType: Type | undefined, + elementType: Type, elementClassType?: Type): Type { if (elementType.flags & TypeFlags.Union) { const types = (elementType as UnionType).types; return getUnionType(types.map(type => { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), /*subtypeReduction*/ true); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + }), UnionReduction.Subtype); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type @@ -15120,7 +15415,7 @@ namespace ts { } // Get the element instance type (the result of newing or invoking this tag) - const elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + const elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType || emptyObjectType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. @@ -15133,7 +15428,7 @@ namespace ts { } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { + if (elementClassType && sourceAttributesType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } @@ -15216,14 +15511,20 @@ namespace ts { * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node: JsxOpeningLikeElement, shouldIncludeAllStatelessAttributesType: boolean): Type { - const links = getNodeLinks(node); - const linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - const elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + function getCustomJsxElementAttributesType(node: JsxOpeningLikeElement, sourceAttributesType: Type, shouldIncludeAllStatelessAttributesType: boolean): Type { + if (!sourceAttributesType) { + // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) + const links = getNodeLinks(node); + const linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { + const elemClassType = getJsxGlobalElementClassType(); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); + } + return links[linkLocation]; + } + else { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } - return links[linkLocation]; } /** @@ -15238,7 +15539,7 @@ namespace ts { else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); } } @@ -15252,7 +15553,7 @@ namespace ts { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); } } @@ -15312,7 +15613,7 @@ namespace ts { } } - function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment) { + function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment, checkMode: CheckMode) { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { @@ -15337,7 +15638,7 @@ namespace ts { } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node); + checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); } else { checkJsxChildren((node as JsxOpeningFragment).parent); @@ -15384,25 +15685,23 @@ namespace ts { * Check assignablity between given attributes property, "source attributes", and the "target attributes" * @param openingLikeElement an opening-like JSX element to check its JSXAttributes */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement: JsxOpeningLikeElement) { + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode) { // The function involves following steps: // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - const targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - const sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, - attribute => { - return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); - }); + const sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); + + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. + const targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. @@ -15413,11 +15712,16 @@ namespace ts { // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties const isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (const attribute of openingLikeElement.attributes.properties) { - if (isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, idText(attribute.name), typeToString(targetAttributesType)); + if (!isJsxAttribute(attribute)) { + continue; + } + const attrName = attribute.name as Identifier; + const isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, idText(attrName), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -15563,17 +15867,35 @@ namespace ts { }); } - function checkNonNullExpression(node: Expression | QualifiedName) { - return checkNonNullType(checkExpression(node), node); - } - - function checkNonNullType(type: Type, errorNode: Node): Type { + function checkNonNullExpression( + node: Expression | QualifiedName, + nullDiagnostic?: DiagnosticMessage, + undefinedDiagnostic?: DiagnosticMessage, + nullOrUndefinedDiagnostic?: DiagnosticMessage, + ) { + return checkNonNullType( + checkExpression(node), + node, + nullDiagnostic, + undefinedDiagnostic, + nullOrUndefinedDiagnostic + ); + } + + function checkNonNullType( + type: Type, + node: Node, + nullDiagnostic?: DiagnosticMessage, + undefinedDiagnostic?: DiagnosticMessage, + nullOrUndefinedDiagnostic?: DiagnosticMessage + ): Type { const kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & TypeFlags.Nullable; if (kind) { - error(errorNode, kind & TypeFlags.Undefined ? kind & TypeFlags.Null ? - Diagnostics.Object_is_possibly_null_or_undefined : - Diagnostics.Object_is_possibly_undefined : - Diagnostics.Object_is_possibly_null); + 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) + ); const t = getNonNullableType(type); return t.flags & (TypeFlags.Nullable | TypeFlags.Never) ? unknownType : t; } @@ -15590,15 +15912,20 @@ namespace ts { function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { let propType: Type; - let leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - const leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; const leftType = checkNonNullExpression(left); + const parentSymbol = getNodeLinks(left).resolvedSymbol; const apparentType = getApparentType(getWidenedType(leftType)); if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } return apparentType; } const assignmentKind = getAssignmentTargetKind(node); const prop = getPropertyOfType(apparentType, right.escapedText); + if (isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } if (!prop) { const indexInfo = getIndexInfoOfType(apparentType, IndexKind.String); if (!(indexInfo && indexInfo.type)) { @@ -15615,13 +15942,6 @@ namespace ts { else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === SyntaxKind.ThisKeyword); - // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module - leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && - !(isNonLocalAlias(leftSymbol, /*excludes*/ SymbolFlags.Value) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop)) - ) { - getSymbolLinks(leftSymbol).referenced = undefined; - } getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); if (assignmentKind) { @@ -15701,6 +16021,9 @@ namespace ts { * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. */ function isPropertyDeclaredInAncestorClass(prop: Symbol): boolean { + if (!(prop.parent.flags & SymbolFlags.Class)) { + return false; + } let classType = getTypeOfSymbol(prop.parent) as InterfaceType; while (true) { classType = getSuperClass(classType); @@ -15861,37 +16184,48 @@ namespace ts { } function markPropertyAsReferenced(prop: Symbol, nodeForCheckWriteOnly: Node | undefined, isThisAccess: boolean) { - if (prop && - noUnusedIdentifiers && - (prop.flags & SymbolFlags.ClassMember) && - prop.valueDeclaration && hasModifier(prop.valueDeclaration, ModifierFlags.Private) - && !(nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly))) { - - if (isThisAccess) { - // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). - const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration); - if (containingMethod && containingMethod.symbol === prop) { - return; - } - } + if (!prop || !noUnusedIdentifiers || !(prop.flags & SymbolFlags.ClassMember) || !prop.valueDeclaration || !hasModifier(prop.valueDeclaration, ModifierFlags.Private)) { + return; + } + if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor))) { + return; + } - if (getCheckFlags(prop) & CheckFlags.Instantiated) { - getSymbolLinks(prop).target.isReferenced = true; - } - else { - prop.isReferenced = true; + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; } } + + if (getCheckFlags(prop) & CheckFlags.Instantiated) { + getSymbolLinks(prop).target.isReferenced = true; + } + else { + prop.isReferenced = true; + } } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: __String): boolean { - const left = node.kind === SyntaxKind.PropertyAccessExpression - ? (node).expression - : (node).left; - + const left = node.kind === SyntaxKind.PropertyAccessExpression ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); } + function isValidPropertyAccessForCompletions(node: PropertyAccessExpression, type: Type, property: Symbol): boolean { + return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + && (!(property.flags & ts.SymbolFlags.Method) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method: Symbol, type: Type) { + const propType = getTypeOfFuncClassEnumModule(method); + const signatures = getSignaturesOfType(propType, SignatureKind.Call); + Debug.assert(signatures.length !== 0); + return signatures.some(sig => { + const thisType = getThisTypeOfSignature(sig); + return !thisType || isTypeAssignableTo(type, thisType); + }); + } + function isValidPropertyAccessWithType( node: PropertyAccessExpression | QualifiedName, left: LeftHandSideExpression | QualifiedName, @@ -16244,6 +16578,13 @@ namespace ts { return getSignatureInstantiation(signature, getInferredTypes(context), isInJavaScriptFile(contextualSignature.declaration)); } + function inferJsxTypeArguments(signature: Signature, sourceAttributesType: Type, context: InferenceContext): Type[] { + const paramType = getTypeAtPosition(signature, 0); + inferTypes(context.inferences, sourceAttributesType, paramType); + + return getInferredTypes(context); + } + function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: ReadonlyArray, excludeArgument: boolean[], context: InferenceContext): Type[] { // Clear out all the inference results from the last time inferTypeArguments was called on this context for (const inference of context.inferences) { @@ -16342,7 +16683,7 @@ namespace ts { const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - const errorInfo = reportErrors && headMessage && chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + const errorInfo = reportErrors && headMessage && (() => chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Type_0_does_not_satisfy_the_constraint_1)); const typeArgumentHeadMessage = headMessage || Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -17018,7 +17359,7 @@ namespace ts { } excludeCount--; if (excludeCount > 0) { - excludeArgument[indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -17063,7 +17404,13 @@ namespace ts { return resolveUntypedCall(node); } - const funcType = checkNonNullExpression(node.expression); + const funcType = checkNonNullExpression( + 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 + ); + if (funcType === silentNeverType) { return silentNeverSignature; } @@ -17100,7 +17447,7 @@ namespace ts { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, SignatureKind.Call); } return resolveErrorCall(node); } @@ -17115,7 +17462,7 @@ namespace ts { function isUntypedFunctionCall(funcType: Type, apparentFuncType: Type, numCallSignatures: number, numConstructSignatures: number) { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & TypeFlags.TypeParameter || - !numCallSignatures && !numConstructSignatures && !(funcType.flags & (TypeFlags.Union | TypeFlags.Never)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (TypeFlags.Union | TypeFlags.Never)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node: NewExpression, candidatesOutArray: Signature[]): Signature { @@ -17190,7 +17537,7 @@ namespace ts { return signature; } - error(node, Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, SignatureKind.Construct); return resolveErrorCall(node); } @@ -17237,6 +17584,28 @@ namespace ts { return true; } + function invocationError(node: Node, apparentType: Type, kind: SignatureKind) { + error(node, kind === SignatureKind.Call + ? Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature + , typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + + function invocationErrorRecovery(apparentType: Type, kind: SignatureKind) { + if (!apparentType.symbol) { + return; + } + const importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !isImportCall(importNode)) { + const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) return; + error(importNode, Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } + function resolveTaggedTemplateExpression(node: TaggedTemplateExpression, candidatesOutArray: Signature[]): Signature { const tagType = checkExpression(node.tag); const apparentType = getApparentType(tagType); @@ -17254,7 +17623,7 @@ namespace ts { } if (!callSignatures.length) { - error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, SignatureKind.Call); return resolveErrorCall(node); } @@ -17311,6 +17680,7 @@ namespace ts { errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, SignatureKind.Call); return resolveErrorCall(node); } @@ -17565,17 +17935,19 @@ namespace ts { if (moduleSymbol) { const esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type: Type, symbol: Symbol): Type { + function getTypeWithSyntheticDefaultImportType(type: Type, symbol: Symbol, originalSymbol: Symbol): Type { if (allowSyntheticDefaultImports && type && type !== unknownType) { const synthType = type as SyntheticDefaultModuleType; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, InternalSymbolName.Default)) { + const file = find(originalSymbol.declarations, isSourceFile); + const hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { const memberTable = createSymbolTable(); const newSymbol = createSymbol(SymbolFlags.Alias, InternalSymbolName.Default); newSymbol.target = resolveSymbol(symbol); @@ -17583,7 +17955,7 @@ namespace ts { const anonymousSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type); const defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & TypeFlags.StructuredType && type.symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -17675,7 +18047,7 @@ namespace ts { const type = getTypeOfSymbol(symbol); if (strictNullChecks) { const declaration = symbol.valueDeclaration; - if (declaration && (declaration).initializer) { + if (declaration && hasInitializer(declaration)) { return getOptionalType(type); } } @@ -17794,7 +18166,6 @@ namespace ts { } function getReturnTypeFromBody(func: FunctionLikeDeclaration, checkMode?: CheckMode): Type { - const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } @@ -17812,9 +18183,9 @@ namespace ts { } } else { - let types: Type[]; + let types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (functionFlags & FunctionFlags.Generator) { // Generator or AsyncGenerator function - types = concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + types = concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { const iterableIteratorAny = functionFlags & FunctionFlags.Async ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function @@ -17827,7 +18198,6 @@ namespace ts { } } else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { // For an async function, the return type will not be never, but rather a Promise for never. return functionFlags & FunctionFlags.Async @@ -17843,9 +18213,10 @@ namespace ts { } // Return a union of the return expression types. - type = getUnionType(types, /*subtypeReduction*/ true); + type = getUnionType(types, UnionReduction.Subtype); } + const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!contextualSignature) { reportErrorsFromWidening(func, type); } @@ -17935,7 +18306,8 @@ namespace ts { return true; } - function checkAndAggregateReturnExpressionTypes(func: FunctionLikeDeclaration, checkMode: CheckMode): Type[] { + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ + function checkAndAggregateReturnExpressionTypes(func: FunctionLikeDeclaration, checkMode: CheckMode): Type[] | undefined { const functionFlags = getFunctionFlags(func); const aggregatedTypes: Type[] = []; let hasReturnWithNoExpression = functionHasImplicitReturn(func); @@ -17960,8 +18332,7 @@ namespace ts { hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction)) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -17969,6 +18340,17 @@ namespace ts { } return aggregatedTypes; } + function mayReturnNever(func: FunctionLikeDeclaration): boolean { + switch (func.kind) { + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return true; + case SyntaxKind.MethodDeclaration: + return func.parent.kind === SyntaxKind.ObjectLiteralExpression; + default: + return false; + } + } /** * TypeScript Specification 1.0 (6.3) - July 2014 @@ -18751,7 +19133,7 @@ namespace ts { leftType; case SyntaxKind.BarBarToken: return getTypeFacts(leftType) & TypeFacts.Falsy ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], UnionReduction.Subtype) : leftType; case SyntaxKind.EqualsToken: checkAssignmentOperator(rightType); @@ -18911,7 +19293,7 @@ namespace ts { checkExpression(node.condition); const type1 = checkExpression(node.whenTrue, checkMode); const type2 = checkExpression(node.whenFalse, checkMode); - return getUnionType([type1, type2], /*subtypeReduction*/ true); + return getUnionType([type1, type2], UnionReduction.Subtype); } function checkTemplateExpression(node: TemplateExpression): Type { @@ -18927,13 +19309,13 @@ namespace ts { return stringType; } - function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper: TypeMapper): Type { + function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper: TypeMapper | undefined): Type { const saveContextualType = node.contextualType; const saveContextualMapper = node.contextualMapper; node.contextualType = contextualType; node.contextualMapper = contextualMapper; const checkMode = contextualMapper === identityMapper ? CheckMode.SkipContextSensitive : - contextualMapper ? CheckMode.Inferential : CheckMode.Normal; + contextualMapper ? CheckMode.Inferential : CheckMode.Contextual; const result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -18943,6 +19325,9 @@ namespace ts { function checkExpressionCached(node: Expression, checkMode?: CheckMode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } // When computing a type that we're going to cache, we need to ignore any ongoing control flow // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart // to the top of the stack ensures all transient types are computed from a known point. @@ -18959,26 +19344,40 @@ namespace ts { return node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression; } - function checkDeclarationInitializer(declaration: VariableLikeDeclaration) { + function checkDeclarationInitializer(declaration: HasExpressionInitializer) { const type = getTypeOfExpression(declaration.initializer, /*cache*/ true); return getCombinedNodeFlags(declaration) & NodeFlags.Const || (getCombinedModifierFlags(declaration) & ModifierFlags.Readonly && !isParameterPropertyDeclaration(declaration)) || isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); } - function isLiteralLikeContextualType(contextualType: Type) { + function isLiteralOfContextualType(candidateType: Type, contextualType: Type): boolean { if (contextualType) { + if (contextualType.flags & TypeFlags.UnionOrIntersection && !(contextualType.flags & TypeFlags.Boolean)) { + // If the contextual type is a union containing both of the 'true' and 'false' types we + // don't consider it a literal context for boolean literals. + const types = (contextualType).types; + return some(types, t => + !(t.flags & TypeFlags.BooleanLiteral && containsType(types, trueType) && containsType(types, falseType)) && + isLiteralOfContextualType(candidateType, t)); + } if (contextualType.flags & TypeFlags.TypeVariable) { + // If the contextual type is a type variable constrained to a primitive type, consider + // this a literal context for literals of that primitive type. For example, given a + // type parameter 'T extends string', infer string literal types for T. const constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (constraint.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.Boolean | TypeFlags.Enum | TypeFlags.ESSymbol)) { - return true; - } - contextualType = constraint; - } - return maybeTypeOfKind(contextualType, (TypeFlags.Literal | TypeFlags.Index | TypeFlags.UniqueESSymbol)); + return constraint.flags & TypeFlags.String && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || + constraint.flags & TypeFlags.Number && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || + constraint.flags & TypeFlags.Boolean && maybeTypeOfKind(candidateType, TypeFlags.BooleanLiteral) || + constraint.flags & TypeFlags.ESSymbol && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol) || + isLiteralOfContextualType(candidateType, constraint); + } + // If the contextual type is a literal of a particular primitive type, we consider this a + // literal context for all literals of that primitive type. + return contextualType.flags & (TypeFlags.StringLiteral | TypeFlags.Index) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || + contextualType.flags & TypeFlags.NumberLiteral && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || + contextualType.flags & TypeFlags.BooleanLiteral && maybeTypeOfKind(candidateType, TypeFlags.BooleanLiteral) || + contextualType.flags & TypeFlags.UniqueESSymbol && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol); } return false; } @@ -19097,10 +19496,11 @@ namespace ts { const ok = (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).expression === node) || (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).expression === node) || - ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === SyntaxKind.TypeQuery && (node.parent).exprName === node)); if (!ok) { - error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -19194,11 +19594,11 @@ namespace ts { case SyntaxKind.JsxExpression: return checkJsxExpression(node, checkMode); case SyntaxKind.JsxElement: - return checkJsxElement(node); + return checkJsxElement(node, checkMode); case SyntaxKind.JsxSelfClosingElement: - return checkJsxSelfClosingElement(node); + return checkJsxSelfClosingElement(node, checkMode); case SyntaxKind.JsxFragment: - return checkJsxFragment(node); + return checkJsxFragment(node, checkMode); case SyntaxKind.JsxAttributes: return checkJsxAttributes(node, checkMode); case SyntaxKind.JsxOpeningElement: @@ -19252,7 +19652,7 @@ namespace ts { error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText as string); } if (func.kind === SyntaxKind.Constructor || func.kind === SyntaxKind.ConstructSignature || func.kind === SyntaxKind.ConstructorType) { @@ -19287,7 +19687,7 @@ namespace ts { return; } - const typePredicate = getSignatureFromDeclaration(parent).typePredicate; + const typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); if (!typePredicate) { return; } @@ -19305,7 +19705,7 @@ namespace ts { Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - const leadingError = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + const leadingError = () => chainDiagnosticMessages(/*details*/ undefined, Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, @@ -19627,7 +20027,7 @@ namespace ts { } } - function checkPropertyDeclaration(node: PropertyDeclaration) { + function checkPropertyDeclaration(node: PropertyDeclaration | PropertySignature) { // Grammar checking if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); @@ -19673,24 +20073,6 @@ namespace ts { return; } - function containsSuperCallAsComputedPropertyName(n: Declaration): boolean { - const name = getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - - function containsSuperCall(n: Node): boolean { - if (isSuperCall(n)) { - return true; - } - else if (isFunctionLike(n)) { - return false; - } - else if (isClassLike(n)) { - return forEach((n).members, containsSuperCallAsComputedPropertyName); - } - return forEachChild(n, containsSuperCall); - } - function isInstancePropertyWithInitializer(n: Node): boolean { return n.kind === SyntaxKind.PropertyDeclaration && !hasModifier(n, ModifierFlags.Static) && @@ -20338,7 +20720,7 @@ namespace ts { return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), UnionReduction.Subtype); } /** @@ -20377,7 +20759,7 @@ namespace ts { const promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -20610,7 +20992,7 @@ namespace ts { expectedReturnType, node, headMessage, - errorInfo); + () => errorInfo); } /** @@ -21012,20 +21394,33 @@ namespace ts { function checkUnusedClassMembers(node: ClassDeclaration | ClassExpression): void { if (compilerOptions.noUnusedLocals && !(node.flags & NodeFlags.Ambient)) { - if (node.members) { - for (const member of node.members) { - if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.PropertyDeclaration) { - if (!member.symbol.isReferenced && hasModifier(member, ModifierFlags.Private)) { - error(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(member.symbol)); + for (const member of node.members) { + switch (member.kind) { + case SyntaxKind.MethodDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + if (member.kind === SyntaxKind.SetAccessor && member.symbol.flags & SymbolFlags.GetAccessor) { + // Already would have reported an error on the getter. + break; } - } - else if (member.kind === SyntaxKind.Constructor) { + const symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && hasModifier(member, ModifierFlags.Private)) { + error(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case SyntaxKind.Constructor: for (const parameter of (member).parameters) { if (!parameter.symbol.isReferenced && hasModifier(parameter, ModifierFlags.Private)) { error(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol)); } } - } + break; + case SyntaxKind.IndexSignature: + // Can't be private + break; + default: + Debug.fail(); } } } @@ -21308,7 +21703,7 @@ namespace ts { } // Check that a parameter initializer contains no references to parameters declared to the right of itself - function checkParameterInitializer(node: VariableLikeDeclaration): void { + function checkParameterInitializer(node: HasExpressionInitializer): void { if (getRootDeclaration(node).kind !== SyntaxKind.Parameter) { return; } @@ -21380,9 +21775,11 @@ namespace ts { } // Check variable, parameter, or property declaration - function checkVariableLikeDeclaration(node: VariableLikeDeclaration) { + function checkVariableLikeDeclaration(node: ParameterDeclaration | PropertyDeclaration | PropertySignature | VariableDeclaration | BindingElement) { checkDecorators(node); - checkSourceElement(node.type); + if (!isBindingElement(node)) { + checkSourceElement(node.type); + } // JSDoc `function(string, string): string` syntax results in parameters with no name if (!node.name) { @@ -21393,7 +21790,7 @@ namespace ts { // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. if (node.name.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(node.name); + checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } @@ -21405,11 +21802,11 @@ namespace ts { } // check computed properties inside property names of binding elements if (node.propertyName && node.propertyName.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(node.propertyName); + checkComputedPropertyName(node.propertyName); } // check private/protected variable access - const parent = (node.parent).parent; + const parent = node.parent.parent; const parentType = getTypeForBindingElementParent(parent); const name = node.propertyName || node.name; const property = getPropertyOfType(parentType, getTextOfPropertyName(name)); @@ -21442,7 +21839,7 @@ namespace ts { return; } const symbol = getSymbolOfNode(node); - const type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + const type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -21670,7 +22067,7 @@ namespace ts { checkGrammarForInOrForOfStatement(node); const rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -21769,7 +22166,7 @@ namespace ts { const arrayTypes = (inputType).types; const filteredTypes = filter(arrayTypes, t => !(t.flags & TypeFlags.StringLike)); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + arrayType = getUnionType(filteredTypes, UnionReduction.Subtype); } } else if (arrayType.flags & TypeFlags.StringLike) { @@ -21819,7 +22216,7 @@ namespace ts { return stringType; } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + return getUnionType([arrayElementType, stringType], UnionReduction.Subtype); } return arrayElementType; @@ -21917,7 +22314,7 @@ namespace ts { return undefined; } - const returnType = getUnionType(map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + const returnType = getUnionType(map(signatures, getReturnTypeOfSignature), UnionReduction.Subtype); const iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { // If `checkAssignability` was specified, we were called from @@ -21992,7 +22389,7 @@ namespace ts { return undefined; } - let nextResult = getUnionType(map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + let nextResult = getUnionType(map(nextMethodSignatures, getReturnTypeOfSignature), UnionReduction.Subtype); if (isTypeAny(nextResult)) { return undefined; } @@ -22056,57 +22453,58 @@ namespace ts { function checkReturnStatement(node: ReturnStatement) { // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - const functionBlock = getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } + if (checkGrammarStatementInAmbientContext(node)) { + return; } const func = getContainingFunction(node); - if (func) { - const signature = getSignatureFromDeclaration(func); - const returnType = getReturnTypeOfSignature(signature); - const functionFlags = getFunctionFlags(func); - if (functionFlags & FunctionFlags.Generator) { // AsyncGenerator function or Generator function + if (!func) { + grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + + const signature = getSignatureFromDeclaration(func); + const returnType = getReturnTypeOfSignature(signature); + const functionFlags = getFunctionFlags(func); + const isGenerator = functionFlags & FunctionFlags.Generator; + if (strictNullChecks || node.expression || returnType.flags & TypeFlags.Never) { + const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added + // TODO: Check return types of generators when return type tracking is added // for generators. return; } - if (strictNullChecks || node.expression || returnType.flags & TypeFlags.Never) { - const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === SyntaxKind.SetAccessor) { - if (node.expression) { - error(node, Diagnostics.Setters_cannot_return_a_value); - } + else if (func.kind === SyntaxKind.SetAccessor) { + if (node.expression) { + error(node, Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === SyntaxKind.Constructor) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } + } + else if (func.kind === SyntaxKind.Constructor) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } - else if (getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & FunctionFlags.Async) { // Async function - const promisedType = getPromisedTypeOfPromise(returnType); - const awaitedType = checkAwaitedType(exprType, node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - // If the function has a return type, but promisedType is - // undefined, an error will be reported in checkAsyncFunctionReturnType - // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); + } + else if (getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & FunctionFlags.Async) { // Async function + const promisedType = getPromisedTypeOfPromise(returnType); + const awaitedType = checkAwaitedType(exprType, node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); } } + else { + checkTypeAssignableTo(exprType, returnType, node); + } } - else if (func.kind !== SyntaxKind.Constructor && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - // The function has a return type, but the return statement doesn't have an expression. - error(node, Diagnostics.Not_all_code_paths_return_a_value); - } + } + else if (func.kind !== SyntaxKind.Constructor && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, Diagnostics.Not_all_code_paths_return_a_value); } } @@ -22431,9 +22829,11 @@ namespace ts { // type parameter at this position, we report an error. const sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); const targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } } // If the type parameter node has a default and it is not identical to the default @@ -22515,7 +22915,10 @@ namespace ts { } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_extends_base_class_1); + const baseWithThis = getTypeWithThisArgument(baseType, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & TypeFlags.TypeVariable && !isMixinConstructorType(staticType)) { @@ -22547,7 +22950,13 @@ namespace ts { const t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1); + const genericDiag = t.symbol && t.symbol.flags & SymbolFlags.Class ? + Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + Diagnostics.Class_0_incorrectly_implements_interface_1; + const baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -22564,6 +22973,37 @@ namespace ts { } } + function issueMemberSpecificError(node: ClassLikeDeclaration, typeWithThis: Type, baseWithThis: Type, broadDiag: DiagnosticMessage) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + let issuedMemberError = false; + for (const member of node.members) { + if (hasStaticModifier(member)) { + continue; + } + const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + const rootChain = () => chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, + unescapeLeadingUnderscores(declaredProp.escapedName), + typeToString(typeWithThis), + typeToString(getTypeOfSymbol(baseProp)) + ); + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type: Type, node: ExpressionWithTypeArguments) { const signatures = getSignaturesOfType(type, SignatureKind.Construct); if (signatures.length) { @@ -22583,10 +23023,6 @@ namespace ts { return getCheckFlags(s) & CheckFlags.Instantiated ? (s).target : s; } - function getClassLikeDeclarationOfSymbol(symbol: Symbol): Declaration { - return forEach(symbol.declarations, d => isClassLike(d) ? d : undefined); - } - function getClassOrInterfaceDeclarationsOfSymbol(symbol: Symbol) { return filter(symbol.declarations, (d: Declaration): d is ClassDeclaration | InterfaceDeclaration => d.kind === SyntaxKind.ClassDeclaration || d.kind === SyntaxKind.InterfaceDeclaration); @@ -22901,6 +23337,7 @@ namespace ts { case SyntaxKind.PlusToken: return left + right; case SyntaxKind.MinusToken: return left - right; case SyntaxKind.PercentToken: return left % right; + case SyntaxKind.AsteriskAsteriskToken: return left ** right; } } break; @@ -23549,7 +23986,7 @@ namespace ts { return checkParameter(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - return checkPropertyDeclaration(node); + return checkPropertyDeclaration(node); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.CallSignature: @@ -24257,6 +24694,7 @@ namespace ts { return undefined; case SyntaxKind.StringLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript @@ -24357,7 +24795,7 @@ namespace ts { } if (isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); } if (isInRightSideOfImportOrExportAssignment(node)) { @@ -24402,7 +24840,7 @@ namespace ts { const typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); const elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, - indexOf((expr.parent).elements, expr), elementType || unknownType); + (expr.parent).elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment @@ -24455,36 +24893,28 @@ namespace ts { } function getRootSymbols(symbol: Symbol): Symbol[] { + const roots = getImmediateRootSymbols(symbol); + return roots ? flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol: Symbol): ReadonlyArray | undefined { if (getCheckFlags(symbol) & CheckFlags.Synthetic) { - const symbols: Symbol[] = []; - const name = symbol.escapedName; - forEach(getSymbolLinks(symbol).containingType.types, t => { - const symbol = getPropertyOfType(t, name); - if (symbol) { - symbols.push(symbol); - } - }); - return symbols; + return mapDefined(getSymbolLinks(symbol).containingType.types, type => getPropertyOfType(type, symbol.escapedName)); } else if (symbol.flags & SymbolFlags.Transient) { - const transient = symbol as TransientSymbol; - if (transient.leftSpread) { - return [...getRootSymbols(transient.leftSpread), ...getRootSymbols(transient.rightSpread)]; - } - if (transient.syntheticOrigin) { - return getRootSymbols(transient.syntheticOrigin); - } - - let target: Symbol; - let next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } + const { leftSpread, rightSpread, syntheticOrigin } = symbol as TransientSymbol; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol: Symbol): Symbol | undefined { + let target: Symbol | undefined; + let next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; } - return [symbol]; + return target; } // Emitter support @@ -24605,7 +25035,7 @@ namespace ts { // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -25066,7 +25496,7 @@ namespace ts { // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope // external modules cannot define or contribute to type declaration files - let current = symbol; + let current = symbol; while (true) { const parent = getParentOfSymbol(current); if (parent) { @@ -25156,7 +25586,12 @@ namespace ts { globalBooleanType = getGlobalType("Boolean" as __String, /*arity*/ 0, /*reportErrors*/ true); globalRegExpType = getGlobalType("RegExp" as __String, /*arity*/ 0, /*reportErrors*/ true); anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type + autoArrayType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + } globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray" as __String, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; @@ -25525,10 +25960,6 @@ namespace ts { } function checkGrammarTypeParameterList(typeParameters: NodeArray, file: SourceFile): boolean { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } - if (typeParameters && typeParameters.length === 0) { const start = typeParameters.pos - "<".length; const end = skipTrivia(file.text, typeParameters.end) + ">".length; @@ -25622,6 +26053,21 @@ namespace ts { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== SyntaxKind.StringKeyword && parameter.type.kind !== SyntaxKind.NumberKeyword) { + const type = getTypeFromTypeNode(parameter.type); + + if (type.flags & TypeFlags.String || type.flags & TypeFlags.Number) { + return grammarErrorOnNode(parameter.name, + Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, + getTextOfNode(parameter.name), + typeToString(type), + typeToString(getTypeFromTypeNode(node.type))); + } + + if (allTypesAssignableToKind(type, TypeFlags.StringLiteral, /*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); } if (!node.type) { @@ -26333,7 +26779,7 @@ namespace ts { } } - function checkGrammarProperty(node: PropertyDeclaration) { + function checkGrammarProperty(node: PropertyDeclaration | PropertySignature) { if (isClassLike(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; @@ -26360,7 +26806,7 @@ namespace ts { return grammarErrorOnFirstToken(node.initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || + if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & NodeFlags.Ambient || hasModifier(node, ModifierFlags.Static | ModifierFlags.Abstract))) { return grammarErrorOnNode(node.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 989bb6a7142d2..4813d4b4300aa 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -82,12 +82,13 @@ namespace ts { es2015: ScriptTarget.ES2015, es2016: ScriptTarget.ES2016, es2017: ScriptTarget.ES2017, + es2018: ScriptTarget.ES2018, esnext: ScriptTarget.ESNext, }), paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, - description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT, + description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, }, { name: "module", @@ -120,6 +121,7 @@ namespace ts { "es7": "lib.es2016.d.ts", "es2016": "lib.es2016.d.ts", "es2017": "lib.es2017.d.ts", + "es2018": "lib.es2018.d.ts", "esnext": "lib.esnext.d.ts", // Host only "dom": "lib.dom.d.ts", @@ -142,7 +144,9 @@ namespace ts { "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, @@ -398,6 +402,13 @@ namespace ts { category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Module_Resolution_Options, + description: Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -700,7 +711,8 @@ namespace ts { export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, target: ScriptTarget.ES5, - strict: true + strict: true, + esModuleInterop: true }; let optionNameMapCache: OptionNameMap; @@ -709,12 +721,11 @@ namespace ts { export function convertEnableAutoDiscoveryToEnable(typeAcquisition: TypeAcquisition): TypeAcquisition { // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - const result: TypeAcquisition = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -1797,9 +1808,8 @@ namespace ts { return options; } - function getDefaultTypeAcquisition(configFileName?: string) { - const options: TypeAcquisition = { enable: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + function getDefaultTypeAcquisition(configFileName?: string): TypeAcquisition { + return { enable: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions: any, @@ -1863,7 +1873,7 @@ namespace ts { return normalizeNonListOptionValue(option, basePath, value); } - function normalizeNonListOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { + function normalizeNonListOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (option.isFilePath) { value = normalizePath(combinePaths(basePath, value)); if (value === "") { @@ -1906,21 +1916,6 @@ namespace ts { */ const invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - /** - * Tests for a path with multiple recursive directory wildcards. - * Matches **\** and **\a\**, but not **\a**b. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. - * (.*\/)? # optionally matches any number of characters followed by a directory separator. - * \*\* # matches a recursive directory wildcard "**" - * ($|\/) # matches either the end of the string or a directory separator. - */ - const invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; - /** * Tests for a path where .. appears after a recursive directory wildcard. * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* @@ -2115,9 +2110,6 @@ namespace ts { if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index c40b36281e774..918dbbd51c0c0 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -191,6 +191,19 @@ namespace ts { return undefined; } + export function firstDefinedIterator(iter: Iterator, callback: (element: T) => U | undefined): U | undefined { + while (true) { + const { value, done } = iter.next(); + if (done) { + return undefined; + } + const result = callback(value); + if (result !== undefined) { + return result; + } + } + } + /** * Iterates through the parent chain of a node and performs the callback on each parent until the callback * returns a truthy value, then returns that value. @@ -215,13 +228,27 @@ namespace ts { export function zipWith(arrayA: ReadonlyArray, arrayB: ReadonlyArray, callback: (a: T, b: U, index: number) => V): V[] { const result: V[] = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (let i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } + export function zipToIterator(arrayA: ReadonlyArray, arrayB: ReadonlyArray): Iterator<[T, U]> { + Debug.assertEqual(arrayA.length, arrayB.length); + let i = 0; + return { + next() { + if (i === arrayA.length) { + return { value: undefined as never, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + export function zipToMap(keys: ReadonlyArray, values: ReadonlyArray): Map { Debug.assert(keys.length === values.length); const map = createMap(); @@ -261,6 +288,8 @@ namespace ts { return undefined; } + export function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => element is U): U | undefined; + export function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined; export function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined { for (let i = array.length - 1; i >= 0; i--) { const value = array[i]; @@ -306,17 +335,6 @@ namespace ts { return false; } - export function indexOf(array: ReadonlyArray, value: T): number { - if (array) { - for (let i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - export function indexOfAnyCharCode(text: string, charCodes: ReadonlyArray, start?: number): number { for (let i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -476,22 +494,32 @@ namespace ts { return result; } - export function flatMapIter(iter: Iterator, mapfn: (x: T) => U | U[] | undefined): U[] { - const result: U[] = []; - while (true) { - const { value, done } = iter.next(); - if (done) break; - const res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push(...res); - } - else { - result.push(res); + export function flatMapIterator(iter: Iterator, mapfn: (x: T) => U[] | Iterator | undefined): Iterator { + const first = iter.next(); + if (first.done) { + return emptyIterator; + } + let currentIter = getIterator(first.value); + return { + next() { + while (true) { + const currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + const iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + + function getIterator(x: T): Iterator { + const res = mapfn(x); + return res === undefined ? emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } /** @@ -550,17 +578,34 @@ namespace ts { return result; } - export function mapDefinedIter(iter: Iterator, mapFn: (x: T) => U | undefined): U[] { - const result: U[] = []; - while (true) { - const { value, done } = iter.next(); - if (done) break; - const res = mapFn(value); - if (res !== undefined) { - result.push(res); + export function mapDefinedIterator(iter: Iterator, mapFn: (x: T) => U | undefined): Iterator { + return { + next() { + while (true) { + const res = iter.next(); + if (res.done) { + return res; + } + const value = mapFn(res.value); + if (value !== undefined) { + return { value, done: false }; + } + } } - } - return result; + }; + } + + export const emptyIterator: Iterator = { next: () => ({ value: undefined as never, done: true }) }; + + export function singleIterator(value: T): Iterator { + let done = false; + return { + next() { + const wasDone = done; + done = true; + return wasDone ? { value: undefined as never, done: true } : { value, done: false }; + } + }; } /** @@ -1358,7 +1403,6 @@ namespace ts { this.set(key, values = [value]); } return values; - } function multiMapRemove(this: MultiMap, key: string, value: T) { const values = this.get(key); @@ -1373,12 +1417,12 @@ namespace ts { /** * Tests whether a value is an array. */ - export function isArray(value: any): value is ReadonlyArray { + export function isArray(value: any): value is ReadonlyArray<{}> { return Array.isArray ? Array.isArray(value) : value instanceof Array; } - export function toArray(value: T | ReadonlyArray): ReadonlyArray; export function toArray(value: T | T[]): T[]; + export function toArray(value: T | ReadonlyArray): ReadonlyArray; export function toArray(value: T | T[]): T[] { return isArray(value) ? value : [value]; } @@ -1952,11 +1996,6 @@ namespace ts { return /^\.\.?($|[\\/])/.test(path); } - /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ - export function moduleHasNonRelativeName(moduleName: string): boolean { - return !isExternalModuleNameRelative(moduleName); - } - export function getEmitScriptTarget(compilerOptions: CompilerOptions) { return compilerOptions.target || ScriptTarget.ES3; } @@ -1979,7 +2018,9 @@ namespace ts { const moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ModuleKind.None && moduleKind < ModuleKind.ES2015 + : moduleKind === ModuleKind.System; } export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictPropertyInitialization" | "alwaysStrict"; @@ -2043,7 +2084,7 @@ namespace ts { function getNormalizedPathComponentsOfUrl(url: string) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] const urlLength = url.length; @@ -2076,7 +2117,7 @@ namespace ts { } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + directorySeparator]; @@ -2097,7 +2138,7 @@ namespace ts { const directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } @@ -2339,7 +2380,6 @@ namespace ts { function getSubPatternFromSpec(spec: string, basePath: string, usage: "files" | "directories" | "exclude", { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter }: WildcardMatcher): string | undefined { let subpattern = ""; - let hasRecursiveDirectoryWildcard = false; let hasWrittenComponent = false; const components = getNormalizedPathComponents(spec, basePath); const lastComponent = lastOrUndefined(components); @@ -2358,12 +2398,7 @@ namespace ts { let optionalCount = 0; for (let component of components) { if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } - subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -3226,4 +3261,8 @@ namespace ts { cachedReadDirectoryResult.clear(); } } + + export function singleElementArray(t: T | undefined): T[] | undefined { + return t === undefined ? undefined : [t]; + } } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index dc76e0ddf5028..b85c79e775cad 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -64,7 +64,7 @@ namespace ts { let currentIdentifiers: Map; let isCurrentFileExternalModule: boolean; let reportedDeclarationError = false; - let errorNameNode: DeclarationName; + let errorNameNode: DeclarationName | QualifiedName; const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; let needsDeclare = true; @@ -148,8 +148,8 @@ namespace ts { moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -651,6 +651,9 @@ namespace ts { } function emitExportAssignment(node: ExportAssignment) { + if (isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === SyntaxKind.Identifier) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -745,6 +748,7 @@ namespace ts { const modifiers = getModifierFlags(node); // If the node is exported if (modifiers & ModifierFlags.Export) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } @@ -901,6 +905,7 @@ namespace ts { } function emitExportDeclaration(node: ExportDeclaration) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -1199,7 +1204,7 @@ namespace ts { write(">"); } } - else { + else { emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); } } @@ -1372,7 +1377,7 @@ namespace ts { // if this is property of type literal, // or is parameter of method/call/construct/index signature of type literal // emit only if type is specified - if (node.type) { + if (hasType(node)) { write(": "); emitType(node.type); } @@ -1866,6 +1871,7 @@ namespace ts { // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 747d19718fc24..96be3e99fdc70 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -939,6 +939,14 @@ "category": "Error", "code": 1335 }, + "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead.": { + "category": "Error", + "code": 1336 + }, + "An index signature parameter type cannot be a union type. Consider using a mapped object type instead.": { + "category": "Error", + "code": 1337 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -1396,6 +1404,10 @@ "category": "Error", "code": 2415 }, + "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'.": { + "category": "Error", + "code": 2416 + }, "Class static side '{0}' incorrectly extends base class static side '{1}'.": { "category": "Error", "code": 2417 @@ -1612,7 +1624,7 @@ "category": "Error", "code": 2474 }, - "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.": { + "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.": { "category": "Error", "code": 2475 }, @@ -2272,7 +2284,26 @@ "category": "Error", "code": 2718 }, - + "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated.": { + "category": "Error", + "code": 2719 + }, + "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?": { + "category": "Error", + "code": 2720 + }, + "Cannot invoke an object which is possibly 'null'.": { + "category": "Error", + "code": 2721 + }, + "Cannot invoke an object which is possibly 'undefined'.": { + "category": "Error", + "code": 2722 + }, + "Cannot invoke an object which is possibly 'null' or 'undefined'.": { + "category": "Error", + "code": 2723 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", "code": 4000 @@ -2619,10 +2650,6 @@ "category": "Error", "code": 5010 }, - "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'.": { - "category": "Error", - "code": 5011 - }, "Cannot read file '{0}': {1}.": { "category": "Error", "code": 5012 @@ -2719,6 +2746,11 @@ "category": "Error", "code": 5067 }, + "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.": { + "category": "Error", + "code": 5068 + }, + "Concatenate and emit output to single file.": { "category": "Message", "code": 6001 @@ -2771,7 +2803,7 @@ "category": "Message", "code": 6013 }, - "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'.": { + "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.": { "category": "Message", "code": 6015 }, @@ -2819,6 +2851,10 @@ "category": "Message", "code": 6030 }, + "Starting compilation in watch mode...": { + "category": "Message", + "code": 6031 + }, "File change detected. Starting incremental compilation...": { "category": "Message", "code": 6032 @@ -3407,6 +3443,14 @@ "category": "Message", "code": 6187 }, + "Numeric separators are not allowed here.": { + "category": "Error", + "code": 6188 + }, + "Multiple consecutive numeric separators are not permitted.": { + "category": "Error", + "code": 6189 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", "code": 7005 @@ -3519,6 +3563,14 @@ "category": "Error", "code": 7036 }, + "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.": { + "category": "Message", + "code": 7037 + }, + "A namespace-style import cannot be called or constructed, and will cause a failure at runtime.": { + "category": "Error", + "code": 7038 + }, "You cannot rename this element.": { "category": "Error", @@ -3710,7 +3762,7 @@ }, "JSX fragment is not supported when using --jsxFactory": { "category": "Error", - "code":17016 + "code": 17016 }, "Circularity detected while resolving configuration: {0}": { @@ -3730,104 +3782,95 @@ "code": 18003 }, - "Add missing 'super()' call.": { + "Add missing 'super()' call": { "category": "Message", "code": 90001 }, - "Make 'super()' call the first statement in the constructor.": { + "Make 'super()' call the first statement in the constructor": { "category": "Message", "code": 90002 }, - "Change 'extends' to 'implements'.": { + "Change 'extends' to 'implements'": { "category": "Message", "code": 90003 }, - "Remove declaration for: '{0}'.": { + "Remove declaration for: '{0}'": { "category": "Message", "code": 90004 }, - "Implement interface '{0}'.": { + "Implement interface '{0}'": { "category": "Message", "code": 90006 }, - "Implement inherited abstract class.": { + "Implement inherited abstract class": { "category": "Message", "code": 90007 }, - "Add 'this.' to unresolved variable.": { + "Add 'this.' to unresolved variable": { "category": "Message", "code": 90008 }, - "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.": { - "category": "Error", - "code": 90009 - }, - "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated.": { - "category": "Error", - "code": 90010 - }, - "Import '{0}' from module \"{1}\".": { + "Import '{0}' from module \"{1}\"": { "category": "Message", "code": 90013 }, - "Change '{0}' to '{1}'.": { + "Change '{0}' to '{1}'": { "category": "Message", "code": 90014 }, - "Add '{0}' to existing import declaration from \"{1}\".": { + "Add '{0}' to existing import declaration from \"{1}\"": { "category": "Message", "code": 90015 }, - "Declare property '{0}'.": { + "Declare property '{0}'": { "category": "Message", "code": 90016 }, - "Add index signature for property '{0}'.": { + "Add index signature for property '{0}'": { "category": "Message", "code": 90017 }, - - "Disable checking for this file.": { + "Disable checking for this file": { "category": "Message", "code": 90018 }, - "Ignore this error message.": { + "Ignore this error message": { "category": "Message", "code": 90019 }, - "Initialize property '{0}' in the constructor.": { + "Initialize property '{0}' in the constructor": { "category": "Message", "code": 90020 }, - "Initialize static property '{0}'.": { + "Initialize static property '{0}'": { "category": "Message", "code": 90021 }, - "Change spelling to '{0}'.": { + "Change spelling to '{0}'": { "category": "Message", "code": 90022 }, - "Declare method '{0}'.": { + "Declare method '{0}'": { "category": "Message", "code": 90023 }, - "Declare static method '{0}'.": { + "Declare static method '{0}'": { "category": "Message", "code": 90024 }, - "Prefix '{0}' with an underscore.": { + "Prefix '{0}' with an underscore": { "category": "Message", "code": 90025 }, - "Rewrite as the indexed access type '{0}'.": { + "Rewrite as the indexed access type '{0}'": { "category": "Message", "code": 90026 }, - "Declare static property '{0}'.": { + "Declare static property '{0}'": { "category": "Message", "code": 90027 }, - "Call decorator expression.": { + "Call decorator expression": { "category": "Message", "code": 90028 }, @@ -3871,11 +3914,11 @@ "category": "Message", "code": 95010 }, - "Infer type of '{0}' from usage.": { + "Infer type of '{0}' from usage": { "category": "Message", "code": 95011 }, - "Infer parameter types from usage.": { + "Infer parameter types from usage": { "category": "Message", "code": 95012 }, @@ -3887,6 +3930,14 @@ "category": "Message", "code": 95014 }, + "Replace import with '{0}'.": { + "category": "Message", + "code": 95015 + }, + "Use synthetic 'default' member.": { + "category": "Message", + "code": 95016 + }, "Convert to ES6 module": { "category": "Message", "code": 95017 diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index eb8841207caed..7ddc8a0cd5f3c 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3831,13 +3831,13 @@ namespace ts { if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === Associativity.Right; } else { diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index b0633ef4d5a26..1cc11acd32daf 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -64,9 +64,9 @@ namespace ts { return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved: Resolved | undefined, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { + function createResolvedModuleWithFailedLookupLocations(resolved: Resolved | undefined, originalPath: string | undefined, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath, extension: resolved.extension, isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations }; } @@ -732,12 +732,12 @@ namespace ts { const result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - const { resolved, isExternalLibraryImport } = result.value; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + const { resolved, originalPath, isExternalLibraryImport } = result.value; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations }; - function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> { + function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, originalPath?: string, isExternalLibraryImport: boolean }> { const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { @@ -752,11 +752,17 @@ namespace ts { if (!resolved) return undefined; let resolvedValue = resolved.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && { ...resolved.value, path: realPath(resolved.value.path, host, traceEnabled), extension: resolved.value.extension }; + let originalPath: string | undefined; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + const path = realPath(resolved.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = { ...resolvedValue, path }; } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath, isExternalLibraryImport: true } }; } else { const { path: candidate, parts } = normalizePathAndParts(combinePaths(containingDirectory, moduleName)); @@ -1115,7 +1121,8 @@ namespace ts { const containingDirectory = getDirectoryPath(containingFile); const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions: Extensions): SearchResult { const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); @@ -1162,7 +1169,7 @@ namespace ts { const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; const resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); } /** diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index cb28be4677a5b..bae9f0594ed19 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -88,20 +88,48 @@ namespace ts { case SyntaxKind.SpreadAssignment: return visitNode(cbNode, (node).expression); case SyntaxKind.Parameter: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, (node).dotDotDotToken) || + visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).type) || + visitNode(cbNode, (node).initializer); case SyntaxKind.PropertyDeclaration: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).exclamationToken) || + visitNode(cbNode, (node).type) || + visitNode(cbNode, (node).initializer); case SyntaxKind.PropertySignature: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).type) || + visitNode(cbNode, (node).initializer); case SyntaxKind.PropertyAssignment: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).initializer); case SyntaxKind.VariableDeclaration: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).exclamationToken) || + visitNode(cbNode, (node).type) || + visitNode(cbNode, (node).initializer); case SyntaxKind.BindingElement: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).propertyName) || - visitNode(cbNode, (node).dotDotDotToken) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).exclamationToken) || - visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node).propertyName) || + visitNode(cbNode, (node).dotDotDotToken) || + visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).initializer); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.CallSignature: @@ -557,7 +585,7 @@ namespace ts { // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -673,7 +701,7 @@ namespace ts { function getLanguageVariant(scriptKind: ScriptKind) { // .tsx and .jsx files are treated as jsx language variant. - return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSON ? LanguageVariant.JSX : LanguageVariant.Standard; + return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSON ? LanguageVariant.JSX : LanguageVariant.Standard; } function initializeState(_sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, scriptKind: ScriptKind) { @@ -1401,9 +1429,13 @@ namespace ts { return token() === SyntaxKind.CommaToken || token() === SyntaxKind.DotDotDotToken || isIdentifierOrPattern(); case ParsingContext.TypeParameters: return isIdentifier(); - case ParsingContext.ArgumentExpressions: case ParsingContext.ArrayLiteralMembers: - return token() === SyntaxKind.CommaToken || token() === SyntaxKind.DotDotDotToken || isStartOfExpression(); + if (token() === SyntaxKind.CommaToken) { + return true; + } + // falls through + case ParsingContext.ArgumentExpressions: + return token() === SyntaxKind.DotDotDotToken || isStartOfExpression(); case ParsingContext.Parameters: return isStartOfParameter(); case ParsingContext.TypeArguments: @@ -1425,7 +1457,7 @@ namespace ts { function isValidHeritageClauseObjectLiteral() { Debug.assert(token() === SyntaxKind.OpenBraceToken); if (nextToken() === SyntaxKind.CloseBraceToken) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -1521,7 +1553,7 @@ namespace ts { function isVariableDeclaratorListTerminator(): boolean { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -1647,6 +1679,11 @@ namespace ts { return undefined; } + if ((node as JSDocContainer).jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + (node as JSDocContainer).jsDocCache = undefined; + } + return node; } @@ -2241,7 +2278,7 @@ namespace ts { // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -3061,7 +3098,7 @@ namespace ts { // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. const arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -3091,7 +3128,7 @@ namespace ts { // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -3247,7 +3284,7 @@ namespace ts { if (first === SyntaxKind.OpenParenToken) { if (second === SyntaxKind.CloseParenToken) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -3472,7 +3509,9 @@ namespace ts { node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(SyntaxKind.ColonToken, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)); return finishNode(node); } @@ -3867,7 +3906,8 @@ namespace ts { // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= NodeFlags.PossiblyContainsDynamicImport; expression = parseTokenNode(); } @@ -3917,7 +3957,7 @@ namespace ts { // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -4333,7 +4373,7 @@ namespace ts { const typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); if (!parseExpected(SyntaxKind.GreaterThanToken)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } @@ -5366,8 +5406,8 @@ namespace ts { // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = hasModifier(node, ModifierFlags.Static) @@ -5462,6 +5502,7 @@ namespace ts { switch (token()) { case SyntaxKind.OpenParenToken: // Method declaration case SyntaxKind.LessThanToken: // Generic Method declaration + case SyntaxKind.ExclamationToken: // Non-null assertion on property name case SyntaxKind.ColonToken: // Type Annotation for declaration case SyntaxKind.EqualsToken: // Initializer for declaration case SyntaxKind.QuestionToken: // Not valid, but permitted so that it gets caught later on. @@ -6240,17 +6281,17 @@ namespace ts { indent += text.length; } - nextJSDocToken(); - while (token() === SyntaxKind.WhitespaceTrivia) { - nextJSDocToken(); + let t = nextJSDocToken(); + while (t === SyntaxKind.WhitespaceTrivia) { + t = nextJSDocToken(); } - if (token() === SyntaxKind.NewLineTrivia) { + if (t === SyntaxKind.NewLineTrivia) { state = JSDocState.BeginningOfLine; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== SyntaxKind.EndOfFileToken) { - switch (token()) { + loop: while (true) { + switch (t) { case SyntaxKind.AtToken: if (state === JSDocState.BeginningOfLine || state === JSDocState.SawAsterisk) { removeTrailingNewlines(comments); @@ -6304,7 +6345,7 @@ namespace ts { indent += whitespace.length; break; case SyntaxKind.EndOfFileToken: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = JSDocState.SavingComments; @@ -6312,10 +6353,11 @@ namespace ts { break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken as JsDocSyntaxKind; } } removeLeadingNewlines(comments); @@ -6426,8 +6468,9 @@ namespace ts { comments.push(text); indent += text.length; } - while (token() !== SyntaxKind.AtToken && token() !== SyntaxKind.EndOfFileToken) { - switch (token()) { + let tok = token() as JsDocSyntaxKind; + loop: while (true) { + switch (tok) { case SyntaxKind.NewLineTrivia: if (state >= JSDocState.SawAsterisk) { state = JSDocState.BeginningOfLine; @@ -6436,8 +6479,9 @@ namespace ts { indent = 0; break; case SyntaxKind.AtToken: + case SyntaxKind.EndOfFileToken: // Done - break; + break loop; case SyntaxKind.WhitespaceTrivia: if (state === JSDocState.SavingComments) { pushComment(scanner.getTokenText()); @@ -6465,11 +6509,7 @@ namespace ts { pushComment(scanner.getTokenText()); break; } - if (token() === SyntaxKind.AtToken) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); @@ -6747,8 +6787,7 @@ namespace ts { let canParseTag = true; let seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case SyntaxKind.AtToken: if (canParseTag) { const child = tryParseChildTag(target); @@ -6844,7 +6883,7 @@ namespace ts { return result; } - function nextJSDocToken(): SyntaxKind { + function nextJSDocToken(): JsDocSyntaxKind { return currentToken = scanner.scanJSDocToken(); } @@ -7048,7 +7087,7 @@ namespace ts { // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -7073,7 +7112,7 @@ namespace ts { // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 4088a6951a17e..88a2f5ee8f1f1 100755 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -6,7 +6,7 @@ namespace ts { const ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; - export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string { + export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string | undefined { return forEachAncestorDirectory(searchPath, ancestor => { const fileName = combinePaths(ancestor, configName); return fileExists(fileName) ? fileName : undefined; @@ -241,22 +241,28 @@ namespace ts { return errorMessage; } - const redForegroundEscapeSequence = "\u001b[91m"; - const yellowForegroundEscapeSequence = "\u001b[93m"; - const blueForegroundEscapeSequence = "\u001b[93m"; + /** @internal */ + export enum ForegroundColorEscapeSequences { + Grey = "\u001b[90m", + Red = "\u001b[91m", + Yellow = "\u001b[93m", + Blue = "\u001b[94m", + Cyan = "\u001b[96m" + } const gutterStyleSequence = "\u001b[30;47m"; const gutterSeparator = " "; const resetEscapeSequence = "\u001b[0m"; const ellipsis = "..."; function getCategoryFormat(category: DiagnosticCategory): string { switch (category) { - case DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case DiagnosticCategory.Error: return redForegroundEscapeSequence; - case DiagnosticCategory.Message: return blueForegroundEscapeSequence; + case DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } - function formatAndReset(text: string, formatStyle: string) { + /** @internal */ + export function formatColorAndReset(text: string, formatStyle: string) { return formatStyle + text + resetEscapeSequence; } @@ -289,7 +295,7 @@ namespace ts { // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } @@ -300,12 +306,12 @@ namespace ts { lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += redForegroundEscapeSequence; + context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. @@ -324,13 +330,19 @@ namespace ts { context += resetEscapeSequence; } - output += host.getNewLine(); - output += `${ relativeFileName }(${ firstLine + 1 },${ firstLineChar + 1 }): `; + output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += formatColorAndReset(`${ firstLine + 1 }`, ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += formatColorAndReset(`${ firstLineChar + 1 }`, ForegroundColorEscapeSequences.Yellow); + output += " - "; } const categoryColor = getCategoryFormat(diagnostic.category); const category = DiagnosticCategory[diagnostic.category].toLowerCase(); - output += `${ formatAndReset(category, categoryColor) } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) }`; + output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(` TS${ diagnostic.code }: `, ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); @@ -339,7 +351,7 @@ namespace ts { output += host.getNewLine(); } - return output; + return output + host.getNewLine(); } export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string { @@ -704,7 +716,7 @@ namespace ts { interface OldProgramState { program: Program | undefined; - file: SourceFile; + oldSourceFile: SourceFile | undefined; /** The collection of paths modified *since* the old program. */ modifiedFilePaths: Path[]; } @@ -754,7 +766,6 @@ namespace ts { /** A transient placeholder used to mark predicted resolution in the result list. */ const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = {}; - for (let i = 0; i < moduleNames.length; i++) { const moduleName = moduleNames[i]; // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions @@ -825,9 +836,13 @@ namespace ts { // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string, oldProgramState: OldProgramState): boolean { - const resolutionToFile = getResolvedModule(oldProgramState.file, moduleName); - if (resolutionToFile) { - // module used to be resolved to file - ignore it + const resolutionToFile = getResolvedModule(oldProgramState.oldSourceFile, moduleName); + const resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. return false; } const ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); @@ -1001,7 +1016,7 @@ namespace ts { const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { const moduleNames = getModuleNames(newSourceFile); - const oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths }; + const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile, modifiedFilePaths }; const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo); @@ -1586,6 +1601,7 @@ namespace ts { // synthesize 'import "tslib"' declaration const externalHelpersModuleReference = createLiteral(externalHelpersModuleNameText); const importDecl = createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + addEmitFlags(importDecl, EmitFlags.NeverApplyImportHelper); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -1945,7 +1961,7 @@ namespace ts { if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. const moduleNames = getModuleNames(file); - const oldProgramState = { program: oldProgram, file, modifiedFilePaths }; + const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths }; const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); Debug.assert(resolutions.length === moduleNames.length); for (let i = 0; i < moduleNames.length; i++) { diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index f085c3ffc069e..c8bb2ec0a25dd 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -35,7 +35,7 @@ namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; // Sets the text for the scanner to scan. An optional subrange starting point and length @@ -193,7 +193,7 @@ namespace ts { /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -201,7 +201,7 @@ namespace ts { Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -216,7 +216,7 @@ namespace ts { /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -224,7 +224,7 @@ namespace ts { Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -561,9 +561,9 @@ namespace ts { return false; } - function scanConflictMarkerTrivia(text: string, pos: number, error?: ErrorCallback) { + function scanConflictMarkerTrivia(text: string, pos: number, error?: (diag: DiagnosticMessage, pos?: number, len?: number) => void) { if (error) { - error(Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } const ch = text.charCodeAt(pos); @@ -852,34 +852,92 @@ namespace ts { scanRange, }; - function error(message: DiagnosticMessage, length?: number): void { + function error(message: DiagnosticMessage): void; + function error(message: DiagnosticMessage, errPos: number, length: number): void; + function error(message: DiagnosticMessage, errPos: number = pos, length?: number): void { if (onError) { + const oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; } } + function scanNumberFragment(): string { + let start = pos; + let allowSeparator = false; + let isPreviousTokenSeparator = false; + let result = ""; + while (true) { + const ch = text.charCodeAt(pos); + if (ch === CharacterCodes._) { + tokenFlags |= TokenFlags.ContainsSeparator; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === CharacterCodes._) { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } + function scanNumber(): string { const start = pos; - while (isDigit(text.charCodeAt(pos))) pos++; + const mainFragment = scanNumberFragment(); + let decimalFragment: string; + let scientificFragment: string; if (text.charCodeAt(pos) === CharacterCodes.dot) { pos++; - while (isDigit(text.charCodeAt(pos))) pos++; + decimalFragment = scanNumberFragment(); } let end = pos; if (text.charCodeAt(pos) === CharacterCodes.E || text.charCodeAt(pos) === CharacterCodes.e) { pos++; tokenFlags |= TokenFlags.Scientific; if (text.charCodeAt(pos) === CharacterCodes.plus || text.charCodeAt(pos) === CharacterCodes.minus) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) pos++; - end = pos; + const preNumericPart = pos; + const finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(Diagnostics.Digit_expected); } else { - error(Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; } } - return "" + +(text.substring(start, end)); + if (tokenFlags & TokenFlags.ContainsSeparator) { + let result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + } } function scanOctalDigits(): number { @@ -894,23 +952,41 @@ namespace ts { * Scans the given number of hexadecimal digits in the text, * returning -1 if the given number is unavailable. */ - function scanExactNumberOfHexDigits(count: number): number { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); + function scanExactNumberOfHexDigits(count: number, canHaveSeparators: boolean): number { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); } /** * Scans as many hexadecimal digits as are available in the text, * returning -1 if the given number of digits was unavailable. */ - function scanMinimumNumberOfHexDigits(count: number): number { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); + function scanMinimumNumberOfHexDigits(count: number, canHaveSeparators: boolean): number { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } - function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean): number { + function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean, canHaveSeparators: boolean): number { let digits = 0; let value = 0; + let allowSeparator = false; + let isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { const ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === CharacterCodes._) { + tokenFlags |= TokenFlags.ContainsSeparator; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= CharacterCodes._0 && ch <= CharacterCodes._9) { value = value * 16 + ch - CharacterCodes._0; } @@ -925,10 +1001,14 @@ namespace ts { } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === CharacterCodes._) { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } @@ -1097,7 +1177,7 @@ namespace ts { } function scanHexadecimalEscape(numDigits: number): string { - const escapedValue = scanExactNumberOfHexDigits(numDigits); + const escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); @@ -1109,7 +1189,7 @@ namespace ts { } function scanExtendedUnicodeEscape(): string { - const escapedValue = scanMinimumNumberOfHexDigits(1); + const escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); let isInvalidExtendedEscape = false; // Validate the value of the digit @@ -1162,7 +1242,7 @@ namespace ts { if (pos + 5 < end && text.charCodeAt(pos + 1) === CharacterCodes.u) { const start = pos; pos += 2; - const value = scanExactNumberOfHexDigits(4); + const value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); pos = start; return value; } @@ -1218,8 +1298,27 @@ namespace ts { // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. let numberOfDigits = 0; + let separatorAllowed = false; + let isPreviousTokenSeparator = false; while (true) { const ch = text.charCodeAt(pos); + // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === CharacterCodes._) { + tokenFlags |= TokenFlags.ContainsSeparator; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; const valueOfCh = ch - CharacterCodes._0; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -1227,11 +1326,17 @@ namespace ts { value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } // Invalid binaryIntegerLiteral or octalIntegerLiteral if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === CharacterCodes._) { + // Literal ends with underscore - not allowed + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } @@ -1435,7 +1540,7 @@ namespace ts { case CharacterCodes._0: if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.X || text.charCodeAt(pos + 1) === CharacterCodes.x)) { pos += 2; - let value = scanMinimumNumberOfHexDigits(1); + let value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); if (value < 0) { error(Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -1489,7 +1594,7 @@ namespace ts { return token = SyntaxKind.NumericLiteral; case CharacterCodes.colon: pos++; - return token = SyntaxKind.ColonToken; + return token = SyntaxKind.ColonToken; case CharacterCodes.semicolon: pos++; return token = SyntaxKind.SemicolonToken; @@ -1800,7 +1905,7 @@ namespace ts { break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -1819,7 +1924,7 @@ namespace ts { } } - function scanJSDocToken(): SyntaxKind { + function scanJSDocToken(): JsDocSyntaxKind { if (pos >= end) { return token = SyntaxKind.EndOfFileToken; } @@ -1828,6 +1933,7 @@ namespace ts { tokenPos = pos; const ch = text.charCodeAt(pos); + pos++; switch (ch) { case CharacterCodes.tab: case CharacterCodes.verticalTab: @@ -1838,56 +1944,31 @@ namespace ts { } return token = SyntaxKind.WhitespaceTrivia; case CharacterCodes.at: - pos++; return token = SyntaxKind.AtToken; case CharacterCodes.lineFeed: case CharacterCodes.carriageReturn: - pos++; return token = SyntaxKind.NewLineTrivia; case CharacterCodes.asterisk: - pos++; return token = SyntaxKind.AsteriskToken; case CharacterCodes.openBrace: - pos++; return token = SyntaxKind.OpenBraceToken; case CharacterCodes.closeBrace: - pos++; return token = SyntaxKind.CloseBraceToken; case CharacterCodes.openBracket: - pos++; return token = SyntaxKind.OpenBracketToken; case CharacterCodes.closeBracket: - pos++; return token = SyntaxKind.CloseBracketToken; case CharacterCodes.lessThan: - pos++; return token = SyntaxKind.LessThanToken; - case CharacterCodes.greaterThan: - pos++; - return token = SyntaxKind.GreaterThanToken; case CharacterCodes.equals: - pos++; return token = SyntaxKind.EqualsToken; case CharacterCodes.comma: - pos++; return token = SyntaxKind.CommaToken; case CharacterCodes.dot: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = SyntaxKind.DotDotDotToken; - } return token = SyntaxKind.DotToken; - case CharacterCodes.exclamation: - pos++; - return token = SyntaxKind.ExclamationToken; - case CharacterCodes.question: - pos++; - return token = SyntaxKind.QuestionToken; } if (isIdentifierStart(ch, ScriptTarget.Latest)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), ScriptTarget.Latest) && pos < end) { pos++; } @@ -1895,7 +1976,7 @@ namespace ts { return token = SyntaxKind.Identifier; } else { - return pos += 1, token = SyntaxKind.Unknown; + return token = SyntaxKind.Unknown; } } diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index b5cd1d9e32239..828c5744bbd91 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -420,7 +420,7 @@ namespace ts { host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); diff --git a/src/compiler/symbolWalker.ts b/src/compiler/symbolWalker.ts index 4af313e38966f..fed5f15f79f0c 100644 --- a/src/compiler/symbolWalker.ts +++ b/src/compiler/symbolWalker.ts @@ -2,6 +2,7 @@ namespace ts { export function createGetSymbolWalker( getRestTypeOfSignature: (sig: Signature) => Type, + getTypePredicateOfSignature: (sig: Signature) => TypePredicate | undefined, getReturnTypeOfSignature: (sig: Signature) => Type, getBaseTypes: (type: Type) => Type[], resolveStructuredTypeMembers: (type: ObjectType) => ResolvedType, @@ -117,8 +118,9 @@ namespace ts { } function visitSignature(signature: Signature): void { - if (signature.typePredicate) { - visitType(signature.typePredicate.type); + const typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); } forEach(signature.typeParameters, visitType); diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index aa928cdaacdcb..841dba8a52834 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -72,6 +72,7 @@ namespace ts { /*@internal*/ debugMode?: boolean; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; + clearScreen?(): void; } export interface FileWatcher { @@ -436,6 +437,9 @@ namespace ts { } const nodeSystem: System = { + clearScreen: () => { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames, diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 0c5c3cfbd3ab2..da0fcc73a98e1 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -859,7 +859,7 @@ namespace ts { statements.push( setTextRange( createStatement( - createExtendsHelper(context, getLocalName(node)) + createExtendsHelper(context, getInternalName(node)) ), /*location*/ extendsClauseElement ) @@ -2553,7 +2553,7 @@ namespace ts { } /** - * Visits an ObjectLiteralExpression with computed propety names. + * Visits an ObjectLiteralExpression with computed property names. * * @param node An ObjectLiteralExpression node. */ diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 5b4c12b4f2319..5d46c8430d2d4 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -968,7 +968,7 @@ namespace ts { name: "typescript:asyncValues", scoped: false, text: ` - var __asyncValues = (this && this.__asyncIterator) || function (o) { + var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index bd2a4ef554d34..8df05e4f3abbf 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -3190,8 +3190,8 @@ namespace ts { // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the diff --git a/src/compiler/transformers/module/es2015.ts b/src/compiler/transformers/module/es2015.ts index 3951d08109da7..4f218e4fdcf11 100644 --- a/src/compiler/transformers/module/es2015.ts +++ b/src/compiler/transformers/module/es2015.ts @@ -25,14 +25,14 @@ namespace ts { if (externalHelpersModuleName) { const statements: Statement[] = []; const statementOffset = addPrologue(statements, node.statements); - append(statements, - createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), - createLiteral(externalHelpersModuleNameText) - ) + const tslibImport = createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), + createLiteral(externalHelpersModuleNameText) ); + addEmitFlags(tslibImport, EmitFlags.NeverApplyImportHelper); + append(statements, tslibImport); addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); return updateSourceFileNode( diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 0c8e2cda0f5f4..0d4e5b6864acf 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -148,7 +148,7 @@ namespace ts { // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return updateSourceFileNode(node, + const updated = updateSourceFileNode(node, setTextRange( createNodeArray([ createStatement( @@ -192,6 +192,9 @@ namespace ts { /*location*/ node.statements ) ); + + addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** @@ -296,7 +299,7 @@ namespace ts { // } // })(function ...) - return updateSourceFileNode( + const updated = updateSourceFileNode( node, setTextRange( createNodeArray([ @@ -328,6 +331,9 @@ namespace ts { /*location*/ node.statements ) ); + + addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** @@ -385,6 +391,18 @@ namespace ts { return { aliasedModuleNames, unaliasedModuleNames, importAliasNames }; } + function getAMDImportExpressionForImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration) { + if (isImportEqualsDeclaration(node) || isExportDeclaration(node) || !getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + const name = getLocalNameForExternalImport(node, currentSourceFile); + const expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return createStatement(createAssignment(name, expr)); + } + /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -402,6 +420,9 @@ namespace ts { // Visit each statement of the module body. append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement)); + if (moduleKind === ModuleKind.AMD) { + addRange(statements, mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset)); // Append the 'export =' statement if provided. @@ -617,7 +638,12 @@ namespace ts { } } - return createNew(createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + const promise = createNew(createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return createCall(createPropertyAccess(promise, createIdentifier("then")), /*typeArguments*/ undefined, [getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg: Expression | undefined, containsLexicalThis: boolean): Expression { @@ -627,7 +653,11 @@ namespace ts { // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately const promiseResolveCall = createCall(createPropertyAccess(createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - const requireCall = createCall(createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + let requireCall = createCall(createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = createCall(getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } let func: FunctionExpression | ArrowFunction; if (languageVersion >= ScriptTarget.ES2015) { @@ -660,6 +690,22 @@ namespace ts { return createCall(createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + + function getHelperExpressionForImport(node: ImportDeclaration, innerExpr: Expression) { + if (!compilerOptions.esModuleInterop || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) { + return innerExpr; + } + if (getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return createCall(getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return createCall(getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } + /** * Visits an ImportDeclaration node. * @@ -681,7 +727,7 @@ namespace ts { createVariableDeclaration( getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, - createRequireCall(node) + getHelperExpressionForImport(node, createRequireCall(node)) ) ); } @@ -694,7 +740,7 @@ namespace ts { createVariableDeclaration( getGeneratedNameForNode(node), /*type*/ undefined, - createRequireCall(node) + getHelperExpressionForImport(node, createRequireCall(node)) ) ); @@ -1671,4 +1717,28 @@ namespace ts { text: ` var __syncRequire = typeof module === "object" && typeof module.exports === "object";` }; + + // emit helper for `import * as Name from "foo"` + const importStarHelper: EmitHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: ` +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}` + }; + + // emit helper for `import Name from "foo"` + const importDefaultHelper: EmitHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: ` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}` + }; } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 3c1bba280f0f9..cdb0d0667ad0a 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -81,7 +81,7 @@ namespace ts { let classAliases: Identifier[]; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ let applicableSubstitutions: TypeScriptSubstitutionFlags; diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index a012c9be7db9a..15e91d755caf7 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -143,6 +143,7 @@ namespace ts { createLiteral(externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + addEmitFlags(externalHelpersImportDeclaration, EmitFlags.NeverApplyImportHelper); externalImports.unshift(externalHelpersImportDeclaration); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 8a0889d01ec87..23798635671a8 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -58,6 +58,23 @@ namespace ts { end: number; } + export type JsDocSyntaxKind = + | SyntaxKind.EndOfFileToken + | SyntaxKind.WhitespaceTrivia + | SyntaxKind.AtToken + | SyntaxKind.NewLineTrivia + | SyntaxKind.AsteriskToken + | SyntaxKind.OpenBraceToken + | SyntaxKind.CloseBraceToken + | SyntaxKind.LessThanToken + | SyntaxKind.OpenBracketToken + | SyntaxKind.CloseBracketToken + | SyntaxKind.EqualsToken + | SyntaxKind.CommaToken + | SyntaxKind.DotToken + | SyntaxKind.Identifier + | SyntaxKind.Unknown; + // token > SyntaxKind.Identifer => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync export const enum SyntaxKind { @@ -438,24 +455,24 @@ namespace ts { } export const enum NodeFlags { - None = 0, - Let = 1 << 0, // Variable declaration - Const = 1 << 1, // Variable declaration - NestedNamespace = 1 << 2, // Namespace declaration - Synthesized = 1 << 3, // Node was synthesized during transformation - Namespace = 1 << 4, // Namespace declaration - ExportContext = 1 << 5, // Export context (initialized by binding) - ContainsThis = 1 << 6, // Interface contains references to "this" - HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding) - HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding) + None = 0, + Let = 1 << 0, // Variable declaration + Const = 1 << 1, // Variable declaration + NestedNamespace = 1 << 2, // Namespace declaration + Synthesized = 1 << 3, // Node was synthesized during transformation + Namespace = 1 << 4, // Namespace declaration + ExportContext = 1 << 5, // Export context (initialized by binding) + ContainsThis = 1 << 6, // Interface contains references to "this" + HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding) + HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding) GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope - HasAsyncFunctions = 1 << 10, // If the file has async functions (initialized by binding) - DisallowInContext = 1 << 11, // If node was parsed in a context where 'in-expressions' are not allowed - YieldContext = 1 << 12, // If node was parsed in the 'yield' context created when parsing a generator - DecoratorContext = 1 << 13, // If node was parsed as part of a decorator - AwaitContext = 1 << 14, // If node was parsed in the 'await' context created when parsing an async function - ThisNodeHasError = 1 << 15, // If the parser encountered an error when parsing the code that created this node - JavaScriptFile = 1 << 16, // If node was parsed in a JavaScript + HasAsyncFunctions = 1 << 10, // If the file has async functions (initialized by binding) + DisallowInContext = 1 << 11, // If node was parsed in a context where 'in-expressions' are not allowed + YieldContext = 1 << 12, // If node was parsed in the 'yield' context created when parsing a generator + DecoratorContext = 1 << 13, // If node was parsed as part of a decorator + AwaitContext = 1 << 14, // If node was parsed in the 'await' context created when parsing an async function + ThisNodeHasError = 1 << 15, // If the parser encountered an error when parsing the code that created this node + JavaScriptFile = 1 << 16, // If node was parsed in a JavaScript ThisNodeOrAnySubNodesHasError = 1 << 17, // If this node or any of its children had an error HasAggregatedChildData = 1 << 18, // If we've computed data from children and cached it in this node @@ -584,6 +601,40 @@ namespace ts { | JSDocFunctionType | EndOfFileToken; + export type HasType = + | SignatureDeclaration + | VariableDeclaration + | ParameterDeclaration + | PropertySignature + | PropertyDeclaration + | TypePredicateNode + | ParenthesizedTypeNode + | TypeOperatorNode + | MappedTypeNode + | AssertionExpression + | TypeAliasDeclaration + | JSDocTypeExpression + | JSDocNonNullableType + | JSDocNullableType + | JSDocOptionalType + | JSDocVariadicType; + + export type HasInitializer = + | HasExpressionInitializer + | ForStatement + | ForInStatement + | ForOfStatement + | JsxAttribute; + + export type HasExpressionInitializer = + | VariableDeclaration + | ParameterDeclaration + | BindingElement + | PropertySignature + | PropertyDeclaration + | PropertyAssignment + | EnumMember; + /* @internal */ export type MutableNodeArray = NodeArray & T[]; @@ -793,6 +844,9 @@ namespace ts { initializer?: Expression; // Optional initializer } + /*@internal*/ + export type BindingElementGrandparent = BindingElement["parent"]["parent"]; + export interface PropertySignature extends TypeElement, JSDocContainer { kind: SyntaxKind.PropertySignature; name: PropertyName; // Declared property name @@ -848,25 +902,18 @@ namespace ts { expression: Expression; } - // SyntaxKind.VariableDeclaration - // SyntaxKind.Parameter - // SyntaxKind.BindingElement - // SyntaxKind.Property - // SyntaxKind.PropertyAssignment - // SyntaxKind.JsxAttribute - // SyntaxKind.ShorthandPropertyAssignment - // SyntaxKind.EnumMember - // SyntaxKind.JSDocPropertyTag - // SyntaxKind.JSDocParameterTag - export interface VariableLikeDeclaration extends NamedDeclaration { - propertyName?: PropertyName; - dotDotDotToken?: DotDotDotToken; - name: DeclarationName; - questionToken?: QuestionToken; - exclamationToken?: ExclamationToken; - type?: TypeNode; - initializer?: Expression; - } + export type VariableLikeDeclaration = + | VariableDeclaration + | ParameterDeclaration + | BindingElement + | PropertyDeclaration + | PropertyAssignment + | PropertySignature + | JsxAttribute + | ShorthandPropertyAssignment + | EnumMember + | JSDocPropertyTag + | JSDocParameterTag; export interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; @@ -949,7 +996,7 @@ namespace ts { export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; body?: FunctionBody; /* @internal */ returnFlowNode?: FlowNode; } @@ -957,14 +1004,14 @@ namespace ts { /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ export interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; } // See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } @@ -973,7 +1020,7 @@ namespace ts { // ClassElement and an ObjectLiteralElement. export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } @@ -982,7 +1029,7 @@ namespace ts { export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; + parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; } export interface TypeNode extends Node { @@ -1366,7 +1413,7 @@ namespace ts { export type BinaryOperatorToken = Token; - export interface BinaryExpression extends Expression, Declaration { + export interface BinaryExpression extends Expression, Declaration { kind: SyntaxKind.BinaryExpression; left: Expression; operatorToken: BinaryOperatorToken; @@ -1493,8 +1540,9 @@ namespace ts { HexSpecifier = 1 << 6, // e.g. `0x00000000` BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000` OctalSpecifier = 1 << 8, // e.g. `0o777` + ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier, - NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinarySpecifier | OctalSpecifier + NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinarySpecifier | OctalSpecifier | ContainsSeparator } export interface NumericLiteral extends LiteralExpression { @@ -1989,7 +2037,7 @@ namespace ts { export interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression; + parent?: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -2482,7 +2530,7 @@ namespace ts { // Stores a mapping 'external module reference text' -> 'resolved file name' | undefined // It is used to resolve module names in the checker. // Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead - /* @internal */ resolvedModules: Map; + /* @internal */ resolvedModules: Map; /* @internal */ resolvedTypeReferenceDirectiveNames: Map; /* @internal */ imports: ReadonlyArray; // Identifier only if `declare global` @@ -2513,7 +2561,7 @@ namespace ts { export interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. @@ -2742,6 +2790,8 @@ namespace ts { getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; + /* @internal */ isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean; + /** * returns unknownSignature in the case of an error. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. @@ -2756,6 +2806,8 @@ namespace ts { getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + /** Exclude accesses to private properties or methods with a `this` parameter that `type` doesn't satisfy. */ + /* @internal */ isValidPropertyAccessForCompletions(node: PropertyAccessExpression, type: Type, property: Symbol): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; /** Follow a *single* alias to get the immediately aliased symbol. */ @@ -2790,12 +2842,22 @@ namespace ts { /* @internal */ getNullType(): Type; /* @internal */ getESSymbolType(): Type; /* @internal */ getNeverType(): Type; - /* @internal */ getUnionType(types: Type[], subtypeReduction?: boolean): Type; + /* @internal */ getUnionType(types: Type[], subtypeReduction?: UnionReduction): Type; /* @internal */ createArrayType(elementType: Type): Type; /* @internal */ createPromiseType(type: Type): Type; /* @internal */ createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): Type; - /* @internal */ createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisParameter: Symbol | undefined, parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasLiteralTypes: boolean): Signature; + /* @internal */ createSignature( + declaration: SignatureDeclaration, + typeParameters: TypeParameter[], + thisParameter: Symbol | undefined, + parameters: Symbol[], + resolvedReturnType: Type, + typePredicate: TypePredicate | undefined, + minArgumentCount: number, + hasRestParameter: boolean, + hasLiteralTypes: boolean, + ): Signature; /* @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol; /* @internal */ createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo; /* @internal */ isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; @@ -2822,6 +2884,26 @@ namespace ts { /* @internal */ getAllPossiblePropertiesOfTypes(type: ReadonlyArray): Symbol[]; /* @internal */ resolveName(name: string, location: Node, meaning: SymbolFlags, excludeGlobals: boolean): Symbol | undefined; /* @internal */ getJsxNamespace(): string; + + /** + * Note that this will return undefined in the following case: + * // a.ts + * export namespace N { export class C { } } + * // b.ts + * <> + * Where `C` is the symbol we're looking for. + * This should be called in a loop climbing parents of the symbol, so we'll get `N`. + */ + /* @internal */ getAccessibleSymbolChain(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, useOnlyExternalAliasing: boolean): Symbol[] | undefined; + + /* @internal */ resolveExternalModuleSymbol(symbol: Symbol): Symbol; + } + + /* @internal */ + export const enum UnionReduction { + None = 0, + Literal, + Subtype } export enum NodeBuilderFlags { @@ -2918,9 +3000,9 @@ namespace ts { None = 0x00000000, // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p WriteTypeParametersOrArguments = 0x00000001, // Use only external alias information to get the symbol name in the given context @@ -3170,6 +3252,7 @@ namespace ts { bindingElement?: BindingElement; // Binding element associated with property symbol exportsSomeValue?: boolean; // True if module exports some value (not just types) enumKind?: EnumKind; // Enum declaration classification + originatingImport?: ImportDeclaration | ImportCall; // Import declaration which produced the symbol, present if the symbol is marked as uncallable but had call signatures in `resolveESModuleSymbol` lateSymbol?: Symbol; // Late-bound symbol for a computed property } @@ -3192,6 +3275,7 @@ namespace ts { ContainsPrivate = 1 << 8, // Synthetic property with private constituent(s) ContainsStatic = 1 << 9, // Synthetic property with static constituent(s) Late = 1 << 10, // Late-bound symbol for a computed property with a dynamic name + ReverseMapped = 1 << 11, // property of reverse-inferred homomorphic mapped type. Synthetic = SyntheticProperty | SyntheticMethod } @@ -3201,6 +3285,12 @@ namespace ts { isRestParameter?: boolean; } + /* @internal */ + export interface ReverseMappedSymbol extends TransientSymbol { + propertyType: Type; + mappedType: MappedType; + } + export const enum InternalSymbolName { Call = "__call", // Call signatures Constructor = "__constructor", // Constructor implementations @@ -3306,7 +3396,7 @@ namespace ts { resolvedJsxElementAttributesType?: Type; // resolved element attributes type of a JSX openinglike element resolvedJsxElementAllAttributesType?: Type; // resolved all element attributes type of a JSX openinglike element hasSuperCall?: boolean; // recorded result when we try to find super-call. We only try to find one if this flag is undefined, indicating that we haven't made an attempt. - superCall?: ExpressionStatement; // Cached first super-call found in the constructor. Used in checking whether super is called before this-accessing + superCall?: SuperCall; // Cached first super-call found in the constructor. Used in checking whether super is called before this-accessing switchTypes?: Type[]; // Cached array of switch case expression types } @@ -3435,6 +3525,7 @@ namespace ts { EvolvingArray = 1 << 8, // Evolving array type ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties ContainsSpread = 1 << 10, // Object literal contains spread operation + ReverseMapped = 1 << 11, // Object contains a property from a reverse-mapped type ClassOrInterface = Class | Interface } @@ -3542,6 +3633,12 @@ namespace ts { finalArrayType?: Type; // Final array type of evolving array type } + /* @internal */ + export interface ReverseMappedType extends ObjectType { + source: Type; + mappedType: MappedType; + } + /* @internal */ // Resolved object, union, or intersection type export interface ResolvedType extends ObjectType, UnionOrIntersectionType { @@ -3555,7 +3652,7 @@ namespace ts { /* @internal */ // Object literals are initially marked fresh. Freshness disappears following an assignment, - // before a type assertion, or when an object literal's type is widened. The regular + // before a type assertion, or when an object literal's type is widened. The regular // version of a fresh type is identical except for the TypeFlags.FreshObjectLiteral flag. export interface FreshObjectLiteralType extends ResolvedType { regularType: ResolvedType; // Regular version of fresh type @@ -3631,7 +3728,13 @@ namespace ts { /* @internal */ thisParameter?: Symbol; // symbol of this-type parameter /* @internal */ - resolvedReturnType: Type; // Resolved return type + // See comment in `instantiateSignature` for why these are set lazily. + resolvedReturnType: Type | undefined; // Lazily set by `getReturnTypeOfSignature`. + /* @internal */ + // Lazily set by `getTypePredicateOfSignature`. + // `undefined` indicates a type predicate that has not yet been computed. + // Uses a special `noTypePredicate` sentinel value to indicate that there is no type predicate. This looks like a TypePredicate at runtime to avoid polymorphism. + resolvedTypePredicate: TypePredicate | undefined; /* @internal */ minArgumentCount: number; // Number of non-optional parameters /* @internal */ @@ -3651,8 +3754,6 @@ namespace ts { /* @internal */ isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison /* @internal */ - typePredicate?: TypePredicate; - /* @internal */ instantiations?: Map; // Generic signature instantiation cache } @@ -3882,6 +3983,7 @@ namespace ts { typeRoots?: string[]; /*@internal*/ version?: boolean; /*@internal*/ watch?: boolean; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } @@ -3954,7 +4056,8 @@ namespace ts { ES2015 = 2, ES2016 = 3, ES2017 = 4, - ESNext = 5, + ES2018 = 5, + ESNext = 6, Latest = ESNext, } @@ -4221,6 +4324,8 @@ namespace ts { * If changing this, remember to change `moduleResolutionIsEqualTo`. */ export interface ResolvedModuleFull extends ResolvedModule { + /* @internal */ + readonly originalPath?: string; /** * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. * This is optional for backwards-compatibility, but will be added if not provided. @@ -4300,11 +4405,11 @@ namespace ts { * If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just * 'throw new Error("NotImplemented")' */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions): void; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; @@ -4446,6 +4551,7 @@ namespace ts { Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions. /*@internal*/ TypeScriptClassWrapper = 1 << 25, // The node is an IIFE class wrapper created by the ts transform. + /*@internal*/ NeverApplyImportHelper = 1 << 26, // Indicates the node should never be wrapped with an import star helper (because, for example, it imports tslib itself) } export interface EmitHelper { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 2eb8bcdae5a18..37b62fd5d85fb 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3,6 +3,7 @@ /* @internal */ namespace ts { export const emptyArray: never[] = [] as never[]; + export const resolvingEmptyArray: never[] = [] as never[]; export const emptyMap: ReadonlyMap = createMap(); export const emptyUnderscoreEscapedMap: ReadonlyUnderscoreEscapedMap = emptyMap as ReadonlyUnderscoreEscapedMap; @@ -102,6 +103,7 @@ namespace ts { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } @@ -346,7 +348,7 @@ namespace ts { export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(isNumericLiteral(node) && node.numericLiteralFlags & TokenFlags.ContainsSeparator)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } @@ -466,7 +468,6 @@ namespace ts { return isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } - /* @internal */ export function isBlockScope(node: Node, parentNode: Node) { switch (node.kind) { case SyntaxKind.SourceFile: @@ -494,7 +495,6 @@ namespace ts { return false; } - /* @internal */ export function isDeclarationWithTypeParameters(node: Node): node is DeclarationWithTypeParameters; export function isDeclarationWithTypeParameters(node: DeclarationWithTypeParameters): node is DeclarationWithTypeParameters { switch (node.kind) { @@ -524,7 +524,6 @@ namespace ts { } } - /* @internal */ export function isAnyImportSyntax(node: Node): node is AnyImportSyntax { switch (node.kind) { case SyntaxKind.ImportDeclaration: @@ -551,7 +550,7 @@ namespace ts { // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. - export function declarationNameToString(name: DeclarationName) { + export function declarationNameToString(name: DeclarationName | QualifiedName) { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } @@ -787,7 +786,7 @@ namespace ts { case SyntaxKind.PropertySignature: case SyntaxKind.Parameter: case SyntaxKind.VariableDeclaration: - return node === (parent).type; + return node === (parent as HasType).type; case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: @@ -805,7 +804,7 @@ namespace ts { return node === (parent).type; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - return (parent).typeArguments && indexOf((parent).typeArguments, node) >= 0; + return contains((parent).typeArguments, node); case SyntaxKind.TaggedTemplateExpression: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -1343,7 +1342,7 @@ namespace ts { case SyntaxKind.EnumMember: case SyntaxKind.PropertyAssignment: case SyntaxKind.BindingElement: - return (parent).initializer === node; + return (parent as HasInitializer).initializer === node; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.DoStatement: @@ -1655,7 +1654,7 @@ namespace ts { result = addRange(result, getJSDocParameterTags(node as ParameterDeclaration)); } - if (isVariableLike(node) && node.initializer && hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && hasInitializer(node) && hasJSDocNodes(node.initializer)) { result = addRange(result, node.initializer.jsDoc); } @@ -1808,7 +1807,6 @@ namespace ts { } } - /* @internal */ // See GH#16030 export function isAnyDeclarationName(name: Node): boolean { switch (name.kind) { @@ -2124,6 +2122,10 @@ namespace ts { return "__@" + symbolName as __String; } + export function isKnownSymbol(symbol: Symbol): boolean { + return startsWith(symbol.escapedName as string, "__@"); + } + /** * Includes the word "Symbol" with unicode escapes */ @@ -2822,8 +2824,8 @@ namespace ts { * Gets the effective type annotation of a variable, parameter, or property. If the node was * parsed in a JavaScript file, gets the type annotation from JSDoc. */ - export function getEffectiveTypeAnnotationNode(node: VariableLikeDeclaration, checkJSDoc?: boolean): TypeNode | undefined { - if (node.type) { + export function getEffectiveTypeAnnotationNode(node: Node, checkJSDoc?: boolean): TypeNode | undefined { + if (hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -3118,7 +3120,6 @@ namespace ts { return flags; } - /* @internal */ export function getModifierFlagsNoCache(node: Node): ModifierFlags { let flags = ModifierFlags.None; @@ -3680,9 +3681,34 @@ namespace ts { } } + // 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); + } + + export function isAbstractConstructorSymbol(symbol: Symbol): boolean { + if (symbol.flags & SymbolFlags.Class) { + const declaration = getClassLikeDeclarationOfSymbol(symbol); + return !!declaration && hasModifier(declaration, ModifierFlags.Abstract); + } + return false; + } + + export function getClassLikeDeclarationOfSymbol(symbol: Symbol): Declaration | undefined { + return find(symbol.declarations, isClassLike); + } + + export function getObjectFlags(type: Type): ObjectFlags { + return type.flags & TypeFlags.Object ? (type).objectFlags : 0; + } + export function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker) { return checker.getSignaturesOfType(type, SignatureKind.Call).length !== 0 || checker.getSignaturesOfType(type, SignatureKind.Construct).length !== 0; } + + export function forSomeAncestorDirectory(directory: string, callback: (directory: string) => boolean): boolean { + return !!forEachAncestorDirectory(directory, d => callback(d) ? true : undefined); + } } namespace ts { @@ -3898,8 +3924,8 @@ namespace ts { // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } const oldStart1 = oldStartN; @@ -4384,7 +4410,7 @@ namespace ts { return node.kind === SyntaxKind.RegularExpressionLiteral; } - export function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression { + export function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral { return node.kind === SyntaxKind.NoSubstitutionTemplateLiteral; } @@ -5215,6 +5241,18 @@ namespace ts { return node && (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor); } + /* @internal */ + export function isMethodOrAccessor(node: Node): node is MethodDeclaration | AccessorDeclaration { + switch (node.kind) { + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return true; + default: + return false; + } + } + // Type members export function isTypeElement(node: Node): node is TypeElement { @@ -5794,4 +5832,37 @@ namespace ts { export function hasJSDocNodes(node: Node): node is HasJSDoc { return !!(node as JSDocContainer).jsDoc && (node as JSDocContainer).jsDoc.length > 0; } + + /** True if has type node attached to it. */ + /* @internal */ + export function hasType(node: Node): node is HasType { + return !!(node as HasType).type; + } + + /** True if has initializer node attached to it. */ + /* @internal */ + export function hasInitializer(node: Node): node is HasInitializer { + return !!(node as HasInitializer).initializer; + } + + /** True if has initializer node attached to it. */ + /* @internal */ + export function hasOnlyExpressionInitializer(node: Node): node is HasExpressionInitializer { + return hasInitializer(node) && !isForStatement(node) && !isForInStatement(node) && !isForOfStatement(node) && !isJsxAttribute(node); + } + + export function isObjectLiteralElement(node: Node): node is ObjectLiteralElement { + switch (node.kind) { + case SyntaxKind.JsxAttribute: + case SyntaxKind.JsxSpreadAttribute: + case SyntaxKind.PropertyAssignment: + case SyntaxKind.ShorthandPropertyAssignment: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return true; + default: + return false; + } + } } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 0b40e20a7b7c1..2d678eb0effcb 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -622,7 +622,7 @@ namespace ts { case SyntaxKind.ForOfStatement: return updateForOf(node, - (node).awaitModifier, + visitNode((node).awaitModifier, visitor, isToken), visitNode((node).initializer, visitor, isForInitializer), visitNode((node).expression, visitor, isExpression), visitNode((node).statement, visitor, isStatement, liftToBlock)); diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 8e49bb71a1592..b4ed1c1ac1b13 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -48,6 +48,15 @@ namespace ts { }; } + /** @internal */ + export function createWatchDiagnosticReporterWithColor(system = sys): DiagnosticReporter { + return diagnostic => { + let output = `[${ formatColorAndReset(new Date().toLocaleTimeString(), ForegroundColorEscapeSequences.Grey) }] `; + output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${system.newLine + system.newLine + system.newLine}`; + system.write(output); + }; + } + export function reportDiagnostics(diagnostics: Diagnostic[], reportDiagnostic: DiagnosticReporter): void { for (const diagnostic of diagnostics) { reportDiagnostic(diagnostic); @@ -131,7 +140,7 @@ namespace ts { reportWatchDiagnostic?: DiagnosticReporter ): WatchingSystemHost { reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system, pretty ? reportDiagnosticWithColorAndContext : reportDiagnosticSimply); - reportWatchDiagnostic = reportWatchDiagnostic || createWatchDiagnosticReporter(system); + reportWatchDiagnostic = reportWatchDiagnostic || pretty ? createWatchDiagnosticReporterWithColor(system) : createWatchDiagnosticReporter(system); parseConfigFile = parseConfigFile || ts.parseConfigFile; return { system, @@ -302,6 +311,8 @@ namespace ts { // There is no extra check needed since we can just rely on the program to decide emit const builder = createBuilder({ getCanonicalFileName, computeHash }); + clearHostScreen(); + reportWatchDiagnostic(createCompilerDiagnostic(Diagnostics.Starting_compilation_in_watch_mode)); synchronizeProgram(); // Update the wild card directory watch @@ -492,7 +503,15 @@ namespace ts { scheduleProgramUpdate(); } + function clearHostScreen() { + if (watchingHost.system.clearScreen) { + watchingHost.system.clearScreen(); + } + } + function updateProgram() { + clearHostScreen(); + timerToUpdateProgram = undefined; reportWatchDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation)); diff --git a/src/harness/externalCompileRunner.ts b/src/harness/externalCompileRunner.ts index 2a44badd81378..c5e1c6ea9ff38 100644 --- a/src/harness/externalCompileRunner.ts +++ b/src/harness/externalCompileRunner.ts @@ -42,21 +42,29 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { const stdio = isWorker ? "pipe" : "inherit"; let types: string[]; if (fs.existsSync(path.join(cwd, "test.json"))) { - const update = cp.spawnSync("git", ["submodule", "update", "--remote"], { cwd, timeout, shell: true, stdio }); - if (update.status !== 0) throw new Error(`git submodule update for ${directoryName} failed!`); + const submoduleDir = path.join(cwd, directoryName); + const reset = cp.spawnSync("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir, timeout, shell: true, stdio }); + if (reset.status !== 0) throw new Error(`git reset for ${directoryName} failed: ${reset.stderr.toString()}`); + const clean = cp.spawnSync("git", ["clean", "-f"], { cwd: submoduleDir, timeout, shell: true, stdio }); + if (clean.status !== 0) throw new Error(`git clean for ${directoryName} failed: ${clean.stderr.toString()}`); + const update = cp.spawnSync("git", ["submodule", "update", "--remote", "."], { cwd: submoduleDir, timeout, shell: true, stdio }); + if (update.status !== 0) throw new Error(`git submodule update for ${directoryName} failed: ${update.stderr.toString()}`); const config = JSON.parse(fs.readFileSync(path.join(cwd, "test.json"), { encoding: "utf8" })) as UserConfig; ts.Debug.assert(!!config.types, "Bad format from test.json: Types field must be present."); types = config.types; - cwd = path.join(cwd, directoryName); + cwd = submoduleDir; } if (fs.existsSync(path.join(cwd, "package.json"))) { if (fs.existsSync(path.join(cwd, "package-lock.json"))) { fs.unlinkSync(path.join(cwd, "package-lock.json")); } + if (fs.existsSync(path.join(cwd, "node_modules"))) { + require("del").sync(path.join(cwd, "node_modules")); + } const install = cp.spawnSync(`npm`, ["i"], { cwd, timeout, shell: true, stdio }); - if (install.status !== 0) throw new Error(`NPM Install for ${directoryName} failed!`); + if (install.status !== 0) throw new Error(`NPM Install for ${directoryName} failed: ${install.stderr.toString()}`); } const args = [path.join(__dirname, "tsc.js")]; if (types) { diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 0776f502130c8..8c5570f730c05 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -27,6 +27,7 @@ namespace FourSlash { // The contents of the file (with markers, etc stripped out) content: string; fileName: string; + symlinks?: string[]; version: number; // File-specific options (name/value pairs) fileOptions: Harness.TestCaseParser.CompilerSettings; @@ -106,15 +107,16 @@ namespace FourSlash { // Name of testcase metadata including ts.CompilerOptions properties that will be used by globalOptions // To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames // Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data - const metadataOptionNames = { - baselineFile: "BaselineFile", - emitThisFile: "emitThisFile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project - fileName: "Filename", - resolveReference: "ResolveReference", // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file - }; + const enum MetadataOptionNames { + baselineFile = "BaselineFile", + emitThisFile = "emitThisFile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project + fileName = "Filename", + resolveReference = "ResolveReference", // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file + symlink = "Symlink", + } // List of allowed metadata names - const fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; + const fileMetadataNames = [MetadataOptionNames.fileName, MetadataOptionNames.emitThisFile, MetadataOptionNames.resolveReference, MetadataOptionNames.symlink]; function convertGlobalOptionsToCompilerOptions(globalOptions: Harness.TestCaseParser.CompilerSettings): ts.CompilerOptions { const settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; @@ -263,7 +265,7 @@ namespace FourSlash { ts.forEach(testData.files, file => { // Create map between fileName and its content for easily looking up when resolveReference flag is specified this.inputFiles.set(file.fileName, file.content); - if (ts.getBaseFileName(file.fileName).toLowerCase() === "tsconfig.json") { + if (isTsconfig(file)) { const configJson = ts.parseConfigFileTextToJson(file.fileName, file.content); if (configJson.config === undefined) { throw new Error(`Failed to parse test tsconfig.json: ${configJson.error.messageText}`); @@ -281,7 +283,7 @@ namespace FourSlash { configFileName = file.fileName; } - if (!startResolveFileRef && file.fileOptions[metadataOptionNames.resolveReference] === "true") { + if (!startResolveFileRef && file.fileOptions[MetadataOptionNames.resolveReference] === "true") { startResolveFileRef = file; } else if (startResolveFileRef) { @@ -354,6 +356,10 @@ namespace FourSlash { Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false); } + for (const file of testData.files) { + ts.forEach(file.symlinks, link => this.languageServiceAdapterHost.addSymlink(link, file.fileName)); + } + this.formatCodeSettings = { baseIndentSize: 0, indentSize: 4, @@ -375,6 +381,7 @@ namespace FourSlash { insertSpaceAfterTypeAssertion: false, placeOpenBraceOnNewLineForFunctions: false, placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false }; // Open the first file by default @@ -435,12 +442,11 @@ namespace FourSlash { this.goToPosition(marker.position); } - public goToEachMarker(action: () => void) { - const markers = this.getMarkers(); + public goToEachMarker(markers: ReadonlyArray, action: (marker: FourSlash.Marker, index: number) => void) { assert(markers.length); - for (const marker of markers) { - this.goToMarker(marker); - action(); + for (let i = 0; i < markers.length; i++) { + this.goToMarker(markers[i]); + action(markers[i], i); } } @@ -510,7 +516,7 @@ namespace FourSlash { } } - private raiseError(message: string) { + private raiseError(message: string): never { throw new Error(this.messageAtLastKnownMarker(message)); } @@ -658,7 +664,7 @@ namespace FourSlash { this.verifyGoToXPlain(arg0, endMarkerNames, getDefs); } else if (ts.isArray(arg0)) { - const pairs: ReadonlyArray<[string | string[], string | string[]]> = arg0; + const pairs = arg0 as ReadonlyArray<[string | string[], string | string[]]>; for (const [start, end] of pairs) { this.verifyGoToXPlain(start, end, getDefs); } @@ -847,10 +853,10 @@ namespace FourSlash { } } - public verifyCompletionsAt(markerName: string, expected: string[], options?: FourSlashInterface.CompletionsAtOptions) { + public verifyCompletionsAt(markerName: string, expected: ReadonlyArray, options?: FourSlashInterface.CompletionsAtOptions) { this.goToMarker(markerName); - const actualCompletions = this.getCompletionListAtCaret(); + const actualCompletions = this.getCompletionListAtCaret(options); if (!actualCompletions) { this.raiseError(`No completions at position '${this.currentCaretPosition}'.`); } @@ -866,13 +872,24 @@ namespace FourSlash { } ts.zipWith(actual, expected, (completion, expectedCompletion, index) => { - if (completion.name !== expectedCompletion) { + const { name, insertText, replacementSpan } = typeof expectedCompletion === "string" ? { name: expectedCompletion, insertText: undefined, replacementSpan: undefined } : expectedCompletion; + if (completion.name !== name) { this.raiseError(`Expected completion at index ${index} to be ${expectedCompletion}, got ${completion.name}`); } + if (completion.insertText !== insertText) { + this.raiseError(`Expected completion insert text at index ${index} to be ${insertText}, got ${completion.insertText}`); + } + const convertedReplacementSpan = replacementSpan && textSpanFromRange(replacementSpan); + try { + assert.deepEqual(completion.replacementSpan, convertedReplacementSpan); + } + catch { + this.raiseError(`Expected completion replacementSpan at index ${index} to be ${stringify(convertedReplacementSpan)}, got ${stringify(completion.replacementSpan)}`); + } }); } - public verifyCompletionListContains(entryId: ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string, spanIndex?: number, hasAction?: boolean, options?: FourSlashInterface.VerifyCompletionListContainsOptions) { + public verifyCompletionListContains(entryId: ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, hasAction?: boolean, options?: FourSlashInterface.VerifyCompletionListContainsOptions) { const completions = this.getCompletionListAtCaret(options); if (completions) { this.assertItemInCompletionList(completions.entries, entryId, text, documentation, kind, spanIndex, hasAction, options); @@ -893,7 +910,7 @@ namespace FourSlash { * @param expectedKind the kind of symbol (see ScriptElementKind) * @param spanIndex the index of the range that the completion item's replacement text span should match */ - public verifyCompletionListDoesNotContain(entryId: ts.Completions.CompletionEntryIdentifier, expectedText?: string, expectedDocumentation?: string, expectedKind?: string, spanIndex?: number, options?: ts.GetCompletionsAtPositionOptions) { + public verifyCompletionListDoesNotContain(entryId: ts.Completions.CompletionEntryIdentifier, expectedText?: string, expectedDocumentation?: string, expectedKind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, options?: FourSlashInterface.CompletionsAtOptions) { let replacementSpan: ts.TextSpan; if (spanIndex !== undefined) { replacementSpan = this.getTextSpanForRangeAtIndex(spanIndex); @@ -902,7 +919,7 @@ namespace FourSlash { const completions = this.getCompletionListAtCaret(options); if (completions) { let filterCompletions = completions.entries.filter(e => e.name === entryId.name && e.source === entryId.source); - filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions; + filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind || (typeof expectedKind === "object" && e.kind === expectedKind.kind)) : filterCompletions; filterCompletions = filterCompletions.filter(entry => { const details = this.getCompletionEntryDetails(entry.name); const documentation = details && ts.displayPartsToString(details.documentation); @@ -1212,7 +1229,7 @@ Actual: ${stringify(fullActual)}`); this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${stringify(missingItem)} in the returned list: (${stringify(references)})`); } - private getCompletionListAtCaret(options?: ts.GetCompletionsAtPositionOptions): ts.CompletionInfo { + private getCompletionListAtCaret(options?: FourSlashInterface.CompletionsAtOptions): ts.CompletionInfo { return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition, options); } @@ -1568,7 +1585,7 @@ Actual: ${stringify(fullActual)}`); } public baselineCurrentFileBreakpointLocations() { - let baselineFile = this.testData.globalOptions[metadataOptionNames.baselineFile]; + let baselineFile = this.testData.globalOptions[MetadataOptionNames.baselineFile]; if (!baselineFile) { baselineFile = this.activeFile.fileName.replace(this.basePath + "/breakpointValidation", "bpSpan"); baselineFile = baselineFile.replace(ts.Extension.Ts, ".baseline"); @@ -1587,7 +1604,7 @@ Actual: ${stringify(fullActual)}`); const allFourSlashFiles = this.testData.files; for (const file of allFourSlashFiles) { - if (file.fileOptions[metadataOptionNames.emitThisFile] === "true") { + if (file.fileOptions[MetadataOptionNames.emitThisFile] === "true") { // Find a file with the flag emitThisFile turned on emitFiles.push(file); } @@ -1599,7 +1616,7 @@ Actual: ${stringify(fullActual)}`); } Harness.Baseline.runBaseline( - this.testData.globalOptions[metadataOptionNames.baselineFile], + this.testData.globalOptions[MetadataOptionNames.baselineFile], () => { let resultString = ""; // Loop through all the emittedFiles and emit them one by one @@ -1639,7 +1656,7 @@ Actual: ${stringify(fullActual)}`); } public baselineQuickInfo() { - let baselineFile = this.testData.globalOptions[metadataOptionNames.baselineFile]; + let baselineFile = this.testData.globalOptions[MetadataOptionNames.baselineFile]; if (!baselineFile) { baselineFile = ts.getBaseFileName(this.activeFile.fileName).replace(ts.Extension.Ts, ".baseline"); } @@ -1726,7 +1743,7 @@ Actual: ${stringify(fullActual)}`); const longestNameLength = max(entries, m => m.name.length); const longestKindLength = max(entries, m => m.kind.length); entries.sort((m, n) => m.sortText > n.sortText ? 1 : m.sortText < n.sortText ? -1 : m.name > n.name ? 1 : m.name < n.name ? -1 : 0); - const membersString = entries.map(m => `${pad(m.name, longestNameLength)} ${pad(m.kind, longestKindLength)} ${m.kindModifiers} ${m.source === undefined ? "" : m.source}`).join("\n"); + const membersString = entries.map(m => `${pad(m.name, longestNameLength)} ${pad(m.kind, longestKindLength)} ${m.kindModifiers} ${m.isRecommended ? "recommended " : ""}${m.source === undefined ? "" : m.source}`).join("\n"); Harness.IO.log(membersString); } @@ -1807,7 +1824,7 @@ Actual: ${stringify(fullActual)}`); } else if (prevChar === " " && /A-Za-z_/.test(ch)) { /* Completions */ - this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset, { includeExternalModuleExports: false }); + this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); } if (i % checkCadence === 0) { @@ -2249,7 +2266,7 @@ Actual: ${stringify(fullActual)}`); public baselineCurrentFileNameOrDottedNameSpans() { Harness.Baseline.runBaseline( - this.testData.globalOptions[metadataOptionNames.baselineFile], + this.testData.globalOptions[MetadataOptionNames.baselineFile], () => { return this.baselineCurrentFileLocations(pos => this.getNameOrDottedNameSpan(pos)); @@ -2376,13 +2393,14 @@ Actual: ${stringify(fullActual)}`); */ public getAndApplyCodeActions(errorCode?: number, index?: number) { const fileName = this.activeFile.fileName; - this.applyCodeActions(this.getCodeFixActions(fileName, errorCode), index); + this.applyCodeActions(this.getCodeFixes(fileName, errorCode), index); } public applyCodeActionFromCompletion(markerName: string, options: FourSlashInterface.VerifyCompletionActionOptions) { this.goToMarker(markerName); - const actualCompletion = this.getCompletionListAtCaret({ includeExternalModuleExports: true }).entries.find(e => e.name === options.name && e.source === options.source); + const actualCompletion = this.getCompletionListAtCaret({ includeExternalModuleExports: true, includeInsertTextCompletions: false }).entries.find(e => + e.name === options.name && e.source === options.source); if (!actualCompletion.hasAction) { this.raiseError(`Completion for ${options.name} does not have an associated action.`); @@ -2429,6 +2447,17 @@ Actual: ${stringify(fullActual)}`); this.verifyRangeIs(expectedText, includeWhiteSpace); } + public verifyCodeFixAll(options: FourSlashInterface.VerifyCodeFixAllOptions): void { + const { fixId, newFileContent } = options; + const fixIds = ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => a.fixId); + ts.Debug.assert(ts.contains(fixIds, fixId), "No available code fix has that group id.", () => `Expected '${fixId}'. Available action ids: ${fixIds}`); + const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings); + assert.deepEqual(commands, options.commands); + assert(changes.every(c => c.fileName === this.activeFile.fileName), "TODO: support testing codefixes that touch multiple files"); + this.applyChanges(changes); + this.verifyCurrentFileContent(newFileContent); + } + /** * Applies fixes for the errors in fileName and compares the results to * expectedContents after all fixes have been applied. @@ -2441,7 +2470,7 @@ Actual: ${stringify(fullActual)}`); public verifyFileAfterCodeFix(expectedContents: string, fileName?: string) { fileName = fileName ? fileName : this.activeFile.fileName; - this.applyCodeActions(this.getCodeFixActions(fileName)); + this.applyCodeActions(this.getCodeFixes(fileName)); const actualContents: string = this.getFileContent(fileName); if (this.removeWhitespace(actualContents) !== this.removeWhitespace(expectedContents)) { @@ -2451,7 +2480,7 @@ Actual: ${stringify(fullActual)}`); public verifyCodeFix(options: FourSlashInterface.VerifyCodeFixOptions) { const fileName = this.activeFile.fileName; - const actions = this.getCodeFixActions(fileName, options.errorCode); + const actions = this.getCodeFixes(fileName, options.errorCode); let index = options.index; if (index === undefined) { if (!(actions && actions.length === 1)) { @@ -2477,7 +2506,7 @@ Actual: ${stringify(fullActual)}`); } private verifyNewContent(options: FourSlashInterface.NewContentOptions) { - if (options.newFileContent) { + if (options.newFileContent !== undefined) { assert(!options.newRangeContent); this.verifyCurrentFileContent(options.newFileContent); } @@ -2490,7 +2519,7 @@ Actual: ${stringify(fullActual)}`); * Rerieves a codefix satisfying the parameters, or undefined if no such codefix is found. * @param fileName Path to file where error should be retrieved from. */ - private getCodeFixActions(fileName: string, errorCode?: number): ts.CodeAction[] { + private getCodeFixes(fileName: string, errorCode?: number): ts.CodeFixAction[] { const diagnosticsForCodeFix = this.getDiagnostics(fileName).map(diagnostic => ({ start: diagnostic.start, length: diagnostic.length, @@ -2506,7 +2535,7 @@ Actual: ${stringify(fullActual)}`); }); } - private applyCodeActions(actions: ts.CodeAction[], index?: number): void { + private applyCodeActions(actions: ReadonlyArray, index?: number): void { if (index === undefined) { if (!(actions && actions.length === 1)) { this.raiseError(`Should find exactly one codefix, but ${actions ? actions.length : "none"} found. ${actions ? actions.map(a => `${Harness.IO.newLine()} "${a.description}"`) : ""}`); @@ -2519,20 +2548,22 @@ Actual: ${stringify(fullActual)}`); } } - const changes = actions[index].changes; + this.applyChanges(actions[index].changes); + } + private applyChanges(changes: ReadonlyArray): void { for (const change of changes) { this.applyEdits(change.fileName, change.textChanges, /*isFormattingEdit*/ false); } } public verifyImportFixAtPosition(expectedTextArray: string[], errorCode?: number) { - const ranges = this.getRanges(); - if (ranges.length === 0) { - this.raiseError("At least one range should be specified in the testfile."); + const ranges = this.getRanges().filter(r => r.fileName === this.activeFile.fileName); + if (ranges.length !== 1) { + this.raiseError("Exactly one range should be specified in the testfile."); } - const codeFixes = this.getCodeFixActions(this.activeFile.fileName, errorCode); + const codeFixes = this.getCodeFixes(this.activeFile.fileName, errorCode); if (codeFixes.length === 0) { if (expectedTextArray.length !== 0) { @@ -2871,7 +2902,7 @@ Actual: ${stringify(fullActual)}`); } public verifyCodeFixAvailable(negative: boolean, info: FourSlashInterface.VerifyCodeFixAvailableOptions[] | undefined) { - const codeFixes = this.getCodeFixActions(this.activeFile.fileName); + const codeFixes = this.getCodeFixes(this.activeFile.fileName); if (negative) { if (codeFixes.length) { @@ -3038,7 +3069,7 @@ Actual: ${stringify(fullActual)}`); } public printAvailableCodeFixes() { - const codeFixes = this.getCodeFixActions(this.activeFile.fileName); + const codeFixes = this.getCodeFixes(this.activeFile.fileName); Harness.IO.log(stringify(codeFixes)); } @@ -3076,7 +3107,7 @@ Actual: ${stringify(fullActual)}`); entryId: ts.Completions.CompletionEntryIdentifier, text: string | undefined, documentation: string | undefined, - kind: string | undefined, + kind: string | undefined | { kind?: string, kindModifiers?: string }, spanIndex: number | undefined, hasAction: boolean | undefined, options: FourSlashInterface.VerifyCompletionListContainsOptions | undefined, @@ -3110,15 +3141,28 @@ Actual: ${stringify(fullActual)}`); } if (kind !== undefined) { - assert.equal(item.kind, kind, this.assertionMessageAtLastKnownMarker("completion item kind for " + entryId)); + if (typeof kind === "string") { + assert.equal(item.kind, kind, this.assertionMessageAtLastKnownMarker("completion item kind for " + entryId)); + } + else { + if (kind.kind) { + assert.equal(item.kind, kind.kind, this.assertionMessageAtLastKnownMarker("completion item kind for " + entryId)); + } + if (kind.kindModifiers !== undefined) { + assert.equal(item.kindModifiers, kind.kindModifiers, this.assertionMessageAtLastKnownMarker("completion item kindModifiers for " + entryId)); + } + } } + + if (spanIndex !== undefined) { const span = this.getTextSpanForRangeAtIndex(spanIndex); assert.isTrue(TestState.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + entryId)); } assert.equal(item.hasAction, hasAction); + assert.equal(item.isRecommended, options && options.isRecommended, "isRecommended"); } private findFile(indexOrName: string | number) { @@ -3168,8 +3212,7 @@ Actual: ${stringify(fullActual)}`); private getTextSpanForRangeAtIndex(index: number): ts.TextSpan { const ranges = this.getRanges(); if (ranges && ranges.length > index) { - const range = ranges[index]; - return { start: range.start, length: range.end - range.start }; + return textSpanFromRange(ranges[index]); } else { this.raiseError("Supplied span index: " + index + " does not exist in range list of size: " + (ranges ? 0 : ranges.length)); @@ -3199,6 +3242,10 @@ Actual: ${stringify(fullActual)}`); } } + function textSpanFromRange(range: FourSlash.Range): ts.TextSpan { + return ts.createTextSpanFromBounds(range.start, range.end); + } + export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) { const content = Harness.IO.readFile(fileName); runFourSlashTestContent(basePath, testType, content, fileName); @@ -3274,12 +3321,21 @@ ${code} // Stuff related to the subfile we're parsing let currentFileContent: string = undefined; let currentFileName = fileName; + let currentFileSymlinks: string[] | undefined; let currentFileOptions: { [s: string]: string } = {}; - function resetLocalData() { + function nextFile() { + const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + file.fileOptions = currentFileOptions; + file.symlinks = currentFileSymlinks; + + // Store result file + files.push(file); + currentFileContent = undefined; currentFileOptions = {}; currentFileName = fileName; + currentFileSymlinks = undefined; } for (let line of lines) { @@ -3308,8 +3364,7 @@ ${code} const match = optionRegex.exec(line.substr(2)); if (match) { const [key, value] = match.slice(1); - const fileMetadataNamesIndex = fileMetadataNames.indexOf(key); - if (fileMetadataNamesIndex === -1) { + if (!ts.contains(fileMetadataNames, key)) { // Check if the match is already existed in the global options if (globalOptions[key] !== undefined) { throw new Error(`Global option '${key}' already exists`); @@ -3317,24 +3372,22 @@ ${code} globalOptions[key] = value; } else { - if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) { - // Found an @FileName directive, if this is not the first then create a new subfile - if (currentFileContent) { - const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); - file.fileOptions = currentFileOptions; - - // Store result file - files.push(file); - - resetLocalData(); - } + switch (key) { + case MetadataOptionNames.fileName: + // Found an @FileName directive, if this is not the first then create a new subfile + if (currentFileContent) { + nextFile(); + } - currentFileName = ts.isRootedDiskPath(value) ? value : basePath + "/" + value; - currentFileOptions[key] = value; - } - else { - // Add other fileMetadata flag - currentFileOptions[key] = value; + currentFileName = ts.isRootedDiskPath(value) ? value : basePath + "/" + value; + currentFileOptions[key] = value; + break; + case MetadataOptionNames.symlink: + currentFileSymlinks = ts.append(currentFileSymlinks, value); + break; + default: + // Add other fileMetadata flag + currentFileOptions[key] = value; } } } @@ -3346,19 +3399,13 @@ ${code} else { // Empty line or code line, terminate current subfile if there is one if (currentFileContent) { - const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); - file.fileOptions = currentFileOptions; - - // Store result file - files.push(file); - - resetLocalData(); + nextFile(); } } } // @Filename is the only directive that can be used in a test that contains tsconfig.json file. - if (containTSConfigJson(files)) { + if (files.some(isTsconfig)) { let directive = getNonFileNameOptionInFileList(files); if (!directive) { directive = getNonFileNameOptionInObject(globalOptions); @@ -3377,8 +3424,8 @@ ${code} }; } - function containTSConfigJson(files: FourSlashFile[]): boolean { - return ts.forEach(files, f => f.fileOptions.Filename === "tsconfig.json"); + function isTsconfig(file: FourSlashFile): boolean { + return ts.getBaseFileName(file.fileName).toLowerCase() === "tsconfig.json"; } function getNonFileNameOptionInFileList(files: FourSlashFile[]): string { @@ -3387,7 +3434,7 @@ ${code} function getNonFileNameOptionInObject(optionObject: { [s: string]: string }): string { for (const option in optionObject) { - if (option !== metadataOptionNames.fileName) { + if (option !== MetadataOptionNames.fileName) { return option; } } @@ -3749,8 +3796,11 @@ namespace FourSlashInterface { this.state.goToMarker(name); } - public eachMarker(action: () => void) { - this.state.goToEachMarker(action); + public eachMarker(markers: ReadonlyArray, action: (marker: FourSlash.Marker, index: number) => void): void; + public eachMarker(action: (marker: FourSlash.Marker, index: number) => void): void; + public eachMarker(a: ReadonlyArray | ((marker: FourSlash.Marker, index: number) => void), b?: (marker: FourSlash.Marker, index: number) => void): void { + const markers = typeof a === "function" ? this.state.getMarkers() : a.map(m => this.state.getMarkerByName(m)); + this.state.goToEachMarker(markers, typeof a === "function" ? a : b); } public rangeStart(range: FourSlash.Range) { @@ -3829,7 +3879,7 @@ namespace FourSlashInterface { // Verifies the completion list contains the specified symbol. The // completion list is brought up if necessary - public completionListContains(entryId: string | ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string, spanIndex?: number, hasAction?: boolean, options?: VerifyCompletionListContainsOptions) { + public completionListContains(entryId: string | ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, hasAction?: boolean, options?: VerifyCompletionListContainsOptions) { if (typeof entryId === "string") { entryId = { name: entryId, source: undefined }; } @@ -3941,7 +3991,7 @@ namespace FourSlashInterface { super(state); } - public completionsAt(markerName: string, completions: string[], options?: CompletionsAtOptions) { + public completionsAt(markerName: string, completions: ReadonlyArray, options?: CompletionsAtOptions) { this.state.verifyCompletionsAt(markerName, completions, options); } @@ -4152,6 +4202,10 @@ namespace FourSlashInterface { this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index); } + public codeFixAll(options: VerifyCodeFixAllOptions): void { + this.state.verifyCodeFixAll(options); + } + public fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, actionName: string, formattingOptions?: ts.FormatCodeSettings): void { this.state.verifyFileAfterApplyingRefactorAtMarker(markerName, expectedContent, refactorNameToApply, actionName, formattingOptions); } @@ -4561,12 +4615,14 @@ namespace FourSlashInterface { newContent: string; } - export interface CompletionsAtOptions { + export type ExpectedCompletionEntry = string | { name: string, insertText?: string, replacementSpan?: FourSlash.Range }; + export interface CompletionsAtOptions extends ts.GetCompletionsAtPositionOptions { isNewIdentifierLocation?: boolean; } export interface VerifyCompletionListContainsOptions extends ts.GetCompletionsAtPositionOptions { sourceDisplay: string; + isRecommended?: true; } export interface NewContentOptions { @@ -4586,6 +4642,12 @@ namespace FourSlashInterface { commands?: ts.CodeActionCommand[]; } + export interface VerifyCodeFixAllOptions { + fixId: string; + newFileContent: string; + commands: ReadonlyArray<{}>; + } + export interface VerifyRefactorOptions { name: string; actionName: string; diff --git a/src/harness/harness.ts b/src/harness/harness.ts index f4a58352b1661..612224cb312a2 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -32,9 +32,30 @@ // this will work in the browser via browserify var _chai: typeof chai = require("chai"); var assert: typeof _chai.assert = _chai.assert; -// chai's builtin `assert.isFalse` is featureful but slow - we don't use those features, -// so we'll just overwrite it as an alterative to migrating a bunch of code off of chai -assert.isFalse = (expr, msg) => { if (expr as any as boolean !== false) throw new Error(msg); }; +{ + // chai's builtin `assert.isFalse` is featureful but slow - we don't use those features, + // so we'll just overwrite it as an alterative to migrating a bunch of code off of chai + assert.isFalse = (expr, msg) => { if (expr as any as boolean !== false) throw new Error(msg); }; + + const assertDeepImpl = assert.deepEqual; + assert.deepEqual = (a, b, msg) => { + if (ts.isArray(a) && ts.isArray(b)) { + assertDeepImpl(arrayExtraKeysObject(a), arrayExtraKeysObject(b), "Array extra keys differ"); + } + assertDeepImpl(a, b, msg); + + function arrayExtraKeysObject(a: ReadonlyArray<{} | null | undefined>): object { + const obj: { [key: string]: {} | null | undefined } = {}; + for (const key in a) { + if (Number.isNaN(Number(key))) { + obj[key] = a[key]; + } + } + return obj; + } + }; +} + declare var __dirname: string; // Node-specific var global: NodeJS.Global = Function("return this").call(undefined); @@ -42,7 +63,7 @@ declare var window: {}; declare var XMLHttpRequest: { new(): XMLHttpRequest; }; -interface XMLHttpRequest { +interface XMLHttpRequest { readonly readyState: number; readonly responseText: string; readonly status: number; @@ -853,7 +874,7 @@ namespace Harness { // Cache of lib files from "built/local" let libFileNameSourceFileMap: ts.Map | undefined; - // Cache of lib files from "tests/lib/" + // Cache of lib files from "tests/lib/" const testLibFileNameSourceFileMap = ts.createMap(); const es6TestLibFileNameSourceFileMap = ts.createMap(); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index d4b5a9c2a16db..d51517c159b5e 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -122,7 +122,7 @@ namespace Harness.LanguageService { getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo; } - export class LanguageServiceAdapterHost { + export abstract class LanguageServiceAdapterHost { public typesRegistry: ts.Map | undefined; protected virtualFileSystem: Utils.VirtualFileSystem = new Utils.VirtualFileSystem(virtualFileSystemRoot, /*useCaseSensitiveFilenames*/false); @@ -166,6 +166,8 @@ namespace Harness.LanguageService { throw new Error("No script with name '" + fileName + "'"); } + public abstract addSymlink(from: string, target: string): void; + public openFile(_fileName: string, _content?: string, _scriptKindName?: string): void { /*overridden*/ } /** @@ -181,7 +183,9 @@ namespace Harness.LanguageService { } /// Native adapter - class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost { + class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost, LanguageServiceAdapterHost { + symlinks = ts.createMap(); + isKnownTypesPackageName(name: string): boolean { return this.typesRegistry && this.typesRegistry.has(name); } @@ -212,13 +216,16 @@ namespace Harness.LanguageService { } directoryExists(dirName: string): boolean { + if (ts.forEachEntry(this.symlinks, (_, key) => ts.forSomeAncestorDirectory(key, ancestor => ancestor === dirName))) { + return true; + } + const fileEntry = this.virtualFileSystem.traversePath(dirName); return fileEntry && fileEntry.isDirectory(); } fileExists(fileName: string): boolean { - const script = this.getScriptSnapshot(fileName); - return script !== undefined; + return this.symlinks.has(fileName) || this.getScriptSnapshot(fileName) !== undefined; } readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { return ts.matchFiles(path, extensions, exclude, include, @@ -228,9 +235,19 @@ namespace Harness.LanguageService { (p) => this.virtualFileSystem.getAccessibleFileSystemEntries(p)); } readFile(path: string): string | undefined { + const target = this.symlinks.get(path); + if (target !== undefined) { + return this.readFile(target); + } + const snapshot = this.getScriptSnapshot(path); return snapshot.getText(0, snapshot.getLength()); } + addSymlink(from: string, target: string) { this.symlinks.set(from, target); } + realpath(path: string): string { + const target = this.symlinks.get(path); + return target === undefined ? path : target; + } getTypeRootsVersion() { return 0; } @@ -246,7 +263,7 @@ namespace Harness.LanguageService { constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) { this.host = new NativeLanguageServiceHost(cancellationToken, options); } - getHost() { return this.host; } + getHost(): LanguageServiceAdapterHost { return this.host; } getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); } getClassifier(): ts.Classifier { return ts.createClassifier(); } getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavaScriptFileExtension(fileName)); } @@ -259,6 +276,8 @@ namespace Harness.LanguageService { public getModuleResolutionsForFile: (fileName: string) => string; public getTypeReferenceDirectiveResolutionsForFile: (fileName: string) => string; + addSymlink() { return ts.notImplemented(); } + constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) { super(cancellationToken, options); this.nativeHost = new NativeLanguageServiceHost(cancellationToken, options); @@ -503,9 +522,10 @@ namespace Harness.LanguageService { getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): ts.TextSpan { return unwrapJSONCallResult(this.shim.getSpanOfEnclosingComment(fileName, position, onlyMultiLine)); } - getCodeFixesAtPosition(): ts.CodeAction[] { + getCodeFixesAtPosition(): never { throw new Error("Not supported on the shim."); } + getCombinedCodeFix = ts.notImplemented; applyCodeActionCommand = ts.notImplemented; getCodeFixDiagnostics(): ts.Diagnostic[] { throw new Error("Not supported on the shim."); diff --git a/src/harness/parallel/host.ts b/src/harness/parallel/host.ts index eca719628c795..59105cd5b0829 100644 --- a/src/harness/parallel/host.ts +++ b/src/harness/parallel/host.ts @@ -9,6 +9,8 @@ namespace Harness.Parallel.Host { on(event: "error", listener: (err: Error) => void): this; on(event: "exit", listener: (code: number, signal: string) => void): this; on(event: "message", listener: (message: ParallelClientMessage) => void): this; + kill(signal?: string): void; + currentTasks?: {file: string}[]; // Custom monkeypatch onto child process handle } interface ProgressBarsOptions { @@ -134,6 +136,11 @@ namespace Harness.Parallel.Host { const newPerfData: {[testHash: string]: number} = {}; const workers: ChildProcessPartial[] = []; + const defaultTimeout = globalTimeout !== undefined + ? globalTimeout + : mocha && mocha.suite && mocha.suite._timeout + ? mocha.suite._timeout + : 20000; // 20 seconds let closedWorkers = 0; for (let i = 0; i < workerCount; i++) { // TODO: Just send the config over the IPC channel or in the command line arguments @@ -141,6 +148,14 @@ namespace Harness.Parallel.Host { const configPath = ts.combinePaths(taskConfigsFolder, `task-config${i}.json`); Harness.IO.writeFile(configPath, JSON.stringify(config)); const child = fork(__filename, [`--config="${configPath}"`]); + let currentTimeout = defaultTimeout; + const killChild = () => { + child.kill(); + console.error(`Worker exceeded ${currentTimeout}ms timeout ${child.currentTasks && child.currentTasks.length ? `while running test '${child.currentTasks[0].file}'.` : `during test setup.`}`); + return process.exit(2); + }; + let timer = setTimeout(killChild, currentTimeout); + const timeoutStack: number[] = []; child.on("error", err => { console.error("Unexpected error in child process:"); console.error(err); @@ -160,8 +175,25 @@ namespace Harness.Parallel.Host { Stack: ${data.payload.stack}`); return process.exit(2); } + case "timeout": { + clearTimeout(timer); + if (data.payload.duration === "reset") { + currentTimeout = timeoutStack.pop() || defaultTimeout; + } + else { + timeoutStack.push(currentTimeout); + currentTimeout = data.payload.duration; + } + timer = setTimeout(killChild, currentTimeout); // Reset timeout on timeout update, for when a timeout changes while a suite is executing + break; + } case "progress": case "result": { + clearTimeout(timer); + timer = setTimeout(killChild, currentTimeout); + if (child.currentTasks) { + child.currentTasks.shift(); + } totalPassing += data.payload.passing; if (data.payload.errors.length) { errorResults = errorResults.concat(data.payload.errors); @@ -195,6 +227,7 @@ namespace Harness.Parallel.Host { while (tasks.length && taskList.reduce((p, c) => p + c.size, 0) < chunkSize) { taskList.push(tasks.pop()); } + child.currentTasks = taskList; if (taskList.length === 1) { child.send({ type: "test", payload: taskList[0] }); } @@ -252,18 +285,22 @@ namespace Harness.Parallel.Host { for (const worker of workers) { const payload = batches.pop(); if (payload) { + worker.currentTasks = payload; worker.send({ type: "batch", payload }); } else { // Out of batches, send off just one test const payload = tasks.pop(); ts.Debug.assert(!!payload); // The reserve kept above should ensure there is always an initial task available, even in suboptimal scenarios + worker.currentTasks = [payload]; worker.send({ type: "test", payload }); } } } else { for (let i = 0; i < workerCount; i++) { - workers[i].send({ type: "test", payload: tasks.pop() }); + const task = tasks.pop(); + workers[i].currentTasks = [task]; + workers[i].send({ type: "test", payload: task }); } } diff --git a/src/harness/parallel/shared.ts b/src/harness/parallel/shared.ts index 2eb7777f82870..26b03ac623425 100644 --- a/src/harness/parallel/shared.ts +++ b/src/harness/parallel/shared.ts @@ -10,5 +10,6 @@ namespace Harness.Parallel { export type ErrorInfo = ParallelErrorMessage["payload"] & { name: string[] }; export type ParallelResultMessage = { type: "result", payload: { passing: number, errors: ErrorInfo[], duration: number, runner: TestRunnerKind | "unittest", file: string } } | never; export type ParallelBatchProgressMessage = { type: "progress", payload: ParallelResultMessage["payload"] } | never; - export type ParallelClientMessage = ParallelErrorMessage | ParallelResultMessage | ParallelBatchProgressMessage; + export type ParallelTimeoutChangeMessage = { type: "timeout", payload: { duration: number | "reset" } } | never; + export type ParallelClientMessage = ParallelErrorMessage | ParallelResultMessage | ParallelBatchProgressMessage | ParallelTimeoutChangeMessage; } \ No newline at end of file diff --git a/src/harness/parallel/worker.ts b/src/harness/parallel/worker.ts index 013992a8e350c..1902ff70b1933 100644 --- a/src/harness/parallel/worker.ts +++ b/src/harness/parallel/worker.ts @@ -36,11 +36,28 @@ namespace Harness.Parallel.Worker { }) as Mocha.ITestDefinition; } + function setTimeoutAndExecute(timeout: number | undefined, f: () => void) { + if (timeout !== undefined) { + const timeoutMsg: ParallelTimeoutChangeMessage = { type: "timeout", payload: { duration: timeout } }; + process.send(timeoutMsg); + } + f(); + if (timeout !== undefined) { + // Reset timeout + const timeoutMsg: ParallelTimeoutChangeMessage = { type: "timeout", payload: { duration: "reset" } }; + process.send(timeoutMsg); + } + } + function executeSuiteCallback(name: string, callback: MochaCallback) { + let timeout: number; const fakeContext: Mocha.ISuiteCallbackContext = { retries() { return this; }, slow() { return this; }, - timeout() { return this; }, + timeout(n) { + timeout = n as number; + return this; + }, }; namestack.push(name); let beforeFunc: Callable; @@ -71,7 +88,10 @@ namespace Harness.Parallel.Worker { finally { beforeFunc = undefined; } - testList.forEach(({ name, callback, kind }) => executeCallback(name, callback, kind)); + + setTimeoutAndExecute(timeout, () => { + testList.forEach(({ name, callback, kind }) => executeCallback(name, callback, kind)); + }); try { if (afterFunc) { @@ -103,9 +123,15 @@ namespace Harness.Parallel.Worker { } function executeTestCallback(name: string, callback: MochaCallback) { + let timeout: number; const fakeContext: Mocha.ITestCallbackContext = { skip() { return this; }, - timeout() { return this; }, + timeout(n) { + timeout = n as number; + const timeoutMsg: ParallelTimeoutChangeMessage = { type: "timeout", payload: { duration: timeout } }; + process.send(timeoutMsg); + return this; + }, retries() { return this; }, slow() { return this; }, }; @@ -131,6 +157,10 @@ namespace Harness.Parallel.Worker { } finally { namestack.pop(); + if (timeout !== undefined) { + const timeoutMsg: ParallelTimeoutChangeMessage = { type: "timeout", payload: { duration: "reset" } }; + process.send(timeoutMsg); + } } passing++; } @@ -157,6 +187,10 @@ namespace Harness.Parallel.Worker { } finally { namestack.pop(); + if (timeout !== undefined) { + const timeoutMsg: ParallelTimeoutChangeMessage = { type: "timeout", payload: { duration: "reset" } }; + process.send(timeoutMsg); + } } if (!completed) { errors.push({ error: "Test completes asynchronously, which is unsupported by the parallel harness", stack: "", name: [...namestack] }); diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index c617cc7a0a3ec..f8d4d171f01df 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -186,7 +186,7 @@ class ProjectRunner extends RunnerBase { getCanonicalFileName: Harness.Compiler.getCanonicalFileName, useCaseSensitiveFileNames: () => Harness.IO.useCaseSensitiveFileNames(), getNewLine: () => Harness.IO.newLine(), - fileExists: fileName => fileName === Harness.Compiler.defaultLibFileName || getSourceFileText(fileName) !== undefined, + fileExists: fileName => fileName === Harness.Compiler.defaultLibFileName || getSourceFileText(fileName) !== undefined, readFile: fileName => Harness.IO.readFile(fileName), getDirectories: path => Harness.IO.getDirectories(path) }; diff --git a/src/harness/runner.ts b/src/harness/runner.ts index 2bd098b742db1..76d65090f02db 100644 --- a/src/harness/runner.ts +++ b/src/harness/runner.ts @@ -100,6 +100,7 @@ interface TestConfig { runners?: string[]; runUnitTests?: boolean; noColors?: boolean; + timeout?: number; } interface TaskSet { @@ -108,12 +109,16 @@ interface TaskSet { } let configOption: string; +let globalTimeout: number; function handleTestConfig() { if (testConfigContent !== "") { const testConfig = JSON.parse(testConfigContent); if (testConfig.light) { Harness.lightMode = true; } + if (testConfig.timeout) { + globalTimeout = testConfig.timeout; + } runUnitTests = testConfig.runUnitTests; if (testConfig.workerCount) { workerCount = +testConfig.workerCount; diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index db38b95ba6a85..25642ab517923 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -108,6 +108,7 @@ "./unittests/reuseProgramStructure.ts", "./unittests/moduleResolution.ts", "./unittests/tsconfigParsing.ts", + "./unittests/asserts.ts", "./unittests/builder.ts", "./unittests/commandLineParsing.ts", "./unittests/configurationExtension.ts", diff --git a/src/harness/unittests/asserts.ts b/src/harness/unittests/asserts.ts new file mode 100644 index 0000000000000..ec274c44c228c --- /dev/null +++ b/src/harness/unittests/asserts.ts @@ -0,0 +1,11 @@ +/// + +namespace ts { + describe("assert", () => { + it("deepEqual", () => { + assert.throws(() => assert.deepEqual(createNodeArray([createIdentifier("A")]), createNodeArray([createIdentifier("B")]))); + assert.throws(() => assert.deepEqual(createNodeArray([], /*hasTrailingComma*/ true), createNodeArray([], /*hasTrailingComma*/ false))); + assert.deepEqual(createNodeArray([createIdentifier("A")], /*hasTrailingComma*/ true), createNodeArray([createIdentifier("A")], /*hasTrailingComma*/ true)); + }); + }); +} diff --git a/src/harness/unittests/builder.ts b/src/harness/unittests/builder.ts index bfdeb1a40678a..a5d880fa55156 100644 --- a/src/harness/unittests/builder.ts +++ b/src/harness/unittests/builder.ts @@ -43,7 +43,7 @@ namespace ts { }); }); - function makeAssertChanges(getProgram: () => Program): (fileNames: ReadonlyArray) => void { + function makeAssertChanges(getProgram: () => Program): (fileNames: ReadonlyArray) => void { const builder = createBuilder({ getCanonicalFileName: identity, computeHash: identity diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index 18e867cb9eaaa..050178f63b36b 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -60,7 +60,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -165,7 +165,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'.", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'esnext'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -263,7 +263,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -283,7 +283,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, diff --git a/src/harness/unittests/compileOnSave.ts b/src/harness/unittests/compileOnSave.ts index 7ef3e2aa1af68..a64d7bdd2a57f 100644 --- a/src/harness/unittests/compileOnSave.ts +++ b/src/harness/unittests/compileOnSave.ts @@ -304,6 +304,24 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, []); }); + it("should return empty array if noEmit is set", () => { + configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compileOnSave": true, + "compilerOptions": { + "noEmit": true + } + }` + }; + + const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, configFile, libFile]); + const typingsInstaller = createTestTypingsInstaller(host); + const session = createSession(host, typingsInstaller); + openFilesForSession([moduleFile1], session); + sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, []); + }); + it("should save when compileOnSave is enabled in base tsconfig.json", () => { configFile = { path: "/a/b/tsconfig.json", diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index 3a73971d7a3ad..0bad2ba1e3a92 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -209,7 +209,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'.", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'esnext'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -266,7 +266,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -297,7 +297,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -328,7 +328,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -359,7 +359,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.asynciterable'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/src/harness/unittests/extractConstants.ts b/src/harness/unittests/extractConstants.ts index 61ffbd01a639b..71b550cba8fa0 100644 --- a/src/harness/unittests/extractConstants.ts +++ b/src/harness/unittests/extractConstants.ts @@ -262,6 +262,18 @@ namespace N { // Force this test to be TS-only y = [#|this.x|]; } }`); + + // TODO (https://github.com/Microsoft/TypeScript/issues/20727): the extracted constant should have a type annotation. + testExtractConstant("extractConstant_ContextualType", ` +interface I { a: 1 | 2 | 3 } +let i: I = [#|{ a: 1 }|]; +`); + + testExtractConstant("extractConstant_ContextualType_Lambda", ` +const myObj: { member(x: number, y: string): void } = { + member: [#|(x, y) => x + y|], +} +`); }); function testExtractConstant(caption: string, text: string) { diff --git a/src/harness/unittests/languageService.ts b/src/harness/unittests/languageService.ts index 1407a518617f8..f14b9daad8206 100644 --- a/src/harness/unittests/languageService.ts +++ b/src/harness/unittests/languageService.ts @@ -40,9 +40,6 @@ export function Component(x: Config): any;` getDefaultLibFileName(options) { return ts.getDefaultLibFilePath(options); }, - fileExists: noop as any, - readFile: noop as any, - readDirectory: noop as any, }); const definitions = languageService.getDefinitionAtPosition("foo.ts", 160); // 160 is the latter `vueTemplateHtml` position expect(definitions).to.exist; // tslint:disable-line no-unused-expression diff --git a/src/harness/unittests/matchFiles.ts b/src/harness/unittests/matchFiles.ts index f2c2369ef37f4..17a0db04fdf31 100644 --- a/src/harness/unittests/matchFiles.ts +++ b/src/harness/unittests/matchFiles.ts @@ -50,6 +50,7 @@ namespace ts { "/dev/x/b.ts", "/dev/x/y/a.ts", "/dev/x/y/b.ts", + "/dev/q/a/c/b/d.ts", "/dev/js/a.js", "/dev/js/b.js", ]); @@ -1171,13 +1172,17 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [ - createDiagnosticForConfigFile(json, 12, 11, ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**/*"), - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, - caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") + errors: [], + fileNames: [ + "c:/dev/x/a.ts", + "c:/dev/x/aa.ts", + "c:/dev/x/b.ts", + "c:/dev/x/y/a.ts", + "c:/dev/x/y/b.ts", ], - fileNames: [], - wildcardDirectories: {} + wildcardDirectories: { + "c:/dev": ts.WatchDirectoryFlags.Recursive + } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath); }); @@ -1192,13 +1197,9 @@ namespace ts { }; const expected: ts.ParsedCommandLine = { options: {}, - errors: [ - createDiagnosticForConfigFile(json, 34, 9, ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**") - ], + errors: [], fileNames: [ "c:/dev/a.ts", - "c:/dev/x/a.ts", - "c:/dev/x/y/a.ts", "c:/dev/z/a.ts" ], wildcardDirectories: { @@ -1426,5 +1427,60 @@ namespace ts { }); }); }); + + describe("exclude or include patterns which start with **", () => { + it("can exclude dirs whose pattern starts with **", () => { + const json = { + exclude: [ + "**/x" + ] + }; + const expected: ts.ParsedCommandLine = { + options: {}, + errors: [], + fileNames: [ + "/dev/A.ts", + "/dev/B.ts", + "/dev/a.ts", + "/dev/b.ts", + "/dev/c.d.ts", + "/dev/q/a/c/b/d.ts", + "/dev/z/a.ts", + "/dev/z/aba.ts", + "/dev/z/abz.ts", + "/dev/z/b.ts", + "/dev/z/bba.ts", + "/dev/z/bbz.ts", + ], + wildcardDirectories: { + "/dev": ts.WatchDirectoryFlags.Recursive + } + }; + validateMatches(expected, json, caseSensitiveHost, caseSensitiveBasePath); + }); + it("can include dirs whose pattern starts with **", () => { + const json = { + include: [ + "**/x", + "**/a/**/b" + ] + }; + const expected: ts.ParsedCommandLine = { + options: {}, + errors: [], + fileNames: [ + "/dev/x/a.ts", + "/dev/x/b.ts", + "/dev/x/y/a.ts", + "/dev/x/y/b.ts", + "/dev/q/a/c/b/d.ts", + ], + wildcardDirectories: { + "/dev": ts.WatchDirectoryFlags.Recursive + } + }; + validateMatches(expected, json, caseSensitiveHost, caseSensitiveBasePath); + }); + }); }); } diff --git a/src/harness/unittests/moduleResolution.ts b/src/harness/unittests/moduleResolution.ts index de79ba06cf9b3..0dd016b2f229c 100644 --- a/src/harness/unittests/moduleResolution.ts +++ b/src/harness/unittests/moduleResolution.ts @@ -313,7 +313,7 @@ namespace ts { const host = createModuleResolutionHost(/*hasDirectoryExists*/ true, { name: realFileName, symlinks: [symlinkFileName] }); const resolution = nodeModuleNameResolver("linked", "/app/app.ts", { preserveSymlinks }, host); const resolvedFileName = preserveSymlinks ? symlinkFileName : realFileName; - checkResolvedModule(resolution.resolvedModule, { resolvedFileName, isExternalLibraryImport: true, extension: Extension.Dts }); + checkResolvedModule(resolution.resolvedModule, createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ true)); }); } }); @@ -338,7 +338,7 @@ namespace ts { const path = normalizePath(combinePaths(currentDirectory, fileName)); return files.has(path); }, - readFile: notImplemented + readFile: notImplemented, }; const program = createProgram(rootFiles, options, host); @@ -426,7 +426,7 @@ export = C; const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName))); return files.has(path); }, - readFile: notImplemented + readFile: notImplemented, }; const program = createProgram(rootFiles, options, host); const diagnostics = sortAndDeduplicateDiagnostics([...program.getSemanticDiagnostics(), ...program.getOptionsDiagnostics()]); @@ -441,7 +441,7 @@ export = C; "/a/b/c.ts": `/// `, "/a/b/d.ts": "var x" }); - test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "/a/b/d.ts"], []); + test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "/a/b/d.ts"], []); }); it("should fail when two files used in program differ only in casing (tripleslash references)", () => { @@ -449,7 +449,7 @@ export = C; "/a/b/c.ts": `/// `, "/a/b/d.ts": "var x" }); - test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); + test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); }); it("should fail when two files used in program differ only in casing (imports)", () => { @@ -457,7 +457,7 @@ export = C; "/a/b/c.ts": `import {x} from "D"`, "/a/b/d.ts": "export var x" }); - test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); + test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); }); it("should fail when two files used in program differ only in casing (imports, relative module names)", () => { @@ -465,7 +465,7 @@ export = C; "moduleA.ts": `import {x} from "./ModuleB"`, "moduleB.ts": "export var x" }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts"], [1149]); + test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts"], [1149]); }); it("should fail when two files exist on disk that differs only in casing", () => { @@ -474,7 +474,7 @@ export = C; "/a/b/D.ts": "export var x", "/a/b/d.ts": "export var y" }); - test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ true, ["c.ts", "d.ts"], [1149]); + test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ true, ["c.ts", "d.ts"], [1149]); }); it("should fail when module name in 'require' calls has inconsistent casing", () => { @@ -483,7 +483,7 @@ export = C; "moduleB.ts": `import a = require("./moduleC")`, "moduleC.ts": "export var x" }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts", "moduleC.ts"], [1149, 1149]); + test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts", "moduleC.ts"], [1149, 1149]); }); it("should fail when module names in 'require' calls has inconsistent casing and current directory has uppercase chars", () => { @@ -496,7 +496,7 @@ import a = require("./moduleA"); import b = require("./moduleB"); ` }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]); + test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]); }); it("should not fail when module names in 'require' calls has consistent casing and current directory has uppercase chars", () => { const files = createMapFromTemplate({ @@ -508,7 +508,7 @@ import a = require("./moduleA"); import b = require("./moduleB"); ` }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []); + test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []); }); }); @@ -1067,7 +1067,7 @@ import b = require("./moduleB"); readFile: fileName => { const file = sourceFiles.get(fileName); return file && file.text; - } + }, }; const program1 = createProgram(names, {}, compilerHost); const diagnostics1 = program1.getFileProcessingDiagnostics().getDiagnostics(); diff --git a/src/harness/unittests/programMissingFiles.ts b/src/harness/unittests/programMissingFiles.ts index ce8abc232e746..2a7f6d24ea787 100644 --- a/src/harness/unittests/programMissingFiles.ts +++ b/src/harness/unittests/programMissingFiles.ts @@ -9,7 +9,7 @@ namespace ts { assert.isTrue(value, `${missing} to be ${value === undefined ? "not present" : "present only once"}, in actual: ${missingPaths} expected: ${expected}`); map.set(missing, false); } - const notFound = mapDefinedIter(map.keys(), k => map.get(k) === true ? k : undefined); + const notFound = arrayFrom(mapDefinedIterator(map.keys(), k => map.get(k) === true ? k : undefined)); assert.equal(notFound.length, 0, `Not found ${notFound} in actual: ${missingPaths} expected: ${expected}`); } diff --git a/src/harness/unittests/reuseProgramStructure.ts b/src/harness/unittests/reuseProgramStructure.ts index fdccc8a7795f1..4a76a479b1831 100644 --- a/src/harness/unittests/reuseProgramStructure.ts +++ b/src/harness/unittests/reuseProgramStructure.ts @@ -345,7 +345,7 @@ namespace ts { const newTexts: NamedSourceText[] = files.concat([{ name: "non-existing-file.ts", text: SourceText.New("", "", `var x = 1`) }]); const program2 = updateProgram(program1, ["a.ts"], options, noop, newTexts); - assert.deepEqual(emptyArray, program2.getMissingFilePaths()); + assert.lengthOf(program2.getMissingFilePaths(), 0); assert.equal(StructureIsReused.Not, program1.structureIsReused); }); @@ -389,6 +389,19 @@ namespace ts { checkResolvedModulesCache(program4, "a.ts", createMapFromTemplate({ b: createResolvedModule("b.ts"), c: undefined })); }); + it("set the resolvedImports after re-using an ambient external module declaration", () => { + const files = [ + { name: "/a.ts", text: SourceText.New("", "", 'import * as a from "a";') }, + { name: "/types/zzz/index.d.ts", text: SourceText.New("", "", 'declare module "a" { }') }, + ]; + const options: CompilerOptions = { target, typeRoots: ["/types"] }; + const program1 = newProgram(files, ["/a.ts"], options); + const program2 = updateProgram(program1, ["/a.ts"], options, files => { + files[0].text = files[0].text.updateProgram('import * as aa from "a";'); + }); + assert.isDefined(program2.getSourceFile("/a.ts").resolvedModules.get("a"), "'a' is not an unresolved module after re-use"); + }); + it("resolved type directives cache follows type directives", () => { const files = [ { name: "/a.ts", text: SourceText.New("/// ", "", "var x = $") }, @@ -826,12 +839,12 @@ namespace ts { updateProgramText(files, root, "const x = 1;"); }); assert.equal(program1.structureIsReused, StructureIsReused.Completely); - assert.deepEqual(program2.getSemanticDiagnostics(), emptyArray); + assert.lengthOf(program2.getSemanticDiagnostics(), 0); }); it("Target changes -> redirect broken", () => { const program1 = createRedirectProgram(); - assert.deepEqual(program1.getSemanticDiagnostics(), emptyArray); + assert.lengthOf(program1.getSemanticDiagnostics(), 0); const program2 = updateRedirectProgram(program1, files => { updateProgramText(files, axIndex, "export default class X { private x: number; private y: number; }"); diff --git a/src/harness/unittests/session.ts b/src/harness/unittests/session.ts index 5cde1e9d2eaa2..f46e173716c43 100644 --- a/src/harness/unittests/session.ts +++ b/src/harness/unittests/session.ts @@ -170,6 +170,19 @@ namespace ts.server { allowNonTsExtensions: true // injected by tsserver }); }); + + it("Status request gives ts.version", () => { + const req: protocol.StatusRequest = { + command: CommandNames.Status, + seq: 0, + type: "request" + }; + + const expected: protocol.StatusResponseBody = { + version: ts.version + }; + assert.deepEqual(session.executeCommand(req).response, expected); + }); }); describe("onMessage", () => { @@ -221,6 +234,7 @@ namespace ts.server { CommandNames.Saveto, CommandNames.SignatureHelp, CommandNames.SignatureHelpFull, + CommandNames.Status, CommandNames.TypeDefinition, CommandNames.ProjectInfo, CommandNames.ReloadProjects, diff --git a/src/harness/unittests/textChanges.ts b/src/harness/unittests/textChanges.ts index ed571b37399fa..934da4e3ba1e8 100644 --- a/src/harness/unittests/textChanges.ts +++ b/src/harness/unittests/textChanges.ts @@ -103,7 +103,7 @@ namespace M /*body */ createBlock(statements) ); - changeTracker.insertNodeBefore(sourceFile, /*before*/findChild("M2", sourceFile), newFunction, { suffix: newLineCharacter }); + changeTracker.insertNodeBefore(sourceFile, /*before*/findChild("M2", sourceFile), newFunction); // replace statements with return statement const newStatement = createReturn( @@ -129,12 +129,11 @@ function bar() { changeTracker.deleteRange(sourceFile, { pos: text.indexOf("function foo"), end: text.indexOf("function bar") }); }); } - function findVariableStatementContaining(name: string, sourceFile: SourceFile) { - const varDecl = findChild(name, sourceFile); - assert.equal(varDecl.kind, SyntaxKind.VariableDeclaration); - const varStatement = varDecl.parent.parent; - assert.equal(varStatement.kind, SyntaxKind.VariableStatement); - return varStatement; + function findVariableStatementContaining(name: string, sourceFile: SourceFile): VariableStatement { + return cast(findVariableDeclarationContaining(name, sourceFile).parent.parent, isVariableStatement); + } + function findVariableDeclarationContaining(name: string, sourceFile: SourceFile): VariableDeclaration { + return cast(findChild(name, sourceFile), isVariableDeclaration); } { const text = ` @@ -306,11 +305,11 @@ var y; // comment 4 var z = 3; // comment 5 // comment 6 var a = 4; // comment 7`; - runSingleFileTest("insertNodeAt1", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.insertNodeAt(sourceFile, text.indexOf("var y"), createTestClass(), { suffix: newLineCharacter }); + runSingleFileTest("insertNodeBefore3", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { + changeTracker.insertNodeBefore(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass()); }); - runSingleFileTest("insertNodeAt2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.insertNodeAt(sourceFile, text.indexOf("; // comment 4"), createTestVariableDeclaration("z1")); + runSingleFileTest("insertNodeAfterVariableDeclaration", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { + changeTracker.insertNodeAfter(sourceFile, findVariableDeclarationContaining("y", sourceFile), createTestVariableDeclaration("z1")); }); } { @@ -325,23 +324,22 @@ namespace M { var a = 4; // comment 7 }`; runSingleFileTest("insertNodeBefore1", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.insertNodeBefore(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { suffix: newLineCharacter }); + changeTracker.insertNodeBefore(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass()); }); runSingleFileTest("insertNodeBefore2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.insertNodeBefore(sourceFile, findChild("M", sourceFile), createTestClass(), { suffix: newLineCharacter }); + changeTracker.insertNodeBefore(sourceFile, findChild("M", sourceFile), createTestClass()); }); runSingleFileTest("insertNodeAfter1", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass()); }); runSingleFileTest("insertNodeAfter2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findChild("M", sourceFile), createTestClass(), { prefix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("M", sourceFile), createTestClass()); }); } - function findOpenBraceForConstructor(sourceFile: SourceFile) { + function findConstructor(sourceFile: SourceFile): ConstructorDeclaration { const classDecl = sourceFile.statements[0]; - const constructorDecl = forEach(classDecl.members, m => m.kind === SyntaxKind.Constructor && (m).body && m); - return constructorDecl.body.getFirstToken(); + return find(classDecl.members, (m): m is ConstructorDeclaration => isConstructorDeclaration(m) && !!m.body)!; } function createTestSuperCall() { const superCall = createCall( @@ -359,8 +357,8 @@ class A { } } `; - runSingleFileTest("insertNodeAfter3", /*placeOpenBraceOnNewLineForFunctions*/ false, text1, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findOpenBraceForConstructor(sourceFile), createTestSuperCall(), { suffix: newLineCharacter }); + runSingleFileTest("insertNodeAtConstructorStart", /*placeOpenBraceOnNewLineForFunctions*/ false, text1, /*validateNodes*/ false, (sourceFile, changeTracker) => { + changeTracker.insertNodeAtConstructorStart(sourceFile, findConstructor(sourceFile), createTestSuperCall()); }); const text2 = ` class A { @@ -370,7 +368,7 @@ class A { } `; runSingleFileTest("insertNodeAfter4", /*placeOpenBraceOnNewLineForFunctions*/ false, text2, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findVariableStatementContaining("x", sourceFile), createTestSuperCall(), { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findVariableStatementContaining("x", sourceFile), createTestSuperCall()); }); const text3 = ` class A { @@ -379,8 +377,8 @@ class A { } } `; - runSingleFileTest("insertNodeAfter3-block with newline", /*placeOpenBraceOnNewLineForFunctions*/ false, text3, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findOpenBraceForConstructor(sourceFile), createTestSuperCall(), { suffix: newLineCharacter }); + runSingleFileTest("insertNodeAtConstructorStart-block with newline", /*placeOpenBraceOnNewLineForFunctions*/ false, text3, /*validateNodes*/ false, (sourceFile, changeTracker) => { + changeTracker.insertNodeAtConstructorStart(sourceFile, findConstructor(sourceFile), createTestSuperCall()); }); } { @@ -638,7 +636,7 @@ class A { } const insertAfter = findChild("x", sourceFile); for (const newNode of newNodes) { - changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode); } }); } @@ -649,7 +647,7 @@ class A { } `; runSingleFileTest("insertNodeAfterInClass1", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), createProperty(undefined, undefined, "a", undefined, createKeywordTypeNode(SyntaxKind.BooleanKeyword), undefined), { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), createProperty(undefined, undefined, "a", undefined, createKeywordTypeNode(SyntaxKind.BooleanKeyword), undefined)); }); } { @@ -659,7 +657,7 @@ class A { } `; runSingleFileTest("insertNodeAfterInClass2", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), createProperty(undefined, undefined, "a", undefined, createKeywordTypeNode(SyntaxKind.BooleanKeyword), undefined), { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), createProperty(undefined, undefined, "a", undefined, createKeywordTypeNode(SyntaxKind.BooleanKeyword), undefined)); }); } { @@ -698,7 +696,7 @@ class A { /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.AnyKeyword), /*initializer*/ undefined); - changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } { @@ -716,7 +714,7 @@ class A { /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.AnyKeyword), /*initializer*/ undefined); - changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } { @@ -733,7 +731,7 @@ interface A { /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.AnyKeyword), /*initializer*/ undefined); - changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } { @@ -750,7 +748,7 @@ interface A { /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.AnyKeyword), /*initializer*/ undefined); - changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } { @@ -759,7 +757,7 @@ let x = foo `; runSingleFileTest("insertNodeInStatementListAfterNodeWithoutSeparator1", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { const newNode = createStatement(createParen(createLiteral(1))); - changeTracker.insertNodeAfter(sourceFile, findVariableStatementContaining("x", sourceFile), newNode, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, findVariableStatementContaining("x", sourceFile), newNode); }); } }); diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index 4e2d63cec90ea..758a55b8f9518 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -80,20 +80,47 @@ namespace ts.tscWatch { checkOutputDoesNotContain(host, expectedNonAffectedFiles); } - function checkOutputErrors(host: WatchedSystem, errors: ReadonlyArray, isInitial?: true, skipWaiting?: true) { + enum ExpectedOutputErrorsPosition { + BeforeCompilationStarts, + AfterCompilationStarting, + AfterFileChangeDetected + } + + function checkOutputErrors( + host: WatchedSystem, + errors: ReadonlyArray, + errorsPosition: ExpectedOutputErrorsPosition, + skipWaiting?: true + ) { const outputs = host.getOutput(); - const expectedOutputCount = (isInitial ? 0 : 1) + errors.length + (skipWaiting ? 0 : 1); + const expectedOutputCount = errors.length + (skipWaiting ? 0 : 1) + 1; assert.equal(outputs.length, expectedOutputCount, "Outputs = " + outputs.toString()); - let index = 0; - if (!isInitial) { - assertWatchDiagnosticAt(host, index, Diagnostics.File_change_detected_Starting_incremental_compilation); - index++; + let index: number; + + switch (errorsPosition) { + case ExpectedOutputErrorsPosition.AfterCompilationStarting: + assertWatchDiagnosticAt(host, 0, Diagnostics.Starting_compilation_in_watch_mode); + index = 1; + break; + case ExpectedOutputErrorsPosition.AfterFileChangeDetected: + assertWatchDiagnosticAt(host, 0, Diagnostics.File_change_detected_Starting_incremental_compilation); + index = 1; + break; + case ExpectedOutputErrorsPosition.BeforeCompilationStarts: + assertWatchDiagnosticAt(host, errors.length, Diagnostics.Starting_compilation_in_watch_mode); + index = 0; + break; } + forEach(errors, error => { assertDiagnosticAt(host, index, error); index++; }); if (!skipWaiting) { + if (errorsPosition === ExpectedOutputErrorsPosition.BeforeCompilationStarts) { + assertWatchDiagnosticAt(host, index, ts.Diagnostics.Starting_compilation_in_watch_mode); + index += 1; + } assertWatchDiagnosticAt(host, index, Diagnostics.Compilation_complete_Watching_for_file_changes); } host.clearOutput(); @@ -333,13 +360,13 @@ namespace ts.tscWatch { checkOutputErrors(host, [ getDiagnosticOfFileFromProgram(watch(), file1.path, file1.content.indexOf(commonFile2Name), commonFile2Name.length, Diagnostics.File_0_not_found, commonFile2.path), getDiagnosticOfFileFromProgram(watch(), file1.path, file1.content.indexOf("y"), 1, Diagnostics.Cannot_find_name_0, "y") - ], /*isInitial*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); host.reloadFS([file1, commonFile2, libFile]); host.runQueuedTimeoutCallbacks(); checkProgramRootFiles(watch(), [file1.path]); checkProgramActualFiles(watch(), [file1.path, libFile.path, commonFile2.path]); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("should reflect change in config file", () => { @@ -667,7 +694,7 @@ namespace ts.tscWatch { const watch = createWatchModeWithConfigFile(config.path, host); checkProgramActualFiles(watch(), [file1.path, file2.path, libFile.path]); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); host.reloadFS([file1, file2, libFile]); host.checkTimeoutQueueLengthAndRun(1); @@ -675,7 +702,7 @@ namespace ts.tscWatch { assert.equal(host.exitCode, ExitStatus.DiagnosticsPresent_OutputsSkipped); checkOutputErrors(host, [ getDiagnosticWithoutFile(Diagnostics.File_0_not_found, config.path) - ], /*isInitial*/ undefined, /*skipWaiting*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected, /*skipWaiting*/ true); }); it("Proper errors: document is not contained in project", () => { @@ -778,7 +805,7 @@ namespace ts.tscWatch { }; const host = createWatchedSystem([moduleFile, file1, libFile]); const watch = createWatchModeWithoutConfigFile([file1.path], host); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); const moduleFileOldPath = moduleFile.path; const moduleFileNewPath = "/a/b/moduleFile1.ts"; @@ -787,12 +814,12 @@ namespace ts.tscWatch { host.runQueuedTimeoutCallbacks(); checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") - ]); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); moduleFile.path = moduleFileOldPath; host.reloadFS([moduleFile, file1, libFile]); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("rename a module file and rename back should restore the states for configured projects", () => { @@ -810,7 +837,7 @@ namespace ts.tscWatch { }; const host = createWatchedSystem([moduleFile, file1, configFile, libFile]); const watch = createWatchModeWithConfigFile(configFile.path, host); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); const moduleFileOldPath = moduleFile.path; const moduleFileNewPath = "/a/b/moduleFile1.ts"; @@ -819,12 +846,12 @@ namespace ts.tscWatch { host.runQueuedTimeoutCallbacks(); checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") - ]); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); moduleFile.path = moduleFileOldPath; host.reloadFS([moduleFile, file1, configFile, libFile]); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("types should load from config file path if config exists", () => { @@ -863,11 +890,11 @@ namespace ts.tscWatch { checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), file1, "./moduleFile") - ], /*isInitial*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); host.reloadFS([file1, moduleFile, libFile]); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("Configure file diagnostics events are generated when the config file has errors", () => { @@ -890,7 +917,7 @@ namespace ts.tscWatch { checkOutputErrors(host, [ getUnknownCompilerOption(watch(), configFile, "foo"), getUnknownCompilerOption(watch(), configFile, "allowJS") - ], /*isInitial*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.BeforeCompilationStarts); }); it("If config file doesnt have errors, they are not reported", () => { @@ -907,7 +934,7 @@ namespace ts.tscWatch { const host = createWatchedSystem([file, configFile, libFile]); createWatchModeWithConfigFile(configFile.path, host); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); }); it("Reports errors when the config file changes", () => { @@ -924,7 +951,7 @@ namespace ts.tscWatch { const host = createWatchedSystem([file, configFile, libFile]); const watch = createWatchModeWithConfigFile(configFile.path, host); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); configFile.content = `{ "compilerOptions": { @@ -935,14 +962,14 @@ namespace ts.tscWatch { host.runQueuedTimeoutCallbacks(); checkOutputErrors(host, [ getUnknownCompilerOption(watch(), configFile, "haha") - ]); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); configFile.content = `{ "compilerOptions": {} }`; host.reloadFS([file, configFile, libFile]); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("non-existing directories listed in config file input array should be tolerated without crashing the server", () => { @@ -1030,13 +1057,13 @@ namespace ts.tscWatch { getDiagnosticOfFile(watch().getCompilerOptions().configFile, configFile.content.indexOf('"declaration"'), '"declaration"'.length, Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration") ]; const intialErrors = errors(); - checkOutputErrors(host, intialErrors, /*isInitial*/ true); + checkOutputErrors(host, intialErrors, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); configFile.content = configFileContentWithoutCommentLine; host.reloadFS(files); host.runQueuedTimeoutCallbacks(); const nowErrors = errors(); - checkOutputErrors(host, nowErrors); + checkOutputErrors(host, nowErrors, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); assert.equal(nowErrors[0].start, intialErrors[0].start - configFileContentComment.length); assert.equal(nowErrors[1].start, intialErrors[1].start - configFileContentComment.length); }); @@ -1667,7 +1694,7 @@ namespace ts.tscWatch { const cannotFindFoo = getDiagnosticOfFileFromProgram(watch(), imported.path, imported.content.indexOf("foo"), "foo".length, Diagnostics.Cannot_find_name_0, "foo"); // ensure that imported file was found - checkOutputErrors(host, [f1IsNotModule, cannotFindFoo], /*isInitial*/ true); + checkOutputErrors(host, [f1IsNotModule, cannotFindFoo], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); const originalFileExists = host.fileExists; { @@ -1687,7 +1714,7 @@ namespace ts.tscWatch { f1IsNotModule, getDiagnosticOfFileFromProgram(watch(), root.path, newContent.indexOf("var x") + "var ".length, "x".length, Diagnostics.Type_0_is_not_assignable_to_type_1, 1, "string"), cannotFindFoo - ]); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); } { let fileExistsIsCalled = false; @@ -1709,7 +1736,7 @@ namespace ts.tscWatch { // ensure file has correct number of errors after edit checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), root, "f2") - ]); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); assert.isTrue(fileExistsIsCalled); } @@ -1730,7 +1757,7 @@ namespace ts.tscWatch { host.reloadFS(files); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, [f1IsNotModule, cannotFindFoo]); + checkOutputErrors(host, [f1IsNotModule, cannotFindFoo], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); assert.isTrue(fileExistsCalled); } }); @@ -1767,15 +1794,15 @@ namespace ts.tscWatch { assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called"); checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), root, "bar") - ], /*isInitial*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); fileExistsCalledForBar = false; root.content = `import {y} from "bar"`; host.reloadFS(files.concat(imported)); host.runQueuedTimeoutCallbacks(); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); - checkOutputErrors(host, emptyArray); }); it("should compile correctly when resolved module goes missing and then comes back (module is not part of the root)", () => { @@ -1807,7 +1834,7 @@ namespace ts.tscWatch { const watch = createWatchModeWithoutConfigFile([root.path], host, { module: ModuleKind.AMD }); assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called"); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); fileExistsCalledForBar = false; host.reloadFS(files); @@ -1815,13 +1842,13 @@ namespace ts.tscWatch { assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), root, "bar") - ]); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); fileExistsCalledForBar = false; host.reloadFS(filesWithImported); host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); - checkOutputErrors(host, emptyArray); }); it("works when module resolution changes to ambient module", () => { @@ -1857,11 +1884,11 @@ declare module "fs" { checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), root, "fs") - ], /*isInitial*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); host.reloadFS(filesWithNodeType); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("works when included file with ambient module changes", () => { @@ -1899,12 +1926,12 @@ declare module "fs" { checkOutputErrors(host, [ getDiagnosticModuleNotFoundOfFile(watch(), root, "fs") - ], /*isInitial*/ true); + ], /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); file.content += fileContentWithFS; host.reloadFS(files); host.runQueuedTimeoutCallbacks(); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); }); it("works when reusing program with files from external library", () => { @@ -1939,7 +1966,7 @@ declare module "fs" { const host = createWatchedSystem(programFiles.concat(configFile), { currentDirectory: "/a/b/projects/myProject/" }); const watch = createWatchModeWithConfigFile(configFile.path, host); checkProgramActualFiles(watch(), programFiles.map(f => f.path)); - checkOutputErrors(host, emptyArray, /*isInitial*/ true); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterCompilationStarting); const expectedFiles: ExpectedFile[] = [ createExpectedEmittedFile(file1), createExpectedEmittedFile(file2), @@ -1958,7 +1985,7 @@ declare module "fs" { host.reloadFS(programFiles.concat(configFile)); host.runQueuedTimeoutCallbacks(); checkProgramActualFiles(watch(), programFiles.map(f => f.path)); - checkOutputErrors(host, emptyArray); + checkOutputErrors(host, emptyArray, /*errorsPosition*/ ExpectedOutputErrorsPosition.AfterFileChangeDetected); verifyExpectedFiles(expectedFiles); @@ -2027,4 +2054,37 @@ declare module "fs" { assert.equal(host.readFile(outputFile1), file1.content + host.newLine); }); }); + + describe("tsc-watch console clearing", () => { + it("clears the console when it starts", () => { + const file = { + path: "f.ts", + content: "" + }; + const host = createWatchedSystem([file]); + + createWatchModeWithoutConfigFile([file.path], host); + host.runQueuedTimeoutCallbacks(); + + host.checkScreenClears(1); + }); + + it("clears the console on recompile", () => { + const file = { + path: "f.ts", + content: "" + }; + const host = createWatchedSystem([file]); + createWatchModeWithoutConfigFile([file.path], host); + + const modifiedFile = { + ...file, + content: "//" + }; + host.reloadFS([modifiedFile]); + host.runQueuedTimeoutCallbacks(); + + host.checkScreenClears(2); + }); + }); } diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 8e0dfe36c2f77..10c5aad92db2b 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -473,7 +473,7 @@ namespace ts.projectSystem { } } - describe("tsserverProjectSystem", () => { + describe("tsserverProjectSystem general functionality", () => { const commonFile1: FileOrFolder = { path: "/a/b/commonFile1.ts", content: "let x = 1" @@ -1184,6 +1184,24 @@ namespace ts.projectSystem { checkNumberOfInferredProjects(projectService, 0); }); + it("external project for dynamic file", () => { + const externalProjectName = "^ScriptDocument1 file1.ts"; + const externalFiles = toExternalFiles(["^ScriptDocument1 file1.ts"]); + const host = createServerHost([]); + const projectService = createProjectService(host); + projectService.openExternalProject({ + rootFiles: externalFiles, + options: {}, + projectFileName: externalProjectName + }); + + checkNumberOfExternalProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 0); + + externalFiles[0].content = "let x =1;"; + projectService.applyChangesInOpenFiles(externalFiles, [], []); + }); + it("external project that included config files", () => { const file1 = { path: "/a/b/f1.ts", @@ -1284,13 +1302,13 @@ namespace ts.projectSystem { service.checkNumberOfProjects({ externalProjects: 1 }); checkProjectActualFiles(service.externalProjects[0], [f1.path, f2.path, libFile.path]); - const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2, { includeExternalModuleExports: false }); + const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); // should contain completions for string assert.isTrue(completions1.entries.some(e => e.name === "charAt"), "should contain 'charAt'"); assert.isFalse(completions1.entries.some(e => e.name === "toExponential"), "should not contain 'toExponential'"); service.closeClientFile(f2.path); - const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2, { includeExternalModuleExports: false }); + const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 2, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); // should contain completions for string assert.isFalse(completions2.entries.some(e => e.name === "charAt"), "should not contain 'charAt'"); assert.isTrue(completions2.entries.some(e => e.name === "toExponential"), "should contain 'toExponential'"); @@ -1316,11 +1334,11 @@ namespace ts.projectSystem { service.checkNumberOfProjects({ externalProjects: 1 }); checkProjectActualFiles(service.externalProjects[0], [f1.path, f2.path, libFile.path]); - const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0, { includeExternalModuleExports: false }); + const completions1 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); assert.isTrue(completions1.entries.some(e => e.name === "somelongname"), "should contain 'somelongname'"); service.closeClientFile(f2.path); - const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0, { includeExternalModuleExports: false }); + const completions2 = service.externalProjects[0].getLanguageService().getCompletionsAtPosition(f1.path, 0, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); assert.isFalse(completions2.entries.some(e => e.name === "somelongname"), "should not contain 'somelongname'"); const sf2 = service.externalProjects[0].getLanguageService().getProgram().getSourceFile(f2.path); assert.equal(sf2.text, ""); @@ -1925,7 +1943,7 @@ namespace ts.projectSystem { // Check identifiers defined in HTML content are available in .ts file const project = configuredProjectAt(projectService, 0); - let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1, { includeExternalModuleExports: false }); + let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`); // Close HTML file @@ -1939,7 +1957,7 @@ namespace ts.projectSystem { checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); // Check identifiers defined in HTML content are not available in .ts file - completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5, { includeExternalModuleExports: false }); + completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5, { includeExternalModuleExports: false, includeInsertTextCompletions: false }); assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`); }); @@ -2806,7 +2824,7 @@ namespace ts.projectSystem { }); - describe("Proper errors", () => { + describe("tsserverProjectSystem Proper errors", () => { it("document is not contained in project", () => { const file1 = { path: "/a/b/app.ts", @@ -2960,7 +2978,7 @@ namespace ts.projectSystem { }); }); - describe("autoDiscovery", () => { + describe("tsserverProjectSystem autoDiscovery", () => { it("does not depend on extension", () => { const file1 = { path: "/a/b/app.html", @@ -2983,7 +3001,7 @@ namespace ts.projectSystem { }); }); - describe("extra resolution pass in lshost", () => { + describe("tsserverProjectSystem extra resolution pass in lshost", () => { it("can load typings that are proper modules", () => { const file1 = { path: "/a/b/app.js", @@ -3025,7 +3043,7 @@ namespace ts.projectSystem { }); }); - describe("navigate-to for javascript project", () => { + describe("tsserverProjectSystem navigate-to for javascript project", () => { function containsNavToItem(items: protocol.NavtoItem[], itemName: string, itemKind: string) { return find(items, item => item.name === itemName && item.kind === itemKind) !== undefined; } @@ -3054,7 +3072,7 @@ namespace ts.projectSystem { }); }); - describe("external projects", () => { + describe("tsserverProjectSystem external projects", () => { it("correctly handling add/remove tsconfig - 1", () => { const f1 = { path: "/a/b/app.ts", @@ -3280,7 +3298,7 @@ namespace ts.projectSystem { }); }); - describe("prefer typings to js", () => { + describe("tsserverProjectSystem prefer typings to js", () => { it("during second resolution pass", () => { const typingsCacheLocation = "/a/typings"; const f1 = { @@ -3308,7 +3326,7 @@ namespace ts.projectSystem { }); }); - describe("format settings", () => { + describe("tsserverProjectSystem format settings", () => { it("can be set globally", () => { const f1 = { path: "/a/b/app.ts", @@ -3349,7 +3367,7 @@ namespace ts.projectSystem { }); }); - describe("watching @types", () => { + describe("tsserverProjectSystem watching @types", () => { it("works correctly when typings are added or removed", () => { const f1 = { path: "/a/b/app.ts", @@ -3395,7 +3413,7 @@ namespace ts.projectSystem { }); }); - describe("Open-file", () => { + describe("tsserverProjectSystem Open-file", () => { it("can be reloaded with empty content", () => { const f = { path: "/a/b/app.ts", @@ -3470,7 +3488,7 @@ namespace ts.projectSystem { }); }); - describe("Language service", () => { + describe("tsserverProjectSystem Language service", () => { it("should work correctly on case-sensitive file systems", () => { const lib = { path: "/a/Lib/lib.d.ts", @@ -3488,7 +3506,7 @@ namespace ts.projectSystem { }); }); - describe("rename a module file and rename back", () => { + describe("tsserverProjectSystem rename a module file and rename back", () => { it("should restore the states for inferred projects", () => { const moduleFile = { path: "/a/b/moduleFile.ts", @@ -3623,7 +3641,7 @@ namespace ts.projectSystem { }); }); - describe("add the missing module file for inferred project", () => { + describe("tsserverProjectSystem add the missing module file for inferred project", () => { it("should remove the `module not found` error", () => { const moduleFile = { path: "/a/b/moduleFile.ts", @@ -3729,7 +3747,7 @@ namespace ts.projectSystem { }); }); - describe("Configure file diagnostics events", () => { + describe("tsserverProjectSystem Configure file diagnostics events", () => { it("are generated when the config file has errors", () => { const file = { @@ -3845,7 +3863,7 @@ namespace ts.projectSystem { }); }); - describe("skipLibCheck", () => { + describe("tsserverProjectSystem skipLibCheck", () => { it("should be turned on for js-only inferred projects", () => { const file1 = { path: "/a/b/file1.js", @@ -4073,7 +4091,7 @@ namespace ts.projectSystem { }); }); - describe("non-existing directories listed in config file input array", () => { + describe("tsserverProjectSystem non-existing directories listed in config file input array", () => { it("should be tolerated without crashing the server", () => { const configFile = { path: "/a/b/tsconfig.json", @@ -4128,7 +4146,7 @@ namespace ts.projectSystem { }); }); - describe("reload", () => { + describe("tsserverProjectSystem reload", () => { it("should work with temp file", () => { const f1 = { path: "/a/b/app.ts", @@ -4267,7 +4285,7 @@ namespace ts.projectSystem { }); }); - describe("Inferred projects", () => { + describe("tsserverProjectSystem Inferred projects", () => { it("should support files without extensions", () => { const f = { path: "/a/compile", @@ -4495,7 +4513,7 @@ namespace ts.projectSystem { }); }); - describe("No overwrite emit error", () => { + describe("tsserverProjectSystem No overwrite emit error", () => { it("for inferred project", () => { const f1 = { path: "/a/b/f1.js", @@ -4578,7 +4596,7 @@ namespace ts.projectSystem { }); }); - describe("emit with outFile or out setting", () => { + describe("tsserverProjectSystem emit with outFile or out setting", () => { function test(opts: CompilerOptions, expectedUsesOutFile: boolean) { const f1 = { path: "/a/a.ts", @@ -4626,7 +4644,7 @@ namespace ts.projectSystem { }); }); - describe("import helpers", () => { + describe("tsserverProjectSystem import helpers", () => { it("should not crash in tsserver", () => { const f1 = { path: "/a/app.ts", @@ -4643,7 +4661,7 @@ namespace ts.projectSystem { }); }); - describe("searching for config file", () => { + describe("tsserverProjectSystem searching for config file", () => { it("should stop at projectRootPath if given", () => { const f1 = { path: "/a/file1.ts", @@ -4735,7 +4753,7 @@ namespace ts.projectSystem { }); }); - describe("cancellationToken", () => { + describe("tsserverProjectSystem cancellationToken", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: ts.AnyFunction; before(() => { @@ -4998,7 +5016,7 @@ namespace ts.projectSystem { }); }); - describe("occurence highlight on string", () => { + describe("tsserverProjectSystem occurence highlight on string", () => { it("should be marked if only on string values", () => { const file1: FileOrFolder = { path: "/a/b/file1.ts", @@ -5044,7 +5062,7 @@ namespace ts.projectSystem { }); }); - describe("maxNodeModuleJsDepth for inferred projects", () => { + describe("tsserverProjectSystem maxNodeModuleJsDepth for inferred projects", () => { it("should be set to 2 if the project has js root files", () => { const file1: FileOrFolder = { path: "/a/b/file1.js", @@ -5098,7 +5116,7 @@ namespace ts.projectSystem { }); }); - describe("Options Diagnostic locations reported correctly with changes in configFile contents", () => { + describe("tsserverProjectSystem Options Diagnostic locations reported correctly with changes in configFile contents", () => { it("when options change", () => { const file = { path: "/a/b/app.ts", @@ -5162,7 +5180,7 @@ namespace ts.projectSystem { }); }); - describe("refactors", () => { + describe("tsserverProjectSystem refactors", () => { it("use formatting options", () => { const file = { path: "/a.ts", @@ -5218,7 +5236,7 @@ namespace ts.projectSystem { }); }); - describe("CachingFileSystemInformation", () => { + describe("tsserverProjectSystem CachingFileSystemInformation", () => { enum CalledMapsWithSingleArg { fileExists = "fileExists", directoryExists = "directoryExists", @@ -5835,7 +5853,7 @@ namespace ts.projectSystem { }); }); - describe("ProjectsChangedInBackground", () => { + describe("tsserverProjectSystem ProjectsChangedInBackground", () => { function verifyFiles(caption: string, actual: ReadonlyArray, expected: ReadonlyArray) { assert.equal(actual.length, expected.length, `Incorrect number of ${caption}. Actual: ${actual} Expected: ${expected}`); const seen = createMap(); @@ -6431,7 +6449,7 @@ namespace ts.projectSystem { }); }); - describe("Watched recursive directories with windows style file system", () => { + describe("tsserverProjectSystem Watched recursive directories with windows style file system", () => { function verifyWatchedDirectories(useProjectAtRoot: boolean) { const root = useProjectAtRoot ? "c:/" : "c:/myfolder/allproject/"; const configFile: FileOrFolder = { diff --git a/src/harness/unittests/typingsInstaller.ts b/src/harness/unittests/typingsInstaller.ts index d0038902ae760..a84520095a475 100644 --- a/src/harness/unittests/typingsInstaller.ts +++ b/src/harness/unittests/typingsInstaller.ts @@ -228,6 +228,37 @@ namespace ts.projectSystem { projectService.checkNumberOfProjects({ externalProjects: 1 }); }); + it("external project - deduplicate from local @types packages", () => { + const appJs = { + path: "/a/b/app.js", + content: "" + }; + const nodeDts = { + path: "/node_modules/@types/node/index.d.ts", + content: "declare var node;" + }; + const host = createServerHost([appJs, nodeDts]); + const installer = new (class extends Installer { + constructor() { + super(host, { typesRegistry: createTypesRegistry("node") }); + } + installWorker() { + assert(false, "nothing should get installed"); + } + })(); + + const projectFileName = "/a/app/test.csproj"; + const projectService = createProjectService(host, { typingsInstaller: installer }); + projectService.openExternalProject({ + projectFileName, + options: {}, + rootFiles: [toExternalFile(appJs.path)], + typeAcquisition: { enable: true, include: ["node"] } + }); + installer.checkPendingCommands(/*expectedCount*/ 0); + projectService.checkNumberOfProjects({ externalProjects: 1 }); + }); + it("external project - no auto in typing acquisition, no .d.ts/js files", () => { const file1 = { path: "/a/b/app.ts", @@ -978,7 +1009,7 @@ namespace ts.projectSystem { installer.installAll(/*expectedCount*/ 1); }); - it("cached unresolved typings are not recomputed if program structure did not change", () => { + it("should recompute resolutions after typings are installed", () => { const host = createServerHost([]); const session = createSession(host); const f = { @@ -1020,7 +1051,7 @@ namespace ts.projectSystem { session.executeCommand(changeRequest); host.checkTimeoutQueueLengthAndRun(2); // This enqueues the updategraph and refresh inferred projects const version2 = proj.getCachedUnresolvedImportsPerFile_TestOnly().getVersion(); - assert.equal(version1, version2, "set of unresolved imports should not change"); + assert.notEqual(version1, version2, "set of unresolved imports should change"); }); }); diff --git a/src/harness/virtualFileSystem.ts b/src/harness/virtualFileSystem.ts index 8accd6f621e44..54572814d8ed1 100644 --- a/src/harness/virtualFileSystem.ts +++ b/src/harness/virtualFileSystem.ts @@ -162,7 +162,7 @@ namespace Utils { /** * Reads the directory at the given path and retrieves a list of file names and a list * of directory names within it. Suitable for use with ts.matchFiles() - * @param path The path to the directory to be read + * @param path The path to the directory to be read */ getAccessibleFileSystemEntries(path: string) { const entry = this.traversePath(path); diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index d4d203cabbbe1..a6fe27ca9c698 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -168,7 +168,7 @@ interface Array {}` mapSeen.set(f, true); } } - assert.equal(mapExpected.size, 0, `Output has missing ${JSON.stringify(flatMapIter(mapExpected.keys(), key => key))} in ${JSON.stringify(host.getOutput())}`); + assert.equal(mapExpected.size, 0, `Output has missing ${JSON.stringify(arrayFrom(mapExpected.keys()))} in ${JSON.stringify(host.getOutput())}`); } export function checkOutputDoesNotContain(host: TestServerHost, expectedToBeAbsent: string[] | ReadonlyArray) { @@ -241,7 +241,7 @@ interface Array {}` ignoreWatchInvokedWithTriggerAsFileCreate: boolean; } - export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost { + export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, ModuleResolutionHost { args: string[] = []; private readonly output: string[] = []; @@ -251,6 +251,7 @@ interface Array {}` private toPath: (f: string) => Path; private timeoutCallbacks = new Callbacks(); private immediateCallbacks = new Callbacks(); + private screenClears = 0; readonly watchedDirectories = createMultiMap(); readonly watchedDirectoriesRecursive = createMultiMap(); @@ -604,6 +605,10 @@ interface Array {}` this.timeoutCallbacks.unregister(timeoutId); } + clearScreen(): void { + this.screenClears += 1; + } + checkTimeoutQueueLengthAndRun(expected: number) { this.checkTimeoutQueueLength(expected); this.runQueuedTimeoutCallbacks(); @@ -638,6 +643,10 @@ interface Array {}` this.immediateCallbacks.unregister(timeoutId); } + checkScreenClears(expected: number): void { + assert.equal(this.screenClears, expected); + } + createDirectory(directoryName: string): void { const folder = this.toFolder(directoryName); diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 001c63b44a1f6..951d34377a6d0 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -761,7 +761,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -770,7 +770,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1088,7 +1089,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3596,11 +3597,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3757,9 +3758,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4897,6 +4899,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5200,6 +5203,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5495,8 +5502,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6057,6 +6065,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6958,8 +6967,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7362,10 +7372,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7534,7 +7544,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7548,10 +7558,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7562,8 +7572,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9163,8 +9173,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9227,6 +9237,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12213,7 +12224,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12301,8 +12312,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14657,6 +14668,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14675,6 +14703,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14779,6 +14826,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14791,7 +14875,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -15029,6 +15113,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15246,7 +15331,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/src/lib/es2015.collection.d.ts b/src/lib/es2015.collection.d.ts index 9b35fcbeffb2c..f6087eb44058a 100644 --- a/src/lib/es2015.collection.d.ts +++ b/src/lib/es2015.collection.d.ts @@ -10,7 +10,7 @@ interface Map { interface MapConstructor { new (): Map; - new (entries?: [K, V][]): Map; + new (entries?: ReadonlyArray<[K, V]>): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -31,7 +31,7 @@ interface WeakMap { interface WeakMapConstructor { new (): WeakMap; - new (entries?: [K, V][]): WeakMap; + new (entries?: ReadonlyArray<[K, V]>): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -47,7 +47,7 @@ interface Set { interface SetConstructor { new (): Set; - new (values?: T[]): Set; + new (values?: ReadonlyArray): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -66,7 +66,7 @@ interface WeakSet { interface WeakSetConstructor { new (): WeakSet; - new (values?: T[]): WeakSet; + new (values?: ReadonlyArray): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index ccff68968f177..eef20591a84f0 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -118,8 +118,9 @@ interface Math { log1p(x: number): number; /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). + * Returns the result of (e^x - 1), which is an implementation-dependent approximation to + * subtracting 1 from the exponential function of x (e raised to the power of x, where e + * is the base of the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; diff --git a/src/lib/es2015.iterable.d.ts b/src/lib/es2015.iterable.d.ts index f3024bc334f02..26722b5ab2f5d 100644 --- a/src/lib/es2015.iterable.d.ts +++ b/src/lib/es2015.iterable.d.ts @@ -52,7 +52,7 @@ interface ArrayConstructor { * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. */ - from(iterable: Iterable): T[]; + from(iterable: Iterable | ArrayLike): T[]; /** * Creates an array from an iterable object. @@ -60,7 +60,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; + from(iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { diff --git a/src/lib/es2017.object.d.ts b/src/lib/es2017.object.d.ts index 4014e8c29278a..775aaece7f621 100644 --- a/src/lib/es2017.object.d.ts +++ b/src/lib/es2017.object.d.ts @@ -9,7 +9,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: any): any[]; + values(o: {}): any[]; /** * Returns an array of key/values of the enumerable properties of an object @@ -21,7 +21,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: any): [string, any][]; + entries(o: {}): [string, any][]; /** * Returns an object containing all own property descriptors of an object diff --git a/src/lib/es2018.d.ts b/src/lib/es2018.d.ts new file mode 100644 index 0000000000000..90f6d4931f4b1 --- /dev/null +++ b/src/lib/es2018.d.ts @@ -0,0 +1 @@ +/// diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index aaefeec7d1a52..0f1a68de4c20d 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -550,7 +550,7 @@ interface Math { */ atan2(y: number, x: number): number; /** - * Returns the smallest number greater than or equal to its numeric argument. + * Returns the smallest integer greater than or equal to its numeric argument. * @param x A numeric expression. */ ceil(x: number): number; @@ -565,7 +565,7 @@ interface Math { */ exp(x: number): number; /** - * Returns the greatest number less than or equal to its numeric argument. + * Returns the greatest integer less than or equal to its numeric argument. * @param x A numeric expression. */ floor(x: number): number; @@ -992,12 +992,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1113,12 +1113,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/src/lib/esnext.array.d.ts b/src/lib/esnext.array.d.ts new file mode 100644 index 0000000000000..ddba47badaaa3 --- /dev/null +++ b/src/lib/esnext.array.d.ts @@ -0,0 +1,203 @@ +interface ReadonlyArray { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by a flatten of depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|U[], + thisArg?: This + ): U[] + + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + ReadonlyArray[][]> | + ReadonlyArray[][][]> | + + ReadonlyArray>> | + ReadonlyArray[][]>> | + ReadonlyArray>[][]> | + ReadonlyArray[]>[]> | + ReadonlyArray>[]> | + ReadonlyArray[]>> | + + ReadonlyArray>>> | + ReadonlyArray[]>>> | + ReadonlyArray>[]>> | + ReadonlyArray>>[]> | + + ReadonlyArray>>>>, + depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray[][]> | + ReadonlyArray[]> | + ReadonlyArray> | + + ReadonlyArray>> | + ReadonlyArray[]>> | + ReadonlyArray>[]> | + + ReadonlyArray>>>, + depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + + ReadonlyArray>>, + depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + ReadonlyArray>, + depth?: 1 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray, + depth: 0 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flatten method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flatten(depth?: number): any[]; + } + +interface Array { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by a flatten of depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|U[], + thisArg?: This + ): U[] + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][][][], depth: 7): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][][], depth: 6): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][], depth: 5): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][], depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][], depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][], depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][], depth?: 1): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[], depth: 0): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flatten method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flatten(depth?: number): any[]; +} diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts index 71fab82a866bc..bbfb9535aa70b 100644 --- a/src/lib/esnext.d.ts +++ b/src/lib/esnext.d.ts @@ -1,2 +1,4 @@ -/// +/// /// +/// +/// diff --git a/src/lib/esnext.promise.d.ts b/src/lib/esnext.promise.d.ts new file mode 100644 index 0000000000000..28f903870b67c --- /dev/null +++ b/src/lib/esnext.promise.d.ts @@ -0,0 +1,12 @@ +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): Promise +} diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 6eb17c33c5ed2..1b0ce074f001d 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -66,12 +66,13 @@ interface ObjectURLOptions { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -119,7 +120,7 @@ interface NotificationEventInit extends ExtendableEventInit { } interface PushEventInit extends ExtendableEventInit { - data?: any; + data?: BufferSource | USVString; } interface SyncEventInit extends ExtendableEventInit { @@ -414,9 +415,10 @@ declare var EventTarget: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -959,6 +961,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -1061,7 +1064,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -1821,6 +1824,43 @@ interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -1833,7 +1873,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FunctionStringCallback { (data: string): void; @@ -1883,7 +1923,7 @@ declare function addEventListener(type: string, listener: EventListenerOrEventLi declare function removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type IDBKeyPath = string; type RequestInfo = Request | string; type USVString = string; diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7ed37669f3479..b01830dcac5fc 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -145,7 +145,7 @@ - + @@ -154,7 +154,7 @@ - + @@ -163,7 +163,7 @@ - + @@ -172,7 +172,7 @@ - + @@ -181,7 +181,7 @@ - + @@ -532,7 +532,7 @@ - + @@ -541,7 +541,7 @@ - + @@ -796,7 +796,7 @@ - + @@ -866,52 +866,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1378,7 +1384,7 @@ - + @@ -1541,10 +1547,13 @@ - + - + + + + @@ -1955,34 +1964,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2058,6 +2070,15 @@ + + + + + + + + + @@ -2354,37 +2375,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2462,10 +2495,13 @@ - + - + + + + @@ -3429,15 +3465,6 @@ - - - - - - - - - @@ -3731,31 +3758,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3770,10 +3803,13 @@ - + - + + + + @@ -3920,37 +3956,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4481,10 +4529,13 @@ - + - + + + + @@ -4701,6 +4752,15 @@ + + + + + + + + + @@ -4791,6 +4851,15 @@ + + + + + + + + + @@ -5396,10 +5465,13 @@ - + - + + + + @@ -5849,10 +5921,13 @@ - + - + + + + @@ -6275,10 +6350,13 @@ - + - + + + + @@ -6390,15 +6468,12 @@ - + - + - + - - - @@ -6504,6 +6579,15 @@ + + + + + + + + + @@ -6582,6 +6666,9 @@ + + + @@ -7350,7 +7437,7 @@ - + @@ -8665,7 +8752,7 @@ - + @@ -8866,7 +8953,7 @@ - + @@ -8875,7 +8962,7 @@ - + @@ -8884,7 +8971,7 @@ - + diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index ea8a9bd98388c..921ca600aa654 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -145,7 +145,7 @@ - + @@ -163,7 +163,7 @@ - + @@ -532,7 +532,7 @@ - + @@ -541,7 +541,7 @@ - + @@ -866,52 +866,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - + - - - @@ -1541,10 +1547,13 @@ - + - + + + + @@ -1955,34 +1964,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2058,6 +2070,15 @@ + + + + + + + + + @@ -2354,37 +2375,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2462,10 +2495,13 @@ - + - + + + + @@ -3220,7 +3256,7 @@ - + @@ -3429,15 +3465,6 @@ - - - - - - - - - @@ -3731,31 +3758,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3770,10 +3803,13 @@ - + - + + + + @@ -3920,37 +3956,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4481,10 +4529,13 @@ - + - + + + + @@ -4701,6 +4752,15 @@ + + + + + + + + + @@ -4791,6 +4851,15 @@ + + + + + + + + + @@ -5396,10 +5465,13 @@ - + - + + + + @@ -5443,7 +5515,7 @@ - + @@ -5849,10 +5921,13 @@ - + - + + + + @@ -6275,10 +6350,13 @@ - + - + + + + @@ -6390,15 +6468,12 @@ - + - + - + - - - @@ -6504,6 +6579,15 @@ + + + + + + + + + @@ -6571,7 +6655,7 @@ - + @@ -6582,6 +6666,9 @@ + + + @@ -7350,7 +7437,7 @@ - + @@ -8374,7 +8461,7 @@ - + @@ -8383,7 +8470,7 @@ - + @@ -8413,7 +8500,7 @@ - + diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 1f5a92cdf4a94..30850814f26a8 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -154,7 +154,7 @@ - + @@ -163,7 +163,7 @@ - + @@ -172,7 +172,7 @@ - + @@ -181,7 +181,7 @@ - + @@ -190,7 +190,7 @@ - + @@ -541,7 +541,7 @@ - + @@ -550,7 +550,7 @@ - + @@ -805,7 +805,7 @@ - + @@ -875,52 +875,58 @@ - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1550,10 +1556,13 @@ - + - + + + + @@ -1964,34 +1973,37 @@ - + - + - + - + - + - + + + + @@ -2067,6 +2079,15 @@ + + + + + + + + + @@ -2089,7 +2110,7 @@ - + @@ -2363,37 +2384,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2471,10 +2504,13 @@ - + + + + @@ -2836,7 +2872,7 @@ - + @@ -3438,15 +3474,6 @@ - - - - - - - - - @@ -3740,31 +3767,37 @@ - + + + + - + - + - + - + - + + + + @@ -3779,10 +3812,13 @@ - + - + + + + @@ -3929,37 +3965,49 @@ - + - + + + + - + - + + + + - + + + + - + + + + @@ -4177,7 +4225,7 @@ - + @@ -4186,7 +4234,7 @@ - + @@ -4490,10 +4538,13 @@ - + + + + @@ -4710,6 +4761,15 @@ + + + + + + + + + @@ -4800,6 +4860,15 @@ + + + + + + + + + @@ -5405,10 +5474,13 @@ - + + + + @@ -5858,10 +5930,13 @@ - + - + + + + @@ -6284,10 +6359,13 @@ - + - + + + + @@ -6358,7 +6436,7 @@ - + @@ -6399,15 +6477,12 @@ - + - + - + - - - @@ -6513,6 +6588,15 @@ + + + + + + + + + @@ -6591,6 +6675,9 @@ + + + @@ -7359,7 +7446,7 @@ - + @@ -8638,7 +8725,7 @@ - + @@ -8875,7 +8962,7 @@ - + @@ -8884,7 +8971,7 @@ - + @@ -8893,7 +8980,7 @@ - + diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index c20900a5abde3..922edbca2de23 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -863,44 +863,53 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + @@ -1535,10 +1544,13 @@ - + - + + + + @@ -1949,31 +1961,37 @@ - + - + - + - + + + + - + - + + + + @@ -2049,6 +2067,15 @@ + + + + + + + + + @@ -2173,7 +2200,7 @@ - + @@ -2345,37 +2372,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2453,10 +2492,13 @@ - + - + + + + @@ -3420,15 +3462,6 @@ - - - - - - - - - @@ -3722,28 +3755,37 @@ - + - + + + + - + + + + - + + + + @@ -3758,10 +3800,13 @@ - + - + + + + @@ -3908,37 +3953,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4469,10 +4526,13 @@ - + - + + + + @@ -4689,6 +4749,15 @@ + + + + + + + + + @@ -4779,6 +4848,15 @@ + + + + + + + + + @@ -5381,10 +5459,13 @@ - + - + + + + @@ -5834,10 +5915,13 @@ - + + + + @@ -6257,10 +6341,13 @@ - + - + + + + @@ -6372,11 +6459,11 @@ - + - + - + @@ -6483,6 +6570,15 @@ + + + + + + + + + @@ -6561,6 +6657,9 @@ + + + @@ -7329,11 +7428,11 @@ - + - + diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 5f702fd6c58ca..c2febd1ee9bda 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -427,7 +427,7 @@ - + @@ -436,7 +436,7 @@ - + @@ -523,7 +523,7 @@ - + @@ -875,52 +875,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1063,7 +1069,7 @@ - + @@ -1414,7 +1420,7 @@ - + @@ -1426,7 +1432,7 @@ - + @@ -1550,10 +1556,13 @@ - + - + + + + @@ -1964,34 +1973,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2067,6 +2079,15 @@ + + + + + + + + + @@ -2363,37 +2384,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2471,10 +2504,13 @@ - + - + + + + @@ -2908,7 +2944,7 @@ - + @@ -2947,7 +2983,7 @@ - + @@ -3438,15 +3474,6 @@ - - - - - - - - - @@ -3740,31 +3767,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3779,10 +3812,13 @@ - + - + + + + @@ -3868,7 +3904,7 @@ - + @@ -3929,37 +3965,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4490,10 +4538,13 @@ - + - + + + + @@ -4710,6 +4761,15 @@ + + + + + + + + + @@ -4800,6 +4860,15 @@ + + + + + + + + + @@ -5405,10 +5474,13 @@ - + - + + + + @@ -5858,10 +5930,13 @@ - + - + + + + @@ -6284,10 +6359,13 @@ - + - + + + + @@ -6399,15 +6477,12 @@ - + - + - + - - - @@ -6513,6 +6588,15 @@ + + + + + + + + + @@ -6591,6 +6675,9 @@ + + + @@ -6883,7 +6970,7 @@ - + @@ -7021,7 +7108,7 @@ - + @@ -7359,7 +7446,7 @@ - + diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index ce91987a422ed..efd7b273f5dbc 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -154,7 +154,7 @@ - + @@ -163,7 +163,7 @@ - + @@ -172,7 +172,7 @@ - + @@ -181,7 +181,7 @@ - + @@ -190,7 +190,7 @@ - + @@ -541,7 +541,7 @@ - + @@ -550,7 +550,7 @@ - + @@ -805,7 +805,7 @@ - + @@ -875,52 +875,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1550,10 +1556,13 @@ - + - + + + + @@ -1964,34 +1973,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2067,6 +2079,15 @@ + + + + + + + + + @@ -2363,37 +2384,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2471,10 +2504,13 @@ - + - + + + + @@ -3438,15 +3474,6 @@ - - - - - - - - - @@ -3740,31 +3767,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3779,10 +3812,13 @@ - + - + + + + @@ -3929,37 +3965,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4490,10 +4538,13 @@ - + - + + + + @@ -4710,6 +4761,15 @@ + + + + + + + + + @@ -4800,6 +4860,15 @@ + + + + + + + + + @@ -4876,7 +4945,7 @@ - + @@ -5405,10 +5474,13 @@ - + - + + + + @@ -5858,10 +5930,13 @@ - + - + + + + @@ -6284,10 +6359,13 @@ - + - + + + + @@ -6399,15 +6477,12 @@ - + - + - + - - - @@ -6513,6 +6588,15 @@ + + + + + + + + + @@ -6591,6 +6675,9 @@ + + + @@ -7359,11 +7446,11 @@ - + - + @@ -8875,7 +8962,7 @@ - + @@ -8884,7 +8971,7 @@ - + @@ -8893,7 +8980,7 @@ - + diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index aa6a6d626bde5..8f52506d6b9d2 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -866,52 +866,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1054,7 +1060,7 @@ - + @@ -1099,7 +1105,7 @@ - + @@ -1541,10 +1547,13 @@ - + - + + + + @@ -1955,34 +1964,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2058,6 +2070,15 @@ + + + + + + + + + @@ -2146,7 +2167,7 @@ - + @@ -2354,37 +2375,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2462,10 +2495,13 @@ - + - + + + + @@ -2554,7 +2590,7 @@ - + @@ -2800,7 +2836,7 @@ - + @@ -2827,7 +2863,7 @@ - + @@ -2899,7 +2935,7 @@ - + @@ -2908,7 +2944,7 @@ - + @@ -2917,7 +2953,7 @@ - + @@ -3001,7 +3037,7 @@ - + @@ -3019,7 +3055,7 @@ - + @@ -3429,15 +3465,6 @@ - - - - - - - - - @@ -3731,31 +3758,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3770,10 +3803,13 @@ - + - + + + + @@ -3859,7 +3895,7 @@ - + @@ -3868,7 +3904,7 @@ - + @@ -3877,7 +3913,7 @@ - + @@ -3920,37 +3956,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4481,10 +4529,13 @@ - + - + + + + @@ -4701,6 +4752,15 @@ + + + + + + + + + @@ -4791,6 +4851,15 @@ + + + + + + + + + @@ -5396,10 +5465,13 @@ - + - + + + + @@ -5849,10 +5921,13 @@ - + - + + + + @@ -6223,7 +6298,7 @@ - + @@ -6275,10 +6350,13 @@ - + - + + + + @@ -6390,15 +6468,12 @@ - + - + - + - - - @@ -6504,6 +6579,15 @@ + + + + + + + + + @@ -6582,6 +6666,9 @@ + + + @@ -7063,7 +7150,7 @@ - + @@ -7350,7 +7437,7 @@ - + @@ -8395,7 +8482,7 @@ - + @@ -8404,7 +8491,7 @@ - + diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 6067b27a51382..76488c39e7696 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -145,7 +145,7 @@ - + @@ -154,7 +154,7 @@ - + @@ -163,7 +163,7 @@ - + @@ -172,7 +172,7 @@ - + @@ -181,7 +181,7 @@ - + @@ -418,7 +418,7 @@ - + @@ -532,7 +532,7 @@ - + @@ -541,7 +541,7 @@ - + @@ -796,7 +796,7 @@ - + @@ -866,52 +866,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1099,7 +1105,7 @@ - + @@ -1541,10 +1547,13 @@ - + - + + + + @@ -1955,34 +1964,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2058,6 +2070,15 @@ + + + + + + + + + @@ -2173,7 +2194,7 @@ - + @@ -2182,7 +2203,7 @@ - + @@ -2354,37 +2375,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2410,7 +2443,7 @@ - + @@ -2462,10 +2495,13 @@ - + - + + + + @@ -2554,7 +2590,7 @@ - + @@ -2818,7 +2854,7 @@ - + @@ -2899,7 +2935,7 @@ - + @@ -2917,7 +2953,7 @@ - + @@ -3148,7 +3184,7 @@ - + @@ -3157,7 +3193,7 @@ - + @@ -3166,7 +3202,7 @@ - + @@ -3429,15 +3465,6 @@ - - - - - - - - - @@ -3731,31 +3758,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3763,17 +3796,20 @@ - + - + - + + + + @@ -3868,7 +3904,7 @@ - + @@ -3920,37 +3956,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4481,10 +4529,13 @@ - + - + + + + @@ -4537,7 +4588,7 @@ - + @@ -4546,7 +4597,7 @@ - + @@ -4701,6 +4752,15 @@ + + + + + + + + + @@ -4791,6 +4851,15 @@ + + + + + + + + + @@ -4867,7 +4936,7 @@ - + @@ -5140,7 +5209,7 @@ - + @@ -5149,7 +5218,7 @@ - + @@ -5158,7 +5227,7 @@ - + @@ -5167,7 +5236,7 @@ - + @@ -5176,7 +5245,7 @@ - + @@ -5185,7 +5254,7 @@ - + @@ -5194,7 +5263,7 @@ - + @@ -5203,7 +5272,7 @@ - + @@ -5212,7 +5281,7 @@ - + @@ -5221,7 +5290,7 @@ - + @@ -5248,7 +5317,7 @@ - + @@ -5257,7 +5326,7 @@ - + @@ -5266,7 +5335,7 @@ - + @@ -5275,7 +5344,7 @@ - + @@ -5284,7 +5353,7 @@ - + @@ -5293,7 +5362,7 @@ - + @@ -5302,7 +5371,7 @@ - + @@ -5311,7 +5380,7 @@ - + @@ -5338,7 +5407,7 @@ - + @@ -5347,7 +5416,7 @@ - + @@ -5356,7 +5425,7 @@ - + @@ -5365,7 +5434,7 @@ - + @@ -5396,10 +5465,13 @@ - + - + + + + @@ -5443,7 +5515,7 @@ - + @@ -5635,7 +5707,7 @@ - + @@ -5644,7 +5716,7 @@ - + @@ -5716,7 +5788,7 @@ - + @@ -5725,7 +5797,7 @@ - + @@ -5734,7 +5806,7 @@ - + @@ -5743,7 +5815,7 @@ - + @@ -5752,7 +5824,7 @@ - + @@ -5761,7 +5833,7 @@ - + @@ -5770,7 +5842,7 @@ - + @@ -5779,7 +5851,7 @@ - + @@ -5788,7 +5860,7 @@ - + @@ -5797,7 +5869,7 @@ - + @@ -5806,7 +5878,7 @@ - + @@ -5815,7 +5887,7 @@ - + @@ -5849,10 +5921,13 @@ - + - + + + + @@ -6040,7 +6115,7 @@ - + @@ -6049,7 +6124,7 @@ - + @@ -6058,7 +6133,7 @@ - + @@ -6067,7 +6142,7 @@ - + @@ -6088,7 +6163,7 @@ - + @@ -6097,7 +6172,7 @@ - + @@ -6106,7 +6181,7 @@ - + @@ -6115,7 +6190,7 @@ - + @@ -6124,7 +6199,7 @@ - + @@ -6133,7 +6208,7 @@ - + @@ -6142,7 +6217,7 @@ - + @@ -6151,7 +6226,7 @@ - + @@ -6160,7 +6235,7 @@ - + @@ -6169,7 +6244,7 @@ - + @@ -6178,7 +6253,7 @@ - + @@ -6187,7 +6262,7 @@ - + @@ -6196,7 +6271,7 @@ - + @@ -6205,7 +6280,7 @@ - + @@ -6214,7 +6289,7 @@ - + @@ -6223,7 +6298,7 @@ - + @@ -6232,7 +6307,7 @@ - + @@ -6241,7 +6316,7 @@ - + @@ -6250,7 +6325,7 @@ - + @@ -6275,10 +6350,13 @@ - + - + + + + @@ -6390,15 +6468,12 @@ - + - + - + - - - @@ -6504,6 +6579,15 @@ + + + + + + + + + @@ -6582,6 +6666,9 @@ + + + @@ -6754,7 +6841,7 @@ - + @@ -7350,7 +7437,7 @@ - + @@ -7549,7 +7636,7 @@ - + @@ -7558,7 +7645,7 @@ - + @@ -7567,7 +7654,7 @@ - + @@ -7576,7 +7663,7 @@ - + @@ -7585,7 +7672,7 @@ - + @@ -7603,7 +7690,7 @@ - + @@ -7612,7 +7699,7 @@ - + @@ -7621,7 +7708,7 @@ - + @@ -8395,7 +8482,7 @@ - + @@ -8404,7 +8491,7 @@ - + @@ -8431,7 +8518,7 @@ - + @@ -8476,7 +8563,7 @@ - + @@ -8485,7 +8572,7 @@ - + @@ -8866,7 +8953,7 @@ - + @@ -8875,7 +8962,7 @@ - + @@ -8884,7 +8971,7 @@ - + diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index 35fa1147eac3b..2418583bb9884 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -145,7 +145,7 @@ - + @@ -154,7 +154,7 @@ - + @@ -163,7 +163,7 @@ - + @@ -172,7 +172,7 @@ - + @@ -181,7 +181,7 @@ - + @@ -337,7 +337,7 @@ - + @@ -532,7 +532,7 @@ - + @@ -541,7 +541,7 @@ - + @@ -796,7 +796,7 @@ - + @@ -866,52 +866,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1541,10 +1547,13 @@ - + - + + + + @@ -1955,34 +1964,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2058,6 +2070,15 @@ + + + + + + + + + @@ -2354,37 +2375,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2462,10 +2495,13 @@ - + - + + + + @@ -2764,7 +2800,7 @@ - + @@ -2836,7 +2872,7 @@ - + @@ -3082,7 +3118,7 @@ - + @@ -3175,7 +3211,7 @@ - + @@ -3429,15 +3465,6 @@ - - - - - - - - - @@ -3731,31 +3758,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3770,10 +3803,13 @@ - + - + + + + @@ -3920,37 +3956,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4441,7 +4489,7 @@ - + @@ -4481,10 +4529,13 @@ - + - + + + + @@ -4701,6 +4752,15 @@ + + + + + + + + + @@ -4791,6 +4851,15 @@ + + + + + + + + + @@ -5396,10 +5465,13 @@ - + - + + + + @@ -5849,10 +5921,13 @@ - + - + + + + @@ -6275,10 +6350,13 @@ - + - + + + + @@ -6390,15 +6468,12 @@ - + - + - + - - - @@ -6504,6 +6579,15 @@ + + + + + + + + + @@ -6582,6 +6666,9 @@ + + + @@ -7350,7 +7437,7 @@ - + @@ -8866,7 +8953,7 @@ - + @@ -8875,7 +8962,7 @@ - + @@ -8884,7 +8971,7 @@ - + diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 88817c1298e0e..42685f7a45e74 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -138,7 +138,7 @@ - + @@ -147,7 +147,7 @@ - + @@ -156,7 +156,7 @@ - + @@ -165,7 +165,7 @@ - + @@ -174,7 +174,7 @@ - + @@ -525,7 +525,7 @@ - + @@ -534,7 +534,7 @@ - + @@ -786,7 +786,7 @@ - + @@ -856,44 +856,53 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + @@ -1365,7 +1374,7 @@ - + @@ -1374,7 +1383,7 @@ - + @@ -1528,10 +1537,13 @@ - + - + + + + @@ -1942,31 +1954,37 @@ - + - + - + - + - + + + + - + - + + + + @@ -2042,6 +2060,15 @@ + + + + + + + + + @@ -2338,37 +2365,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2446,10 +2485,13 @@ - + - + + + + @@ -3413,15 +3455,6 @@ - - - - - - - - - @@ -3715,28 +3748,37 @@ - + - + + + + - + - + + + + - + - + + + + @@ -3751,10 +3793,13 @@ - + - + + + + @@ -3901,37 +3946,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4462,10 +4519,13 @@ - + - + + + + @@ -4682,6 +4742,15 @@ + + + + + + + + + @@ -4772,6 +4841,15 @@ + + + + + + + + + @@ -5374,10 +5452,13 @@ - + - + + + + @@ -5827,10 +5908,13 @@ - + - + + + + @@ -6250,10 +6334,13 @@ - + - + + + + @@ -6365,11 +6452,11 @@ - + - + - + @@ -6476,6 +6563,15 @@ + + + + + + + + + @@ -6554,6 +6650,9 @@ + + + @@ -7322,7 +7421,7 @@ - + @@ -8838,7 +8937,7 @@ - + @@ -8847,7 +8946,7 @@ - + @@ -8856,7 +8955,7 @@ - + diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index e80dfb3e45535..bcace1bd16201 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -138,7 +138,7 @@ - + @@ -147,7 +147,7 @@ - + @@ -156,7 +156,7 @@ - + @@ -165,7 +165,7 @@ - + @@ -174,7 +174,7 @@ - + @@ -210,7 +210,7 @@ - + @@ -276,7 +276,7 @@ - + @@ -411,7 +411,7 @@ - + @@ -525,7 +525,7 @@ - + @@ -534,7 +534,7 @@ - + @@ -786,7 +786,7 @@ - + @@ -856,48 +856,57 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - + @@ -1041,7 +1050,7 @@ - + @@ -1086,7 +1095,7 @@ - + @@ -1528,10 +1537,13 @@ - + - + + + + @@ -1942,31 +1954,37 @@ - + - + - + - + - + + + + - + - + + + + @@ -2042,6 +2060,15 @@ + + + + + + + + + @@ -2166,7 +2193,7 @@ - + @@ -2338,37 +2365,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2446,10 +2485,13 @@ - + - + + + + @@ -2874,7 +2916,7 @@ - + @@ -2883,7 +2925,7 @@ - + @@ -2892,7 +2934,7 @@ - + @@ -2901,7 +2943,7 @@ - + @@ -2910,7 +2952,7 @@ - + @@ -2922,7 +2964,7 @@ - + @@ -3413,15 +3455,6 @@ - - - - - - - - - @@ -3715,28 +3748,37 @@ - + - + + + + - + - + + + + - + - + + + + @@ -3751,10 +3793,13 @@ - + - + + + + @@ -3840,7 +3885,7 @@ - + @@ -3849,7 +3894,7 @@ - + @@ -3858,7 +3903,7 @@ - + @@ -3901,37 +3946,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4462,10 +4519,13 @@ - + - + + + + @@ -4682,6 +4742,15 @@ + + + + + + + + + @@ -4772,6 +4841,15 @@ + + + + + + + + + @@ -5374,10 +5452,13 @@ - + - + + + + @@ -5421,7 +5502,7 @@ - + @@ -5827,10 +5908,13 @@ - + - + + + + @@ -6250,10 +6334,13 @@ - + - + + + + @@ -6365,11 +6452,11 @@ - + - + - + @@ -6476,6 +6563,15 @@ + + + + + + + + + @@ -6554,6 +6650,9 @@ + + + @@ -6846,7 +6945,7 @@ - + @@ -6984,7 +7083,7 @@ - + @@ -7322,11 +7421,11 @@ - + - + @@ -8346,7 +8445,7 @@ - + @@ -8355,7 +8454,7 @@ - + @@ -8367,7 +8466,7 @@ - + @@ -8376,7 +8475,7 @@ - + @@ -8385,7 +8484,7 @@ - + @@ -8838,7 +8937,7 @@ - + @@ -8847,7 +8946,7 @@ - + @@ -8856,7 +8955,7 @@ - + diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 2b490cc372cfc..ca1dcf2d4cbcd 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -144,7 +144,7 @@ - + @@ -153,7 +153,7 @@ - + @@ -162,7 +162,7 @@ - + @@ -171,7 +171,7 @@ - + @@ -180,7 +180,7 @@ - + @@ -531,7 +531,7 @@ - + @@ -540,7 +540,7 @@ - + @@ -795,7 +795,7 @@ - + @@ -865,52 +865,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -1540,10 +1546,13 @@ - + - + + + + @@ -1954,34 +1963,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2057,6 +2069,15 @@ + + + + + + + + + @@ -2353,37 +2374,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2461,10 +2494,13 @@ - + - + + + + @@ -3009,7 +3045,7 @@ - + @@ -3428,15 +3464,6 @@ - - - - - - - - - @@ -3730,31 +3757,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3769,10 +3802,13 @@ - + - + + + + @@ -3919,37 +3955,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4480,10 +4528,13 @@ - + - + + + + @@ -4700,6 +4751,15 @@ + + + + + + + + + @@ -4790,6 +4850,15 @@ + + + + + + + + + @@ -5395,10 +5464,13 @@ - + - + + + + @@ -5848,10 +5920,13 @@ - + - + + + + @@ -6274,10 +6349,13 @@ - + - + + + + @@ -6389,15 +6467,12 @@ - + - + - + - - - @@ -6503,6 +6578,15 @@ + + + + + + + + + @@ -6581,6 +6665,9 @@ + + + @@ -7349,7 +7436,7 @@ - + @@ -8865,7 +8952,7 @@ - + @@ -8874,7 +8961,7 @@ - + @@ -8883,7 +8970,7 @@ - + diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 43e951d850448..34cf0f01ff643 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -411,7 +411,7 @@ - + @@ -859,52 +859,58 @@ - + - + - + - + - + + + + - + - + + + + - + - + + + + - + - - - @@ -975,7 +981,7 @@ - + @@ -1047,7 +1053,7 @@ - + @@ -1092,7 +1098,7 @@ - + @@ -1534,10 +1540,13 @@ - + - + + + + @@ -1948,34 +1957,37 @@ - + - + - + - + - + - + - + - + + + + @@ -2051,6 +2063,15 @@ + + + + + + + + + @@ -2166,7 +2187,7 @@ - + @@ -2347,37 +2368,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -2455,10 +2488,13 @@ - + - + + + + @@ -2547,7 +2583,7 @@ - + @@ -2892,7 +2928,7 @@ - + @@ -2901,7 +2937,7 @@ - + @@ -2910,7 +2946,7 @@ - + @@ -2958,7 +2994,7 @@ - + @@ -2985,7 +3021,7 @@ - + @@ -2994,7 +3030,7 @@ - + @@ -3141,7 +3177,7 @@ - + @@ -3150,7 +3186,7 @@ - + @@ -3422,15 +3458,6 @@ - - - - - - - - - @@ -3724,31 +3751,37 @@ - + - + + + + - + - + - + - + - + + + + @@ -3763,10 +3796,13 @@ - + - + + + + @@ -3852,7 +3888,7 @@ - + @@ -3861,7 +3897,7 @@ - + @@ -3870,7 +3906,7 @@ - + @@ -3913,37 +3949,49 @@ - + - + + + + - + - + + + + - + - + + + + - + - + + + + @@ -4474,10 +4522,13 @@ - + - + + + + @@ -4641,7 +4692,7 @@ - + @@ -4694,6 +4745,15 @@ + + + + + + + + + @@ -4784,6 +4844,15 @@ + + + + + + + + + @@ -5151,7 +5220,7 @@ - + @@ -5196,7 +5265,7 @@ - + @@ -5259,7 +5328,7 @@ - + @@ -5286,7 +5355,7 @@ - + @@ -5331,7 +5400,7 @@ - + @@ -5340,7 +5409,7 @@ - + @@ -5349,7 +5418,7 @@ - + @@ -5358,7 +5427,7 @@ - + @@ -5389,10 +5458,13 @@ - + - + + + + @@ -5436,7 +5508,7 @@ - + @@ -5736,7 +5808,7 @@ - + @@ -5763,7 +5835,7 @@ - + @@ -5790,7 +5862,7 @@ - + @@ -5842,10 +5914,13 @@ - + - + + + + @@ -6144,7 +6219,7 @@ - + @@ -6153,7 +6228,7 @@ - + @@ -6162,7 +6237,7 @@ - + @@ -6198,7 +6273,7 @@ - + @@ -6207,7 +6282,7 @@ - + @@ -6216,7 +6291,7 @@ - + @@ -6252,7 +6327,7 @@ - + @@ -6268,10 +6343,13 @@ - + - + + + + @@ -6383,15 +6461,12 @@ - + - + - + - - - @@ -6492,7 +6567,16 @@ - + + + + + + + + + + @@ -6575,6 +6659,9 @@ + + + @@ -6867,7 +6954,7 @@ - + @@ -7005,7 +7092,7 @@ - + @@ -7343,7 +7430,7 @@ - + @@ -8388,7 +8475,7 @@ - + @@ -8397,7 +8484,7 @@ - + @@ -8406,7 +8493,7 @@ - + @@ -8478,7 +8565,7 @@ - + diff --git a/src/server/cancellationToken/cancellationToken.ts b/src/server/cancellationToken/cancellationToken.ts index 6f2f4a8897c11..b7243ccd87111 100644 --- a/src/server/cancellationToken/cancellationToken.ts +++ b/src/server/cancellationToken/cancellationToken.ts @@ -46,7 +46,7 @@ function createCancellationToken(args: string[]): ServerCancellationToken { let perRequestPipeName: string; let currentRequestId: number; return { - isCancellationRequested: () => perRequestPipeName !== undefined && pipeExists(perRequestPipeName), + isCancellationRequested: () => perRequestPipeName !== undefined && pipeExists(perRequestPipeName), setRequest(requestId: number) { currentRequestId = requestId; perRequestPipeName = namePrefix + requestId; diff --git a/src/server/client.ts b/src/server/client.ts index 8286119e8289e..f34516ac4fd92 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -180,14 +180,15 @@ namespace ts.server { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, - entries: response.body.map(entry => { - + entries: response.body.map(entry => { if (entry.replacementSpan !== undefined) { - const { name, kind, kindModifiers, sortText, replacementSpan } = entry; - return { name, kind, kindModifiers, sortText, replacementSpan: this.decodeSpan(replacementSpan, fileName) }; + const { name, kind, kindModifiers, sortText, replacementSpan, hasAction, source, isRecommended } = entry; + // TODO: GH#241 + const res: CompletionEntry = { name, kind, kindModifiers, sortText, replacementSpan: this.decodeSpan(replacementSpan, fileName), hasAction, source, isRecommended }; + return res; } - return entry as { name: string, kind: ScriptElementKind, kindModifiers: string, sortText: string }; + return entry as { name: string, kind: ScriptElementKind, kindModifiers: string, sortText: string }; // TODO: GH#18217 }) }; } @@ -199,7 +200,7 @@ namespace ts.server { const response = this.processResponse(request); Debug.assert(response.body.length === 1, "Unexpected length of completion details response body."); - const convertedCodeActions = map(response.body[0].codeActions, codeAction => this.convertCodeActions(codeAction, fileName)); + const convertedCodeActions = map(response.body[0].codeActions, ({ description, changes }) => ({ description, changes: this.convertChanges(changes, fileName) })); return { ...response.body[0], codeActions: convertedCodeActions }; } @@ -552,15 +553,18 @@ namespace ts.server { return notImplemented(); } - getCodeFixesAtPosition(file: string, start: number, end: number, errorCodes: number[]): CodeAction[] { + getCodeFixesAtPosition(file: string, start: number, end: number, errorCodes: ReadonlyArray): ReadonlyArray { const args: protocol.CodeFixRequestArgs = { ...this.createFileRangeRequestArgs(file, start, end), errorCodes }; const request = this.processRequest(CommandNames.GetCodeFixes, args); const response = this.processResponse(request); - return response.body.map(entry => this.convertCodeActions(entry, file)); + // TODO: GH#20538 shouldn't need cast + return (response.body as ReadonlyArray).map(({ description, changes, fixId }) => ({ description, changes: this.convertChanges(changes, file), fixId })); } + getCombinedCodeFix = notImplemented; + applyCodeActionCommand = notImplemented; private createFileLocationOrRangeRequestArgs(positionOrRange: number | TextRange, fileName: string): protocol.FileLocationOrRangeRequestArgs { @@ -637,14 +641,11 @@ namespace ts.server { }); } - convertCodeActions(entry: protocol.CodeAction, fileName: string): CodeAction { - return { - description: entry.description, - changes: entry.changes.map(change => ({ - fileName: change.fileName, - textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, fileName)) - })) - }; + private convertChanges(changes: protocol.FileCodeEdits[], fileName: string): FileTextChanges[] { + return changes.map(change => ({ + fileName: change.fileName, + textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, fileName)) + })); } convertTextChangeToCodeEdit(change: protocol.CodeEdit, fileName: string): ts.TextChange { diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index a5b09c6a63f5d..664938a4cdc21 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -547,9 +547,11 @@ namespace ts.server { } switch (response.kind) { case ActionSet: + project.resolutionCache.clear(); this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings); break; case ActionInvalidate: + project.resolutionCache.clear(); this.typingsCache.deleteTypingsForProject(response.projectName); break; } @@ -1774,9 +1776,10 @@ namespace ts.server { const path = normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); let info = this.getScriptInfoForPath(path); if (!info) { - Debug.assert(isRootedDiskPath(fileName) || openedByClient, "Script info with relative file name can only be open script info"); - Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); const isDynamic = isDynamicFileName(fileName); + Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "Script info with non-dynamic relative file name can only be open script info"); + Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); + Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "Dynamic files must always have current directory context since containing external project name will always match the script info name."); // If the file is not opened by client and the file doesnot exist on the disk, return if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; diff --git a/src/server/project.ts b/src/server/project.ts index ce750c78e235c..ebc93ae3e1e09 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -121,6 +121,7 @@ namespace ts.server { private program: Program; private externalFiles: SortedReadonlyArray; private missingFilesMap: Map; + private plugins: PluginModule[] = []; private cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); private lastCachedUnresolvedImportsList: SortedReadonlyArray; @@ -506,8 +507,27 @@ namespace ts.server { } abstract getTypeAcquisition(): TypeAcquisition; + protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition { + if (!newTypeAcquisition || !newTypeAcquisition.include) { + // Nothing to filter out, so just return as-is + return newTypeAcquisition; + } + return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) }; + } + getExternalFiles(): SortedReadonlyArray { - return emptyArray as SortedReadonlyArray; + return toSortedArray(flatMap(this.plugins, plugin => { + if (typeof plugin.getExternalFiles !== "function") return; + try { + return plugin.getExternalFiles(this); + } + catch (e) { + this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`); + if (e.stack) { + this.projectService.logger.info(e.stack); + } + } + })); } getSourceFile(path: Path) { @@ -718,7 +738,8 @@ namespace ts.server { this.projectStateVersion++; } - private extractUnresolvedImportsFromSourceFile(file: SourceFile, result: Push) { + /* @internal */ + private extractUnresolvedImportsFromSourceFile(file: SourceFile, result: Push, ambientModules: string[]) { const cached = this.cachedUnresolvedImportsPerFile.get(file.path); if (cached) { // found cached result - use it and return @@ -731,7 +752,7 @@ namespace ts.server { if (file.resolvedModules) { file.resolvedModules.forEach((resolvedModule, name) => { // pick unresolved non-relative names - if (!resolvedModule && !isExternalModuleNameRelative(name)) { + if (!resolvedModule && !isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { // for non-scoped names extract part up-to the first slash // for scoped names - extract up to the second slash let trimmed = name.trim(); @@ -748,6 +769,10 @@ namespace ts.server { }); } this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || emptyArray); + + function isAmbientlyDeclaredModule(name: string) { + return ambientModules.some(m => m === name); + } } /** @@ -777,8 +802,9 @@ namespace ts.server { // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasChanges || changedFiles.length) { const result: string[] = []; + const ambientModules = this.program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); for (const sourceFile of this.program.getSourceFiles()) { - this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + this.extractUnresolvedImportsFromSourceFile(sourceFile, result, ambientModules); } this.lastCachedUnresolvedImportsList = toDeduplicatedSortedArray(result); } @@ -804,6 +830,13 @@ namespace ts.server { return !hasChanges; } + + + protected removeExistingTypings(include: string[]): string[] { + const existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + return include.filter(i => existing.indexOf(i) < 0); + } + private setTypings(typings: SortedReadonlyArray): boolean { if (arrayIsEqualTo(this.typingFiles, typings)) { return false; @@ -1008,6 +1041,84 @@ namespace ts.server { orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); } + + protected enableGlobalPlugins() { + const host = this.projectService.host; + const options = this.getCompilationSettings(); + + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + const searchPaths = [combinePaths(this.projectService.getExecutingFilePath(), "../../.."), ...this.projectService.pluginProbeLocations]; + + if (this.projectService.globalPlugins) { + // Enable global plugins with synthetic configuration entries + for (const globalPluginName of this.projectService.globalPlugins) { + // Skip empty names from odd commandline parses + if (!globalPluginName) continue; + + // Skip already-locally-loaded plugins + if (options.plugins && options.plugins.some(p => p.name === globalPluginName)) continue; + + // Provide global: true so plugins can detect why they can't find their config + this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); + this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths); + } + } + } + + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]) { + this.projectService.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); + + const log = (message: string) => { + this.projectService.logger.info(message); + }; + + for (const searchPath of searchPaths) { + const resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); + if (resolvedModule) { + this.enableProxy(resolvedModule, pluginConfigEntry); + return; + } + } + this.projectService.logger.info(`Couldn't find ${pluginConfigEntry.name}`); + } + + private enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport) { + try { + if (typeof pluginModuleFactory !== "function") { + this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did expose a proper factory function`); + return; + } + + const info: PluginCreateInfo = { + config: configEntry, + project: this, + languageService: this.languageService, + languageServiceHost: this, + serverHost: this.projectService.host + }; + + const pluginModule = pluginModuleFactory({ typescript: ts }); + const newLS = pluginModule.create(info); + for (const k of Object.keys(this.languageService)) { + if (!(k in newLS)) { + this.projectService.logger.info(`Plugin activation warning: Missing proxied method ${k} in created LS. Patching.`); + (newLS as any)[k] = (this.languageService as any)[k]; + } + } + this.projectService.logger.info(`Plugin validation succeded`); + this.languageService = newLS; + this.plugins.push(pluginModule); + } + catch (e) { + this.projectService.logger.info(`Plugin activation failed: ${e}`); + } + } } /** @@ -1071,6 +1182,7 @@ namespace ts.server { projectService.host, currentDirectory); this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); + this.enableGlobalPlugins(); } addRoot(info: ScriptInfo) { @@ -1132,8 +1244,6 @@ namespace ts.server { /*@internal*/ configFileSpecs: ConfigFileSpecs; - private plugins: PluginModule[] = []; - /** Ref count to the project when opened from external project */ private externalProjectRefCount = 0; @@ -1215,69 +1325,7 @@ namespace ts.server { } } - if (this.projectService.globalPlugins) { - // Enable global plugins with synthetic configuration entries - for (const globalPluginName of this.projectService.globalPlugins) { - // Skip empty names from odd commandline parses - if (!globalPluginName) continue; - - // Skip already-locally-loaded plugins - if (options.plugins && options.plugins.some(p => p.name === globalPluginName)) continue; - - // Provide global: true so plugins can detect why they can't find their config - this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); - this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths); - } - } - } - - private enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]) { - this.projectService.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); - - const log = (message: string) => { - this.projectService.logger.info(message); - }; - - for (const searchPath of searchPaths) { - const resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); - if (resolvedModule) { - this.enableProxy(resolvedModule, pluginConfigEntry); - return; - } - } - this.projectService.logger.info(`Couldn't find ${pluginConfigEntry.name}`); - } - - private enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport) { - try { - if (typeof pluginModuleFactory !== "function") { - this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did expose a proper factory function`); - return; - } - - const info: PluginCreateInfo = { - config: configEntry, - project: this, - languageService: this.languageService, - languageServiceHost: this, - serverHost: this.projectService.host - }; - - const pluginModule = pluginModuleFactory({ typescript: ts }); - const newLS = pluginModule.create(info); - for (const k of Object.keys(this.languageService)) { - if (!(k in newLS)) { - this.projectService.logger.info(`Plugin activation warning: Missing proxied method ${k} in created LS. Patching.`); - (newLS as any)[k] = (this.languageService as any)[k]; - } - } - this.projectService.logger.info(`Plugin validation succeded`); - this.languageService = newLS; - this.plugins.push(pluginModule); - } - catch (e) { - this.projectService.logger.info(`Plugin activation failed: ${e}`); - } + this.enableGlobalPlugins(); } /** @@ -1299,28 +1347,13 @@ namespace ts.server { } setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void { - this.typeAcquisition = newTypeAcquisition; + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); } getTypeAcquisition() { return this.typeAcquisition; } - getExternalFiles(): SortedReadonlyArray { - return toSortedArray(flatMap(this.plugins, plugin => { - if (typeof plugin.getExternalFiles !== "function") return; - try { - return plugin.getExternalFiles(this); - } - catch (e) { - this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`); - if (e.stack) { - this.projectService.logger.info(e.stack); - } - } - })); - } - /*@internal*/ watchWildcards(wildcardDirectories: Map) { updateWatchingWildcardDirectories( @@ -1445,7 +1478,7 @@ namespace ts.server { Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); - this.typeAcquisition = newTypeAcquisition; + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); } } } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 6e96365a4ac11..b3cbba27a2067 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -71,6 +71,7 @@ namespace ts.server.protocol { SignatureHelp = "signatureHelp", /* @internal */ SignatureHelpFull = "signatureHelp-full", + Status = "status", TypeDefinition = "typeDefinition", ProjectInfo = "projectInfo", ReloadProjects = "reloadProjects", @@ -99,9 +100,14 @@ namespace ts.server.protocol { BreakpointStatement = "breakpointStatement", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", - ApplyCodeActionCommand = "applyCodeActionCommand", /* @internal */ GetCodeFixesFull = "getCodeFixes-full", + // TODO: GH#20538 + /* @internal */ + GetCombinedCodeFix = "getCombinedCodeFix", + /* @internal */ + GetCombinedCodeFixFull = "getCombinedCodeFix-full", + ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", @@ -216,6 +222,24 @@ namespace ts.server.protocol { projectFileName?: string; } + export interface StatusRequest extends Request { + command: CommandTypes.Status; + } + + export interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + + /** + * Response to StatusRequest + */ + export interface StatusResponse extends Response { + body: StatusResponseBody; + } + /** * Requests a JS Doc comment template for a given position */ @@ -533,6 +557,19 @@ namespace ts.server.protocol { arguments: CodeFixRequestArgs; } + // TODO: GH#20538 + /* @internal */ + export interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + + // TODO: GH#20538 + /* @internal */ + export interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } + export interface ApplyCodeActionCommandRequest extends Request { command: CommandTypes.ApplyCodeActionCommand; arguments: ApplyCodeActionCommandRequestArgs; @@ -582,7 +619,21 @@ namespace ts.server.protocol { /** * Errorcodes we want to get the fixes for. */ - errorCodes?: number[]; + errorCodes?: ReadonlyArray; + } + + // TODO: GH#20538 + /* @internal */ + export interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + + // TODO: GH#20538 + /* @internal */ + export interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; } export interface ApplyCodeActionCommandRequestArgs { @@ -1568,7 +1619,7 @@ namespace ts.server.protocol { export interface CodeFixResponse extends Response { /** The code actions that are available */ - body?: CodeAction[]; + body?: CodeAction[]; // TODO: GH#20538 CodeFixAction[] } export interface CodeAction { @@ -1580,6 +1631,23 @@ namespace ts.server.protocol { commands?: {}[]; } + // TODO: GH#20538 + /* @internal */ + export interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray<{}>; + } + + // TODO: GH#20538 + /* @internal */ + export interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } + /** * Format and format on key response message. */ @@ -1625,6 +1693,11 @@ namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ includeExternalModuleExports: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + includeInsertTextCompletions: boolean; } /** @@ -1701,8 +1774,15 @@ namespace ts.server.protocol { */ sortText: string; /** - * An optional span that indicates the text to be replaced by this completion item. If present, - * this span should be used instead of the default one. + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; /** @@ -1714,6 +1794,12 @@ namespace ts.server.protocol { * Identifier (not necessarily human-readable) identifying where this completion came from. */ source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; } /** @@ -2481,6 +2567,7 @@ namespace ts.server.protocol { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } export interface CompilerOptions { diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index fe71040b4f632..9650130634e86 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -257,7 +257,7 @@ namespace ts.server { export class ScriptVersionCache { private changes: TextChange[] = []; private readonly versions: LineIndexSnapshot[] = new Array(ScriptVersionCache.maxVersions); - private minVersion = 0; // no versions earlier than min version will maintain change history + private minVersion = 0; // no versions earlier than min version will maintain change history private currentVersion = 0; diff --git a/src/server/server.ts b/src/server/server.ts index 86349fa2be568..8e53c4d51092a 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -979,6 +979,10 @@ namespace ts.server { allowLocalPluginLoads }; + logger.info(`Starting TS Server`); + logger.info(`Version: ${versionMajorMinor}`); + logger.info(`Arguments: ${process.argv.join(" ")}`); + const ioSession = new IOSession(options); process.on("uncaughtException", err => { ioSession.logError(err, "unknown"); diff --git a/src/server/session.ts b/src/server/session.ts index 309a6aef0cab4..693d1651c911d 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1207,10 +1207,10 @@ namespace ts.server { if (simplifiedResult) { return mapDefined(completions && completions.entries, entry => { if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - const { name, kind, kindModifiers, sortText, replacementSpan, hasAction, source } = entry; + const { name, kind, kindModifiers, sortText, insertText, replacementSpan, hasAction, source, isRecommended } = entry; const convertedSpan = replacementSpan ? this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name, kind, kindModifiers, sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source }; + return { name, kind, kindModifiers, sortText, insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source, isRecommended }; } }).sort((a, b) => compareStringsCaseSensitiveUI(a.name, b.name)); } @@ -1230,7 +1230,7 @@ namespace ts.server { return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source); }); return simplifiedResult - ? result.map(details => ({ ...details, codeActions: map(details.codeActions, action => this.mapCodeAction(action, scriptInfo)) })) + ? result.map(details => ({ ...details, codeActions: map(details.codeActions, action => this.mapCodeAction(project, action)) })) : result; } @@ -1245,7 +1245,7 @@ namespace ts.server { // if specified a project, we only return affected file list in this project const projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; for (const project of projectsToSearch) { - if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { result.push({ projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), @@ -1538,18 +1538,14 @@ namespace ts.server { const oldText = snapshot.getText(0, snapshot.getLength()); mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); } - return { - renameLocation: mappedRenameLocation, - renameFilename, - edits: edits.map(change => this.mapTextChangesToCodeEdits(project, change)) - }; + return { renameLocation: mappedRenameLocation, renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; } else { return result; } } - private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): protocol.CodeAction[] | CodeAction[] { + private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { if (args.errorCodes.length === 0) { return undefined; } @@ -1564,22 +1560,35 @@ namespace ts.server { return undefined; } if (simplifiedResult) { - return codeActions.map(codeAction => this.mapCodeAction(codeAction, scriptInfo)); + return codeActions.map(codeAction => this.mapCodeAction(project, codeAction)); } else { return codeActions; } } - private applyCodeActionCommand(commandName: string, requestSeq: number, args: protocol.ApplyCodeActionCommandRequestArgs): void { + private getCombinedCodeFix({ scope, fixId }: protocol.GetCombinedCodeFixRequestArgs, simplifiedResult: boolean): protocol.CombinedCodeActions | CombinedCodeActions { + Debug.assert(scope.type === "file"); + const { file, project } = this.getFileAndProject(scope.args); + const formatOptions = this.projectService.getFormatCodeOptions(file); + const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, formatOptions); + if (simplifiedResult) { + return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; + } + else { + return res; + } + } + + private applyCodeActionCommand(args: protocol.ApplyCodeActionCommandRequestArgs): {} { const commands = args.command as CodeActionCommand | CodeActionCommand[]; // They should be sending back the command we sent them. for (const command of toArray(commands)) { const { project } = this.getFileAndProject(command); - const output = (success: boolean, message: string) => this.doOutput({}, commandName, requestSeq, success, message); project.getLanguageService().applyCodeActionCommand(command).then( - result => { output(/*success*/ true, result.successMessage); }, - error => { output(/*success*/ false, error); }); + _result => { /* TODO: GH#20447 report success message? */ }, + _error => { /* TODO: GH#20447 report errors */ }); } + return {}; } private getStartAndEndPosition(args: protocol.FileRangeRequestArgs, scriptInfo: ScriptInfo) { @@ -1604,16 +1613,16 @@ namespace ts.server { return { startPosition, endPosition }; } - private mapCodeAction({ description, changes: unmappedChanges, commands }: CodeAction, scriptInfo: ScriptInfo): protocol.CodeAction { - const changes = unmappedChanges.map(change => ({ - fileName: change.fileName, - textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo)) - })); + private mapCodeAction(project: Project, { description, changes: unmappedChanges, commands }: CodeAction): protocol.CodeAction { + const changes = unmappedChanges.map(change => this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(toNormalizedPath(change.fileName)))); return { description, changes, commands }; } - private mapTextChangesToCodeEdits(project: Project, textChanges: FileTextChanges): protocol.FileCodeEdits { - const scriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(textChanges.fileName)); + private mapTextChangesToCodeEdits(project: Project, textChanges: ReadonlyArray): protocol.FileCodeEdits[] { + return textChanges.map(change => this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(toNormalizedPath(change.fileName)))); + } + + private mapTextChangesToCodeEditsUsingScriptinfo(textChanges: FileTextChanges, scriptInfo: ScriptInfo): protocol.FileCodeEdits { return { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo)) @@ -1703,19 +1712,23 @@ namespace ts.server { } private handlers = createMapFromTemplate<(request: protocol.Request) => HandlerResponse>({ + [CommandNames.Status]: () => { + const response: protocol.StatusResponseBody = { version }; + return this.requiredResponse(response); + }, [CommandNames.OpenExternalProject]: (request: protocol.OpenExternalProjectRequest) => { this.projectService.openExternalProject(request.arguments, /*suppressRefreshOfInferredProjects*/ false); - // TODO: report errors + // TODO: GH#20447 report errors return this.requiredResponse(/*response*/ true); }, [CommandNames.OpenExternalProjects]: (request: protocol.OpenExternalProjectsRequest) => { this.projectService.openExternalProjects(request.arguments.projects); - // TODO: report errors + // TODO: GH#20447 report errors return this.requiredResponse(/*response*/ true); }, [CommandNames.CloseExternalProject]: (request: protocol.CloseExternalProjectRequest) => { this.projectService.closeExternalProject(request.arguments.projectFileName); - // TODO: report errors + // TODO: GH#20447 report errors return this.requiredResponse(/*response*/ true); }, [CommandNames.SynchronizeProjectList]: (request: protocol.SynchronizeProjectListRequest) => { @@ -1956,9 +1969,14 @@ namespace ts.server { [CommandNames.GetCodeFixesFull]: (request: protocol.CodeFixRequest) => { return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); }, + [CommandNames.GetCombinedCodeFix]: (request: protocol.GetCombinedCodeFixRequest) => { + return this.requiredResponse(this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true)); + }, + [CommandNames.GetCombinedCodeFixFull]: (request: protocol.GetCombinedCodeFixRequest) => { + return this.requiredResponse(this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ false)); + }, [CommandNames.ApplyCodeActionCommand]: (request: protocol.ApplyCodeActionCommandRequest) => { - this.applyCodeActionCommand(request.command, request.seq, request.arguments); - return this.notRequired(); // Response will come asynchronously. + return this.requiredResponse(this.applyCodeActionCommand(request.arguments)); }, [CommandNames.GetSupportedCodeFixes]: () => { return this.requiredResponse(this.getSupportedCodeFixes()); diff --git a/src/server/typingsInstaller/typingsInstaller.ts b/src/server/typingsInstaller/typingsInstaller.ts index 3e8f79d0f1d5f..283770d1dc862 100644 --- a/src/server/typingsInstaller/typingsInstaller.ts +++ b/src/server/typingsInstaller/typingsInstaller.ts @@ -205,35 +205,29 @@ namespace ts.server.typingsInstaller { this.knownCachesSet.set(cacheLocation, true); } - private filterTypings(typingsToInstall: string[]) { - if (typingsToInstall.length === 0) { - return typingsToInstall; - } - const result: string[] = []; - for (const typing of typingsToInstall) { - if (this.missingTypingsSet.get(typing) || this.packageNameToTypingLocation.get(typing)) { - continue; + private filterTypings(typingsToInstall: ReadonlyArray): ReadonlyArray { + return typingsToInstall.filter(typing => { + if (this.missingTypingsSet.get(typing)) { + if (this.log.isEnabled()) this.log.writeLine(`'${typing}' is in missingTypingsSet - skipping...`); + return false; } - const validationResult = JsTyping.validatePackageName(typing); - if (validationResult === JsTyping.PackageNameValidationResult.Ok) { - if (this.typesRegistry.has(typing)) { - result.push(typing); - } - else { - if (this.log.isEnabled()) { - this.log.writeLine(`Entry for package '${typing}' does not exist in local types registry - skipping...`); - } - } + if (this.packageNameToTypingLocation.get(typing)) { + if (this.log.isEnabled()) this.log.writeLine(`'${typing}' already has a typing - skipping...`); + return false; } - else { + const validationResult = JsTyping.validatePackageName(typing); + if (validationResult !== JsTyping.PackageNameValidationResult.Ok) { // add typing name to missing set so we won't process it again this.missingTypingsSet.set(typing, true); - if (this.log.isEnabled()) { - this.log.writeLine(JsTyping.renderPackageNameValidationFailure(validationResult, typing)); - } + if (this.log.isEnabled()) this.log.writeLine(JsTyping.renderPackageNameValidationFailure(validationResult, typing)); + return false; } - } - return result; + if (!this.typesRegistry.has(typing)) { + if (this.log.isEnabled()) this.log.writeLine(`Entry for package '${typing}' does not exist in local types registry - skipping...`); + return false; + } + return true; + }); } protected ensurePackageDirectoryExists(directory: string) { diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 57dbc5711e7d8..26df417f87924 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -262,8 +262,8 @@ namespace ts.BreakpointResolver { } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.SpreadElement || node.kind === SyntaxKind.PropertyAssignment || @@ -427,8 +427,9 @@ namespace ts.BreakpointResolver { } else { const functionDeclaration = parameter.parent; - const indexOfParameter = indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + const indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 32b3dac2ccaad..3e4c6058a3630 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -837,7 +837,7 @@ namespace ts { return ClassificationType.keyword; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === SyntaxKind.LessThanToken || tokenKind === SyntaxKind.GreaterThanToken) { // If the node owning the token has a type argument list or type parameter list, then diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index ad9ab520dabcf..aa1f2fb6885e7 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -1,40 +1,56 @@ /* @internal */ namespace ts { - export interface CodeFix { + export interface CodeFixRegistration { errorCodes: number[]; - getCodeActions(context: CodeFixContext): CodeAction[] | undefined; + getCodeActions(context: CodeFixContext): CodeFixAction[] | undefined; + fixIds?: string[]; + getAllCodeActions?(context: CodeFixAllContext): CombinedCodeActions; } - export interface CodeFixContext extends textChanges.TextChangesContext { - errorCode: number; + export interface CodeFixContextBase extends textChanges.TextChangesContext { sourceFile: SourceFile; - span: TextSpan; program: Program; host: LanguageServiceHost; cancellationToken: CancellationToken; } + export interface CodeFixAllContext extends CodeFixContextBase { + fixId: {}; + } + + export interface CodeFixContext extends CodeFixContextBase { + errorCode: number; + span: TextSpan; + } + export namespace codefix { - const codeFixes: CodeFix[][] = []; - - export function registerCodeFix(codeFix: CodeFix) { - forEach(codeFix.errorCodes, error => { - let fixes = codeFixes[error]; - if (!fixes) { - fixes = []; - codeFixes[error] = fixes; + const codeFixRegistrations: CodeFixRegistration[][] = []; + const fixIdToRegistration = createMap(); + + export function registerCodeFix(reg: CodeFixRegistration) { + for (const error of reg.errorCodes) { + let registrations = codeFixRegistrations[error]; + if (!registrations) { + registrations = []; + codeFixRegistrations[error] = registrations; } - fixes.push(codeFix); - }); + registrations.push(reg); + } + if (reg.fixIds) { + for (const fixId of reg.fixIds) { + Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } } export function getSupportedErrorCodes() { - return Object.keys(codeFixes); + return Object.keys(codeFixRegistrations); } - export function getFixes(context: CodeFixContext): CodeAction[] { - const fixes = codeFixes[context.errorCode]; - const allActions: CodeAction[] = []; + export function getFixes(context: CodeFixContext): CodeFixAction[] { + const fixes = codeFixRegistrations[context.errorCode]; + const allActions: CodeFixAction[] = []; forEach(fixes, f => { const actions = f.getCodeActions(context); @@ -52,5 +68,40 @@ namespace ts { return allActions; } + + export function getAllFixes(context: CodeFixAllContext): CombinedCodeActions { + // Currently fixId is always a string. + return fixIdToRegistration.get(cast(context.fixId, isString))!.getAllCodeActions!(context); + } + + function createCombinedCodeActions(changes: FileTextChanges[], commands?: CodeActionCommand[]): CombinedCodeActions { + return { changes, commands }; + } + + export function createFileTextChanges(fileName: string, textChanges: TextChange[]): FileTextChanges { + return { fileName, textChanges }; + } + + export function codeFixAll(context: CodeFixAllContext, errorCodes: number[], use: (changes: textChanges.ChangeTracker, error: Diagnostic, commands: Push) => void): CombinedCodeActions { + const commands: CodeActionCommand[] = []; + const changes = textChanges.ChangeTracker.with(context, t => + eachDiagnostic(context, errorCodes, diag => use(t, diag, commands))); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + + export function codeFixAllWithTextChanges(context: CodeFixAllContext, errorCodes: number[], use: (changes: Push, error: Diagnostic) => void): CombinedCodeActions { + const changes: TextChange[] = []; + eachDiagnostic(context, errorCodes, diag => use(changes, diag)); + changes.sort((a, b) => b.span.start - a.span.start); + return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); + } + + function eachDiagnostic({ program, sourceFile }: CodeFixAllContext, errorCodes: number[], cb: (diag: Diagnostic) => void): void { + for (const diag of program.getSemanticDiagnostics(sourceFile)) { + if (contains(errorCodes, diag.code)) { + cb(diag); + } + } + } } } diff --git a/src/services/codefixes/addMissingInvocationForDecorator.ts b/src/services/codefixes/addMissingInvocationForDecorator.ts index 7f17aab6db2a8..d063df87be422 100644 --- a/src/services/codefixes/addMissingInvocationForDecorator.ts +++ b/src/services/codefixes/addMissingInvocationForDecorator.ts @@ -1,20 +1,22 @@ /* @internal */ namespace ts.codefix { + const fixId = "addMissingInvocationForDecorator"; + const errorCodes = [Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; registerCodeFix({ - errorCodes: [Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - const decorator = getAncestor(token, SyntaxKind.Decorator) as Decorator; - Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - const replacement = createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); - const changeTracker = textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, decorator.expression, replacement); - - return [{ - description: getLocaleSpecificMessage(Diagnostics.Call_decorator_expression), - changes: changeTracker.getChanges() - }]; - } + errorCodes, + getCodeActions: (context) => { + const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, context.span.start)); + return [{ description: getLocaleSpecificMessage(Diagnostics.Call_decorator_expression), changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file!, diag.start!)), }); + + function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + const decorator = findAncestor(token, isDecorator)!; + Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + const replacement = createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } } diff --git a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts index e18190d6f6ac7..de4498035becd 100644 --- a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts +++ b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts @@ -1,27 +1,36 @@ /* @internal */ namespace ts.codefix { + const fixId = "correctQualifiedNameToIndexedAccessType"; + const errorCodes = [Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; registerCodeFix({ - errorCodes: [Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - const qualifiedName = getAncestor(token, SyntaxKind.QualifiedName) as QualifiedName; - Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - if (!isIdentifier(qualifiedName.left)) { - return undefined; + errorCodes, + getCodeActions(context) { + const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) return undefined; + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, qualifiedName)); + const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Rewrite_as_the_indexed_access_type_0), [`${qualifiedName.left.text}["${qualifiedName.right.text}"]`]); + return [{ description, changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: (context) => codeFixAll(context, errorCodes, (changes, diag) => { + const q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); } - const leftText = qualifiedName.left.getText(sourceFile); - const rightText = qualifiedName.right.getText(sourceFile); - const replacement = createIndexedAccessTypeNode( - createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), - createLiteralTypeNode(createLiteral(rightText))); - const changeTracker = textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, qualifiedName, replacement); - - return [{ - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Rewrite_as_the_indexed_access_type_0), [`${leftText}["${rightText}"]`]), - changes: changeTracker.getChanges() - }]; - } + }), }); + + function getQualifiedName(sourceFile: SourceFile, pos: number): QualifiedName & { left: Identifier } | undefined { + const qualifiedName = findAncestor(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), isQualifiedName)!; + Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return isIdentifier(qualifiedName.left) ? qualifiedName as QualifiedName & { left: Identifier } : undefined; + } + + function doChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, qualifiedName: QualifiedName): void { + const rightText = qualifiedName.right.text; + const replacement = createIndexedAccessTypeNode( + createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), + createLiteralTypeNode(createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } } diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 291dc61c32f74..6a59e61d52dec 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -1,18 +1,47 @@ /* @internal */ namespace ts.codefix { - registerCodeFix({ - errorCodes: getApplicableDiagnosticCodes(), - getCodeActions: getDisableJsDiagnosticsCodeActions + const fixId = "disableJsDiagnostics"; + const errorCodes = mapDefined(Object.keys(Diagnostics), key => { + const diag = (Diagnostics as MapLike)[key]; + return diag.category === DiagnosticCategory.Error ? diag.code : undefined; }); - function getApplicableDiagnosticCodes(): number[] { - const allDiagnostcs = >Diagnostics; - return Object.keys(allDiagnostcs) - .filter(d => allDiagnostcs[d] && allDiagnostcs[d].category === DiagnosticCategory.Error) - .map(d => allDiagnostcs[d].code); - } + registerCodeFix({ + errorCodes, + getCodeActions(context) { + const { sourceFile, program, newLineCharacter, span } = context; - function getIgnoreCommentLocationForLocation(sourceFile: SourceFile, position: number, newLineCharacter: string) { + if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + + return [{ + description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message), + changes: [createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], + fixId, + }, + { + description: getLocaleSpecificMessage(Diagnostics.Disable_checking_for_this_file), + changes: [createFileTextChanges(sourceFile.fileName, [{ + span: { + start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, + length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 + }, + newText: `// @ts-nocheck${newLineCharacter}` + }])], + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + fixId: undefined, + }]; + }, + fixIds: [fixId], // No point applying as a group, doing it once will fix all errors + getAllCodeActions: context => codeFixAllWithTextChanges(context, errorCodes, (changes, err) => { + if (err.start !== undefined) { + changes.push(getIgnoreCommentLocationForLocation(err.file!, err.start, context.newLineCharacter)); + } + }), + }); + + function getIgnoreCommentLocationForLocation(sourceFile: SourceFile, position: number, newLineCharacter: string): TextChange { const { line } = getLineAndCharacterOfPosition(sourceFile, position); const lineStartPosition = getStartPositionOfLine(line, sourceFile); const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); @@ -38,33 +67,4 @@ namespace ts.codefix { newText: `${position === startPosition ? "" : newLineCharacter}// @ts-ignore${newLineCharacter}` }; } - - function getDisableJsDiagnosticsCodeActions(context: CodeFixContext): CodeAction[] | undefined { - const { sourceFile, program, newLineCharacter, span } = context; - - if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { - return undefined; - } - - return [{ - description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)] - }] - }, - { - description: getLocaleSpecificMessage(Diagnostics.Disable_checking_for_this_file), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { - start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, - length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 - }, - newText: `// @ts-nocheck${newLineCharacter}` - }] - }] - }]; - } } diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 19bd592b7a7d6..0fc6a430e192a 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -1,209 +1,194 @@ /* @internal */ namespace ts.codefix { + const errorCodes = [ + Diagnostics.Property_0_does_not_exist_on_type_1.code, + Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ]; + const fixId = "addMissingMember"; registerCodeFix({ - errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code, - Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], - getCodeActions: getActionsForAddMissingMember - }); + errorCodes, + getCodeActions(context) { + const info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) return undefined; + const { classDeclaration, classDeclarationSourceFile, inJs, makeStatic, token, call } = info; + const methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + const addMember = inJs ? + singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + return concatenate(singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: context => { + const seenNames = createMap(); + return codeFixAll(context, errorCodes, (changes, diag) => { + const { program } = context; + const info = getInfo(diag.file!, diag.start!, program.getTypeChecker()); + if (!info) return; + const { classDeclaration, classDeclarationSourceFile, inJs, makeStatic, token, call } = info; + if (!addToSeen(seenNames, token.text)) { + return; + } - function getActionsForAddMissingMember(context: CodeFixContext): CodeAction[] | undefined { + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + } + else { + const typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + } + } + }); + }, + }); - const tokenSourceFile = context.sourceFile; - const start = context.span.start; + interface Info { token: Identifier; classDeclaration: ClassLikeDeclaration; makeStatic: boolean; classDeclarationSourceFile: SourceFile; inJs: boolean; call: CallExpression; } + function getInfo(tokenSourceFile: SourceFile, tokenPos: number, checker: TypeChecker): Info | undefined { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - const token = getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); - - if (token.kind !== SyntaxKind.Identifier) { + const token = getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + if (!isIdentifier(token)) { return undefined; } - if (!isPropertyAccessExpression(token.parent)) { + const classAndMakeStatic = getClassAndMakeStatic(token, checker); + if (!classAndMakeStatic) { return undefined; } + const { classDeclaration, makeStatic } = classAndMakeStatic; + const classDeclarationSourceFile = classDeclaration.getSourceFile(); + const inJs = isInJavaScriptFile(classDeclarationSourceFile); + const call = tryCast(token.parent.parent, isCallExpression); - const tokenName = token.getText(tokenSourceFile); + return { token, classDeclaration, makeStatic, classDeclarationSourceFile, inJs, call }; + } - let makeStatic = false; - let classDeclaration: ClassLikeDeclaration; + function getClassAndMakeStatic(token: Node, checker: TypeChecker): { readonly classDeclaration: ClassLikeDeclaration, readonly makeStatic: boolean } | undefined { + const { parent } = token; + if (!isPropertyAccessExpression(parent)) { + return undefined; + } - if (token.parent.expression.kind === SyntaxKind.ThisKeyword) { + if (parent.expression.kind === SyntaxKind.ThisKeyword) { const containingClassMemberDeclaration = getThisContainer(token, /*includeArrowFunctions*/ false); if (!isClassElement(containingClassMemberDeclaration)) { return undefined; } - - classDeclaration = containingClassMemberDeclaration.parent; - + const classDeclaration = containingClassMemberDeclaration.parent; // Property accesses on `this` in a static method are accesses of a static member. - makeStatic = classDeclaration && hasModifier(containingClassMemberDeclaration, ModifierFlags.Static); + return isClassLike(classDeclaration) ? { classDeclaration, makeStatic: hasModifier(containingClassMemberDeclaration, ModifierFlags.Static) } : undefined; } else { - - const checker = context.program.getTypeChecker(); - const leftExpression = token.parent.expression; - const leftExpressionType = checker.getTypeAtLocation(leftExpression); - - if (leftExpressionType.flags & TypeFlags.Object) { - const symbol = leftExpressionType.symbol; - if (symbol.flags & SymbolFlags.Class) { - classDeclaration = symbol.declarations && symbol.declarations[0]; - if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { - // The expression is a class symbol but the type is not the instance-side. - makeStatic = true; - } - } + const leftExpressionType = checker.getTypeAtLocation(parent.expression); + const { symbol } = leftExpressionType; + if (!(leftExpressionType.flags & TypeFlags.Object && symbol.flags & SymbolFlags.Class)) { + return undefined; } + const classDeclaration = cast(first(symbol.declarations), isClassLike); + // The expression is a class symbol but the type is not the instance-side. + return { classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; } + } - if (!classDeclaration || !isClassLike(classDeclaration)) { - return undefined; - } - - const classDeclarationSourceFile = getSourceFileOfNode(classDeclaration); - const classOpenBrace = getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); - - return isInJavaScriptFile(classDeclarationSourceFile) ? - getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : - getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); - - function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration: ClassLikeDeclaration, makeStatic: boolean): CodeAction[] | undefined { - let actions: CodeAction[]; + function getActionsForAddMissingMemberInJavaScriptFile(context: CodeFixContext, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { + const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic)); + if (changes.length === 0) return undefined; + const description = formatStringFromArgs(getLocaleSpecificMessage(makeStatic ? Diagnostics.Initialize_static_property_0 : Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); + return { description, changes, fixId }; + } - const methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); - if (methodCodeAction) { - actions = [methodCodeAction]; + function addMissingMemberInJs(changeTracker: textChanges.ChangeTracker, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): void { + if (makeStatic) { + if (classDeclaration.kind === SyntaxKind.ClassExpression) { + return; } - - if (makeStatic) { - if (classDeclaration.kind === SyntaxKind.ClassExpression) { - return actions; - } - - const className = classDeclaration.name.getText(); - - const staticInitialization = createStatement(createAssignment( - createPropertyAccess(createIdentifier(className), tokenName), - createIdentifier("undefined"))); - - const staticInitializationChangeTracker = textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter( - classDeclarationSourceFile, - classDeclaration, - staticInitialization, - { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); - const initializeStaticAction = { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Initialize_static_property_0), [tokenName]), - changes: staticInitializationChangeTracker.getChanges() - }; - - (actions || (actions = [])).push(initializeStaticAction); - return actions; + const className = classDeclaration.name.getText(); + const staticInitialization = initializePropertyToUndefined(createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); + } + else { + const classConstructor = getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; } - else { - const classConstructor = getFirstConstructorWithBody(classDeclaration); - if (!classConstructor) { - return actions; - } - - const propertyInitialization = createStatement(createAssignment( - createPropertyAccess(createThis(), tokenName), - createIdentifier("undefined"))); + const propertyInitialization = initializePropertyToUndefined(createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + } + } - const propertyInitializationChangeTracker = textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeBefore( - classDeclarationSourceFile, - classConstructor.body.getLastToken(), - propertyInitialization, - { suffix: context.newLineCharacter }); + function initializePropertyToUndefined(obj: Expression, propertyName: string) { + return createStatement(createAssignment(createPropertyAccess(obj, propertyName), createIdentifier("undefined"))); + } - const initializeAction = { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), - changes: propertyInitializationChangeTracker.getChanges() - }; + function getActionsForAddMissingMemberInTypeScriptFile(context: CodeFixContext, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, token: Identifier, makeStatic: boolean): CodeFixAction[] | undefined { + const typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + const addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + } - (actions || (actions = [])).push(initializeAction); - return actions; - } + function getTypeNode(checker: TypeChecker, classDeclaration: ClassLikeDeclaration, token: Node) { + let typeNode: TypeNode; + if (token.parent.parent.kind === SyntaxKind.BinaryExpression) { + const binaryExpression = token.parent.parent as BinaryExpression; + const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } + return typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword); + } - function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration: ClassLikeDeclaration, makeStatic: boolean): CodeAction[] | undefined { - let actions: CodeAction[]; - - const methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); - if (methodCodeAction) { - actions = [methodCodeAction]; - } + function createAddPropertyDeclarationAction(context: textChanges.TextChangesContext, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, makeStatic: boolean, tokenName: string, typeNode: TypeNode): CodeFixAction { + const description = formatStringFromArgs(getLocaleSpecificMessage(makeStatic ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0), [tokenName]); + const changes = textChanges.ChangeTracker.with(context, t => addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic)); + return { description, changes, fixId }; + } - let typeNode: TypeNode; - if (token.parent.parent.kind === SyntaxKind.BinaryExpression) { - const binaryExpression = token.parent.parent as BinaryExpression; - const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - const checker = context.program.getTypeChecker(); - const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); - } - typeNode = typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword); - - const property = createProperty( - /*decorators*/undefined, - /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, - tokenName, - /*questionToken*/ undefined, - typeNode, - /*initializer*/ undefined); - const propertyChangeTracker = textChanges.ChangeTracker.fromContext(context); - propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - - const diag = makeStatic ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0; - actions = append(actions, { - description: formatStringFromArgs(getLocaleSpecificMessage(diag), [tokenName]), - changes: propertyChangeTracker.getChanges() - }); + function addPropertyDeclaration(changeTracker: textChanges.ChangeTracker, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, typeNode: TypeNode, makeStatic: boolean): void { + const property = createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, + tokenName, + /*questionToken*/ undefined, + typeNode, + /*initializer*/ undefined); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } - if (!makeStatic) { - // Index signatures cannot have the static modifier. - const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword); - const indexingParameter = createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - "x", - /*questionToken*/ undefined, - stringTypeNode, - /*initializer*/ undefined); - const indexSignature = createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, - [indexingParameter], - typeNode); - - const indexSignatureChangeTracker = textChanges.ChangeTracker.fromContext(context); - indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); - - actions.push({ - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_index_signature_for_property_0), [tokenName]), - changes: indexSignatureChangeTracker.getChanges() - }); - } + function createAddIndexSignatureAction(context: textChanges.TextChangesContext, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, typeNode: TypeNode): CodeFixAction { + // Index signatures cannot have the static modifier. + const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword); + const indexingParameter = createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + "x", + /*questionToken*/ undefined, + stringTypeNode, + /*initializer*/ undefined); + const indexSignature = createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, + [indexingParameter], + typeNode); + + const changes = textChanges.ChangeTracker.with(context, t => t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature)); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return { description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes, fixId: undefined }; + } - return actions; - } + function getActionForMethodDeclaration(context: textChanges.TextChangesContext, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, token: Identifier, callExpression: CallExpression, makeStatic: boolean, inJs: boolean): CodeFixAction | undefined { + const description = formatStringFromArgs(getLocaleSpecificMessage(makeStatic ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0), [token.text]); + const changes = textChanges.ChangeTracker.with(context, t => addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs)); + return { description, changes, fixId }; + } - function getActionForMethodDeclaration(includeTypeScriptSyntax: boolean): CodeAction | undefined { - if (token.parent.parent.kind === SyntaxKind.CallExpression) { - const callExpression = token.parent.parent; - const methodDeclaration = createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - - const methodDeclarationChangeTracker = textChanges.ChangeTracker.fromContext(context); - methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); - const diag = makeStatic ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0; - return { - description: formatStringFromArgs(getLocaleSpecificMessage(diag), [tokenName]), - changes: methodDeclarationChangeTracker.getChanges() - }; - } - } + function addMethodDeclaration(changeTracker: textChanges.ChangeTracker, classDeclarationSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, token: Identifier, callExpression: CallExpression, makeStatic: boolean, inJs: boolean) { + const methodDeclaration = createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } } diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 9796bf2fa22c4..a28a46caf1b16 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -1,34 +1,42 @@ /* @internal */ namespace ts.codefix { + const fixId = "fixCannotFindModule"; + const errorCodes = [Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; registerCodeFix({ - errorCodes: [ - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, - ], + errorCodes, getCodeActions: context => { - const { sourceFile, span: { start } } = context; - const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - if (!isStringLiteral(token)) { - throw Debug.fail(); // These errors should only happen on the module name. - } - - const action = tryGetCodeActionForInstallPackageTypes(context.host, sourceFile.fileName, token.text); - return action && [action]; + const codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); + return codeAction && [{ fixId, ...codeAction }]; }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (_, diag, commands) => { + const pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + if (pkg) { + commands.push(getCommand(diag.file.fileName, pkg)); + } + }), }); - export function tryGetCodeActionForInstallPackageTypes(host: LanguageServiceHost, fileName: string, moduleName: string): CodeAction | undefined { - const { packageName } = getPackageName(moduleName); + function getModuleName(sourceFile: SourceFile, pos: number): string { + return cast(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isStringLiteral).text; + } - if (!host.isKnownTypesPackageName(packageName)) { - // If !registry, registry not available yet, can't do anything. - return undefined; - } + function getCommand(fileName: string, packageName: string): InstallPackageAction { + return { type: "install package", file: fileName, packageName }; + } - const typesPackageName = getTypesPackageName(packageName); - return { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Install_0), [typesPackageName]), + function getTypesPackageNameToInstall(host: LanguageServiceHost, moduleName: string): string | undefined { + const { packageName } = getPackageName(moduleName); + // If !registry, registry not available yet, can't do anything. + return host.isKnownTypesPackageName(packageName) ? getTypesPackageName(packageName) : undefined; + } + + export function tryGetCodeActionForInstallPackageTypes(host: LanguageServiceHost, fileName: string, moduleName: string): CodeAction | undefined { + const packageName = getTypesPackageNameToInstall(host, moduleName); + return packageName === undefined ? undefined : { + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Install_0), [packageName]), changes: [], - commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + commands: [getCommand(fileName, packageName)], }; } } diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index 768eaf752b780..da3685339ab21 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -1,52 +1,48 @@ /* @internal */ namespace ts.codefix { + const errorCodes = [ + Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + const fixId = "fixClassDoesntImplementInheritedAbstractMember"; registerCodeFix({ - errorCodes: [Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code], - getCodeActions: getActionForClassLikeMissingAbstractMember + errorCodes, + getCodeActions(context) { + const { program, sourceFile, span } = context; + const changes = textChanges.ChangeTracker.with(context, t => + addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t)); + return changes.length === 0 ? undefined : [{ description: getLocaleSpecificMessage(Diagnostics.Implement_inherited_abstract_class), changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { + addMissingMembers(getClass(diag.file!, diag.start!), context.sourceFile, context.program.getTypeChecker(), changes); + }), }); - registerCodeFix({ - errorCodes: [Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code], - getCodeActions: getActionForClassLikeMissingAbstractMember - }); - - function getActionForClassLikeMissingAbstractMember(context: CodeFixContext): CodeAction[] | undefined { - const sourceFile = context.sourceFile; - const start = context.span.start; + function getClass(sourceFile: SourceFile, pos: number): ClassLikeDeclaration { // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - const checker = context.program.getTypeChecker(); - - if (isClassLike(token.parent)) { - const classDeclaration = token.parent as ClassLikeDeclaration; - - const extendsNode = getClassExtendsHeritageClauseElement(classDeclaration); - const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - const extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); - const abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + const classDeclaration = token.parent; + Debug.assert(isClassLike(classDeclaration)); + return classDeclaration as ClassLikeDeclaration; + } - const newNodes = createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); - const changes = newNodesToChanges(newNodes, getOpenBraceOfClassLike(classDeclaration, sourceFile), context); - if (changes && changes.length > 0) { - return [{ - description: getLocaleSpecificMessage(Diagnostics.Implement_inherited_abstract_class), - changes - }]; - } - } + function addMissingMembers(classDeclaration: ClassLikeDeclaration, sourceFile: SourceFile, checker: TypeChecker, changeTracker: textChanges.ChangeTracker): void { + const extendsNode = getClassExtendsHeritageClauseElement(classDeclaration); + const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - return undefined; + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); } function symbolPointsToNonPrivateAndAbstractMember(symbol: Symbol): boolean { - const decls = symbol.getDeclarations(); - Debug.assert(!!(decls && decls.length > 0)); - const flags = getModifierFlags(decls[0]); + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + const flags = getModifierFlags(first(symbol.getDeclarations())); return !(flags & ModifierFlags.Private) && !!(flags & ModifierFlags.Abstract); } -} \ No newline at end of file +} diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 1a0cf17bbd663..0236b0c79b7bb 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -1,64 +1,70 @@ /* @internal */ namespace ts.codefix { + const errorCodes = [Diagnostics.Class_0_incorrectly_implements_interface_1.code, + Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + const fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? registerCodeFix({ - errorCodes: [Diagnostics.Class_0_incorrectly_implements_interface_1.code], - getCodeActions: getActionForClassLikeIncorrectImplementsInterface + errorCodes, + getCodeActions(context) { + const { program, sourceFile, span } = context; + const classDeclaration = getClass(sourceFile, span.start); + const checker = program.getTypeChecker(); + return mapDefined(getClassImplementsHeritageClauseElements(classDeclaration), implementedTypeNode => { + const changes = textChanges.ChangeTracker.with(context, t => addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t)); + if (changes.length === 0) return undefined; + const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); + return { description, changes, fixId }; + }); + }, + fixIds: [fixId], + getAllCodeActions(context) { + const seenClassDeclarations = createMap(); + return codeFixAll(context, errorCodes, (changes, diag) => { + const classDeclaration = getClass(diag.file!, diag.start!); + if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { + for (const implementedTypeNode of getClassImplementsHeritageClauseElements(classDeclaration)) { + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file!, classDeclaration, changes); + } + } + }); + }, }); - function getActionForClassLikeIncorrectImplementsInterface(context: CodeFixContext): CodeAction[] | undefined { - const sourceFile = context.sourceFile; - const start = context.span.start; - const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - const checker = context.program.getTypeChecker(); - - const classDeclaration = getContainingClass(token); - if (!classDeclaration) { - return undefined; - } - - const openBrace = getOpenBraceOfClassLike(classDeclaration, sourceFile); - const classType = checker.getTypeAtLocation(classDeclaration) as InterfaceType; - const implementedTypeNodes = getClassImplementsHeritageClauseElements(classDeclaration); + function getClass(sourceFile: SourceFile, pos: number): ClassLikeDeclaration { + const classDeclaration = getContainingClass(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); + Debug.assert(!!classDeclaration); + return classDeclaration!; + } - const hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, IndexKind.Number); - const hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, IndexKind.String); + function addMissingDeclarations( + checker: TypeChecker, + implementedTypeNode: ExpressionWithTypeArguments, + sourceFile: SourceFile, + classDeclaration: ClassLikeDeclaration, + changeTracker: textChanges.ChangeTracker + ): void { + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + const implementedType = checker.getTypeAtLocation(implementedTypeNode) as InterfaceType; + const implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + const nonPrivateMembers = implementedTypeSymbols.filter(symbol => !(getModifierFlags(symbol.valueDeclaration) & ModifierFlags.Private)); - const result: CodeAction[] = []; - for (const implementedTypeNode of implementedTypeNodes) { - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - const implementedType = checker.getTypeAtLocation(implementedTypeNode) as InterfaceType; - const implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - const nonPrivateMembers = implementedTypeSymbols.filter(symbol => !(getModifierFlags(symbol.valueDeclaration) & ModifierFlags.Private)); + const classType = checker.getTypeAtLocation(classDeclaration); - let newNodes: Node[] = []; - createAndAddMissingIndexSignatureDeclaration(implementedType, IndexKind.Number, hasNumericIndexSignature, newNodes); - createAndAddMissingIndexSignatureDeclaration(implementedType, IndexKind.String, hasStringIndexSignature, newNodes); - newNodes = newNodes.concat(createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); - const message = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - if (newNodes.length > 0) { - pushAction(result, newNodes, message); - } + if (!checker.getIndexTypeOfType(classType, IndexKind.Number)) { + createMissingIndexSignatureDeclaration(implementedType, IndexKind.Number); + } + if (!checker.getIndexTypeOfType(classType, IndexKind.String)) { + createMissingIndexSignatureDeclaration(implementedType, IndexKind.String); } - return result; - - function createAndAddMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind, hasIndexSigOfKind: boolean, newNodes: Node[]): void { - if (hasIndexSigOfKind) { - return; - } + createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member)); + function createMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind): void { const indexInfoOfKind = checker.getIndexInfoOfType(type, kind); - - if (!indexInfoOfKind) { - return; + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); } - const newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration); - newNodes.push(newIndexSignatureDeclaration); - } - - function pushAction(result: CodeAction[], newNodes: Node[], description: string): void { - result.push({ description, changes: newNodesToChanges(newNodes, openBrace, context) }); } } -} \ No newline at end of file +} diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index e5c4266684d22..1595bbf3c1383 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -1,49 +1,52 @@ /* @internal */ namespace ts.codefix { + const fixId = "classSuperMustPrecedeThisAccess"; + const errorCodes = [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; registerCodeFix({ - errorCodes: [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - - const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== SyntaxKind.ThisKeyword) { - return undefined; - } - - const constructor = getContainingFunction(token); - const superCall = findSuperCall((constructor).body); - if (!superCall) { - return undefined; - } - - // figure out if the `this` access is actually inside the supercall - // i.e. super(this.a), since in that case we won't suggest a fix - if (superCall.expression && superCall.expression.kind === SyntaxKind.CallExpression) { - const expressionArguments = (superCall.expression).arguments; - for (const arg of expressionArguments) { - if ((arg).expression === token) { - return undefined; - } + errorCodes, + getCodeActions(context) { + const { sourceFile, span } = context; + const nodes = getNodes(sourceFile, span.start); + if (!nodes) return undefined; + const { constructor, superCall } = nodes; + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, constructor, superCall)); + return [{ description: getLocaleSpecificMessage(Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions(context) { + const { sourceFile } = context; + const seenClasses = createMap(); // Ensure we only do this once per class. + return codeFixAll(context, errorCodes, (changes, diag) => { + const nodes = getNodes(diag.file!, diag.start!); + if (!nodes) return; + const { constructor, superCall } = nodes; + if (addToSeen(seenClasses, getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); } - } - const changeTracker = textChanges.ChangeTracker.fromContext(context); - changeTracker.insertNodeAfter(sourceFile, getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); - changeTracker.deleteNode(sourceFile, superCall); + }); + }, + }); - return [{ - description: getLocaleSpecificMessage(Diagnostics.Make_super_call_the_first_statement_in_the_constructor), - changes: changeTracker.getChanges() - }]; + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, constructor: ConstructorDeclaration, superCall: ExpressionStatement): void { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.deleteNode(sourceFile, superCall); + } - function findSuperCall(n: Node): ExpressionStatement { - if (n.kind === SyntaxKind.ExpressionStatement && isSuperCall((n).expression)) { - return n; - } - if (isFunctionLike(n)) { - return undefined; - } - return forEachChild(n, findSuperCall); - } - } - }); + function getNodes(sourceFile: SourceFile, pos: number): { readonly constructor: ConstructorDeclaration, readonly superCall: ExpressionStatement } { + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + Debug.assert(token.kind === SyntaxKind.ThisKeyword); + const constructor = getContainingFunction(token) as ConstructorDeclaration; + const superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(arg => isPropertyAccessExpression(arg) && arg.expression === token) ? { constructor, superCall } : undefined; + } + + function findSuperCall(n: Node): ExpressionStatement & { expression: CallExpression } | undefined { + return isExpressionStatement(n) && isSuperCall(n.expression) + ? n as ExpressionStatement & { expression: CallExpression } + : isFunctionLike(n) + ? undefined + : forEachChild(n, findSuperCall); + } } diff --git a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts index 24f44a877b34e..8fe2e8458a86b 100644 --- a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts +++ b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts @@ -1,23 +1,28 @@ /* @internal */ namespace ts.codefix { + const fixId = "constructorForDerivedNeedSuperCall"; + const errorCodes = [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; registerCodeFix({ - errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - - if (token.kind !== SyntaxKind.ConstructorKeyword) { - return undefined; - } + errorCodes, + getCodeActions(context) { + const { sourceFile, span } = context; + const ctr = getNode(sourceFile, span.start); + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, ctr)); + return [{ description: getLocaleSpecificMessage(Diagnostics.Add_missing_super_call), changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => + doChange(changes, context.sourceFile, getNode(diag.file, diag.start!))), + }); - const changeTracker = textChanges.ChangeTracker.fromContext(context); - const superCall = createStatement(createCall(createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ emptyArray)); - changeTracker.insertNodeAfter(sourceFile, getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); + function getNode(sourceFile: SourceFile, pos: number): ConstructorDeclaration { + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + Debug.assert(token.kind === SyntaxKind.ConstructorKeyword); + return token.parent as ConstructorDeclaration; + } - return [{ - description: getLocaleSpecificMessage(Diagnostics.Add_missing_super_call), - changes: changeTracker.getChanges() - }]; - } - }); -} \ No newline at end of file + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, ctr: ConstructorDeclaration) { + const superCall = createStatement(createCall(createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } +} diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 57bf2dd279511..d98ca556f47ec 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -1,43 +1,52 @@ /* @internal */ namespace ts.codefix { + const fixId = "extendsInterfaceBecomesImplements"; + const errorCodes = [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; registerCodeFix({ - errorCodes: [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - const start = context.span.start; - const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - const classDeclNode = getContainingClass(token); - if (!(token.kind === SyntaxKind.Identifier && isClassLike(classDeclNode))) { - return undefined; - } + errorCodes, + getCodeActions(context) { + const { sourceFile } = context; + const nodes = getNodes(sourceFile, context.span.start); + if (!nodes) return undefined; + const { extendsToken, heritageClauses } = nodes; + const changes = textChanges.ChangeTracker.with(context, t => doChanges(t, sourceFile, extendsToken, heritageClauses)); + return [{ description: getLocaleSpecificMessage(Diagnostics.Change_extends_to_implements), changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { + const nodes = getNodes(diag.file, diag.start!); + if (nodes) doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }), + }); - const heritageClauses = classDeclNode.heritageClauses; - if (!(heritageClauses && heritageClauses.length > 0)) { - return undefined; - } + function getNodes(sourceFile: SourceFile, pos: number) { + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + const heritageClauses = getContainingClass(token)!.heritageClauses; + const extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === SyntaxKind.ExtendsKeyword ? { extendsToken, heritageClauses } : undefined; + } - const extendsToken = heritageClauses[0].getFirstToken(); - if (!(extendsToken && extendsToken.kind === SyntaxKind.ExtendsKeyword)) { - return undefined; - } + function doChanges(changes: textChanges.ChangeTracker, sourceFile: SourceFile, extendsToken: Node, heritageClauses: ReadonlyArray): void { + changes.replaceRange(sourceFile, { pos: extendsToken.getStart(), end: extendsToken.end }, createToken(SyntaxKind.ImplementsKeyword)); - const changeTracker = textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, extendsToken, createToken(SyntaxKind.ImplementsKeyword)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === SyntaxKind.ExtendsKeyword && + heritageClauses[1].token === SyntaxKind.ImplementsKeyword) { - // We replace existing keywords with commas. - for (let i = 1; i < heritageClauses.length; i++) { - const keywordToken = heritageClauses[i].getFirstToken(); - if (keywordToken) { - changeTracker.replaceNode(sourceFile, keywordToken, createToken(SyntaxKind.CommaToken)); - } - } + const implementsToken = heritageClauses[1].getFirstToken()!; + const implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, createToken(SyntaxKind.CommaToken)); - const result = [{ - description: getLocaleSpecificMessage(Diagnostics.Change_extends_to_implements), - changes: changeTracker.getChanges() - }]; + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + const text = sourceFile.text; + let end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; + } - return result; + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end }); } - }); + } } diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index 5ac4f035f736f..19610da0b1509 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -1,20 +1,26 @@ /* @internal */ namespace ts.codefix { + const fixId = "forgottenThisPropertyAccess"; + const errorCodes = [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; registerCodeFix({ - errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== SyntaxKind.Identifier) { - return undefined; - } - const changeTracker = textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, token, createPropertyAccess(createThis(), token)); - - return [{ - description: getLocaleSpecificMessage(Diagnostics.Add_this_to_unresolved_variable), - changes: changeTracker.getChanges() - }]; - } + errorCodes, + getCodeActions(context) { + const { sourceFile } = context; + const token = getNode(sourceFile, context.span.start); + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, token)); + return [{ description: getLocaleSpecificMessage(Diagnostics.Add_this_to_unresolved_variable), changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { + doChange(changes, context.sourceFile, getNode(diag.file, diag.start!)); + }), }); + + function getNode(sourceFile: SourceFile, pos: number): Identifier { + return cast(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isIdentifier); + } + + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Identifier): void { + changes.replaceNode(sourceFile, token, createPropertyAccess(createThis(), token)); + } } \ No newline at end of file diff --git a/src/services/codefixes/fixInvalidImportSyntax.ts b/src/services/codefixes/fixInvalidImportSyntax.ts new file mode 100644 index 0000000000000..f98f1eaea7cc9 --- /dev/null +++ b/src/services/codefixes/fixInvalidImportSyntax.ts @@ -0,0 +1,98 @@ +/* @internal */ +namespace ts.codefix { + registerCodeFix({ + errorCodes: [Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + + function getActionsForInvalidImport(context: CodeFixContext): CodeAction[] | undefined { + const sourceFile = context.sourceFile; + + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent as ImportDeclaration; + if (!isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + + function getCodeFixesForImportDeclaration(context: CodeFixContext, node: ImportDeclaration) { + const sourceFile = getSourceFileOfNode(node); + const namespace = getNamespaceDeclarationNode(node) as NamespaceImport; + const opts = context.program.getCompilerOptions(); + const variations: CodeAction[] = []; + + // import Bluebird from "bluebird"; + const replacement = createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + createImportClause(namespace.name, /*namedBindings*/ undefined), + node.moduleSpecifier + ); + const changeTracker = textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + const changes = changeTracker.getChanges(); + variations.push({ + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes + }); + + if (getEmitModuleKind(opts) === ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + const replacement = createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, + namespace.name, + createExternalModuleReference(node.moduleSpecifier) + ); + const changeTracker = textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + const changes = changeTracker.getChanges(); + variations.push({ + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes + }); + } + + return variations; + } + + registerCodeFix({ + errorCodes: [ + Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + + function getActionsForUsageOfInvalidImport(context: CodeFixContext): CodeAction[] | undefined { + const sourceFile = context.sourceFile; + const targetKind = Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? SyntaxKind.CallExpression : SyntaxKind.NewExpression; + const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), a => a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length)) as CallExpression | NewExpression; + if (!node) { + return []; + } + const expr = node.expression; + const type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && (type.symbol as TransientSymbol).originatingImport)) { + return []; + } + const fixes: CodeAction[] = []; + const relatedImport = (type.symbol as TransientSymbol).originatingImport; + if (!isImportCall(relatedImport)) { + addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + const propertyAccess = createPropertyAccess(expr, "default"); + const changeTracker = textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + const changes = changeTracker.getChanges(); + fixes.push({ + description: getLocaleSpecificMessage(Diagnostics.Use_synthetic_default_member), + changes + }); + return fixes; + } +} diff --git a/src/services/codefixes/fixJSDocTypes.ts b/src/services/codefixes/fixJSDocTypes.ts index 8d5cd562497fb..8c43ed0cc7fb3 100644 --- a/src/services/codefixes/fixJSDocTypes.ts +++ b/src/services/codefixes/fixJSDocTypes.ts @@ -1,61 +1,91 @@ /* @internal */ namespace ts.codefix { + const fixIdPlain = "fixJSDocTypes_plain"; + const fixIdNullable = "fixJSDocTypes_nullable"; + const errorCodes = [Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; registerCodeFix({ - errorCodes: [Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], - getCodeActions: getActionsForJSDocTypes + errorCodes, + getCodeActions(context) { + const { sourceFile } = context; + const checker = context.program.getTypeChecker(); + const info = getInfo(sourceFile, context.span.start, checker); + if (!info) return undefined; + const { typeNode, type } = info; + const original = typeNode.getText(sourceFile); + const actions = [fix(type, fixIdPlain)]; + if (typeNode.kind === SyntaxKind.JSDocNullableType) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, TypeFlags.Undefined), fixIdNullable)); + } + return actions; + + function fix(type: Type, fixId: string): CodeFixAction { + const newText = typeString(type, checker); + return { + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_0_to_1), [original, newText]), + changes: [createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], + fixId, + }; + } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions(context) { + const { fixId, program, sourceFile } = context; + const checker = program.getTypeChecker(); + return codeFixAllWithTextChanges(context, errorCodes, (changes, err) => { + const info = getInfo(err.file, err.start!, checker); + if (!info) return; + const { typeNode, type } = info; + const fixedType = typeNode.kind === SyntaxKind.JSDocNullableType && fixId === fixIdNullable ? checker.getNullableType(type, TypeFlags.Undefined) : type; + changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + }); + } }); - function getActionsForJSDocTypes(context: CodeFixContext): CodeAction[] | undefined { - const sourceFile = context.sourceFile; - const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + function getInfo(sourceFile: SourceFile, pos: number, checker: TypeChecker): { readonly typeNode: TypeNode, type: Type } { + const decl = findAncestor(getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + const typeNode = decl && decl.type; + return typeNode && { typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } - // NOTE: Some locations are not handled yet: - // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments - const decl = ts.findAncestor(node, - n => - n.kind === SyntaxKind.AsExpression || - n.kind === SyntaxKind.CallSignature || - n.kind === SyntaxKind.ConstructSignature || - n.kind === SyntaxKind.FunctionDeclaration || - n.kind === SyntaxKind.GetAccessor || - n.kind === SyntaxKind.IndexSignature || - n.kind === SyntaxKind.MappedType || - n.kind === SyntaxKind.MethodDeclaration || - n.kind === SyntaxKind.MethodSignature || - n.kind === SyntaxKind.Parameter || - n.kind === SyntaxKind.PropertyDeclaration || - n.kind === SyntaxKind.PropertySignature || - n.kind === SyntaxKind.SetAccessor || - n.kind === SyntaxKind.TypeAliasDeclaration || - n.kind === SyntaxKind.TypeAssertionExpression || - n.kind === SyntaxKind.VariableDeclaration); - if (!decl) return; - const checker = context.program.getTypeChecker(); + function createChange(declaration: TypeNode, sourceFile: SourceFile, newText: string): TextChange { + return { span: createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText }; + } - const jsdocType = (decl as VariableDeclaration).type; - if (!jsdocType) return; - const original = getTextOfNode(jsdocType); - const type = checker.getTypeFromTypeNode(jsdocType); - const actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTruncation))]; - if (jsdocType.kind === SyntaxKind.JSDocNullableType) { - // for nullable types, suggest the flow-compatible `T | null | undefined` - // in addition to the jsdoc/closure-compatible `T | null` - const replacementWithUndefined = checker.typeToString(checker.getNullableType(type, TypeFlags.Undefined), /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTruncation); - actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); - } - return actions; + function typeString(type: Type, checker: TypeChecker): string { + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTruncation); } - function createAction(declaration: TypeNode, fileName: string, original: string, replacement: string): CodeAction { - return { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_0_to_1), [original, replacement]), - changes: [{ - fileName, - textChanges: [{ - span: { start: declaration.getStart(), length: declaration.getWidth() }, - newText: replacement - }] - }], - }; + // TODO: GH#19856 Node & { type: TypeNode } + type TypeContainer = + | AsExpression | CallSignatureDeclaration | ConstructSignatureDeclaration | FunctionDeclaration + | GetAccessorDeclaration | IndexSignatureDeclaration | MappedTypeNode | MethodDeclaration + | MethodSignature | ParameterDeclaration | PropertyDeclaration | PropertySignature | SetAccessorDeclaration + | TypeAliasDeclaration | TypeAssertion | VariableDeclaration; + function isTypeContainer(node: Node): node is TypeContainer { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case SyntaxKind.AsExpression: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.IndexSignature: + case SyntaxKind.MappedType: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.Parameter: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + case SyntaxKind.SetAccessor: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.VariableDeclaration: + return true; + default: + return false; + } } } diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index 2546a92a32fce..729f14e9ef946 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -1,19 +1,34 @@ /* @internal */ namespace ts.codefix { + const fixId = "fixSpelling"; + const errorCodes = [ + Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ]; registerCodeFix({ - errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], - getCodeActions: getActionsForCorrectSpelling + errorCodes, + getCodeActions(context) { + const { sourceFile } = context; + const info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) return undefined; + const { node, suggestion } = info; + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, node, suggestion)); + const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_spelling_to_0), [suggestion]); + return [{ description, changes, fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file!, diag.start!, context.program.getTypeChecker()); + if (info) doChange(changes, context.sourceFile, info.node, info.suggestion); + }), }); - function getActionsForCorrectSpelling(context: CodeFixContext): CodeAction[] | undefined { - const sourceFile = context.sourceFile; - + function getInfo(sourceFile: SourceFile, pos: number, checker: TypeChecker): { node: Node, suggestion: string } | undefined { // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 - const checker = context.program.getTypeChecker(); + const node = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 + let suggestion: string; if (isPropertyAccessExpression(node.parent) && node.parent.name === node) { Debug.assert(node.kind === SyntaxKind.Identifier); @@ -26,18 +41,12 @@ namespace ts.codefix { Debug.assert(name !== undefined, "name should be defined"); suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - if (suggestion) { - return [{ - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_spelling_to_0), [suggestion]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: node.getStart(), length: node.getWidth() }, - newText: suggestion - }], - }], - }]; - } + + return suggestion === undefined ? undefined : { node, suggestion }; + } + + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, node: Node, suggestion: string) { + changes.replaceNode(sourceFile, node, createIdentifier(suggestion)); } function convertSemanticMeaningToSymbolFlags(meaning: SemanticMeaning): SymbolFlags { diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 473c474855010..b7d948b3deb4a 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -1,207 +1,235 @@ /* @internal */ namespace ts.codefix { + const fixIdPrefix = "unusedIdentifier_prefix"; + const fixIdDelete = "unusedIdentifier_delete"; + const errorCodes = [ + Diagnostics._0_is_declared_but_its_value_is_never_read.code, + Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ]; registerCodeFix({ - errorCodes: [ - Diagnostics._0_is_declared_but_its_value_is_never_read.code, - Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ], - getCodeActions: (context: CodeFixContext) => { - const sourceFile = context.sourceFile; - const start = context.span.start; - - let token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - - // this handles var ["computed"] = 12; - if (token.kind === SyntaxKind.OpenBracketToken) { - token = getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); + errorCodes, + getCodeActions(context) { + const { sourceFile } = context; + const token = getToken(sourceFile, context.span.start); + const result: CodeFixAction[] = []; + + const deletion = textChanges.ChangeTracker.with(context, t => tryDeleteDeclaration(t, sourceFile, token)); + if (deletion.length) { + const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); + result.push({ description, changes: deletion, fixId: fixIdDelete }); } - switch (token.kind) { - case ts.SyntaxKind.Identifier: - return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); - - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.NamespaceImport: - return [deleteNode(token.parent)]; + const prefix = textChanges.ChangeTracker.with(context, t => tryPrefixDeclaration(t, context.errorCode, sourceFile, token)); + if (prefix.length) { + const description = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); + result.push({ description, changes: prefix, fixId: fixIdPrefix }); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete], + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { + const { sourceFile } = context; + const token = getToken(diag.file!, diag.start!); + switch (context.fixId) { + case fixIdPrefix: + if (isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + tryDeleteDeclaration(changes, sourceFile, token); + break; default: - return deleteDefault(); + Debug.fail(JSON.stringify(context.fixId)); } + }), + }); - function deleteDefault(): CodeAction[] | undefined { - if (isDeclarationName(token)) { - return [deleteNode(token.parent)]; + function getToken(sourceFile: SourceFile, pos: number): Node { + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + // this handles var ["computed"] = 12; + return token.kind === SyntaxKind.OpenBracketToken ? getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + } + + function tryPrefixDeclaration(changes: textChanges.ChangeTracker, errorCode: number, sourceFile: SourceFile, token: Node): void { + // Don't offer to prefix a property. + if (errorCode !== Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, createIdentifier(`_${token.text}`)); + } + } + + function canPrefix(token: Identifier): boolean { + switch (token.parent.kind) { + case SyntaxKind.Parameter: + return true; + case SyntaxKind.VariableDeclaration: { + const varDecl = token.parent as VariableDeclaration; + switch (varDecl.parent.parent.kind) { + case SyntaxKind.ForOfStatement: + case SyntaxKind.ForInStatement: + return true; } - else if (isLiteralComputedPropertyDeclarationName(token)) { - return [deleteNode(token.parent.parent)]; + } + } + return false; + } + + function tryDeleteDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node): void { + switch (token.kind) { + case SyntaxKind.Identifier: + tryDeleteIdentifier(changes, sourceFile, token); + break; + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.NamespaceImport: + changes.deleteNode(sourceFile, token.parent); + break; + default: + tryDeleteDefault(changes, sourceFile, token); + } + } + + function tryDeleteDefault(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node): void { + if (isDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent); + } + else if (isLiteralComputedPropertyDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent.parent); + } + } + + function tryDeleteIdentifier(changes: textChanges.ChangeTracker, sourceFile: SourceFile, identifier: Identifier): void { + const parent = identifier.parent; + switch (parent.kind) { + case SyntaxKind.VariableDeclaration: + tryDeleteVariableDeclaration(changes, sourceFile, parent); + break; + + case SyntaxKind.TypeParameter: + const typeParameters = (parent.parent).typeParameters; + if (typeParameters.length === 1) { + const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + const nextToken = getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + Debug.assert(previousToken.kind === SyntaxKind.LessThanToken); + Debug.assert(nextToken.kind === SyntaxKind.GreaterThanToken); + + changes.deleteNodeRange(sourceFile, previousToken, nextToken); } else { - return undefined; + changes.deleteNodeInList(sourceFile, parent); } - } + break; - function prefixIdentifierWithUnderscore(identifier: Identifier): CodeAction { - const startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); - return { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), - changes: [{ - fileName: sourceFile.path, - textChanges: [{ - span: { start: startPosition, length: 0 }, - newText: "_" - }] - }] - }; - } - - function deleteIdentifierOrPrefixWithUnderscore(identifier: Identifier, errorCode: number): CodeAction[] | undefined { - const parent = identifier.parent; - switch (parent.kind) { - case ts.SyntaxKind.VariableDeclaration: - return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - - case SyntaxKind.TypeParameter: - const typeParameters = (parent.parent).typeParameters; - if (typeParameters.length === 1) { - const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - const nextToken = getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - Debug.assert(previousToken.kind === SyntaxKind.LessThanToken); - Debug.assert(nextToken.kind === SyntaxKind.GreaterThanToken); - - return [deleteNodeRange(previousToken, nextToken)]; - } - else { - return [deleteNodeInList(parent)]; - } - - case ts.SyntaxKind.Parameter: - const functionDeclaration = parent.parent; - const deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); - return errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ? [deleteAction] - : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; - - // handle case where 'import a = A;' - case SyntaxKind.ImportEqualsDeclaration: - const importEquals = getAncestor(identifier, SyntaxKind.ImportEqualsDeclaration); - return [deleteNode(importEquals)]; - - case SyntaxKind.ImportSpecifier: - const namedImports = parent.parent; - if (namedImports.elements.length === 1) { - return deleteNamedImportBinding(namedImports); - } - else { - // delete import specifier - return [deleteNodeInList(parent)]; - } - - case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *' - const importClause = parent; - if (!importClause.namedBindings) { // |import d from './file'| - const importDecl = getAncestor(importClause, SyntaxKind.ImportDeclaration); - return [deleteNode(importDecl)]; - } - else { - // import |d,| * as ns from './file' - const start = importClause.name.getStart(sourceFile); - const nextToken = getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === SyntaxKind.CommaToken) { - // shift first non-whitespace position after comma to the start position of the node - return [deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; - } - else { - return [deleteNode(importClause.name)]; - } - } - - case SyntaxKind.NamespaceImport: - return deleteNamedImportBinding(parent); - - default: - return deleteDefault(); + case SyntaxKind.Parameter: + const functionDeclaration = parent.parent; + if (functionDeclaration.parameters.length === 1) { + changes.deleteNode(sourceFile, parent); } - } - - function deleteNamedImportBinding(namedBindings: NamedImportBindings): CodeAction[] | undefined { - if ((namedBindings.parent).name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - const previousToken = getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === SyntaxKind.CommaToken) { - return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; - } - return undefined; + else { + changes.deleteNodeInList(sourceFile, parent); + } + break; + + // handle case where 'import a = A;' + case SyntaxKind.ImportEqualsDeclaration: + const importEquals = getAncestor(identifier, SyntaxKind.ImportEqualsDeclaration); + changes.deleteNode(sourceFile, importEquals); + break; + + case SyntaxKind.ImportSpecifier: + const namedImports = parent.parent; + if (namedImports.elements.length === 1) { + tryDeleteNamedImportBinding(changes, sourceFile, namedImports); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - const importDecl = getAncestor(namedBindings, SyntaxKind.ImportDeclaration); - return [deleteNode(importDecl)]; + // delete import specifier + changes.deleteNodeInList(sourceFile, parent); } - } - - // token.parent is a variableDeclaration - function deleteVariableDeclarationOrPrefixWithUnderscore(identifier: Identifier, varDecl: ts.VariableDeclaration): CodeAction[] | undefined { - switch (varDecl.parent.parent.kind) { - case SyntaxKind.ForStatement: - const forStatement = varDecl.parent.parent; - const forInitializer = forStatement.initializer; - return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; + break; - case SyntaxKind.ForOfStatement: - const forOfStatement = varDecl.parent.parent; - Debug.assert(forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList); - const forOfInitializer = forOfStatement.initializer; - return [ - replaceNode(forOfInitializer.declarations[0], createObjectLiteral()), - prefixIdentifierWithUnderscore(identifier) - ]; - - case SyntaxKind.ForInStatement: - // There is no valid fix in the case of: - // for .. in - return [prefixIdentifierWithUnderscore(identifier)]; - - default: - const variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return [deleteNode(variableStatement)]; - } - else { - return [deleteNodeInList(varDecl)]; - } + case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *' + const importClause = parent; + if (!importClause.namedBindings) { // |import d from './file'| + changes.deleteNode(sourceFile, getAncestor(importClause, SyntaxKind.ImportDeclaration)!); } - } - - function deleteNode(n: Node) { - return makeChange(textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); - } - - function deleteRange(range: TextRange) { - return makeChange(textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); - } + else { + // import |d,| * as ns from './file' + const start = importClause.name.getStart(sourceFile); + const nextToken = getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === SyntaxKind.CommaToken) { + // shift first non-whitespace position after comma to the start position of the node + const end = skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end }); + } + else { + changes.deleteNode(sourceFile, importClause.name); + } + } + break; - function deleteNodeInList(n: Node) { - return makeChange(textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); - } + case SyntaxKind.NamespaceImport: + tryDeleteNamedImportBinding(changes, sourceFile, parent); + break; - function deleteNodeRange(start: Node, end: Node) { - return makeChange(textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); + default: + tryDeleteDefault(changes, sourceFile, identifier); + break; + } + } + + function tryDeleteNamedImportBinding(changes: textChanges.ChangeTracker, sourceFile: SourceFile, namedBindings: NamedImportBindings): void { + if ((namedBindings.parent).name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + const previousToken = getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === SyntaxKind.CommaToken) { + changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); } - - function replaceNode(n: Node, newNode: Node) { - return makeChange(textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + const importDecl = getAncestor(namedBindings, SyntaxKind.ImportDeclaration); + changes.deleteNode(sourceFile, importDecl); + } + } + + // token.parent is a variableDeclaration + function tryDeleteVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, varDecl: VariableDeclaration): void { + switch (varDecl.parent.parent.kind) { + case SyntaxKind.ForStatement: { + const forStatement = varDecl.parent.parent; + const forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + changes.deleteNode(sourceFile, forInitializer); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + break; } - function makeChange(changeTracker: textChanges.ChangeTracker): CodeAction { - return { - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }; - } + case SyntaxKind.ForOfStatement: + const forOfStatement = varDecl.parent.parent; + Debug.assert(forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList); + const forOfInitializer = forOfStatement.initializer; + changes.replaceNode(sourceFile, forOfInitializer.declarations[0], createObjectLiteral()); + break; + + case SyntaxKind.ForInStatement: + case SyntaxKind.TryStatement: + break; + + default: + const variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + changes.deleteNode(sourceFile, variableStatement); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } } - }); + } } \ No newline at end of file diff --git a/src/services/codefixes/fixes.ts b/src/services/codefixes/fixes.ts index 5b1ee8ec8572c..bdbd8311a762d 100644 --- a/src/services/codefixes/fixes.ts +++ b/src/services/codefixes/fixes.ts @@ -15,3 +15,5 @@ /// /// /// +/// + diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 206a3864ac052..47e23e717d9b5 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -1,61 +1,24 @@ /* @internal */ namespace ts.codefix { - - export function newNodesToChanges(newNodes: Node[], insertAfter: Node, context: CodeFixContext) { - const sourceFile = context.sourceFile; - - const changeTracker = textChanges.ChangeTracker.fromContext(context); - - for (const newNode of newNodes) { - changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); - } - - const changes = changeTracker.getChanges(); - if (!some(changes)) { - return changes; - } - - Debug.assert(changes.length === 1); - const consolidatedChanges: FileTextChanges[] = [{ - fileName: changes[0].fileName, - textChanges: [{ - span: changes[0].textChanges[0].span, - newText: changes[0].textChanges.reduce((prev, cur) => prev + cur.newText, "") - }] - - }]; - return consolidatedChanges; - } - /** * Finds members of the resolved type that are missing in the class pointed to by class decl * and generates source code for the missing members. * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: Symbol[], checker: TypeChecker): Node[] { + export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray, checker: TypeChecker, out: (node: ClassElement) => void): void { const classMembers = classDeclaration.symbol.members; - const missingMembers = possiblyMissingSymbols.filter(symbol => !classMembers.has(symbol.escapedName)); - - let newNodes: Node[] = []; - for (const symbol of missingMembers) { - const newNode = createNewNodeForMemberSymbol(symbol, classDeclaration, checker); - if (newNode) { - if (Array.isArray(newNode)) { - newNodes = newNodes.concat(newNode); - } - else { - newNodes.push(newNode); - } + for (const symbol of possiblyMissingSymbols) { + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); } } - return newNodes; } /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function createNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, checker: TypeChecker): Node[] | Node | undefined { + function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, checker: TypeChecker, out: (node: Node) => void): void { const declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -63,7 +26,7 @@ namespace ts.codefix { const declaration = declarations[0] as Declaration; // Clone name to remove leading trivia. - const name = getSynthesizedClone(getNameOfDeclaration(declaration)) as PropertyName; + const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration)) as PropertyName; const visibilityModifier = createVisibilityModifier(getModifierFlags(declaration)); const modifiers = visibilityModifier ? createNodeArray([visibilityModifier]) : undefined; const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -75,14 +38,14 @@ namespace ts.codefix { case SyntaxKind.PropertySignature: case SyntaxKind.PropertyDeclaration: const typeNode = checker.typeToTypeNode(type, enclosingDeclaration); - const property = createProperty( + out(createProperty( /*decorators*/undefined, modifiers, name, optional ? createToken(SyntaxKind.QuestionToken) : undefined, typeNode, - /*initializer*/ undefined); - return property; + /*initializer*/ undefined)); + break; case SyntaxKind.MethodSignature: case SyntaxKind.MethodDeclaration: // The signature for the implementation appears as an entry in `signatures` iff @@ -94,81 +57,71 @@ namespace ts.codefix { // correspondence of declarations and signatures. const signatures = checker.getSignaturesOfType(type, SignatureKind.Call); if (!some(signatures)) { - return undefined; + break; } if (declarations.length === 1) { Debug.assert(signatures.length === 1); const signature = signatures[0]; - return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody()); + break; } - const signatureDeclarations: MethodDeclaration[] = []; for (const signature of signatures) { - const methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, getSynthesizedDeepClones(modifiers), getSynthesizedDeepClone(name)); } if (declarations.length > signatures.length) { const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1] as SignatureDeclaration); - const methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + outputMethod(signature, modifiers, name, createStubbedMethodBody()); } else { Debug.assert(declarations.length === signatures.length); - const methodImplementingSignatures = createMethodImplementingSignatures(signatures, name, optional, modifiers); - signatureDeclarations.push(methodImplementingSignatures); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); } - return signatureDeclarations; - default: - return undefined; + break; } - function signatureToMethodDeclaration(signature: Signature, enclosingDeclaration: Node, body?: Block) { - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.SuppressAnyReturnType); - if (signatureDeclaration) { - signatureDeclaration.decorators = undefined; - signatureDeclaration.modifiers = modifiers; - signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? createToken(SyntaxKind.QuestionToken) : undefined; - signatureDeclaration.body = body; - } - return signatureDeclaration; + function outputMethod(signature: Signature, modifiers: NodeArray, name: PropertyName, body?: Block): void { + const method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) out(method); } } - export function createMethodFromCallExpression(callExpression: CallExpression, methodName: string, includeTypeScriptSyntax: boolean, makeStatic: boolean): MethodDeclaration { - const parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); - - let typeParameters: TypeParameterDeclaration[]; - if (includeTypeScriptSyntax) { - const typeArgCount = length(callExpression.typeArguments); - for (let i = 0; i < typeArgCount; i++) { - const name = typeArgCount < 8 ? String.fromCharCode(CharacterCodes.T + i) : `T${i}`; - const typeParameter = createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); - (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); - } + function signatureToMethodDeclaration(checker: TypeChecker, signature: Signature, enclosingDeclaration: ClassLikeDeclaration, modifiers: NodeArray, name: PropertyName, optional: boolean, body: Block | undefined) { + const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.SuppressAnyReturnType); + if (!signatureDeclaration) { + return undefined; } - const newMethod = createMethod( + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? createToken(SyntaxKind.QuestionToken) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + + function getSynthesizedDeepClones(nodes: NodeArray | undefined): NodeArray | undefined { + return nodes && createNodeArray(nodes.map(getSynthesizedDeepClone)); + } + + export function createMethodFromCallExpression({ typeArguments, arguments: args }: CallExpression, methodName: string, inJs: boolean, makeStatic: boolean): MethodDeclaration { + return createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, /*asteriskToken*/ undefined, methodName, /*questionToken*/ undefined, - typeParameters, - parameters, - /*type*/ includeTypeScriptSyntax ? createKeywordTypeNode(SyntaxKind.AnyKeyword) : undefined, - createStubbedMethodBody() - ); - return newMethod; + /*typeParameters*/ inJs ? undefined : map(typeArguments, (_, i) => + createTypeParameterDeclaration(CharacterCodes.T + typeArguments.length - 1 <= CharacterCodes.Z ? String.fromCharCode(CharacterCodes.T + i) : `T${i}`)), + /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : createKeywordTypeNode(SyntaxKind.AnyKeyword), + createStubbedMethodBody()); } - function createDummyParameters(argCount: number, names: string[] | undefined, minArgumentCount: number | undefined, addAnyType: boolean) { + function createDummyParameters(argCount: number, names: string[] | undefined, minArgumentCount: number | undefined, inJs: boolean): ParameterDeclaration[] { const parameters: ParameterDeclaration[] = []; for (let i = 0; i < argCount; i++) { const newParameter = createParameter( @@ -177,11 +130,10 @@ namespace ts.codefix { /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || `arg${i}`, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? createToken(SyntaxKind.QuestionToken) : undefined, - /*type*/ addAnyType ? createKeywordTypeNode(SyntaxKind.AnyKeyword) : undefined, + /*type*/ inJs ? undefined : createKeywordTypeNode(SyntaxKind.AnyKeyword), /*initializer*/ undefined); parameters.push(newParameter); } - return parameters; } @@ -205,7 +157,7 @@ namespace ts.codefix { const maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.name); - const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); + const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { const anyArrayType = createArrayTypeNode(createKeywordTypeNode(SyntaxKind.AnyKeyword)); @@ -229,7 +181,7 @@ namespace ts.codefix { /*returnType*/ undefined); } - export function createStubbedMethod( + function createStubbedMethod( modifiers: ReadonlyArray, name: PropertyName, optional: boolean, @@ -258,7 +210,7 @@ namespace ts.codefix { /*multiline*/ true); } - function createVisibilityModifier(flags: ModifierFlags) { + function createVisibilityModifier(flags: ModifierFlags): Modifier | undefined { if (flags & ModifierFlags.Public) { return createToken(SyntaxKind.PublicKeyword); } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index af670d386de2e..8f69cd95c11b8 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -9,14 +9,17 @@ namespace ts.codefix { Diagnostics.Cannot_find_namespace_0.code, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], - getCodeActions: getImportCodeActions + getCodeActions: getImportCodeActions, + // TODO: GH#20315 + fixIds: [], + getAllCodeActions: notImplemented, }); type ImportCodeActionKind = "CodeChange" | "InsertingIntoExistingImport" | "NewImport"; // Map from module Id to an array of import declarations in that module. type ImportDeclarationMap = AnyImportSyntax[][]; - interface ImportCodeAction extends CodeAction { + interface ImportCodeAction extends CodeFixAction { kind: ImportCodeActionKind; moduleSpecifier?: string; } @@ -27,11 +30,12 @@ namespace ts.codefix { } interface SymbolAndTokenContext extends SymbolContext { - symbolToken: Node | undefined; + symbolToken: Identifier | undefined; } interface ImportCodeFixContext extends SymbolAndTokenContext { host: LanguageServiceHost; + program: Program; checker: TypeChecker; compilerOptions: CompilerOptions; getCanonicalFileName: GetCanonicalFileName; @@ -154,6 +158,8 @@ namespace ts.codefix { return { description: formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), changes, + // TODO: GH#20315 + fixId: undefined, kind, moduleSpecifier }; @@ -161,15 +167,18 @@ namespace ts.codefix { function convertToImportCodeFixContext(context: CodeFixContext): ImportCodeFixContext { const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - const checker = context.program.getTypeChecker(); - const symbolToken = getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + const { program } = context; + const checker = program.getTypeChecker(); + // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. + const symbolToken = cast(getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), isIdentifier); return { host: context.host, newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, + program, checker, - compilerOptions: context.program.getCompilerOptions(), + compilerOptions: program.getCompilerOptions(), cachedImportDeclarations: [], getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolToken.getText(), @@ -205,14 +214,17 @@ namespace ts.codefix { for (const declaration of declarations) { const namespace = getNamespaceImportName(declaration); if (namespace) { - actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + const moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(escapeLeadingUnderscores(context.symbolName))) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } } } return [...actions, ...getCodeActionsForAddImport(moduleSymbols, context, declarations)]; } - function getNamespaceImportName(declaration: AnyImportSyntax): Identifier { + function getNamespaceImportName(declaration: AnyImportSyntax): Identifier | undefined { if (declaration.kind === SyntaxKind.ImportDeclaration) { const namedBindings = declaration.importClause && isImportClause(declaration.importClause) && declaration.importClause.namedBindings; return namedBindings && namedBindings.kind === SyntaxKind.NamespaceImport ? namedBindings.name : undefined; @@ -249,7 +261,7 @@ namespace ts.codefix { } function getCodeActionForNewImport(context: SymbolContext & { kind: ImportKind }, moduleSpecifier: string): ImportCodeAction { - const { kind, sourceFile, newLineCharacter, symbolName } = context; + const { kind, sourceFile, symbolName } = context; const lastImportDeclaration = findLast(sourceFile.statements, isAnyImportSyntax); const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier); @@ -268,10 +280,10 @@ namespace ts.codefix { const changes = ChangeTracker.with(context, changeTracker => { if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } else { - changeTracker.insertNodeAt(sourceFile, getSourceFileImportLocation(sourceFile), importDecl, { suffix: `${newLineCharacter}${newLineCharacter}` }); + changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); } }); @@ -294,6 +306,10 @@ namespace ts.codefix { return literal; } + function usesJsExtensionOnImports(sourceFile: SourceFile): boolean { + return firstDefined(sourceFile.imports, ({ text }) => pathIsRelative(text) ? fileExtensionIs(text, Extension.Js) : undefined) || false; + } + function createImportClauseOfKind(kind: ImportKind.Default | ImportKind.Named | ImportKind.Namespace, symbolName: string) { const id = createIdentifier(symbolName); switch (kind) { @@ -309,6 +325,7 @@ namespace ts.codefix { } export function getModuleSpecifiersForNewImport( + program: Program, sourceFile: SourceFile, moduleSymbols: ReadonlyArray, options: CompilerOptions, @@ -316,68 +333,84 @@ namespace ts.codefix { host: LanguageServiceHost, ): string[] { const { baseUrl, paths, rootDirs } = options; - const choicesForEachExportingModule = mapIterator(arrayIterator(moduleSymbols), moduleSymbol => { - const moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - const sourceDirectory = getDirectoryPath(sourceFile.fileName); - const global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } + const addJsExtension = usesJsExtensionOnImports(sourceFile); + const choicesForEachExportingModule = flatMap(moduleSymbols, moduleSymbol => + getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(moduleFileName => { + const sourceDirectory = getDirectoryPath(sourceFile.fileName); + const global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } - const relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); - if (!baseUrl) { - return [relativePath]; - } + const relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); + if (!baseUrl) { + return [relativePath]; + } - const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } + const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } - const importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); - if (paths) { - const fromPaths = tryGetModuleNameFromPaths(removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; + const importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + if (paths) { + const fromPaths = tryGetModuleNameFromPaths(removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } } - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - const pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - const relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + const pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + const relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + })); // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) - return best(choicesForEachExportingModule, (a, b) => a[0].length < b[0].length); + return best(arrayIterator(choicesForEachExportingModule), (a, b) => a[0].length < b[0].length); + } + + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program: Program, { fileName }: SourceFile): ReadonlyArray { + const symlinks = mapDefined(program.getSourceFiles(), sf => + sf.resolvedModules && firstDefinedIterator(sf.resolvedModules.values(), res => + res && res.resolvedFileName === fileName ? res.originalPath : undefined)); + return symlinks.length === 0 ? [fileName] : symlinks; } function getRelativePathNParents(relativePath: string): number { @@ -395,9 +428,10 @@ namespace ts.codefix { } } - function tryGetModuleNameFromPaths(relativeNameWithIndex: string, relativeName: string, paths: MapLike>): string | undefined { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex: string, relativeToBaseUrl: string, paths: MapLike>): string | undefined { for (const key in paths) { - for (const pattern of paths[key]) { + for (const patternText of paths[key]) { + const pattern = removeFileExtension(normalizePath(patternText)); const indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -405,14 +439,14 @@ namespace ts.codefix { else if (indexOfStar !== -1) { const prefix = pattern.substr(0, indexOfStar); const suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - startsWith(relativeName, prefix) && - endsWith(relativeName, suffix)) { - const matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + startsWith(relativeToBaseUrl, prefix) && + endsWith(relativeToBaseUrl, suffix)) { + const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -435,12 +469,13 @@ namespace ts.codefix { host: GetEffectiveTypeRootsHost, getCanonicalFileName: (file: string) => string, moduleFileName: string, + addJsExtension: boolean, ): string | undefined { const roots = getEffectiveTypeRoots(options, host); return roots && firstDefined(roots, unNormalizedTypeRoot => { const typeRoot = toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); if (startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options); + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); } }); } @@ -571,17 +606,28 @@ namespace ts.codefix { } function getPathRelativeToRootDirs(path: string, rootDirs: ReadonlyArray, getCanonicalFileName: GetCanonicalFileName): string | undefined { - return firstDefined(rootDirs, rootDir => getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName)); + return firstDefined(rootDirs, rootDir => { + const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } - function removeExtensionAndIndexPostFix(fileName: string, options: CompilerOptions): string { + function removeExtensionAndIndexPostFix(fileName: string, options: CompilerOptions, addJsExtension: boolean): string { const noExtension = removeFileExtension(fileName); - return getEmitModuleResolutionKind(options) === ModuleResolutionKind.NodeJs ? removeSuffix(noExtension, "/index") : noExtension; + return addJsExtension + ? noExtension + ".js" + : getEmitModuleResolutionKind(options) === ModuleResolutionKind.NodeJs + ? removeSuffix(noExtension, "/index") + : noExtension; } function getRelativePathIfInDirectory(path: string, directoryPath: string, getCanonicalFileName: GetCanonicalFileName): string | undefined { const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return isRootedDiskPath(relativePath) || startsWith(relativePath, "..") ? undefined : relativePath; + return isRootedDiskPath(relativePath) ? undefined : relativePath; + } + + function isPathRelativeToParent(path: string): boolean { + return startsWith(path, ".."); } function getRelativePath(path: string, directoryPath: string, getCanonicalFileName: GetCanonicalFileName) { @@ -613,7 +659,7 @@ namespace ts.codefix { } const existingDeclaration = firstDefined(declarations, moduleSpecifierFromAnyImport); - const moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + const moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.program, ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); return moduleSpecifiers.map(spec => getCodeActionForNewImport(ctx, spec)); } @@ -663,7 +709,7 @@ namespace ts.codefix { } } - function getCodeActionForUseExistingNamespaceImport(namespacePrefix: string, context: SymbolContext, symbolToken: Node): ImportCodeAction { + function getCodeActionForUseExistingNamespaceImport(namespacePrefix: string, context: SymbolContext, symbolToken: Identifier): ImportCodeAction { const { symbolName, sourceFile } = context; /** @@ -676,13 +722,10 @@ namespace ts.codefix { * namespace instead of altering the import declaration. For example, "foo" would * become "ns.foo" */ - return createCodeAction( - Diagnostics.Change_0_to_1, - [symbolName, `${namespacePrefix}.${symbolName}`], - ChangeTracker.with(context, tracker => - tracker.replaceNode(sourceFile, symbolToken, createPropertyAccess(createIdentifier(namespacePrefix), symbolName))), - "CodeChange", - /*moduleSpecifier*/ undefined); + // Prefix the node instead of it replacing it, because this may be used for import completions and we don't want the text changes to overlap with the identifier being completed. + const changes = ChangeTracker.with(context, tracker => + tracker.changeIdentifierToPropertyAccess(sourceFile, namespacePrefix, symbolToken)); + return createCodeAction(Diagnostics.Change_0_to_1, [symbolName, `${namespacePrefix}.${symbolName}`], changes, "CodeChange", /*moduleSpecifier*/ undefined); } function getImportCodeActions(context: CodeFixContext): ImportCodeAction[] { @@ -746,11 +789,14 @@ namespace ts.codefix { forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, moduleSymbol => { cancellationToken.throwIfCancellationRequested(); // check the default export - const defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol); if (defaultExport) { const localSymbol = getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if (( + localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName + ) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used const symbolId = getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, { ...context, kind: ImportKind.Default })); @@ -763,6 +809,22 @@ namespace ts.codefix { const symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, { ...context, kind: ImportKind.Named })); } + + function getEscapedNameForExportDefault(symbol: Symbol): __String | undefined { + return firstDefined(symbol.declarations, declaration => { + if (isExportAssignment(declaration)) { + if (isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (isExportSpecifier(declaration)) { + Debug.assert(declaration.name.escapedText === InternalSymbolName.Default); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 3f03180360d2e..95d85bc5aa028 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -1,270 +1,268 @@ /* @internal */ namespace ts.codefix { - registerCodeFix({ - errorCodes: [ - // Variable declarations - Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + const fixId = "inferFromUsage"; + const errorCodes = [ + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - Diagnostics.Member_0_implicitly_has_an_1_type.code, - ], - getCodeActions: getActionsForAddExplicitTypeAnnotation + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type.code, + ]; + registerCodeFix({ + errorCodes, + getCodeActions({ sourceFile, program, span: { start }, errorCode, cancellationToken }) { + if (isSourceFileJavaScript(sourceFile)) { + return undefined; // TODO: GH#20113 + } + + const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + const fix = getFix(sourceFile, token, errorCode, program, cancellationToken); + if (!fix) return undefined; + + const { declaration, textChanges } = fix; + const name = getNameOfDeclaration(declaration); + const description = formatStringFromArgs(getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); + return [{ description, changes: [{ fileName: sourceFile.fileName, textChanges }], fixId }]; + }, + fixIds: [fixId], + getAllCodeActions(context) { + const { sourceFile, program, cancellationToken } = context; + const seenFunctions = createMap(); + return codeFixAllWithTextChanges(context, errorCodes, (changes, err) => { + const fix = getFix(sourceFile, getTokenAtPosition(err.file!, err.start!, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + if (fix) changes.push(...fix.textChanges); + }); + }, }); - function getActionsForAddExplicitTypeAnnotation({ sourceFile, program, span: { start }, errorCode, cancellationToken }: CodeFixContext): CodeAction[] | undefined { - const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - let writer: StringSymbolWriter; - - if (isInJavaScriptFile(token)) { - return undefined; - } - - switch (token.kind) { - case SyntaxKind.Identifier: - case SyntaxKind.DotDotDotToken: - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.ReadonlyKeyword: - // Allowed - break; + function getDiagnostic(errorCode: number, token: Node): DiagnosticMessage { + switch (errorCode) { + case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + return isSetAccessor(getContainingFunction(token)) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return Diagnostics.Infer_parameter_types_from_usage; default: - return undefined; + return Diagnostics.Infer_type_of_0_from_usage; } + } - const containingFunction = getContainingFunction(token); - const checker = program.getTypeChecker(); + interface Fix { + readonly declaration: Declaration; + readonly textChanges: TextChange[]; + } + + function getFix(sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, seenFunctions?: Map): Fix | undefined { + if (!isAllowedTokenKind(token.kind)) { + return undefined; + } switch (errorCode) { // Variable and Property declarations 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: - return getCodeActionForVariableDeclaration(token.parent); - case Diagnostics.Variable_0_implicitly_has_an_1_type.code: - return getCodeActionForVariableUsage(token); + return getCodeActionForVariableDeclaration(token.parent, sourceFile, program, cancellationToken); + + case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + const symbol = program.getTypeChecker().getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, sourceFile, program, cancellationToken); + } + } + + const containingFunction = getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction); + return getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken); } - // falls through + // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return getCodeActionForParameters(token.parent); + return !seenFunctions || addToSeen(seenFunctions, getNodeId(containingFunction)) + ? getCodeActionForParameters(token.parent, containingFunction, sourceFile, program, cancellationToken) + : undefined; // Get Accessor declarations 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: - return isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + return isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; - } - - return undefined; - - function getCodeActionForVariableDeclaration(declaration: VariableDeclaration | PropertyDeclaration | PropertySignature) { - if (!isIdentifier(declaration.name)) { - return undefined; - } - - const type = inferTypeForVariableFromUsage(declaration.name); - const typeString = type && typeToString(type, declaration); + return isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; - if (!typeString) { - return undefined; - } - - return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), `: ${typeString}`); + default: + throw Debug.fail(String(errorCode)); } + } - function getCodeActionForVariableUsage(token: Identifier) { - const symbol = checker.getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); + function isAllowedTokenKind(kind: SyntaxKind): boolean { + switch (kind) { + case SyntaxKind.Identifier: + case SyntaxKind.DotDotDotToken: + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.ReadonlyKeyword: + return true; + default: + return false; } + } - function isApplicableFunctionForInference(declaration: FunctionLike): declaration is MethodDeclaration | FunctionDeclaration | ConstructorDeclaration { - switch (declaration.kind) { - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.Constructor: - return true; - case SyntaxKind.FunctionExpression: - return !!(declaration as FunctionExpression).name; - } - return false; - } + function getCodeActionForVariableDeclaration(declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): Fix | undefined { + if (!isIdentifier(declaration.name)) return undefined; + const type = inferTypeForVariableFromUsage(declaration.name, sourceFile, program, cancellationToken); + return makeFix(declaration, declaration.name.getEnd(), type, program); + } - function getCodeActionForParameters(parameterDeclaration: ParameterDeclaration): CodeAction[] { - if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; - } + function isApplicableFunctionForInference(declaration: FunctionLike): declaration is MethodDeclaration | FunctionDeclaration | ConstructorDeclaration { + switch (declaration.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.Constructor: + return true; + case SyntaxKind.FunctionExpression: + return !!(declaration as FunctionExpression).name; + } + return false; + } - const types = inferTypeForParametersFromUsage(containingFunction) || - map(containingFunction.parameters, p => isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name)); + function getCodeActionForParameters(parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): Fix | undefined { + if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; + } - if (!types) { - return undefined; - } + const types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(p => isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, sourceFile, program, cancellationToken) : undefined); + if (!types) return undefined; - const textChanges: TextChange[] = zipWith(containingFunction.parameters, types, (parameter, type) => { - if (type && !parameter.type && !parameter.initializer) { - const typeString = typeToString(type, containingFunction); - return typeString ? { - span: { start: parameter.end, length: 0 }, - newText: `: ${typeString}` - } : undefined; - } - }).filter(c => !!c); - - return textChanges.length ? [{ - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), - changes: [{ - fileName: sourceFile.fileName, - textChanges - }] - }] : undefined; + // We didn't actually find a set of type inference positions matching each parameter position + if (containingFunction.parameters.length !== types.length) { + return undefined; } - function getCodeActionForSetAccessor(setAccessorDeclaration: SetAccessorDeclaration) { - const setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !isIdentifier(setAccessorDeclaration.name) || !isIdentifier(setAccessorParameter.name)) { - return undefined; - } - - const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || - inferTypeForVariableFromUsage(setAccessorParameter.name); - const typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } + const textChanges = arrayFrom(mapDefinedIterator(zipToIterator(containingFunction.parameters, types), ([parameter, type]) => + type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined)); + return textChanges.length ? { declaration: parameterDeclaration, textChanges } : undefined; + } - return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), `: ${typeString}`); + function getCodeActionForSetAccessor(setAccessorDeclaration: SetAccessorDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): Fix | undefined { + const setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !isIdentifier(setAccessorDeclaration.name) || !isIdentifier(setAccessorParameter.name)) { + return undefined; } - function getCodeActionForGetAccessor(getAccessorDeclaration: GetAccessorDeclaration) { - if (!isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - - const type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); - const typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } + const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, sourceFile, program, cancellationToken) || + inferTypeForVariableFromUsage(setAccessorParameter.name, sourceFile, program, cancellationToken); + return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); + } - const closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, SyntaxKind.CloseParenToken); - return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), `: ${typeString}`); + function getCodeActionForGetAccessor(getAccessorDeclaration: GetAccessorDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): Fix | undefined { + if (!isIdentifier(getAccessorDeclaration.name)) { + return undefined; } - function createCodeActions(name: string, start: number, typeString: string) { - return [{ - description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Infer_type_of_0_from_usage), [name]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start, length: 0 }, - newText: typeString - }] - }] - }]; - } + const type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, sourceFile, program, cancellationToken); + const closeParenToken = findChildOfKind(getAccessorDeclaration, SyntaxKind.CloseParenToken, sourceFile); + return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + } - function getReferences(token: PropertyName | Token) { - const references = FindAllReferences.findReferencedSymbols( - program, - cancellationToken, - program.getSourceFiles(), - token.getSourceFile(), - token.getStart()); + function makeFix(declaration: Declaration, start: number, type: Type | undefined, program: Program): Fix | undefined { + return type && { declaration, textChanges: [makeChange(declaration, start, type, program)] }; + } - Debug.assert(!!references, "Found no references!"); - Debug.assert(references.length === 1, "Found more references than expected"); + function makeChange(declaration: Declaration, start: number, type: Type | undefined, program: Program): TextChange | undefined { + const typeString = type && typeToString(type, declaration, program.getTypeChecker()); + return typeString === undefined ? undefined : { span: createTextSpan(start, 0), newText: `: ${typeString}` }; + } - return map(references[0].references, r => getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false)); - } + function getReferences(token: PropertyName | Token, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): Identifier[] { + const references = FindAllReferences.findReferencedSymbols( + program, + cancellationToken, + program.getSourceFiles(), + sourceFile, + token.getStart(sourceFile)); - function inferTypeForVariableFromUsage(token: Identifier) { - return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + if (!references || references.length !== 1) { + return []; } - function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration) { - switch (containingFunction.kind) { - case SyntaxKind.Constructor: - case SyntaxKind.FunctionExpression: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodDeclaration: - const isConstructor = containingFunction.kind === SyntaxKind.Constructor; - const searchToken = isConstructor ? - >getFirstChildOfKind(containingFunction, sourceFile, SyntaxKind.ConstructorKeyword) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); - } - } - } + return references[0].references.map(r => getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false)); + } - function getTypeAccessiblityWriter() { - if (!writer) { - let str = ""; - let typeIsAccessible = true; - - const writeText: (text: string) => void = text => str += text; - writer = { - string: () => typeIsAccessible ? str : undefined, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: () => str += " ", - increaseIndent: noop, - decreaseIndent: noop, - clear: () => { str = ""; typeIsAccessible = true; }, - trackSymbol: (symbol, declaration, meaning) => { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== SymbolAccessibility.Accessible) { - typeIsAccessible = false; - } - }, - reportInaccessibleThisError: () => { typeIsAccessible = false; }, - reportPrivateInBaseOfClassExpression: () => { typeIsAccessible = false; }, - reportInaccessibleUniqueSymbolError: () => { typeIsAccessible = false; } - }; - } - writer.clear(); - return writer; - } + function inferTypeForVariableFromUsage(token: Identifier, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): Type | undefined { + return InferFromReference.inferTypeFromReferences(getReferences(token, sourceFile, program, cancellationToken), program.getTypeChecker(), cancellationToken); + } - function typeToString(type: Type, enclosingDeclaration: Declaration) { - const writer = getTypeAccessiblityWriter(); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + switch (containingFunction.kind) { + case SyntaxKind.Constructor: + case SyntaxKind.FunctionExpression: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + const isConstructor = containingFunction.kind === SyntaxKind.Constructor; + const searchToken = isConstructor ? + findChildOfKind>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, sourceFile, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); + } } + } - function getFirstChildOfKind(node: Node, sourcefile: SourceFile, kind: SyntaxKind) { - for (const child of node.getChildren(sourcefile)) { - if (child.kind === kind) return child; - } - return undefined; - } + function getTypeAccessiblityWriter(checker: TypeChecker): StringSymbolWriter { + let str = ""; + let typeIsAccessible = true; + + const writeText: (text: string) => void = text => str += text; + return { + string: () => typeIsAccessible ? str : undefined, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: () => writeText(" "), + increaseIndent: noop, + decreaseIndent: noop, + clear: () => { str = ""; typeIsAccessible = true; }, + trackSymbol: (symbol, declaration, meaning) => { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== SymbolAccessibility.Accessible) { + typeIsAccessible = false; + } + }, + reportInaccessibleThisError: () => { typeIsAccessible = false; }, + reportPrivateInBaseOfClassExpression: () => { typeIsAccessible = false; }, + reportInaccessibleUniqueSymbolError: () => { typeIsAccessible = false; } + }; + } + + function typeToString(type: Type, enclosingDeclaration: Declaration, checker: TypeChecker): string { + const writer = getTypeAccessiblityWriter(checker); + checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); + return writer.string(); } namespace InferFromReference { @@ -295,6 +293,10 @@ namespace ts.codefix { } export function inferTypeForParametersFromReferences(references: Identifier[], declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + if (references.length === 0) { + return undefined; + } + if (declaration.parameters) { const usageContext: UsageContext = {}; for (const reference of references) { @@ -319,7 +321,7 @@ namespace ts.codefix { } } if (types.length) { - const type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); paramTypes[parameterIndex] = isRestParameter ? checker.createArrayType(type) : type; } } @@ -556,12 +558,12 @@ namespace ts.codefix { return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(map(usageContext.candidateTypes, t => checker.getBaseTypeOfLiteralType(t)), /*subtypeReduction*/ true)); + return checker.getWidenedType(checker.getUnionType(map(usageContext.candidateTypes, t => checker.getBaseTypeOfLiteralType(t)), UnionReduction.Subtype)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) { const paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then" as __String).callContexts, /*isRestParameter*/ false, checker); const types = paramType.getCallSignatures().map(c => c.getReturnType()); - return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + return checker.createPromiseType(types.length ? checker.getUnionType(types, UnionReduction.Subtype) : checker.getAnyType()); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push" as __String))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push" as __String).callContexts, /*isRestParameter*/ false, checker)); @@ -624,7 +626,7 @@ namespace ts.codefix { } if (types.length) { - const type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); return isRestParameter ? checker.createArrayType(type) : type; } return undefined; diff --git a/src/services/completions.ts b/src/services/completions.ts index 2e9a26c6883dd..bdd5e4a86a217 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -39,44 +39,60 @@ namespace ts.Completions { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } + const contextToken = findPrecedingToken(position, sourceFile); + if (contextToken && isBreakOrContinueStatement(contextToken.parent) + && (contextToken.kind === SyntaxKind.BreakKeyword || contextToken.kind === SyntaxKind.ContinueKeyword || contextToken.kind === SyntaxKind.Identifier)) { + return getLabelCompletionAtPosition(contextToken.parent); + } + const completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); if (!completionData) { return undefined; } - const { symbols, isGlobalCompletion, isMemberCompletion, allowStringLiteral, isNewIdentifierLocation, location, request, keywordFilters, symbolToOriginInfoMap } = completionData; + switch (completionData.kind) { + case CompletionDataKind.Data: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case CompletionDataKind.JsDocTagName: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(JsDoc.getJSDocTagNameCompletions()); + case CompletionDataKind.JsDocTag: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(JsDoc.getJSDocTagCompletions()); + case CompletionDataKind.JsDocParameterName: + return jsdocCompletionInfo(JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw Debug.assertNever(completionData); + } + } + + function jsdocCompletionInfo(entries: CompletionEntry[]): CompletionInfo { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; + } + + function completionInfoFromData(sourceFile: SourceFile, typeChecker: TypeChecker, compilerOptions: CompilerOptions, log: Log, completionData: CompletionData, includeInsertTextCompletions: boolean): CompletionInfo { + const { symbols, completionKind, isNewIdentifierLocation, location, propertyAccessToConvert, keywordFilters, symbolToOriginInfoMap, recommendedCompletion } = completionData; - if (sourceFile.languageVariant === LanguageVariant.JSX && - location && location.parent && location.parent.kind === SyntaxKind.JsxClosingElement) { + if (sourceFile.languageVariant === LanguageVariant.JSX && location && location.parent && isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any - const tagName = (location.parent.parent).openingElement.tagName; + // var x =
+ // The completion list at "1" will contain "div" with type any + const tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ - name: (tagName).getFullText(), + name: tagName.getFullText(), kind: ScriptElementKind.classElement, kindModifiers: undefined, sortText: "0", }]}; } - if (request) { - const entries = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? JsDoc.getJSDocTagCompletions() - : JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; - } - const entries: CompletionEntry[] = []; if (isSourceFileJavaScript(sourceFile)) { - const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); + const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { @@ -84,7 +100,7 @@ namespace ts.Completions { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location @@ -92,17 +108,29 @@ namespace ts.Completions { // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + const isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== KeywordCompletionFilters.None || !isMemberCompletion) { addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion, isMemberCompletion, isNewIdentifierLocation, entries }; + return { isGlobalCompletion: completionKind === CompletionKind.Global, isMemberCompletion, isNewIdentifierLocation, entries }; + } + + function isMemberCompletionKind(kind: CompletionKind): boolean { + switch (kind) { + case CompletionKind.ObjectPropertyDeclaration: + case CompletionKind.MemberLike: + case CompletionKind.PropertyAccess: + return true; + default: + return false; + } } function getJavaScriptCompletionEntries( sourceFile: SourceFile, position: number, - uniqueNames: Map<{}>, + uniqueNames: Map, target: ScriptTarget, entries: Push): void { getNameTable(sourceFile).forEach((pos, name) => { @@ -111,16 +139,9 @@ namespace ts.Completions { return; } const realName = unescapeLeadingUnderscores(name); - - if (uniqueNames.has(realName) || isStringANonContextualKeyword(realName)) { - return; - } - - uniqueNames.set(realName, true); - const displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (addToSeen(uniqueNames, realName) && isIdentifierText(realName, target) && !isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: ScriptElementKind.warning, kindModifiers: "", sortText: "1" @@ -132,17 +153,22 @@ namespace ts.Completions { function createCompletionEntry( symbol: Symbol, location: Node, - performCharacterChecks: boolean, + sourceFile: SourceFile, typeChecker: TypeChecker, target: ScriptTarget, - allowStringLiteral: boolean, + kind: CompletionKind, origin: SymbolOriginInfo | undefined, + recommendedCompletion: Symbol | undefined, + propertyAccessToConvert: PropertyAccessExpression | undefined, + includeInsertTextCompletions: boolean, ): CompletionEntry | undefined { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - const displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + const { name, needsConvertPropertyAccess } = info; + Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); + if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } @@ -155,15 +181,31 @@ namespace ts.Completions { // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name, kind: SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: origin === undefined ? undefined : true, + // TODO: GH#20619 Use configured quote style + insertText: needsConvertPropertyAccess ? `["${name}"]` : undefined, + replacementSpan: needsConvertPropertyAccess + ? createTextSpanFromBounds(findChildOfKind(propertyAccessToConvert, SyntaxKind.DotToken, sourceFile)!.getStart(sourceFile), propertyAccessToConvert.name.end) + : undefined, + hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), + isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } + + function isRecommendedCompletionMatch(localSymbol: Symbol, recommendedCompletion: Symbol, checker: TypeChecker): boolean { + return localSymbol === recommendedCompletion || + !!(localSymbol.flags & SymbolFlags.ExportValue) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; + } + + function trueOrUndefined(b: boolean): true | undefined { + return b ? true : undefined; + } + function getSourceFromOrigin(origin: SymbolOriginInfo | undefined): string | undefined { return origin && stripQuotes(origin.moduleSymbol.name); } @@ -172,11 +214,14 @@ namespace ts.Completions { symbols: ReadonlyArray, entries: Push, location: Node, - performCharacterChecks: boolean, + sourceFile: SourceFile, typeChecker: TypeChecker, target: ScriptTarget, log: Log, - allowStringLiteral: boolean, + kind: CompletionKind, + includeInsertTextCompletions?: boolean, + propertyAccessToConvert?: PropertyAccessExpression | undefined, + recommendedCompletion?: Symbol, symbolToOriginInfoMap?: SymbolOriginInfoMap, ): Map { const start = timestamp(); @@ -185,35 +230,40 @@ namespace ts.Completions { // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. const uniques = createMap(); - if (symbols) { - for (const symbol of symbols) { - const origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[getSymbolId(symbol)] : undefined; - const entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin); - if (!entry) { - continue; - } - - const { name } = entry; - if (uniques.has(name)) { - continue; - } + for (const symbol of symbols) { + const origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[getSymbolId(symbol)] : undefined; + const entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions); + if (!entry) { + continue; + } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !some(symbol.declarations, d => d.getSourceFile() === location.getSourceFile()))) { - uniques.set(name, true); - } + const { name } = entry; + if (uniques.has(name)) { + continue; + } - entries.push(entry); + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !some(symbol.declarations, d => d.getSourceFile() === location.getSourceFile()))) { + uniques.set(name, true); } + + entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start)); return uniques; } + function getLabelCompletionAtPosition(node: BreakOrContinueStatement): CompletionInfo | undefined { + const entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; + } + } + function getStringLiteralCompletionEntries(sourceFile: SourceFile, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost, log: Log): CompletionInfo | undefined { const node = findPrecedingToken(position, sourceFile); - if (!node || node.kind !== SyntaxKind.StringLiteral) { + if (!node || !isStringLiteral(node) && !isNoSubstitutionTemplateLiteral(node)) { return undefined; } @@ -232,7 +282,7 @@ namespace ts.Completions { // foo({ // '/*completion position*/' // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); } else if (isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { // Get all names of properties on the expression @@ -241,7 +291,8 @@ namespace ts.Completions { // } // let a: A; // a['/*completion position*/'] - return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); + const type = typeChecker.getTypeAtLocation(node.parent.expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else if (node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration || isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || isImportCall(node.parent) @@ -252,20 +303,18 @@ namespace ts.Completions { // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - const entries = PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + const entries = PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); return pathCompletionsInfo(entries); } - else if (isEqualityExpression(node.parent)) { - // Get completions from the type of the other operand - // i.e. switch (a) { - // case '/*completion position*/' + else if (isIndexedAccessTypeNode(node.parent.parent)) { + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; // } - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); - } - else if (isCaseOrDefaultClause(node.parent)) { - // Get completions from the type of the switch expression - // i.e. x === '/*completion position' - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation((node.parent.parent.parent).expression), typeChecker); + // let x: Foo["/*completion position*/"] + const type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else { const argumentInfo = SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -278,7 +327,7 @@ namespace ts.Completions { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" - return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); + return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); } } @@ -294,11 +343,11 @@ namespace ts.Completions { }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element: ObjectLiteralElement, typeChecker: TypeChecker, target: ScriptTarget, log: Log): CompletionInfo | undefined { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element: ObjectLiteralElement, sourceFile: SourceFile, typeChecker: TypeChecker, target: ScriptTarget, log: Log): CompletionInfo | undefined { const type = typeChecker.getContextualType((element.parent)); const entries: CompletionEntry[] = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, CompletionKind.String); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries }; } @@ -323,11 +372,10 @@ namespace ts.Completions { return undefined; } - function getStringLiteralCompletionEntriesFromElementAccess(node: ElementAccessExpression, typeChecker: TypeChecker, target: ScriptTarget, log: Log): CompletionInfo | undefined { - const type = typeChecker.getTypeAtLocation(node.expression); + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode: StringLiteral | NoSubstitutionTemplateLiteral, sourceFile: SourceFile, type: Type, typeChecker: TypeChecker, target: ScriptTarget, log: Log): CompletionInfo | undefined { const entries: CompletionEntry[] = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, CompletionKind.String); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries }; } @@ -346,6 +394,32 @@ namespace ts.Completions { return undefined; } + function getLabelStatementCompletions(node: Node): CompletionEntry[] { + const entries: CompletionEntry[] = []; + const uniques = createMap(); + let current = node; + + while (current) { + if (isFunctionLike(current)) { + break; + } + if (isLabeledStatement(current)) { + const name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name, + kindModifiers: ScriptElementKindModifier.none, + kind: ScriptElementKind.label, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } + function addStringLiteralCompletionsFromType(type: Type, result: Push, typeChecker: TypeChecker, uniques = createMap()): void { if (type && type.flags & TypeFlags.TypeParameter) { type = typeChecker.getBaseConstraintOfType(type); @@ -372,6 +446,13 @@ namespace ts.Completions { } } + interface SymbolCompletion { + type: "symbol"; + symbol: Symbol; + location: Node; + symbolToOriginInfoMap: SymbolOriginInfoMap; + previousToken: Node; + } function getSymbolCompletionFromEntryId( typeChecker: TypeChecker, log: (message: string) => void, @@ -380,31 +461,34 @@ namespace ts.Completions { position: number, { name, source }: CompletionEntryIdentifier, allSourceFiles: ReadonlyArray, - ): { type: "symbol", symbol: Symbol, location: Node, symbolToOriginInfoMap: SymbolOriginInfoMap } | { type: "request", request: Request } | { type: "none" } { - const completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + ): SymbolCompletion | { type: "request", request: Request } | { type: "none" } { + const completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - - const { symbols, location, allowStringLiteral, symbolToOriginInfoMap, request } = completionData; - if (request) { - return { type: "request", request }; + if (completionData.kind !== CompletionDataKind.Data) { + return { type: "request", request: completionData }; } + const { symbols, location, completionKind, symbolToOriginInfoMap, previousToken } = completionData; + // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - const symbol = find(symbols, s => { - const origin = symbolToOriginInfoMap[getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol, location, symbolToOriginInfoMap } : { type: "none" }; + return firstDefined(symbols, (symbol): SymbolCompletion => { // TODO: Shouldn't need return type annotation (GH#12632) + const origin = symbolToOriginInfoMap[getSymbolId(symbol)]; + const info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol" as "symbol", symbol, location, symbolToOriginInfoMap, previousToken } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol: Symbol, origin: SymbolOriginInfo | undefined, target: ScriptTarget): string { - return origin && origin.isDefaultExport && symbol.name === "default" ? codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + return origin && origin.isDefaultExport && symbol.escapedName === InternalSymbolName.Default + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? firstDefined(symbol.declarations, d => isExportAssignment(d) && isIdentifier(d.expression) ? d.expression.text : undefined) + || codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; } export interface CompletionEntryIdentifier { @@ -413,7 +497,7 @@ namespace ts.Completions { } export function getCompletionEntryDetails( - typeChecker: TypeChecker, + program: Program, log: (message: string) => void, compilerOptions: CompilerOptions, sourceFile: SourceFile, @@ -424,6 +508,7 @@ namespace ts.Completions { formatContext: formatting.FormatContext, getCanonicalFileName: GetCanonicalFileName, ): CompletionEntryDetails { + const typeChecker = program.getTypeChecker(); const { name } = entryId; // Compute all the completion symbols again. const symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); @@ -431,19 +516,19 @@ namespace ts.Completions { case "request": { const { request } = symbolCompletion; switch (request.kind) { - case "JsDocTagName": + case CompletionDataKind.JsDocTagName: return JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case CompletionDataKind.JsDocTag: return JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case CompletionDataKind.JsDocParameterName: return JsDoc.getJSDocParameterNameCompletionDetails(name); default: return Debug.assertNever(request); } } case "symbol": { - const { symbol, location, symbolToOriginInfoMap } = symbolCompletion; - const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles); + const { symbol, location, symbolToOriginInfoMap, previousToken } = symbolCompletion; + const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles); const kindModifiers = SymbolDisplay.getSymbolModifiers(symbol); const { displayParts, documentation, symbolKind, tags } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, SemanticMeaning.All); return { name, kindModifiers, kind: symbolKind, displayParts, documentation, tags, codeActions, source: sourceDisplay }; @@ -467,30 +552,51 @@ namespace ts.Completions { } } + interface CodeActionsAndSourceDisplay { + readonly codeActions: CodeAction[] | undefined; + readonly sourceDisplay: SymbolDisplayPart[] | undefined; + } function getCompletionEntryCodeActionsAndSourceDisplay( symbolToOriginInfoMap: SymbolOriginInfoMap, symbol: Symbol, + program: Program, checker: TypeChecker, host: LanguageServiceHost, compilerOptions: CompilerOptions, sourceFile: SourceFile, + previousToken: Node, formatContext: formatting.FormatContext, getCanonicalFileName: GetCanonicalFileName, allSourceFiles: ReadonlyArray, - ): { codeActions: CodeAction[] | undefined, sourceDisplay: SymbolDisplayPart[] | undefined } { + ): CodeActionsAndSourceDisplay { const symbolOriginInfo = symbolToOriginInfoMap[getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport( + symbolOriginInfo: SymbolOriginInfo, + symbol: Symbol, + program: Program, + checker: TypeChecker, + host: LanguageServiceHost, + compilerOptions: CompilerOptions, + sourceFile: SourceFile, + previousToken: Node, + formatContext: formatting.FormatContext, + getCanonicalFileName: GetCanonicalFileName, + allSourceFiles: ReadonlyArray + ): CodeActionsAndSourceDisplay { const { moduleSymbol, isDefaultExport } = symbolOriginInfo; const exportedSymbol = skipAlias(symbol.exportSymbol || symbol, checker); const moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); Debug.assert(contains(moduleSymbols, moduleSymbol)); - const sourceDisplay = [textPart(first(codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + const sourceDisplay = [textPart(first(codefix.getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; const codeActions = codefix.getCodeActionForImport(moduleSymbols, { host, + program, checker, newLineCharacter: host.getNewLine(), compilerOptions, @@ -498,9 +604,9 @@ namespace ts.Completions { formatContext, symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), getCanonicalFileName, - symbolToken: undefined, + symbolToken: tryCast(previousToken, isIdentifier), kind: isDefaultExport ? codefix.ImportKind.Default : codefix.ImportKind.Named, - }); + }).slice(0, 1); // Only take the first code action return { sourceDisplay, codeActions }; } @@ -529,19 +635,91 @@ namespace ts.Completions { return completion.type === "symbol" ? completion.symbol : undefined; } + const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName } interface CompletionData { - symbols: ReadonlyArray; - isGlobalCompletion: boolean; - isMemberCompletion: boolean; - allowStringLiteral: boolean; - isNewIdentifierLocation: boolean; - location: Node | undefined; - isRightOfDot: boolean; - request?: Request; - keywordFilters: KeywordCompletionFilters; - symbolToOriginInfoMap: SymbolOriginInfoMap; + readonly kind: CompletionDataKind.Data; + readonly symbols: ReadonlyArray; + readonly completionKind: CompletionKind; + /** Note that the presence of this alone doesn't mean that we need a conversion. Only do that if the completion is not an ordinary identifier. */ + readonly propertyAccessToConvert: PropertyAccessExpression | undefined; + readonly isNewIdentifierLocation: boolean; + readonly location: Node | undefined; + readonly keywordFilters: KeywordCompletionFilters; + readonly symbolToOriginInfoMap: SymbolOriginInfoMap; + readonly recommendedCompletion: Symbol | undefined; + readonly previousToken: Node | undefined; + } + type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }; + + const enum CompletionKind { + ObjectPropertyDeclaration, + Global, + PropertyAccess, + MemberLike, + String, + None, + } + + function getRecommendedCompletion(currentToken: Node, checker: TypeChecker): Symbol | undefined { + const ty = getContextualType(currentToken, checker); + const symbol = ty && ty.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & SymbolFlags.Enum || symbol.flags & SymbolFlags.Class && !isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, currentToken, checker) + : undefined; + } + + function getContextualType(currentToken: Node, checker: ts.TypeChecker): Type | undefined { + const { parent } = currentToken; + switch (currentToken.kind) { + case ts.SyntaxKind.Identifier: + return getContextualTypeFromParent(currentToken as ts.Identifier, checker); + case ts.SyntaxKind.EqualsToken: + return ts.isVariableDeclaration(parent) ? checker.getContextualType(parent.initializer) : + ts.isBinaryExpression(parent) ? checker.getTypeAtLocation(parent.left) : undefined; + case ts.SyntaxKind.NewKeyword: + return checker.getContextualType(parent as ts.Expression); + case ts.SyntaxKind.CaseKeyword: + return getSwitchedType(cast(currentToken.parent, isCaseClause), checker); + default: + return isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(currentToken as ts.Expression); + } + } + + function getContextualTypeFromParent(node: ts.Expression, checker: ts.TypeChecker): Type | undefined { + const { parent } = node; + switch (parent.kind) { + case ts.SyntaxKind.NewExpression: + return checker.getContextualType(parent as ts.NewExpression); + case ts.SyntaxKind.BinaryExpression: { + const { left, operatorToken, right } = parent as ts.BinaryExpression; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case ts.SyntaxKind.CaseClause: + return (parent as ts.CaseClause).expression === node ? getSwitchedType(parent as ts.CaseClause, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + + function getSwitchedType(caseClause: ts.CaseClause, checker: ts.TypeChecker): ts.Type { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } + + function getFirstSymbolInChain(symbol: Symbol, enclosingDeclaration: Node, checker: TypeChecker): Symbol | undefined { + const chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ SymbolFlags.All, /*useOnlyExternalAliasing*/ false); + if (chain) return first(chain); + return isModuleSymbol(symbol.parent) ? symbol : symbol.parent && getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker); + } + + function isModuleSymbol(symbol: Symbol): boolean { + return symbol.declarations.some(d => d.kind === SyntaxKind.SourceFile); } - type Request = { kind: "JsDocTagName" } | { kind: "JsDocTag" } | { kind: "JsDocParameterName", tag: JSDocParameterTag }; function getCompletionData( typeChecker: TypeChecker, @@ -551,9 +729,7 @@ namespace ts.Completions { allSourceFiles: ReadonlyArray, options: GetCompletionsAtPositionOptions, target: ScriptTarget, - ): CompletionData | undefined { - let request: Request | undefined; - + ): CompletionData | Request | undefined { let start = timestamp(); let currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -571,7 +747,7 @@ namespace ts.Completions { if (sourceFile.text.charCodeAt(position - 1) === CharacterCodes.at) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: CompletionDataKind.JsDocTagName }; } else { // When completion is requested without "@", we will have check to make sure that @@ -592,7 +768,7 @@ namespace ts.Completions { // */ const lineStart = getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: CompletionDataKind.JsDocTag }; } } } @@ -603,7 +779,7 @@ namespace ts.Completions { const tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: CompletionDataKind.JsDocTagName }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === SyntaxKind.JSDocTypeExpression) { currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -616,25 +792,10 @@ namespace ts.Completions { } } if (isJSDocParameterTag(tag) && (nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag }; + return { kind: CompletionDataKind.JsDocParameterName, tag }; } } - if (request) { - return { - symbols: emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request, - keywordFilters: KeywordCompletionFilters.None, - symbolToOriginInfoMap: undefined, - }; - } - if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -663,6 +824,7 @@ namespace ts.Completions { // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. let node = currentToken; + let propertyAccessToConvert: PropertyAccessExpression | undefined; let isRightOfDot = false; let isRightOfOpenTag = false; let isStartingCloseTag = false; @@ -677,18 +839,19 @@ namespace ts.Completions { let parent = contextToken.parent; if (contextToken.kind === SyntaxKind.DotToken) { - if (parent.kind === SyntaxKind.PropertyAccessExpression) { - node = (contextToken.parent).expression; - isRightOfDot = true; - } - else if (parent.kind === SyntaxKind.QualifiedName) { - node = (contextToken.parent).left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case SyntaxKind.PropertyAccessExpression: + propertyAccessToConvert = parent as PropertyAccessExpression; + node = propertyAccessToConvert.expression; + break; + case SyntaxKind.QualifiedName: + node = (parent as QualifiedName).left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === LanguageVariant.JSX) { @@ -728,10 +891,8 @@ namespace ts.Completions { } const semanticStart = timestamp(); - let isGlobalCompletion = false; - let isMemberCompletion: boolean; - let allowStringLiteral = false; - let isNewIdentifierLocation: boolean; + let completionKind = CompletionKind.None; + let isNewIdentifierLocation = false; let keywordFilters = KeywordCompletionFilters.None; let symbols: Symbol[] = []; const symbolToOriginInfoMap: SymbolOriginInfoMap = []; @@ -747,8 +908,7 @@ namespace ts.Completions { else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = CompletionKind.MemberLike; } else if (isStartingCloseTag) { const tagName = (contextToken.parent.parent).openingElement.tagName; @@ -757,8 +917,7 @@ namespace ts.Completions { if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = CompletionKind.MemberLike; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -771,7 +930,8 @@ namespace ts.Completions { log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); - return { symbols, isGlobalCompletion, isMemberCompletion, allowStringLiteral, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request, keywordFilters, symbolToOriginInfoMap }; + const recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); + return { kind: CompletionDataKind.Data, symbols, completionKind, propertyAccessToConvert, isNewIdentifierLocation, location, keywordFilters, symbolToOriginInfoMap, recommendedCompletion, previousToken }; type JSDocTagWithTypeExpression = JSDocParameterTag | JSDocPropertyTag | JSDocReturnTag | JSDocTypeTag | JSDocTypedefTag; @@ -788,9 +948,7 @@ namespace ts.Completions { function getTypeScriptMemberSymbols(): void { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = CompletionKind.PropertyAccess; // Since this is qualified name check its a type node location const isTypeLocation = insideJsDocTagTypeExpression || isPartOfTypeNode(node.parent); @@ -840,9 +998,8 @@ namespace ts.Completions { symbols.push(...getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); } else { - // Filter private properties for (const symbol of type.getApparentProperties()) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (typeChecker.isValidPropertyAccessForCompletions((node.parent), type, symbol)) { symbols.push(symbol); } } @@ -867,7 +1024,7 @@ namespace ts.Completions { if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = CompletionKind.None; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter @@ -889,7 +1046,7 @@ namespace ts.Completions { if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), (jsxContainer).attributes.properties); - isMemberCompletion = true; + completionKind = CompletionKind.MemberLike; isNewIdentifierLocation = false; return true; } @@ -897,7 +1054,7 @@ namespace ts.Completions { } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = CompletionKind.None; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { @@ -933,13 +1090,8 @@ namespace ts.Completions { position; const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === SyntaxKind.SourceFile || - scopeNode.kind === SyntaxKind.TemplateExpression || - scopeNode.kind === SyntaxKind.JsxExpression || - scopeNode.kind === SyntaxKind.Block || // Some blocks aren't statements, but all get global completions - isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = CompletionKind.Global; } const symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias; @@ -953,6 +1105,18 @@ namespace ts.Completions { return true; } + function isGlobalCompletionScope(scopeNode: Node): boolean { + switch (scopeNode.kind) { + case SyntaxKind.SourceFile: + case SyntaxKind.TemplateExpression: + case SyntaxKind.JsxExpression: + case SyntaxKind.Block: + return true; + default: + return isStatement(scopeNode); + } + } + function filterGlobalCompletion(symbols: Symbol[]): void { filterMutate(symbols, symbol => { if (!isSourceFile(location)) { @@ -1033,28 +1197,21 @@ namespace ts.Completions { codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, moduleSymbol => { for (let symbol of typeChecker.getExportsOfModule(moduleSymbol)) { - let { name } = symbol; - // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || some(symbol.declarations, d => isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier)) { + if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || some(symbol.declarations, d => isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier)) { continue; } - const isDefaultExport = name === "default"; + const isDefaultExport = symbol.name === InternalSymbolName.Default; if (isDefaultExport) { - const localSymbol = getLocalSymbolForExportDefault(symbol); - if (localSymbol) { - symbol = localSymbol; - name = localSymbol.name; - } - else { - name = codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); - } + symbol = getLocalSymbolForExportDefault(symbol) || symbol; } - if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + const origin: SymbolOriginInfo = { moduleSymbol, isDefaultExport }; + if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); symbolToOriginInfoMap[getSymbolId(symbol)] = { moduleSymbol, isDefaultExport }; } @@ -1219,8 +1376,7 @@ namespace ts.Completions { */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer: ObjectLiteralExpression | ObjectBindingPattern): boolean { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = CompletionKind.ObjectPropertyDeclaration; let typeMembers: Symbol[]; let existingMembers: ReadonlyArray; @@ -1247,7 +1403,7 @@ namespace ts.Completions { // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - let canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement; + let canGetType = hasInitializer(rootDeclaration) || hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement; if (!canGetType && rootDeclaration.kind === SyntaxKind.Parameter) { if (isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); @@ -1298,7 +1454,7 @@ namespace ts.Completions { return false; } - isMemberCompletion = true; + completionKind = CompletionKind.MemberLike; isNewIdentifierLocation = false; const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); @@ -1318,7 +1474,7 @@ namespace ts.Completions { */ function getGetClassLikeCompletionSymbols(classLikeDeclaration: ClassLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = CompletionKind.MemberLike; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -1481,7 +1637,7 @@ namespace ts.Completions { switch (contextToken.kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.CommaToken: - return isConstructorDeclaration(contextToken.parent) && contextToken.parent; + return isConstructorDeclaration(contextToken.parent) && contextToken.parent; default: if (isConstructorParameterCompletion(contextToken)) { @@ -1683,7 +1839,10 @@ namespace ts.Completions { return true; } - return isDeclarationName(contextToken) && !isJsxAttribute(contextToken.parent); + return isDeclarationName(contextToken) + && !isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + && !(isClassLike(contextToken.parent) && position > previousToken.end); } function isFunctionLikeButNotConstructor(kind: SyntaxKind) { @@ -1722,10 +1881,10 @@ namespace ts.Completions { } if (existingImportsOrExports.size === 0) { - return filter(exportsOfModule, e => e.escapedName !== "default"); + return filter(exportsOfModule, e => e.escapedName !== InternalSymbolName.Default); } - return filter(exportsOfModule, e => e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName)); + return filter(exportsOfModule, e => e.escapedName !== InternalSymbolName.Default && !existingImportsOrExports.get(e.escapedName)); } /** @@ -1869,55 +2028,44 @@ namespace ts.Completions { } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol: Symbol, target: ScriptTarget, performCharacterChecks: boolean, allowStringLiteral: boolean, origin: SymbolOriginInfo | undefined): string | undefined { + interface CompletionEntryDisplayNameForSymbol { + readonly name: string; + readonly needsConvertPropertyAccess: boolean; + } + function getCompletionEntryDisplayNameForSymbol( + symbol: Symbol, + target: ScriptTarget, + origin: SymbolOriginInfo | undefined, + kind: CompletionKind, + ): CompletionEntryDisplayNameForSymbol | undefined { const name = getSymbolName(symbol, origin, target); - if (!name) return undefined; - - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if (symbol.flags & SymbolFlags.Namespace) { - const firstCharCode = name.charCodeAt(0); - if (isSingleOrDoubleQuote(firstCharCode)) { - // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) - return undefined; - } + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & SymbolFlags.Module && startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || isKnownSymbol(symbol)) { + return undefined; } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & SymbolFlags.ClassMember) { - const escapedName = symbol.escapedName as string; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === CharacterCodes._ && - escapedName.charCodeAt(1) === CharacterCodes._ && - escapedName.charCodeAt(2) === CharacterCodes.at) { + const validIdentiferResult: CompletionEntryDisplayNameForSymbol = { name, needsConvertPropertyAccess: false }; + if (isIdentifierText(name, target)) return validIdentiferResult; + switch (kind) { + case CompletionKind.None: + case CompletionKind.Global: + case CompletionKind.MemberLike: return undefined; - } - } - - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name: string, target: ScriptTarget, performCharacterChecks: boolean, allowStringLiteral: boolean): string { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; + case CompletionKind.ObjectPropertyDeclaration: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case CompletionKind.PropertyAccess: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === CharacterCodes.space ? undefined : { name, needsConvertPropertyAccess: true }; + case CompletionKind.String: + return validIdentiferResult; + default: + Debug.assertNever(kind); } - - return name; } // A cache of completion entries for keywords, these do not change between sessions @@ -1930,7 +2078,7 @@ namespace ts.Completions { return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); type FilterKeywordCompletions = (entryName: string) => boolean; - function generateKeywordCompletions(keywordFilter: KeywordCompletionFilters) { + function generateKeywordCompletions(keywordFilter: KeywordCompletionFilters): CompletionEntry[] { switch (keywordFilter) { case KeywordCompletionFilters.None: return getAllKeywordCompletions(); @@ -1938,6 +2086,8 @@ namespace ts.Completions { return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case KeywordCompletionFilters.ConstructorParameterKeywords: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + default: + Debug.assertNever(keywordFilter); } } @@ -1998,15 +2148,16 @@ namespace ts.Completions { return isConstructorParameterCompletionKeyword(stringToToken(text)); } - function isEqualityExpression(node: Node): node is BinaryExpression { - return isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); - } - - function isEqualityOperatorKind(kind: SyntaxKind) { - return kind === SyntaxKind.EqualsEqualsToken || - kind === SyntaxKind.ExclamationEqualsToken || - kind === SyntaxKind.EqualsEqualsEqualsToken || - kind === SyntaxKind.ExclamationEqualsEqualsToken; + function isEqualityOperatorKind(kind: ts.SyntaxKind): kind is EqualityOperator { + switch (kind) { + case ts.SyntaxKind.EqualsEqualsEqualsToken: + case ts.SyntaxKind.EqualsEqualsToken: + case ts.SyntaxKind.ExclamationEqualsEqualsToken: + case ts.SyntaxKind.ExclamationEqualsToken: + return true; + default: + return false; + } } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ @@ -2041,8 +2192,7 @@ namespace ts.Completions { /** * Gets all properties on a type, but if that type is a union of several types, - * tries to only include those types which declare properties, not methods. - * This ensures that we don't try providing completions for all the methods on e.g. Array. + * excludes array-like types or callable/constructable types. */ function getPropertiesForCompletion(type: Type, checker: TypeChecker, isForAccess: boolean): Symbol[] { if (!(type.flags & TypeFlags.Union)) { diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index d9a9a03c38b45..5c1e7116af470 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -2,19 +2,15 @@ namespace ts.DocumentHighlights { export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] | undefined { const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) return undefined; - Debug.assert(node.parent !== undefined); - - if (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent)) { + if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. const { openingElement, closingElement } = node.parent.parent; const highlightSpans = [openingElement, closingElement].map(({ tagName }) => getHighlightSpanForNode(tagName, sourceFile)); return [{ fileName: sourceFile.fileName, highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } function getHighlightSpanForNode(node: Node, sourceFile: SourceFile): HighlightSpan { @@ -25,8 +21,8 @@ namespace ts.DocumentHighlights { }; } - function getSemanticDocumentHighlights(node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { - const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position: number, node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] { + const referenceEntries = FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 86db21e322569..8b7473357fe63 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -43,32 +43,21 @@ namespace ts.FindAllReferences { export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { const referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); - - if (!referencedSymbols || !referencedSymbols.length) { - return undefined; - } - - const out: ReferencedSymbol[] = []; const checker = program.getTypeChecker(); - for (const { definition, references } of referencedSymbols) { + return !referencedSymbols || !referencedSymbols.length ? undefined : mapDefined(referencedSymbols, ({ definition, references }) => // Only include referenced symbols that have a valid definition. - if (definition) { - out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); - } - } - - return out; + definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); } export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ImplementationLocation[] { // A node in a JSDoc comment can't have an implementation anyway. const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); const checker = program.getTypeChecker(); return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } - function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node): Entry[] | undefined { + function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number): Entry[] | undefined { if (node.kind === SyntaxKind.SourceFile) { return undefined; } @@ -89,7 +78,7 @@ namespace ts.FindAllReferences { } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } @@ -98,13 +87,13 @@ namespace ts.FindAllReferences { return map(x, toReferenceEntry); } - export function getReferenceEntriesForNode(node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined { - return flattenEntries(Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + export function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined { + return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } function findAllReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined { const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols: SymbolAndEntries[]): Entry[] { @@ -253,9 +242,10 @@ namespace ts.FindAllReferences { /* @internal */ namespace ts.FindAllReferences.Core { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - export function getReferencedSymbolsForNode(node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined { - if (node.kind === ts.SyntaxKind.SourceFile) { - return undefined; + export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined { + if (isSourceFile(node)) { + const reference = GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { @@ -271,11 +261,7 @@ namespace ts.FindAllReferences.Core { // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === SyntaxKind.StringLiteral) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & SymbolFlags.Module && isModuleReferenceLocation(node)) { @@ -286,7 +272,7 @@ namespace ts.FindAllReferences.Core { } function isModuleReferenceLocation(node: ts.Node): boolean { - if (node.kind !== SyntaxKind.StringLiteral) { + if (node.kind !== SyntaxKind.StringLiteral && node.kind !== SyntaxKind.NoSubstitutionTemplateLiteral) { return false; } switch (node.parent.kind) { @@ -376,7 +362,7 @@ namespace ts.FindAllReferences.Core { const searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), symbol.declarations); const result: SymbolAndEntries[] = []; - const state = new State(sourceFiles, /*isForConstructor*/ node.kind === SyntaxKind.ConstructorKeyword, checker, cancellationToken, searchMeaning, options, result); + const state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === SyntaxKind.DefaultKeyword) { addReference(node, symbol, node, state); @@ -403,6 +389,21 @@ namespace ts.FindAllReferences.Core { return result; } + function getSpecialSearchKind(node: Node): SpecialSearchKind { + switch (node.kind) { + case SyntaxKind.ConstructorKeyword: + return SpecialSearchKind.Constructor; + case SyntaxKind.Identifier: + if (isClassLike(node.parent)) { + Debug.assert(node.parent.name === node); + return SpecialSearchKind.Class; + } + // falls through + default: + return SpecialSearchKind.None; + } + } + /** Handle a few special cases relating to export/import specifiers. */ function skipPastExportOrImportSpecifier(symbol: Symbol, node: Node, checker: TypeChecker): Symbol { const { parent } = node; @@ -439,6 +440,12 @@ namespace ts.FindAllReferences.Core { includes(symbol: Symbol): boolean; } + const enum SpecialSearchKind { + None, + Constructor, + Class, + } + /** * Holds all state needed for the finding references. * Unlike `Search`, there is only one `State`. @@ -472,7 +479,7 @@ namespace ts.FindAllReferences.Core { constructor( readonly sourceFiles: ReadonlyArray, /** True if we're searching for constructor references. */ - readonly isForConstructor: boolean, + readonly specialSearchKind: SpecialSearchKind, readonly checker: TypeChecker, readonly cancellationToken: CancellationToken, readonly searchMeaning: SemanticMeaning, @@ -489,6 +496,9 @@ namespace ts.FindAllReferences.Core { /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ createSearch(location: Node, symbol: Symbol, comingFrom: ImportExport | undefined, searchOptions: { text?: string, allSearchSymbols?: Symbol[] } = {}): Search { // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). const { text = stripQuotes(unescapeLeadingUnderscores((getLocalSymbolForExportDefault(symbol) || symbol).escapedName)), allSearchSymbols = undefined, @@ -845,11 +855,18 @@ namespace ts.FindAllReferences.Core { return; } - if (state.isForConstructor) { - findConstructorReferences(referenceLocation, sourceFile, search, state); - } - else { - addReference(referenceLocation, relatedSymbol, search.location, state); + switch (state.specialSearchKind) { + case SpecialSearchKind.None: + addReference(referenceLocation, relatedSymbol, search.location, state); + break; + case SpecialSearchKind.Constructor: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case SpecialSearchKind.Class: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + Debug.assertNever(state.specialSearchKind); } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); @@ -961,24 +978,49 @@ namespace ts.FindAllReferences.Core { } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ - function findConstructorReferences(referenceLocation: Node, sourceFile: SourceFile, search: Search, state: State): void { + function addConstructorReferences(referenceLocation: Node, sourceFile: SourceFile, search: Search, state: State): void { if (isNewExpressionTarget(referenceLocation)) { addReference(referenceLocation, search.symbol, search.location, state); } - const pusher = state.referenceAdder(search.symbol, search.location); + const pusher = () => state.referenceAdder(search.symbol, search.location); if (isClassLike(referenceLocation.parent)) { Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. - findOwnConstructorReferences(search.symbol, sourceFile, pusher); + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } else { // If this class appears in `extends C`, then the extending class' "super" calls are references. const classExtending = tryGetClassByExtendingIdentifier(referenceLocation); - if (classExtending && isClassLike(classExtending)) { - findSuperConstructorAccesses(classExtending, pusher); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + + function addClassStaticThisReferences(referenceLocation: Node, search: Search, state: State): void { + addReference(referenceLocation, search.symbol, search.location, state); + if (isClassLike(referenceLocation.parent)) { + Debug.assert(referenceLocation.parent.name === referenceLocation); + // This is the class declaration. + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + } + } + + function addStaticThisReferences(classLike: ClassLikeDeclaration, pusher: (node: Node) => void): void { + for (const member of classLike.members) { + if (!(isMethodOrAccessor(member) && hasModifier(member, ModifierFlags.Static))) { + continue; } + member.body.forEachChild(function cb(node) { + if (node.kind === SyntaxKind.ThisKeyword) { + pusher(node); + } + else if (!isFunctionLike(node)) { + node.forEachChild(cb); + } + }); } } @@ -992,7 +1034,7 @@ namespace ts.FindAllReferences.Core { */ function findOwnConstructorReferences(classSymbol: Symbol, sourceFile: SourceFile, addNode: (node: Node) => void): void { for (const decl of classSymbol.members.get(InternalSymbolName.Constructor).declarations) { - const ctrKeyword = ts.findChildOfKind(decl, ts.SyntaxKind.ConstructorKeyword, sourceFile)!; + const ctrKeyword = findChildOfKind(decl, ts.SyntaxKind.ConstructorKeyword, sourceFile)!; Debug.assert(decl.kind === SyntaxKind.Constructor && !!ctrKeyword); addNode(ctrKeyword); } @@ -1060,7 +1102,7 @@ namespace ts.FindAllReferences.Core { const containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { const parent = containingTypeReference.parent; - if (isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { + if (hasType(parent) && parent.type === containingTypeReference && hasInitializer(parent) && isImplementationExpression(parent.initializer)) { addReference(parent.initializer); } else if (isFunctionLike(parent) && parent.type === containingTypeReference && (parent as FunctionLikeDeclaration).body) { @@ -1385,7 +1427,7 @@ namespace ts.FindAllReferences.Core { // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, implementations: boolean): Symbol[] { // The search set contains at least the current symbol - const result = [symbol]; + const result: Symbol[] = []; const containingObjectLiteralElement = getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { @@ -1402,9 +1444,9 @@ namespace ts.FindAllReferences.Core { // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), contextualSymbol => { - addRange(result, checker.getRootSymbols(contextualSymbol)); - }); + for (const contextualSymbol of getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker)) { + addRootSymbols(contextualSymbol); + } /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of @@ -1445,9 +1487,7 @@ namespace ts.FindAllReferences.Core { // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list for (const rootSymbol of checker.getRootSymbols(sym)) { - if (rootSymbol !== sym) { - result.push(rootSymbol); - } + result.push(rootSymbol); // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { @@ -1471,7 +1511,7 @@ namespace ts.FindAllReferences.Core { * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. * The value of previousIterationSymbol is undefined when the function is first called. */ - function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, result: Symbol[], previousIterationSymbolsCache: SymbolTable, checker: TypeChecker): void { + function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, result: Push, previousIterationSymbolsCache: SymbolTable, checker: TypeChecker): void { if (!symbol) { return; } @@ -1540,9 +1580,7 @@ namespace ts.FindAllReferences.Core { // compare to our searchSymbol const containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - const contextualSymbol = forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), contextualSymbol => - find(checker.getRootSymbols(contextualSymbol), search.includes)); - + const contextualSymbol = firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); if (contextualSymbol) { return contextualSymbol; } @@ -1571,7 +1609,7 @@ namespace ts.FindAllReferences.Core { function findRootSymbol(sym: Symbol): Symbol | undefined { // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) // Or a union property, use its underlying unioned symbols - return forEach(state.checker.getRootSymbols(sym), rootSymbol => { + return firstDefined(checker.getRootSymbols(sym), rootSymbol => { // if it is in the list, then we are done if (search.includes(rootSymbol)) { return rootSymbol; @@ -1582,12 +1620,12 @@ namespace ts.FindAllReferences.Core { // parent symbol if (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { // Parents will only be defined if implementations is true - if (search.parents && !some(search.parents, parent => explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker))) { + if (search.parents && !some(search.parents, parent => explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker))) { return undefined; } const result: Symbol[] = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ createSymbolTable(), checker); return find(result, search.includes); } @@ -1609,28 +1647,12 @@ namespace ts.FindAllReferences.Core { } /** Gets all symbols for one property. Does not get symbols for every property. */ - function getPropertySymbolsFromContextualType(node: ObjectLiteralElement, checker: TypeChecker): Symbol[] | undefined { - const objectLiteral = node.parent; - const contextualType = checker.getContextualType(objectLiteral); + function getPropertySymbolsFromContextualType(node: ObjectLiteralElement, checker: TypeChecker): ReadonlyArray { + const contextualType = checker.getContextualType(node.parent); const name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - const result: Symbol[] = []; - const symbol = contextualType.getProperty(name); - if (symbol) { - result.push(symbol); - } - - if (contextualType.flags & TypeFlags.Union) { - forEach((contextualType).types, t => { - const symbol = t.getProperty(name); - if (symbol) { - result.push(symbol); - } - }); - } - return result; - } - return undefined; + const symbol = contextualType && name && contextualType.getProperty(name); + return symbol ? [symbol] : + contextualType && contextualType.flags & TypeFlags.Union ? mapDefined((contextualType).types, t => t.getProperty(name)) : emptyArray; } /** @@ -1670,14 +1692,12 @@ namespace ts.FindAllReferences.Core { if (!node) { return false; } - else if (isVariableLike(node)) { - if (node.initializer) { - return true; - } - else if (node.kind === SyntaxKind.VariableDeclaration) { - const parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && hasModifier(parentStatement, ModifierFlags.Ambient); - } + else if (isVariableLike(node) && hasInitializer(node)) { + return true; + } + else if (node.kind === SyntaxKind.VariableDeclaration) { + const parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && hasModifier(parentStatement, ModifierFlags.Ambient); } else if (isFunctionLike(node)) { return !!(node as FunctionLikeDeclaration).body || hasModifier(node, ModifierFlags.Ambient); diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 8214ffd6f2ddb..04f599039daf5 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -47,7 +47,7 @@ namespace ts.formatting { rule("IgnoreBeforeComment", anyToken, comments, anyContext, RuleAction.Ignore), rule("IgnoreAfterLineComment", SyntaxKind.SingleLineCommentTrivia, anyToken, anyContext, RuleAction.Ignore), - rule("NoSpaceBeforeColon", anyToken, SyntaxKind.ColonToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], RuleAction.Delete), + rule("NotSpaceBeforeColon", anyToken, SyntaxKind.ColonToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], RuleAction.Delete), rule("SpaceAfterColon", SyntaxKind.ColonToken, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], RuleAction.Space), rule("NoSpaceBeforeQuestionMark", anyToken, SyntaxKind.QuestionToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], RuleAction.Delete), // insert space after '?' only when it is used in conditional operator @@ -69,10 +69,10 @@ namespace ts.formatting { rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, SyntaxKind.MinusMinusToken, [isNonJsxSameLineTokenContext], RuleAction.Delete), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", SyntaxKind.PlusPlusToken, SyntaxKind.PlusToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], RuleAction.Space), rule("SpaceAfterAddWhenFollowedByUnaryPlus", SyntaxKind.PlusToken, SyntaxKind.PlusToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], RuleAction.Space), rule("SpaceAfterAddWhenFollowedByPreincrement", SyntaxKind.PlusToken, SyntaxKind.PlusPlusToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], RuleAction.Space), @@ -80,7 +80,7 @@ namespace ts.formatting { rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", SyntaxKind.MinusToken, SyntaxKind.MinusToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], RuleAction.Space), rule("SpaceAfterSubtractWhenFollowedByPredecrement", SyntaxKind.MinusToken, SyntaxKind.MinusMinusToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], RuleAction.Space), - rule("NoSpaceAfterCloseBrace", SyntaxKind.CloseBraceToken, [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken, SyntaxKind.SemicolonToken], [isNonJsxSameLineTokenContext], RuleAction.Delete), + rule("NoSpaceAfterCloseBrace", SyntaxKind.CloseBraceToken, [SyntaxKind.CommaToken, SyntaxKind.SemicolonToken], [isNonJsxSameLineTokenContext], RuleAction.Delete), // For functions and control block place } on a new line [multi-line rule] rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, SyntaxKind.CloseBraceToken, [isMultilineBlockContext], RuleAction.NewLine), @@ -198,7 +198,7 @@ namespace ts.formatting { RuleAction.Delete), // decorators - rule("SpaceBeforeAt", anyToken, SyntaxKind.AtToken, [isNonJsxSameLineTokenContext], RuleAction.Space), + rule("SpaceBeforeAt", [SyntaxKind.CloseParenToken, SyntaxKind.Identifier], SyntaxKind.AtToken, [isNonJsxSameLineTokenContext], RuleAction.Space), rule("NoSpaceAfterAt", SyntaxKind.AtToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.Delete), // Insert space after @ in decorator rule("SpaceAfterDecorator", @@ -231,8 +231,8 @@ namespace ts.formatting { rule("SpaceAfterConstructor", SyntaxKind.ConstructorKeyword, SyntaxKind.OpenParenToken, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], RuleAction.Space), rule("NoSpaceAfterConstructor", SyntaxKind.ConstructorKeyword, SyntaxKind.OpenParenToken, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], RuleAction.Delete), - rule("SpaceAfterComma", SyntaxKind.CommaToken, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], RuleAction.Space), - rule("NoSpaceAfterComma", SyntaxKind.CommaToken, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], RuleAction.Delete), + rule("SpaceAfterComma", SyntaxKind.CommaToken, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], RuleAction.Space), + rule("NoSpaceAfterComma", SyntaxKind.CommaToken, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], RuleAction.Delete), // Insert space after function keyword for anonymous functions rule("SpaceAfterAnonymousFunctionKeyword", SyntaxKind.FunctionKeyword, SyntaxKind.OpenParenToken, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], RuleAction.Space), @@ -300,9 +300,12 @@ namespace ts.formatting { rule("SpaceAfterTypeAssertion", SyntaxKind.GreaterThanToken, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], RuleAction.Space), rule("NoSpaceAfterTypeAssertion", SyntaxKind.GreaterThanToken, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], RuleAction.Delete), + + rule("SpaceBeforeTypeAnnotation", anyToken, SyntaxKind.ColonToken, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], RuleAction.Space), + rule("NoSpaceBeforeTypeAnnotation", anyToken, SyntaxKind.ColonToken, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], RuleAction.Delete), ]; - // These rules are lower in priority than user-configurable + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. const lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? rule("NoSpaceBeforeSemicolon", anyToken, SyntaxKind.SemicolonToken, [isNonJsxSameLineTokenContext], RuleAction.Delete), @@ -312,10 +315,6 @@ namespace ts.formatting { rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, SyntaxKind.OpenBraceToken, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], RuleAction.Space, RuleFlags.CanDeleteNewLines), rule("NoSpaceBeforeComma", anyToken, SyntaxKind.CommaToken, [isNonJsxSameLineTokenContext], RuleAction.Delete), - // No space before and after indexer - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(SyntaxKind.AsyncKeyword), SyntaxKind.OpenBracketToken, [isNonJsxSameLineTokenContext], RuleAction.Delete), - rule("NoSpaceAfterCloseBracket", SyntaxKind.CloseBracketToken, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], RuleAction.Delete), - rule("SpaceAfterSemicolon", SyntaxKind.SemicolonToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.Space), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] @@ -323,10 +322,15 @@ namespace ts.formatting { "SpaceBetweenStatements", [SyntaxKind.CloseParenToken, SyntaxKind.DoKeyword, SyntaxKind.ElseKeyword, SyntaxKind.CaseKeyword], anyToken, - [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], + [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], RuleAction.Space), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [SyntaxKind.TryKeyword, SyntaxKind.FinallyKeyword], SyntaxKind.OpenBraceToken, [isNonJsxSameLineTokenContext], RuleAction.Space), + + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(SyntaxKind.AsyncKeyword), SyntaxKind.OpenBracketToken, [isNonJsxSameLineTokenContext], RuleAction.Delete), + rule("NoSpaceAfterCloseBracket", SyntaxKind.CloseBracketToken, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], RuleAction.Delete), + rule("SpaceAfterSemicolon", SyntaxKind.SemicolonToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.Space), ]; return [ @@ -440,6 +444,19 @@ namespace ts.formatting { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context: FormattingContext): boolean { + return !isTypeAnnotationContext(context); + } + + function isTypeAnnotationContext(context: FormattingContext): boolean { + const contextKind = context.contextNode.kind; + return contextKind === SyntaxKind.PropertyDeclaration || + contextKind === SyntaxKind.PropertySignature || + contextKind === SyntaxKind.Parameter || + contextKind === SyntaxKind.VariableDeclaration || + isFunctionLikeKind(contextKind); + } + function isConditionalOperatorContext(context: FormattingContext): boolean { return context.contextNode.kind === SyntaxKind.ConditionalExpression; } @@ -613,12 +630,12 @@ namespace ts.formatting { return context.TokensAreOnSameLine() && context.contextNode.kind !== SyntaxKind.JsxText; } - function isNonJsxElementContext(context: FormattingContext): boolean { - return context.contextNode.kind !== SyntaxKind.JsxElement; + function isNonJsxElementOrFragmentContext(context: FormattingContext): boolean { + return context.contextNode.kind !== SyntaxKind.JsxElement && context.contextNode.kind !== SyntaxKind.JsxFragment; } function isJsxExpressionContext(context: FormattingContext): boolean { - return context.contextNode.kind === SyntaxKind.JsxExpression; + return context.contextNode.kind === SyntaxKind.JsxExpression || context.contextNode.kind === SyntaxKind.JsxSpreadAttribute; } function isNextTokenParentJsxAttribute(context: FormattingContext): boolean { diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 0a444a7280afd..1e6323be9fa0d 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -367,12 +367,13 @@ namespace ts.formatting { function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorSettings): number { const containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : Value.Unknown; - - function getActualIndentationFromList(list: ReadonlyArray): number { - const index = indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : Value.Unknown; + if (containingList) { + const index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return Value.Unknown; } function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorSettings): number { @@ -508,6 +509,7 @@ namespace ts.formatting { case SyntaxKind.ArrayBindingPattern: case SyntaxKind.ObjectBindingPattern: case SyntaxKind.JsxOpeningElement: + case SyntaxKind.JsxOpeningFragment: case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxExpression: case SyntaxKind.MethodSignature: @@ -554,6 +556,8 @@ namespace ts.formatting { (!!(child).namedBindings && (child).namedBindings.kind !== SyntaxKind.NamedImports); case SyntaxKind.JsxElement: return childKind !== SyntaxKind.JsxClosingElement; + case SyntaxKind.JsxFragment: + return childKind !== SyntaxKind.JsxClosingFragment; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 35f4d079e292c..5f17eccf9c5be 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -1,22 +1,9 @@ /* @internal */ namespace ts.GoToDefinition { export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[] { - /// Triple slash reference comments - const comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - const referenceFile = tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - - // Type reference directives - const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - const referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + const reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -115,6 +102,23 @@ namespace ts.GoToDefinition { return getDefinitionFromSymbol(typeChecker, symbol, node); } + export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { fileName: string, file: SourceFile } | undefined { + const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + const file = tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file }; + } + + const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + const reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + const file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file }; + } + + return undefined; + } + /// Goto type export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] { const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -301,7 +305,7 @@ namespace ts.GoToDefinition { return createDefinitionInfo(decl, symbolKind, symbolName, containerName); } - function findReferenceInPosition(refs: ReadonlyArray, pos: number): FileReference { + export function findReferenceInPosition(refs: ReadonlyArray, pos: number): FileReference { for (const ref of refs) { if (ref.pos <= pos && pos <= ref.end) { return ref; diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index f12df4613c041..d2ce802f177b2 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -290,7 +290,7 @@ namespace ts.FindAllReferences { function isNameMatch(name: __String): boolean { // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports - return name === exportSymbol.escapedName || exportKind !== ExportKind.Named && name === "default"; + return name === exportSymbol.escapedName || exportKind !== ExportKind.Named && name === InternalSymbolName.Default; } } @@ -534,7 +534,7 @@ namespace ts.FindAllReferences { // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) const importedName = symbolName(importedSymbol); - if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { + if (importedName === undefined || importedName === InternalSymbolName.Default || importedName === symbol.escapedName) { return { kind: ImportExport.Import, symbol: importedSymbol, ...isImport }; } } @@ -604,7 +604,7 @@ namespace ts.FindAllReferences { } function symbolName(symbol: Symbol): __String | undefined { - if (symbol.escapedName !== "default") { + if (symbol.escapedName !== InternalSymbolName.Default) { return symbol.escapedName; } @@ -616,7 +616,7 @@ namespace ts.FindAllReferences { /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol: Symbol, checker: TypeChecker): Symbol { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (const declaration of symbol.declarations) { if (isExportSpecifier(declaration) && !(declaration as ExportSpecifier).propertyName && !(declaration as ExportSpecifier).parent.parent.moduleSpecifier) { diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 79b08780226f1..46f2458bba9ac 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -1,6 +1,5 @@ /* @internal */ namespace ts.JsDoc { - const singleLineTemplate = { newText: "/** */", caretOffset: 3 }; const jsDocTagNames = [ "augments", "author", @@ -113,7 +112,7 @@ namespace ts.JsDoc { function forEachUnique(array: T[], callback: (element: T, index: number) => U): U { if (array) { for (let i = 0; i < array.length; i++) { - if (indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { const result = callback(array[i], i); if (result) { return result; @@ -197,9 +196,16 @@ namespace ts.JsDoc { /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. - * Invalid positions are - * - within comments, strings (including template literals and regex), and JSXText - * - within a token + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations * * Hosts should ideally check that: * - The line is all whitespace up to 'position' before performing the insertion. @@ -225,19 +231,17 @@ namespace ts.JsDoc { const commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - // if climbing the tree did not find a declaration with parameters, complete to a single line comment - return singleLineTemplate; + return undefined; } const { commentOwner, parameters } = commentOwnerInfo; - - if (commentOwner.kind === SyntaxKind.JsxText) { + if (commentOwner.getStart() < position) { return undefined; } - if (commentOwner.getStart() < position || parameters.length === 0) { - // if climbing the tree found a declaration with parameters but the request was made inside it - // or if there are no parameters, complete to a single line comment - return singleLineTemplate; + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + const singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; } const posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); @@ -247,11 +251,19 @@ namespace ts.JsDoc { const indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, () => " "); const isJavaScriptFile = hasJavaScriptFileExtension(sourceFile.fileName); - const docParams = parameters.map(({name}, i) => { - const nameText = isIdentifier(name) ? name.text : `param${i}`; - const type = isJavaScriptFile ? "{any} " : ""; - return `${indentationStr} * @param ${type}${nameText}${newLine}`; - }).join(""); + let docParams = ""; + for (let i = 0; i < parameters.length; i++) { + const currentName = parameters[i].name; + const paramName = currentName.kind === SyntaxKind.Identifier ? + (currentName).escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += `${indentationStr} * @param {any} ${paramName}${newLine}`; + } + else { + docParams += `${indentationStr} * @param ${paramName}${newLine}`; + } + } // A doc comment consists of the following // * The opening comment line @@ -273,7 +285,7 @@ namespace ts.JsDoc { interface CommentOwnerInfo { readonly commentOwner: Node; - readonly parameters: ReadonlyArray; + readonly parameters?: ReadonlyArray; } function getCommentOwnerInfo(tokenAtPos: Node): CommentOwnerInfo | undefined { for (let commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { @@ -285,18 +297,32 @@ namespace ts.JsDoc { const { parameters } = commentOwner as FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | MethodSignature; return { commentOwner, parameters }; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.PropertySignature: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.EnumMember: + case SyntaxKind.TypeAliasDeclaration: + return { commentOwner }; + case SyntaxKind.VariableStatement: { const varStatement = commentOwner; const varDeclarations = varStatement.declarationList.declarations; const parameters = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return parameters ? { commentOwner, parameters } : undefined; + return { commentOwner, parameters }; } case SyntaxKind.SourceFile: return undefined; + case SyntaxKind.ModuleDeclaration: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === SyntaxKind.ModuleDeclaration ? undefined : { commentOwner }; + case SyntaxKind.BinaryExpression: { const be = commentOwner as BinaryExpression; if (getSpecialPropertyAssignmentKind(be) === ts.SpecialPropertyAssignmentKind.None) { @@ -305,11 +331,6 @@ namespace ts.JsDoc { const parameters = isFunctionLike(be.right) ? be.right.parameters : emptyArray; return { commentOwner, parameters }; } - - case SyntaxKind.JsxText: { - const parameters: ReadonlyArray = emptyArray; - return { commentOwner, parameters }; - } } } } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 762726adb771c..8449805ee71be 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -46,7 +46,7 @@ namespace ts.NavigateTo { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. let containerMatches = matches; if (patternMatcher.patternContainsDots) { diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 15c1ff997586d..97569e0bae901 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -1,12 +1,12 @@ /* @internal */ namespace ts.Completions.PathCompletions { - export function getStringLiteralCompletionsFromModuleNames(node: StringLiteral, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): CompletionEntry[] { + export function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): CompletionEntry[] { const literalValue = normalizeSlashes(node.text); const scriptPath = node.getSourceFile().path; const scriptDirectory = getDirectoryPath(scriptPath); - const span = getDirectoryFragmentTextSpan((node).text, node.getStart() + 1); + const span = getDirectoryFragmentTextSpan((node).text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || isRootedDiskPath(literalValue)) { const extensions = getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -147,25 +147,15 @@ namespace ts.Completions.PathCompletions { getCompletionEntriesForDirectoryFragment(fragment, normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); for (const path in paths) { - if (!paths.hasOwnProperty(path)) continue; const patterns = paths[path]; - if (!patterns) continue; - - if (path === "*") { - for (const pattern of patterns) { - for (const match of getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host)) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(entry => entry.name === match)) continue; - result.push(createCompletionEntryForModule(match, ScriptElementKind.externalModuleName, span)); + if (paths.hasOwnProperty(path) && patterns) { + for (const pathCompletion of getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host)) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(entry => entry.name === pathCompletion)) { + result.push(createCompletionEntryForModule(pathCompletion, ScriptElementKind.externalModuleName, span)); } } } - else if (startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(entry => entry.name === path)) continue; - result.push(createCompletionEntryForModule(path, ScriptElementKind.externalModuleName, span)); - } - } } } @@ -187,52 +177,66 @@ namespace ts.Completions.PathCompletions { return result; } - function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost): string[] { - if (host.readDirectory) { - const parsed = hasZeroOrOneAsteriskCharacter(pattern) ? tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - const normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - const normalizedPrefixDirectory = getDirectoryPath(normalizedPrefix); - const normalizedPrefixBase = getBaseFileName(normalizedPrefix); - - const fragmentHasPath = stringContains(fragment, directorySeparator); - - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + getDirectoryPath(fragment)) : normalizedPrefixDirectory; - - const normalizedSuffix = normalizePath(parsed.suffix); - const baseDirectory = combinePaths(baseUrl, expandedPrefixDirectory); - const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - const includeGlob = normalizedSuffix ? "**/*" : "./*"; - - const matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - const result: string[] = []; - - // Trim away prefix and suffix - for (const match of matches) { - const normalizedMatch = normalizePath(match); - if (!endsWith(normalizedMatch, normalizedSuffix) || !startsWith(normalizedMatch, completePrefix)) { - continue; - } + function getCompletionsForPathMapping( + path: string, patterns: ReadonlyArray, fragment: string, baseUrl: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost, + ): string[] { + if (!endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !stringContains(path, "*") && startsWith(path, fragment) ? [path] : emptyArray; + } - const start = completePrefix.length; - const length = normalizedMatch.length - start - normalizedSuffix.length; + const pathPrefix = path.slice(0, path.length - 1); + if (!startsWith(fragment, pathPrefix)) { + return emptyArray; + } - result.push(removeFileExtension(normalizedMatch.substr(start, length))); - } - return result; - } - } + const remainingFragment = fragment.slice(pathPrefix.length); + return flatMap(patterns, pattern => getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host)); + } + + function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost): string[] | undefined { + if (!host.readDirectory) { + return undefined; } - return undefined; + const parsed = hasZeroOrOneAsteriskCharacter(pattern) ? tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + const normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + const normalizedPrefixDirectory = getDirectoryPath(normalizedPrefix); + const normalizedPrefixBase = getBaseFileName(normalizedPrefix); + + const fragmentHasPath = stringContains(fragment, directorySeparator); + + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + getDirectoryPath(fragment)) : normalizedPrefixDirectory; + + const normalizedSuffix = normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + const baseDirectory = normalizePath(combinePaths(baseUrl, expandedPrefixDirectory)); + const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + const includeGlob = normalizedSuffix ? "**/*" : "./*"; + + const matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + // Trim away prefix and suffix + return mapDefined(matches, match => { + const normalizedMatch = normalizePath(match); + if (!endsWith(normalizedMatch, normalizedSuffix) || !startsWith(normalizedMatch, completePrefix)) { + return; + } + + const start = completePrefix.length; + const length = normalizedMatch.length - start - normalizedSuffix.length; + return removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment: string, scriptPath: string, options: CompilerOptions, typeChecker: TypeChecker, host: LanguageServiceHost): string[] { diff --git a/src/services/preProcess.ts b/src/services/preProcess.ts index 8f6a468be6495..a99683d45effa 100644 --- a/src/services/preProcess.ts +++ b/src/services/preProcess.ts @@ -295,7 +295,7 @@ namespace ts { // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index e0a1924793976..85ef9113bdaca 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -33,8 +33,8 @@ namespace ts { } export function getApplicableRefactors(context: RefactorContext): ApplicableRefactorInfo[] { - return flatMapIter(refactors.values(), refactor => - context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context)); + return arrayFrom(flatMapIterator(refactors.values(), refactor => + context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context))); } export function getEditsForRefactor(context: RefactorContext, refactorName: string, actionName: string): RefactorEditInfo | undefined { diff --git a/src/services/refactors/convertFunctionToEs6Class.ts b/src/services/refactors/convertFunctionToEs6Class.ts index b66d14ee44961..cddf40ae01740 100644 --- a/src/services/refactors/convertFunctionToEs6Class.ts +++ b/src/services/refactors/convertFunctionToEs6Class.ts @@ -50,7 +50,6 @@ namespace ts.refactor.convertFunctionToES6Class { const { file: sourceFile } = context; const ctorSymbol = getConstructorSymbol(context); - const newLine = context.formatContext.options.newLineCharacter; const deletedNodes: Node[] = []; const deletes: (() => any)[] = []; @@ -88,7 +87,7 @@ namespace ts.refactor.convertFunctionToES6Class { } // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); for (const deleteCallback of deletes) { deleteCallback(); } diff --git a/src/services/refactors/convertToEs6Module.ts b/src/services/refactors/convertToEs6Module.ts index a18084b9d46ea..53c09a91f6efb 100644 --- a/src/services/refactors/convertToEs6Module.ts +++ b/src/services/refactors/convertToEs6Module.ts @@ -427,7 +427,7 @@ namespace ts.refactor { import x from "x"; const [a, b, c] = x; */ - const tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + const tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); return [ makeImport(createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), makeConst(/*modifiers*/ undefined, getSynthesizedDeepClone(name), createIdentifier(tmp)), diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 55b732e24baca..b3110a0ca368f 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -658,11 +658,10 @@ namespace ts.refactor.extractSymbol { case SyntaxKind.Constructor: return "constructor"; case SyntaxKind.FunctionExpression: - return scope.name - ? `function expression '${scope.name.text}'` - : "anonymous function expression"; case SyntaxKind.FunctionDeclaration: - return `function '${scope.name.text}'`; + return scope.name + ? `function '${scope.name.text}'` + : "anonymous function"; case SyntaxKind.ArrowFunction: return "arrow function"; case SyntaxKind.MethodDeclaration: @@ -811,13 +810,10 @@ namespace ts.refactor.extractSymbol { const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { - prefix: isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, - suffix: context.newLineCharacter - }); + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } const newNodes: Node[] = []; @@ -960,10 +956,12 @@ namespace ts.refactor.extractSymbol { } } - const replacementRange = isReadonlyArray(range.range) - ? { pos: first(range.range).getStart(), end: last(range.range).end } - : { pos: range.range.getStart(), end: range.range.end }; - changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } const edits = changeTracker.getChanges(); const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; @@ -1006,7 +1004,7 @@ namespace ts.refactor.extractSymbol { const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file.text); const isJS = isInJavaScriptFile(scope); - const variableType = isJS + const variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, NodeBuilderFlags.NoTruncation); @@ -1041,7 +1039,7 @@ namespace ts.refactor.extractSymbol { // Declare const maxInsertionPos = node.pos; const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); @@ -1056,8 +1054,8 @@ namespace ts.refactor.extractSymbol { const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); if (oldVariableDeclaration) { // Declare - // CONSIDER: could detect that each is on a separate line - changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume const localReference = createIdentifier(localNameText); @@ -1079,17 +1077,10 @@ namespace ts.refactor.extractSymbol { // Declare const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); if (nodeToInsertBefore.pos === 0) { - // If we're at the beginning of the file, we need to take care not to insert before header comments - // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved - // for imports. - const insertionPos = getSourceFileImportLocation(file); - changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { - prefix: insertionPos === 0 ? undefined : context.newLineCharacter, - suffix: isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter - }); + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); } else { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume @@ -1286,12 +1277,12 @@ namespace ts.refactor.extractSymbol { * If `scope` contains a function after `minPos`, then return the first such function. * Otherwise, return `undefined`. */ - function getNodeToInsertFunctionBefore(minPos: number, scope: Scope): Node | undefined { + function getNodeToInsertFunctionBefore(minPos: number, scope: Scope): Statement | ClassElement | undefined { return find(getStatementsOrClassElements(scope), child => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); } - function getNodeToInsertPropertyBefore(maxPos: number, scope: ClassLikeDeclaration): Node { + function getNodeToInsertPropertyBefore(maxPos: number, scope: ClassLikeDeclaration): ClassElement { const members = scope.members; Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. @@ -1317,7 +1308,7 @@ namespace ts.refactor.extractSymbol { return prevMember; } - function getNodeToInsertConstantBefore(node: Node, scope: Scope): Node { + function getNodeToInsertConstantBefore(node: Node, scope: Scope): Statement { Debug.assert(!isClassLike(scope)); let prevScope: Scope | undefined = undefined; diff --git a/src/services/rename.ts b/src/services/rename.ts index cfe79679fba0a..ca46a93f3c979 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -38,9 +38,17 @@ namespace ts.Rename { return undefined; } - const displayName = stripQuotes(getDeclaredName(typeChecker, symbol, node)); const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + + const specifierName = (isImportOrExportSpecifierName(node) || isStringOrNumericLiteral(node) && node.parent.kind === SyntaxKind.ComputedPropertyName) + ? stripQuotes(getTextOfIdentifierOrLiteral(node)) + : undefined; + const displayName = specifierName || typeChecker.symbolToString(symbol); + const fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === SyntaxKind.StringLiteral) { diff --git a/src/services/services.ts b/src/services/services.ts index 24679e6a16786..eb5e3ae574379 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -488,6 +488,7 @@ namespace ts { parameters: Symbol[]; thisParameter: Symbol; resolvedReturnType: Type; + resolvedTypePredicate: TypePredicate | undefined; minTypeArgumentCount: number; minArgumentCount: number; hasRestParameter: boolean; @@ -1268,6 +1269,7 @@ namespace ts { } return host.readFile && host.readFile(fileName); }, + realpath: host.realpath && (path => host.realpath(path)), directoryExists: directoryName => { return directoryProbablyExists(directoryName, host); }, @@ -1430,7 +1432,7 @@ namespace ts { return [...program.getOptionsDiagnostics(cancellationToken), ...program.getGlobalDiagnostics(cancellationToken)]; } - function getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions = { includeExternalModuleExports: false }): CompletionInfo { + function getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions = { includeExternalModuleExports: false, includeInsertTextCompletions: false }): CompletionInfo { synchronizeHostData(); return Completions.getCompletionsAtPosition( host, @@ -1446,7 +1448,7 @@ namespace ts { function getCompletionEntryDetails(fileName: string, position: number, name: string, formattingOptions?: FormatCodeSettings, source?: string): CompletionEntryDetails { synchronizeHostData(); return Completions.getCompletionEntryDetails( - program.getTypeChecker(), + program, log, program.getCompilerOptions(), getValidSourceFile(fileName), @@ -1881,7 +1883,7 @@ namespace ts { return []; } - function getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[] { + function getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const span = createTextSpanFromBounds(start, end); @@ -1894,6 +1896,16 @@ namespace ts { }); } + function getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions { + synchronizeHostData(); + Debug.assert(scope.type === "file"); + const sourceFile = getValidSourceFile(scope.fileName); + const newLineCharacter = getNewLineOrDefaultFromHost(host); + const formatContext = formatting.getFormatContext(formatOptions); + + return codefix.getAllFixes({ fixId, sourceFile, program, newLineCharacter, host, cancellationToken, formatContext }); + } + function applyCodeActionCommand(action: CodeActionCommand): Promise; function applyCodeActionCommand(action: CodeActionCommand[]): Promise; function applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -2041,7 +2053,7 @@ namespace ts { } function getTodoCommentsRegExp(): RegExp { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: @@ -2188,6 +2200,7 @@ namespace ts { isValidBraceCompletionAtPosition, getSpanOfEnclosingComment, getCodeFixesAtPosition, + getCombinedCodeFix, applyCodeActionCommand, getEmitOutput, getNonBoundSourceFile, @@ -2238,20 +2251,6 @@ namespace ts { isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node: Node): node is ObjectLiteralElement { - switch (node.kind) { - case SyntaxKind.JsxAttribute: - case SyntaxKind.JsxSpreadAttribute: - case SyntaxKind.PropertyAssignment: - case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - return true; - } - return false; - } - /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ diff --git a/src/services/shims.ts b/src/services/shims.ts index 7c932361c1079..fda698785b35e 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -141,7 +141,7 @@ namespace ts { getEncodedSemanticClassifications(fileName: string, start: number, length: number): string; getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): string; - getCompletionEntryDetails(fileName: string, position: number, entryName: string, options: string/*Services.FormatCodeOptions*/, source: string | undefined): string; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, options: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined): string; getQuickInfoAtPosition(fileName: string, position: number): string; @@ -330,7 +330,7 @@ namespace ts { // if shimHost is a COM object then property check will become method call with no arguments. // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { - this.resolveModuleNames = (moduleNames: string[], containingFile: string) => { + this.resolveModuleNames = (moduleNames: string[], containingFile: string): ResolvedModuleFull[] => { const resolutionsInFile = >JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile)); return map(moduleNames, name => { const result = getProperty(resolutionsInFile, name); @@ -906,11 +906,11 @@ namespace ts { } /** Get a string based representation of a completion list entry details */ - public getCompletionEntryDetails(fileName: string, position: number, entryName: string, options: string/*Services.FormatCodeOptions*/, source: string | undefined) { + public getCompletionEntryDetails(fileName: string, position: number, entryName: string, options: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined) { return this.forwardJSONCall( `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, () => { - const localOptions: ts.FormatCodeOptions = JSON.parse(options); + const localOptions: ts.FormatCodeOptions = options === undefined ? undefined : JSON.parse(options); return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); } ); diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 36c83f5f4af38..f5338db954bd0 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -197,7 +197,7 @@ namespace ts.SignatureHelp { function getArgumentIndex(argumentsList: Node, node: Node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -224,12 +224,12 @@ namespace ts.SignatureHelp { // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. const listChildren = argumentsList.getChildren(); @@ -253,9 +253,11 @@ namespace ts.SignatureHelp { // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (isTemplateLiteralKind(node.kind)) { if (isInsideTemplateLiteral(node, position)) { @@ -307,9 +309,8 @@ namespace ts.SignatureHelp { // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === SyntaxKind.TemplateExpression) { diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index fe04342b8f7ff..6f979f1721b56 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -91,9 +91,14 @@ namespace ts.SymbolDisplay { } export function getSymbolModifiers(symbol: Symbol): string { - return symbol && symbol.declarations && symbol.declarations.length > 0 + const nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 ? getNodeModifiers(symbol.declarations[0]) : ScriptElementKindModifier.none; + + const symbolModifiers = symbol && symbol.flags & SymbolFlags.Optional ? + ScriptElementKindModifier.optionalModifier + : ScriptElementKindModifier.none; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; } interface SymbolDisplayPartsDocumentationAndSymbolKind { @@ -105,7 +110,7 @@ namespace ts.SymbolDisplay { // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location export function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node, - location: Node, semanticMeaning = getMeaningFromLocation(location)): SymbolDisplayPartsDocumentationAndSymbolKind { + location: Node, semanticMeaning = getMeaningFromLocation(location), alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { const displayParts: SymbolDisplayPart[] = []; let documentation: SymbolDisplayPart[]; @@ -115,6 +120,7 @@ namespace ts.SymbolDisplay { let hasAddedSymbolInfo: boolean; const isThisExpression = location.kind === SyntaxKind.ThisKeyword && isExpression(location); let type: Type; + let documentationFromAlias: SymbolDisplayPart[]; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Alias) { @@ -243,6 +249,7 @@ namespace ts.SymbolDisplay { } } if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (getDeclarationOfKind(symbol, SyntaxKind.ClassExpression)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -258,14 +265,14 @@ namespace ts.SymbolDisplay { writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & SymbolFlags.Interface) && (semanticMeaning & SemanticMeaning.Type)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(keywordPart(SyntaxKind.InterfaceKeyword)); displayParts.push(spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & SymbolFlags.TypeAlias) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(keywordPart(SyntaxKind.TypeKeyword)); displayParts.push(spacePart()); addFullSymbolName(symbol); @@ -276,7 +283,7 @@ namespace ts.SymbolDisplay { addRange(displayParts, typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, TypeFormatFlags.InTypeAlias)); } if (symbolFlags & SymbolFlags.Enum) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (forEach(symbol.declarations, isConstEnumDeclaration)) { displayParts.push(keywordPart(SyntaxKind.ConstKeyword)); displayParts.push(spacePart()); @@ -286,7 +293,7 @@ namespace ts.SymbolDisplay { addFullSymbolName(symbol); } if (symbolFlags & SymbolFlags.Module) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); const declaration = getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration); const isNamespace = declaration && declaration.name && declaration.name.kind === SyntaxKind.Identifier; displayParts.push(keywordPart(isNamespace ? SyntaxKind.NamespaceKeyword : SyntaxKind.ModuleKeyword)); @@ -294,7 +301,7 @@ namespace ts.SymbolDisplay { addFullSymbolName(symbol); } if ((symbolFlags & SymbolFlags.TypeParameter) && (semanticMeaning & SemanticMeaning.Type)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(punctuationPart(SyntaxKind.OpenParenToken)); displayParts.push(textPart("type parameter")); displayParts.push(punctuationPart(SyntaxKind.CloseParenToken)); @@ -328,7 +335,7 @@ namespace ts.SymbolDisplay { else if (declaration.kind === SyntaxKind.TypeAliasDeclaration) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(keywordPart(SyntaxKind.TypeKeyword)); displayParts.push(spacePart()); @@ -354,7 +361,32 @@ namespace ts.SymbolDisplay { } } if (symbolFlags & SymbolFlags.Alias) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + const resolvedNode = resolvedSymbol.declarations[0]; + const declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + const isExternalModuleDeclaration = + ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, ModifierFlags.Ambient); + const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( + typeChecker, + resolvedSymbol, + ts.getSourceFileOfNode(resolvedNode), + resolvedNode, + declarationName, + semanticMeaning, + shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push(...resolvedInfo.displayParts); + displayParts.push(lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } + switch (symbol.declarations[0].kind) { case SyntaxKind.NamespaceExportDeclaration: displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); @@ -400,7 +432,7 @@ namespace ts.SymbolDisplay { if (symbolKind !== ScriptElementKind.unknown) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(keywordPart(SyntaxKind.ThisKeyword)); } else { @@ -472,12 +504,24 @@ namespace ts.SymbolDisplay { } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } + return { displayParts, documentation, symbolKind, tags }; - function addNewLineIfDisplayPartsExist() { + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart(ScriptElementKind.alias); + displayParts.push(spacePart()); + } } function addInPrefix() { @@ -486,17 +530,20 @@ namespace ts.SymbolDisplay { displayParts.push(spacePart()); } - function addFullSymbolName(symbol: Symbol, enclosingDeclaration?: Node) { - const fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, + function addFullSymbolName(symbolToDisplay: Symbol, enclosingDeclaration?: Node) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + const fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing); addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol: Symbol, symbolKind: string) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); - if (!some(symbol.declarations, d => isArrowFunction(d) || (isFunctionExpression(d) || isClassExpression(d)) && !d.name)) { + if (symbol && !some(symbol.declarations, d => isArrowFunction(d) || (isFunctionExpression(d) || isClassExpression(d)) && !d.name)) { displayParts.push(spacePart()); addFullSymbolName(symbol); } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 7c4e25537efbe..e73c639ba79bd 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -117,7 +117,7 @@ namespace ts.textChanges { readonly options?: never; } - export interface ChangeMultipleNodesOptions extends ChangeNodeOptions { + interface ChangeMultipleNodesOptions extends ChangeNodeOptions { nodeSeparator: string; } interface ReplaceWithMultipleNodes extends BaseChange { @@ -192,8 +192,11 @@ namespace ts.textChanges { } export class ChangeTracker { - private changes: Change[] = []; + private readonly changes: Change[] = []; private readonly newLineCharacter: string; + private readonly deletedNodesInLists: true[] = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + // Map from class id to nodes to insert at the start + private readonly nodesInsertedAtClassStarts = createMap<{ sourceFile: SourceFile, cls: ClassLikeDeclaration, members: ClassElement[] }>(); public static fromContext(context: TextChangesContext): ChangeTracker { return new ChangeTracker(context.newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed, context.formatContext); @@ -220,14 +223,14 @@ namespace ts.textChanges { public deleteNode(sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = {}) { const startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); const endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; } public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = {}) { const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); const endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; } @@ -245,6 +248,9 @@ namespace ts.textChanges { this.deleteNode(sourceFile, node); return this; } + const id = getNodeId(node); + Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); + this.deletedNodesInLists[id] = true; if (index !== containingList.length - 1) { const nextToken = getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { @@ -258,9 +264,17 @@ namespace ts.textChanges { } } else { - const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); + const prev = containingList[index - 1]; + if (this.deletedNodesInLists[getNodeId(prev)]) { + const pos = skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + const end = getAdjustedEndPosition(sourceFile, node, {}); + this.deleteRange(sourceFile, { pos, end }); + } + else { + const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); + if (previousToken && isSeparator(node, previousToken)) { + this.deleteNodeRange(sourceFile, previousToken, node); + } } } return this; @@ -305,40 +319,99 @@ namespace ts.textChanges { return this; } - public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray, options: ChangeMultipleNodesOptions) { - const startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - const endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray): void { + this.replaceWithMultiple(sourceFile, oldNode.getStart(sourceFile), oldNode.getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); } - public replaceNodesWithNodes(sourceFile: SourceFile, oldNodes: ReadonlyArray, newNodes: ReadonlyArray, options: ChangeMultipleNodesOptions) { - const startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); - const endPosition = getAdjustedEndPosition(sourceFile, lastOrUndefined(oldNodes), options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + public replaceNodesWithNodes(sourceFile: SourceFile, oldNodes: ReadonlyArray, newNodes: ReadonlyArray): void { + this.replaceWithMultiple(sourceFile, first(oldNodes).getStart(sourceFile), last(oldNodes).getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); } - public replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: ReadonlyArray, options: ChangeMultipleNodesOptions) { - return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); + private insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}) { + this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile, options, node: newNode, range: { pos, end: pos } }); + return this; } - public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options: ChangeMultipleNodesOptions) { - const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - const endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + public insertNodeAtTopOfFile(sourceFile: SourceFile, newNode: Statement, blankLineBetween: boolean): void { + const pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); } - public insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}) { - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile, options, node: newNode, range: { pos, end: pos } }); - return this; + public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false) { + const startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + } + + public changeIdentifierToPropertyAccess(sourceFile: SourceFile, prefix: string, node: Identifier): void { + const startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, createPropertyAccess(createIdentifier(prefix), ""), {}); + } + + private getOptionsForInsertNodeBefore(before: Node, doubleNewlines: boolean): ChangeNodeOptions { + if (isStatement(before) || isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2; + return { suffix: ", " }; + } + throw Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + } + + public insertNodeAtConstructorStart(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void { + const firstStatement = firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement, ...ctr.body.statements]); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + } + + public insertNodeAtConstructorEnd(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void { + const lastStatement = lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [...ctr.body.statements, newStatement]); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + } + + private replaceConstructorBody(sourceFile: SourceFile, ctr: ConstructorDeclaration, statements: ReadonlyArray): void { + this.replaceNode(sourceFile, ctr.body, createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + } + + public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void { + const startPosition = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, { + prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); } - public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, options: InsertNodeOptions & ConfigurableStart = {}) { - const startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); + public insertNodeAtClassStart(sourceFile: SourceFile, cls: ClassLikeDeclaration, newElement: ClassElement): void { + const firstMember = firstOrUndefined(cls.members); + if (!firstMember) { + const id = getNodeId(cls).toString(); + const newMembers = this.nodesInsertedAtClassStarts.get(id); + if (newMembers) { + Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); + newMembers.members.push(newElement); + } + else { + this.nodesInsertedAtClassStarts.set(id, { sourceFile, cls, members: [newElement] }); + } + } + else { + this.insertNodeBefore(sourceFile, firstMember, newElement); + } } - public insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node, options: InsertNodeOptions & ConfigurableEnd = {}) { - if ((isStatementButNotDeclaration(after)) || + public insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node): this { + if (isStatementButNotDeclaration(after) || after.kind === SyntaxKind.PropertyDeclaration || after.kind === SyntaxKind.PropertySignature || after.kind === SyntaxKind.MethodSignature) { @@ -354,8 +427,21 @@ namespace ts.textChanges { }); } } - const endPosition = getAdjustedEndPosition(sourceFile, after, options); - return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); + const endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, this.getInsertNodeAfterOptions(after)); + } + + private getInsertNodeAfterOptions(node: Node): InsertNodeOptions { + if (isClassDeclaration(node) || isModuleDeclaration(node)) { + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + } + else if (isStatement(node) || isClassElement(node) || isTypeElement(node)) { + return { suffix: this.newLineCharacter }; + } + else if (isVariableDeclaration(node)) { + return { prefix: ", " }; + } + throw Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it } /** @@ -502,7 +588,18 @@ namespace ts.textChanges { return this; } + private finishInsertNodeAtClassStart(): void { + this.nodesInsertedAtClassStarts.forEach(({ sourceFile, cls, members }) => { + const newCls = cls.kind === SyntaxKind.ClassDeclaration + ? updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) + : updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); + this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + }); + } + public getChanges(): FileTextChanges[] { + this.finishInsertNodeAtClassStart(); + const changesPerFile = createMap(); // group changes per file for (const c of this.changes) { @@ -751,4 +848,46 @@ namespace ts.textChanges { this.lastNonTriviaPosition = 0; } } + + function getInsertionPositionAtSourceFileTop({ text }: SourceFile): number { + const shebang = getShebang(text); + let position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + + // For a source file, it is possible there are detached comments we should not skip + let ranges = getLeadingCommentRanges(text, position); + if (!ranges) return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === SyntaxKind.MultiLineCommentTrivia && isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (const range of ranges) { + if (range.kind === SyntaxKind.SingleLineCommentTrivia && isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + + function advancePastLineBreak() { + if (position < text.length) { + const charCode = text.charCodeAt(position); + if (isLineBreak(charCode)) { + position++; + + if (position < text.length && charCode === CharacterCodes.carriageReturn && text.charCodeAt(position) === CharacterCodes.lineFeed) { + position++; + } + } + } + } + } } diff --git a/src/services/types.ts b/src/services/types.ts index e74b830cc45c9..597709a7c7919 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -181,6 +181,7 @@ namespace ts { */ readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; fileExists?(path: string): boolean; /* @@ -294,7 +295,11 @@ namespace ts { getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + // TODO: GH#20538 return `ReadonlyArray` + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + // TODO: GH#20538 + /* @internal */ + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -322,8 +327,13 @@ namespace ts { dispose(): void; } + // TODO: GH#20538 + /* @internal */ + export interface CombinedCodeFixScope { type: "file"; fileName: string; } + export interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } export interface ApplyCodeActionCommandResult { @@ -409,6 +419,23 @@ namespace ts { commands?: CodeActionCommand[]; } + // TODO: GH#20538 + /* @internal */ + export interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } + + // TODO: GH#20538 + /* @internal */ + export interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } + // Publicly, this type is just `{}`. Internally it is a union of all the actions we use. // See `commands?: {}[]` in protocol.ts export type CodeActionCommand = InstallPackageAction; @@ -571,6 +598,7 @@ namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } export interface FormatCodeSettings extends EditorSettings { @@ -589,6 +617,7 @@ namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } export interface DefinitionInfo { @@ -714,19 +743,22 @@ namespace ts { entries: CompletionEntry[]; } + // see comments in protocol.ts export interface CompletionEntry { name: string; kind: ScriptElementKind; - kindModifiers: string; // see ScriptElementKindModifier, comma separated + kindModifiers: string; // see ScriptElementKindModifier, comma separated sortText: string; + insertText?: string; /** - * An optional span that indicates the text to be replaced by this completion item. It will be - * set if the required span differs from the one generated by the default replacement behavior and should - * be used in that case + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; hasAction?: true; source?: string; + isRecommended?: true; } export interface CompletionEntryDetails { @@ -926,6 +958,7 @@ namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", + optionalModifier = "optional" } export const enum ClassificationTypeNames { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 98eaec59e6435..8fe12d29313ba 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -445,7 +445,7 @@ namespace ts { return position < candidate.end || !isCompletedNode(candidate, sourceFile); } - export function isCompletedNode(n: Node, sourceFile: SourceFile): boolean { + function isCompletedNode(n: Node, sourceFile: SourceFile): boolean { if (nodeIsMissing(n)) { return false; } @@ -512,7 +512,7 @@ namespace ts { case SyntaxKind.ExpressionStatement: return isCompletedNode((n).expression, sourceFile) || - hasChildOfKind(n, SyntaxKind.SemicolonToken); + hasChildOfKind(n, SyntaxKind.SemicolonToken, sourceFile); case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.ArrayBindingPattern: @@ -540,11 +540,9 @@ namespace ts { return isCompletedNode((n).statement, sourceFile); case SyntaxKind.DoStatement: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - const hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile); - } - return isCompletedNode((n).statement, sourceFile); + return hasChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile) + ? nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile) + : isCompletedNode((n).statement, sourceFile); case SyntaxKind.TypeQuery: return isCompletedNode((n).exprName, sourceFile); @@ -619,12 +617,12 @@ namespace ts { }; } - export function hasChildOfKind(n: Node, kind: SyntaxKind, sourceFile?: SourceFile): boolean { + export function hasChildOfKind(n: Node, kind: SyntaxKind, sourceFile: SourceFile): boolean { return !!findChildOfKind(n, kind, sourceFile); } - export function findChildOfKind(n: Node, kind: SyntaxKind, sourceFile?: SourceFileLike): Node | undefined { - return forEach(n.getChildren(sourceFile), c => c.kind === kind && c); + export function findChildOfKind(n: Node, kind: T["kind"], sourceFile: SourceFileLike): T | undefined { + return find(n.getChildren(sourceFile), (c): c is T => c.kind === kind); } export function findContainingList(node: Node): SyntaxList | undefined { @@ -1099,6 +1097,16 @@ namespace ts { return !seen[id] && (seen[id] = true); }; } + + /** Add a value to a set, and return true if it wasn't already present. */ + export function addToSeen(seen: Map, key: string | number): boolean { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } } // Display-part writer helpers @@ -1266,19 +1274,6 @@ namespace ts { }); } - export function getDeclaredName(typeChecker: TypeChecker, symbol: Symbol, location: Node): string { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || isStringOrNumericLiteral(location) && location.parent.kind === SyntaxKind.ComputedPropertyName) { - return getTextOfIdentifierOrLiteral(location); - } - - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - const localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - export function isImportOrExportSpecifierName(location: Node): location is Identifier { return location.parent && (location.parent.kind === SyntaxKind.ImportSpecifier || location.parent.kind === SyntaxKind.ExportSpecifier) && @@ -1292,12 +1287,16 @@ namespace ts { */ export function stripQuotes(name: string) { const length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } + export function startsWithQuote(name: string): boolean { + return isSingleOrDoubleQuote(name.charCodeAt(0)); + } + export function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean { const scriptKind = getScriptKind(fileName, host); return forEach(scriptKinds, k => k === scriptKind); @@ -1320,57 +1319,6 @@ namespace ts { return position; } - export function getOpenBrace(constructor: ConstructorDeclaration, sourceFile: SourceFile) { - // First token is the open curly, this is where we want to put the 'super' call. - return constructor.body.getFirstToken(sourceFile); - } - - export function getOpenBraceOfClassLike(declaration: ClassLikeDeclaration, sourceFile: SourceFile) { - return getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); - } - - export function getSourceFileImportLocation({ text }: SourceFile) { - const shebang = getShebang(text); - let position = 0; - if (shebang !== undefined) { - position = shebang.length; - advancePastLineBreak(); - } - - // For a source file, it is possible there are detached comments we should not skip - let ranges = getLeadingCommentRanges(text, position); - if (!ranges) return position; - // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === SyntaxKind.MultiLineCommentTrivia && isPinnedComment(text, ranges[0])) { - position = ranges[0].end; - advancePastLineBreak(); - ranges = ranges.slice(1); - } - // As well as any triple slash references - for (const range of ranges) { - if (range.kind === SyntaxKind.SingleLineCommentTrivia && isRecognizedTripleSlashComment(text, range.pos, range.end)) { - position = range.end; - advancePastLineBreak(); - continue; - } - break; - } - return position; - - function advancePastLineBreak() { - if (position < text.length) { - const charCode = text.charCodeAt(position); - if (isLineBreak(charCode)) { - position++; - - if (position < text.length && charCode === CharacterCodes.carriageReturn && text.charCodeAt(position) === CharacterCodes.lineFeed) { - position++; - } - } - } - } - } - /** * Creates a deep, memberwise clone of a node with no source map location. * diff --git a/tests/baselines/reference/ES5For-of31.types b/tests/baselines/reference/ES5For-of31.types index ee12f3894a8bb..309c8d1cab8c5 100644 --- a/tests/baselines/reference/ES5For-of31.types +++ b/tests/baselines/reference/ES5For-of31.types @@ -5,11 +5,11 @@ var a: string, b: number; for ({ a: b = 1, b: a = ""} of []) { >{ a: b = 1, b: a = ""} : { a?: number; b?: string; } ->a : undefined +>a : number >b = 1 : 1 >b : number >1 : 1 ->b : undefined +>b : string >a = "" : "" >a : string >"" : "" diff --git a/tests/baselines/reference/abstractPropertyNegative.errors.txt b/tests/baselines/reference/abstractPropertyNegative.errors.txt index 314ab842ded14..6e4cae81db9f9 100644 --- a/tests/baselines/reference/abstractPropertyNegative.errors.txt +++ b/tests/baselines/reference/abstractPropertyNegative.errors.txt @@ -7,15 +7,12 @@ tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstra tests/cases/compiler/abstractPropertyNegative.ts(15,5): error TS1244: Abstract methods can only appear within an abstract class. tests/cases/compiler/abstractPropertyNegative.ts(16,37): error TS1005: '{' expected. tests/cases/compiler/abstractPropertyNegative.ts(19,3): error TS2540: Cannot assign to 'ro' because it is a constant or a read-only property. -tests/cases/compiler/abstractPropertyNegative.ts(24,7): error TS2415: Class 'WrongTypePropertyImpl' incorrectly extends base class 'WrongTypeProperty'. - Types of property 'num' are incompatible. - Type 'string' is not assignable to type 'number'. -tests/cases/compiler/abstractPropertyNegative.ts(30,7): error TS2415: Class 'WrongTypeAccessorImpl' incorrectly extends base class 'WrongTypeAccessor'. - Types of property 'num' are incompatible. - Type 'string' is not assignable to type 'number'. -tests/cases/compiler/abstractPropertyNegative.ts(33,7): error TS2415: Class 'WrongTypeAccessorImpl2' incorrectly extends base class 'WrongTypeAccessor'. - Types of property 'num' are incompatible. - Type 'string' is not assignable to type 'number'. +tests/cases/compiler/abstractPropertyNegative.ts(25,5): error TS2416: Property 'num' in type 'WrongTypePropertyImpl' is not assignable to the same property in base type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/compiler/abstractPropertyNegative.ts(31,9): error TS2416: Property 'num' in type 'WrongTypeAccessorImpl' is not assignable to the same property in base type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/compiler/abstractPropertyNegative.ts(34,5): error TS2416: Property 'num' in type 'WrongTypeAccessorImpl2' is not assignable to the same property in base type 'number'. + Type 'string' is not assignable to type 'number'. tests/cases/compiler/abstractPropertyNegative.ts(38,18): error TS2676: Accessors must both be abstract or non-abstract. tests/cases/compiler/abstractPropertyNegative.ts(39,9): error TS2676: Accessors must both be abstract or non-abstract. tests/cases/compiler/abstractPropertyNegative.ts(40,9): error TS2676: Accessors must both be abstract or non-abstract. @@ -65,28 +62,25 @@ tests/cases/compiler/abstractPropertyNegative.ts(41,18): error TS2676: Accessors abstract num: number; } class WrongTypePropertyImpl extends WrongTypeProperty { - ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2415: Class 'WrongTypePropertyImpl' incorrectly extends base class 'WrongTypeProperty'. -!!! error TS2415: Types of property 'num' are incompatible. -!!! error TS2415: Type 'string' is not assignable to type 'number'. num = "nope, wrong"; + ~~~ +!!! error TS2416: Property 'num' in type 'WrongTypePropertyImpl' is not assignable to the same property in base type 'number'. +!!! error TS2416: Type 'string' is not assignable to type 'number'. } abstract class WrongTypeAccessor { abstract get num(): number; } class WrongTypeAccessorImpl extends WrongTypeAccessor { - ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2415: Class 'WrongTypeAccessorImpl' incorrectly extends base class 'WrongTypeAccessor'. -!!! error TS2415: Types of property 'num' are incompatible. -!!! error TS2415: Type 'string' is not assignable to type 'number'. get num() { return "nope, wrong"; } + ~~~ +!!! error TS2416: Property 'num' in type 'WrongTypeAccessorImpl' is not assignable to the same property in base type 'number'. +!!! error TS2416: Type 'string' is not assignable to type 'number'. } class WrongTypeAccessorImpl2 extends WrongTypeAccessor { - ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2415: Class 'WrongTypeAccessorImpl2' incorrectly extends base class 'WrongTypeAccessor'. -!!! error TS2415: Types of property 'num' are incompatible. -!!! error TS2415: Type 'string' is not assignable to type 'number'. num = "nope, wrong"; + ~~~ +!!! error TS2416: Property 'num' in type 'WrongTypeAccessorImpl2' is not assignable to the same property in base type 'number'. +!!! error TS2416: Type 'string' is not assignable to type 'number'. } abstract class AbstractAccessorMismatch { diff --git a/tests/baselines/reference/allowSyntheticDefaultImports1.js b/tests/baselines/reference/allowSyntheticDefaultImports1.js index fee1d13770630..8c5565a1fb723 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports1.js +++ b/tests/baselines/reference/allowSyntheticDefaultImports1.js @@ -4,21 +4,12 @@ import Namespace from "./b"; export var x = new Namespace.Foo(); -//// [b.ts] +//// [b.d.ts] export class Foo { member: string; } -//// [b.js] -"use strict"; -exports.__esModule = true; -var Foo = /** @class */ (function () { - function Foo() { - } - return Foo; -}()); -exports.Foo = Foo; //// [a.js] "use strict"; exports.__esModule = true; diff --git a/tests/baselines/reference/allowSyntheticDefaultImports1.symbols b/tests/baselines/reference/allowSyntheticDefaultImports1.symbols index ecbe9e4c2057a..5ee2812ab59c6 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports1.symbols +++ b/tests/baselines/reference/allowSyntheticDefaultImports1.symbols @@ -4,15 +4,15 @@ import Namespace from "./b"; export var x = new Namespace.Foo(); >x : Symbol(x, Decl(a.ts, 1, 10)) ->Namespace.Foo : Symbol(Namespace.Foo, Decl(b.ts, 0, 0)) +>Namespace.Foo : Symbol(Namespace.Foo, Decl(b.d.ts, 0, 0)) >Namespace : Symbol(Namespace, Decl(a.ts, 0, 6)) ->Foo : Symbol(Namespace.Foo, Decl(b.ts, 0, 0)) +>Foo : Symbol(Namespace.Foo, Decl(b.d.ts, 0, 0)) -=== tests/cases/compiler/b.ts === +=== tests/cases/compiler/b.d.ts === export class Foo { ->Foo : Symbol(Foo, Decl(b.ts, 0, 0)) +>Foo : Symbol(Foo, Decl(b.d.ts, 0, 0)) member: string; ->member : Symbol(Foo.member, Decl(b.ts, 0, 18)) +>member : Symbol(Foo.member, Decl(b.d.ts, 0, 18)) } diff --git a/tests/baselines/reference/allowSyntheticDefaultImports1.types b/tests/baselines/reference/allowSyntheticDefaultImports1.types index c2265d7611b38..c8092331a4784 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports1.types +++ b/tests/baselines/reference/allowSyntheticDefaultImports1.types @@ -9,7 +9,7 @@ export var x = new Namespace.Foo(); >Namespace : typeof Namespace >Foo : typeof Namespace.Foo -=== tests/cases/compiler/b.ts === +=== tests/cases/compiler/b.d.ts === export class Foo { >Foo : Foo diff --git a/tests/baselines/reference/allowSyntheticDefaultImports2.js b/tests/baselines/reference/allowSyntheticDefaultImports2.js index 5dc8472d58bc8..c1e43a4fc81e4 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports2.js +++ b/tests/baselines/reference/allowSyntheticDefaultImports2.js @@ -4,28 +4,11 @@ import Namespace from "./b"; export var x = new Namespace.Foo(); -//// [b.ts] +//// [b.d.ts] export class Foo { member: string; } -//// [b.js] -System.register([], function (exports_1, context_1) { - "use strict"; - var __moduleName = context_1 && context_1.id; - var Foo; - return { - setters: [], - execute: function () { - Foo = /** @class */ (function () { - function Foo() { - } - return Foo; - }()); - exports_1("Foo", Foo); - } - }; -}); //// [a.js] System.register(["./b"], function (exports_1, context_1) { "use strict"; diff --git a/tests/baselines/reference/allowSyntheticDefaultImports2.symbols b/tests/baselines/reference/allowSyntheticDefaultImports2.symbols index 615b1095c66c3..a2b33c94d82a5 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports2.symbols +++ b/tests/baselines/reference/allowSyntheticDefaultImports2.symbols @@ -4,14 +4,14 @@ import Namespace from "./b"; export var x = new Namespace.Foo(); >x : Symbol(x, Decl(a.ts, 1, 10)) ->Namespace.Foo : Symbol(Namespace.Foo, Decl(b.ts, 0, 0)) +>Namespace.Foo : Symbol(Namespace.Foo, Decl(b.d.ts, 0, 0)) >Namespace : Symbol(Namespace, Decl(a.ts, 0, 6)) ->Foo : Symbol(Namespace.Foo, Decl(b.ts, 0, 0)) +>Foo : Symbol(Namespace.Foo, Decl(b.d.ts, 0, 0)) -=== tests/cases/compiler/b.ts === +=== tests/cases/compiler/b.d.ts === export class Foo { ->Foo : Symbol(Foo, Decl(b.ts, 0, 0)) +>Foo : Symbol(Foo, Decl(b.d.ts, 0, 0)) member: string; ->member : Symbol(Foo.member, Decl(b.ts, 0, 18)) +>member : Symbol(Foo.member, Decl(b.d.ts, 0, 18)) } diff --git a/tests/baselines/reference/allowSyntheticDefaultImports2.types b/tests/baselines/reference/allowSyntheticDefaultImports2.types index c40fbc7e98859..420c19b7c1dd7 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports2.types +++ b/tests/baselines/reference/allowSyntheticDefaultImports2.types @@ -9,7 +9,7 @@ export var x = new Namespace.Foo(); >Namespace : typeof Namespace >Foo : typeof Namespace.Foo -=== tests/cases/compiler/b.ts === +=== tests/cases/compiler/b.d.ts === export class Foo { >Foo : Foo diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 546e57ffed3cd..3eabea4435a54 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -453,6 +454,9 @@ declare namespace ts { interface JSDocContainer { } type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -604,15 +608,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends NamedDeclaration { - propertyName?: PropertyName; - dotDotDotToken?: DotDotDotToken; - name: DeclarationName; - questionToken?: QuestionToken; - exclamationToken?: ExclamationToken; - type?: TypeNode; - initializer?: Expression; - } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -660,30 +656,30 @@ declare namespace ts { } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; + parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -1280,7 +1276,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression; + parent?: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1622,7 +1618,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -2073,6 +2069,7 @@ declare namespace ts { EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, ContainsSpread = 1024, + ReverseMapped = 2048, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2301,6 +2298,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2358,8 +2356,9 @@ declare namespace ts { ES2015 = 2, ES2016 = 3, ES2017 = 4, - ESNext = 5, - Latest = 5, + ES2018 = 5, + ESNext = 6, + Latest = 6, } enum LanguageVariant { Standard = 0, @@ -2473,11 +2472,11 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; } interface SourceMapRange extends TextRange { @@ -2764,6 +2763,7 @@ declare namespace ts { realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; + clearScreen?(): void; } interface FileWatcher { close(): void; @@ -2916,7 +2916,7 @@ declare namespace ts { function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; - function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; @@ -3108,6 +3108,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; @@ -3130,7 +3131,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -3775,7 +3776,7 @@ declare namespace ts { } } declare namespace ts { - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -3925,6 +3926,7 @@ declare namespace ts { useCaseSensitiveFileNames?(): boolean; readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; @@ -3983,7 +3985,7 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4001,6 +4003,7 @@ declare namespace ts { } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4211,6 +4214,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4228,6 +4232,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4343,14 +4348,16 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: string; /** - * An optional span that indicates the text to be replaced by this completion item. It will be - * set if the required span differs from the one generated by the default replacement behavior and should - * be used in that case + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; hasAction?: true; source?: string; + isRecommended?: true; } interface CompletionEntryDetails { name: string; @@ -4508,6 +4515,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", + optionalModifier = "optional", } enum ClassificationTypeNames { comment = "comment", @@ -4903,6 +4911,7 @@ declare namespace ts.server.protocol { Rename = "rename", Saveto = "saveto", SignatureHelp = "signatureHelp", + Status = "status", TypeDefinition = "typeDefinition", ProjectInfo = "projectInfo", ReloadProjects = "reloadProjects", @@ -5004,6 +5013,21 @@ declare namespace ts.server.protocol { file: string; projectFileName?: string; } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } /** * Requests a JS Doc comment template for a given position */ @@ -5293,7 +5317,7 @@ declare namespace ts.server.protocol { /** * Errorcodes we want to get the fixes for. */ - errorCodes?: number[]; + errorCodes?: ReadonlyArray; } interface ApplyCodeActionCommandRequestArgs { /** May also be an array of commands. */ @@ -6088,6 +6112,11 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ includeExternalModuleExports: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + includeInsertTextCompletions: boolean; } /** * Completions request; value of command field is "completions". @@ -6157,8 +6186,15 @@ declare namespace ts.server.protocol { */ sortText: string; /** - * An optional span that indicates the text to be replaced by this completion item. If present, - * this span should be used instead of the default one. + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; /** @@ -6170,6 +6206,12 @@ declare namespace ts.server.protocol { * Identifier (not necessarily human-readable) identifying where this completion came from. */ source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; } /** * Additional completion entry details, available on demand @@ -6822,6 +6864,7 @@ declare namespace ts.server.protocol { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -7064,10 +7107,12 @@ declare namespace ts.server { private getApplicableRefactors(args); private getEditsForRefactor(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); - private applyCodeActionCommand(commandName, requestSeq, args); + private getCombinedCodeFix({scope, fixId}, simplifiedResult); + private applyCodeActionCommand(args); private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction({description, changes: unmappedChanges, commands}, scriptInfo); + private mapCodeAction(project, {description, changes: unmappedChanges, commands}); private mapTextChangesToCodeEdits(project, textChanges); + private mapTextChangesToCodeEditsUsingScriptinfo(textChanges, scriptInfo); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); private getDiagnosticsForProject(next, delay, fileName); @@ -7208,6 +7253,7 @@ declare namespace ts.server { private program; private externalFiles; private missingFilesMap; + private plugins; private cachedUnresolvedImportsPerFile; private lastCachedUnresolvedImportsList; protected languageService: LanguageService; @@ -7286,6 +7332,7 @@ declare namespace ts.server { disableLanguageService(): void; getProjectName(): string; abstract getTypeAcquisition(): TypeAcquisition; + protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; close(): void; @@ -7306,12 +7353,12 @@ declare namespace ts.server { removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; registerFileUpdate(fileName: string): void; markAsDirty(): void; - private extractUnresolvedImportsFromSourceFile(file, result); /** * Updates set of files that contribute to this project * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph(): boolean; + protected removeExistingTypings(include: string[]): string[]; private setTypings(typings); private updateGraphWorker(); private detachScriptInfoFromProject(uncheckedFileName); @@ -7322,6 +7369,9 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; + protected enableGlobalPlugins(): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + private enableProxy(pluginModuleFactory, configEntry); } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -7350,7 +7400,6 @@ declare namespace ts.server { private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; - private plugins; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; @@ -7361,8 +7410,6 @@ declare namespace ts.server { updateGraph(): boolean; getConfigFilePath(): NormalizedPath; enablePlugins(): void; - private enablePlugin(pluginConfigEntry, searchPaths); - private enableProxy(pluginModuleFactory, configEntry); /** * Get the errors that dont have any file name associated */ @@ -7374,7 +7421,6 @@ declare namespace ts.server { setProjectErrors(projectErrors: Diagnostic[]): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; getTypeAcquisition(): TypeAcquisition; - getExternalFiles(): SortedReadonlyArray; close(): void; getEffectiveTypeRoots(): string[]; } diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index d4036d5a02b2b..630b7a08a28db 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -453,6 +454,9 @@ declare namespace ts { interface JSDocContainer { } type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -604,15 +608,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends NamedDeclaration { - propertyName?: PropertyName; - dotDotDotToken?: DotDotDotToken; - name: DeclarationName; - questionToken?: QuestionToken; - exclamationToken?: ExclamationToken; - type?: TypeNode; - initializer?: Expression; - } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -660,30 +656,30 @@ declare namespace ts { } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; + parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -1280,7 +1276,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression; + parent?: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1622,7 +1618,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -2073,6 +2069,7 @@ declare namespace ts { EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, ContainsSpread = 1024, + ReverseMapped = 2048, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2301,6 +2298,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2358,8 +2356,9 @@ declare namespace ts { ES2015 = 2, ES2016 = 3, ES2017 = 4, - ESNext = 5, - Latest = 5, + ES2018 = 5, + ESNext = 6, + Latest = 6, } enum LanguageVariant { Standard = 0, @@ -2473,11 +2472,11 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; } interface SourceMapRange extends TextRange { @@ -2764,6 +2763,7 @@ declare namespace ts { realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; + clearScreen?(): void; } interface FileWatcher { close(): void; @@ -2792,7 +2792,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -2969,7 +2969,7 @@ declare namespace ts { function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; - function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; @@ -3161,6 +3161,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3722,7 +3723,7 @@ declare namespace ts { } } declare namespace ts { - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -3925,6 +3926,7 @@ declare namespace ts { useCaseSensitiveFileNames?(): boolean; readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; @@ -3983,7 +3985,7 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4001,6 +4003,7 @@ declare namespace ts { } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4211,6 +4214,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4228,6 +4232,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4343,14 +4348,16 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: string; /** - * An optional span that indicates the text to be replaced by this completion item. It will be - * set if the required span differs from the one generated by the default replacement behavior and should - * be used in that case + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. */ replacementSpan?: TextSpan; hasAction?: true; source?: string; + isRecommended?: true; } interface CompletionEntryDetails { name: string; @@ -4508,6 +4515,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", + optionalModifier = "optional", } enum ClassificationTypeNames { comment = "comment", diff --git a/tests/baselines/reference/apparentTypeSubtyping.errors.txt b/tests/baselines/reference/apparentTypeSubtyping.errors.txt index 01fffeb382494..cde65657778c6 100644 --- a/tests/baselines/reference/apparentTypeSubtyping.errors.txt +++ b/tests/baselines/reference/apparentTypeSubtyping.errors.txt @@ -1,7 +1,6 @@ -tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts(9,7): error TS2415: Class 'Derived' incorrectly extends base class 'Base'. - Types of property 'x' are incompatible. - Type 'String' is not assignable to type 'string'. - 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. +tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts(10,5): error TS2416: Property 'x' in type 'Derived' is not assignable to the same property in base type 'string'. + Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. ==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts (1 errors) ==== @@ -14,12 +13,11 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtypi // is String (S) a subtype of U extends String (T)? Would only be true if we used the apparent type of U (T) class Derived extends Base { // error - ~~~~~~~ -!!! error TS2415: Class 'Derived' incorrectly extends base class 'Base'. -!!! error TS2415: Types of property 'x' are incompatible. -!!! error TS2415: Type 'String' is not assignable to type 'string'. -!!! error TS2415: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. x: String; + ~ +!!! error TS2416: Property 'x' in type 'Derived' is not assignable to the same property in base type 'string'. +!!! error TS2416: Type 'String' is not assignable to type 'string'. +!!! error TS2416: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. } class Base2 { diff --git a/tests/baselines/reference/apparentTypeSupertype.errors.txt b/tests/baselines/reference/apparentTypeSupertype.errors.txt index c7610a80f2f37..066d0be2710fe 100644 --- a/tests/baselines/reference/apparentTypeSupertype.errors.txt +++ b/tests/baselines/reference/apparentTypeSupertype.errors.txt @@ -1,8 +1,7 @@ -tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts(9,7): error TS2415: Class 'Derived' incorrectly extends base class 'Base'. - Types of property 'x' are incompatible. - Type 'U' is not assignable to type 'string'. - Type 'String' is not assignable to type 'string'. - 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. +tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts(10,5): error TS2416: Property 'x' in type 'Derived' is not assignable to the same property in base type 'string'. + Type 'U' is not assignable to type 'string'. + Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. ==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts (1 errors) ==== @@ -15,11 +14,10 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty // is String (S) a subtype of U extends String (T)? Would only be true if we used the apparent type of U (T) class Derived extends Base { // error - ~~~~~~~ -!!! error TS2415: Class 'Derived' incorrectly extends base class 'Base'. -!!! error TS2415: Types of property 'x' are incompatible. -!!! error TS2415: Type 'U' is not assignable to type 'string'. -!!! error TS2415: Type 'String' is not assignable to type 'string'. -!!! error TS2415: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. x: U; + ~ +!!! error TS2416: Property 'x' in type 'Derived' is not assignable to the same property in base type 'string'. +!!! error TS2416: Type 'U' is not assignable to type 'string'. +!!! error TS2416: Type 'String' is not assignable to type 'string'. +!!! error TS2416: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. } \ No newline at end of file diff --git a/tests/baselines/reference/argumentExpressionContextualTyping.types b/tests/baselines/reference/argumentExpressionContextualTyping.types index 3b0fec11aa2cf..01320b302e61d 100644 --- a/tests/baselines/reference/argumentExpressionContextualTyping.types +++ b/tests/baselines/reference/argumentExpressionContextualTyping.types @@ -51,13 +51,13 @@ var o1: { x: [string, number], y: { c: boolean, d: string, e: number } } = { x: >c : boolean >d : string >e : number ->{ x: ["string", 1], y: { c: true, d: "world", e: 3 } } : { x: [string, number]; y: { c: true; d: string; e: number; }; } +>{ x: ["string", 1], y: { c: true, d: "world", e: 3 } } : { x: [string, number]; y: { c: boolean; d: string; e: number; }; } >x : [string, number] >["string", 1] : [string, number] >"string" : "string" >1 : 1 ->y : { c: true; d: string; e: number; } ->{ c: true, d: "world", e: 3 } : { c: true; d: string; e: number; } +>y : { c: boolean; d: string; e: number; } +>{ c: true, d: "world", e: 3 } : { c: boolean; d: string; e: number; } >c : boolean >true : true >d : string @@ -96,7 +96,7 @@ var array = ["string", 1, true]; var tuple: [string, number, boolean] = ["string", 1, true]; >tuple : [string, number, boolean] ->["string", 1, true] : [string, number, true] +>["string", 1, true] : [string, number, boolean] >"string" : "string" >1 : 1 >true : true @@ -109,7 +109,7 @@ baz(tuple); baz(["string", 1, true]); >baz(["string", 1, true]) : void >baz : (x: [string, number, boolean]) => void ->["string", 1, true] : [string, number, true] +>["string", 1, true] : [string, number, boolean] >"string" : "string" >1 : 1 >true : true diff --git a/tests/baselines/reference/arrayBestCommonTypes.types b/tests/baselines/reference/arrayBestCommonTypes.types index 864b1adfacba6..8d98b90ee314c 100644 --- a/tests/baselines/reference/arrayBestCommonTypes.types +++ b/tests/baselines/reference/arrayBestCommonTypes.types @@ -255,14 +255,14 @@ module EmptyTypes { >x : boolean >y : base >base : base ->[{ x: true, y: new derived() }, { x: false, y: new base() }] : ({ x: true; y: derived; } | { x: false; y: base; })[] ->{ x: true, y: new derived() } : { x: true; y: derived; } +>[{ x: true, y: new derived() }, { x: false, y: new base() }] : { x: boolean; y: derived; }[] +>{ x: true, y: new derived() } : { x: boolean; y: derived; } >x : boolean >true : true >y : derived >new derived() : derived >derived : typeof derived ->{ x: false, y: new base() } : { x: false; y: base; } +>{ x: false, y: new base() } : { x: boolean; y: base; } >x : boolean >false : false >y : base @@ -658,14 +658,14 @@ module NonEmptyTypes { >x : boolean >y : base >base : base ->[{ x: true, y: new derived() }, { x: false, y: new base() }] : ({ x: true; y: derived; } | { x: false; y: base; })[] ->{ x: true, y: new derived() } : { x: true; y: derived; } +>[{ x: true, y: new derived() }, { x: false, y: new base() }] : { x: boolean; y: base; }[] +>{ x: true, y: new derived() } : { x: boolean; y: derived; } >x : boolean >true : true >y : derived >new derived() : derived >derived : typeof derived ->{ x: false, y: new base() } : { x: false; y: base; } +>{ x: false, y: new base() } : { x: boolean; y: base; } >x : boolean >false : false >y : base diff --git a/tests/baselines/reference/arrayConcat2.types b/tests/baselines/reference/arrayConcat2.types index b63f33eb7b117..2e33d4cd023b3 100644 --- a/tests/baselines/reference/arrayConcat2.types +++ b/tests/baselines/reference/arrayConcat2.types @@ -5,17 +5,17 @@ var a: string[] = []; a.concat("hello", 'world'); >a.concat("hello", 'world') : string[] ->a.concat : { (...items: ReadonlyArray[]): string[]; (...items: (string | ReadonlyArray)[]): string[]; } +>a.concat : { (...items: (string[] | ReadonlyArray)[]): string[]; (...items: (string | string[] | ReadonlyArray)[]): string[]; } >a : string[] ->concat : { (...items: ReadonlyArray[]): string[]; (...items: (string | ReadonlyArray)[]): string[]; } +>concat : { (...items: (string[] | ReadonlyArray)[]): string[]; (...items: (string | string[] | ReadonlyArray)[]): string[]; } >"hello" : "hello" >'world' : "world" a.concat('Hello'); >a.concat('Hello') : string[] ->a.concat : { (...items: ReadonlyArray[]): string[]; (...items: (string | ReadonlyArray)[]): string[]; } +>a.concat : { (...items: (string[] | ReadonlyArray)[]): string[]; (...items: (string | string[] | ReadonlyArray)[]): string[]; } >a : string[] ->concat : { (...items: ReadonlyArray[]): string[]; (...items: (string | ReadonlyArray)[]): string[]; } +>concat : { (...items: (string[] | ReadonlyArray)[]): string[]; (...items: (string | string[] | ReadonlyArray)[]): string[]; } >'Hello' : "Hello" var b = new Array(); @@ -25,8 +25,8 @@ var b = new Array(); b.concat('hello'); >b.concat('hello') : string[] ->b.concat : { (...items: ReadonlyArray[]): string[]; (...items: (string | ReadonlyArray)[]): string[]; } +>b.concat : { (...items: (string[] | ReadonlyArray)[]): string[]; (...items: (string | string[] | ReadonlyArray)[]): string[]; } >b : string[] ->concat : { (...items: ReadonlyArray[]): string[]; (...items: (string | ReadonlyArray)[]): string[]; } +>concat : { (...items: (string[] | ReadonlyArray)[]): string[]; (...items: (string | string[] | ReadonlyArray)[]): string[]; } >'hello' : "hello" diff --git a/tests/baselines/reference/arrayConcat3.js b/tests/baselines/reference/arrayConcat3.js new file mode 100644 index 0000000000000..90226797706e2 --- /dev/null +++ b/tests/baselines/reference/arrayConcat3.js @@ -0,0 +1,12 @@ +//// [arrayConcat3.ts] +// TODO: remove lib hack when https://github.com/Microsoft/TypeScript/issues/20454 is fixed +type Fn = (subj: U) => U +function doStuff(a: Array>, b: Array>) { + b.concat(a); +} + + +//// [arrayConcat3.js] +function doStuff(a, b) { + b.concat(a); +} diff --git a/tests/baselines/reference/arrayConcat3.symbols b/tests/baselines/reference/arrayConcat3.symbols new file mode 100644 index 0000000000000..373c8d7041b84 --- /dev/null +++ b/tests/baselines/reference/arrayConcat3.symbols @@ -0,0 +1,32 @@ +=== tests/cases/compiler/arrayConcat3.ts === +// TODO: remove lib hack when https://github.com/Microsoft/TypeScript/issues/20454 is fixed +type Fn = (subj: U) => U +>Fn : Symbol(Fn, Decl(arrayConcat3.ts, 0, 0)) +>T : Symbol(T, Decl(arrayConcat3.ts, 1, 8)) +>U : Symbol(U, Decl(arrayConcat3.ts, 1, 29)) +>T : Symbol(T, Decl(arrayConcat3.ts, 1, 8)) +>subj : Symbol(subj, Decl(arrayConcat3.ts, 1, 42)) +>U : Symbol(U, Decl(arrayConcat3.ts, 1, 29)) +>U : Symbol(U, Decl(arrayConcat3.ts, 1, 29)) + +function doStuff(a: Array>, b: Array>) { +>doStuff : Symbol(doStuff, Decl(arrayConcat3.ts, 1, 55)) +>T : Symbol(T, Decl(arrayConcat3.ts, 2, 17)) +>T1 : Symbol(T1, Decl(arrayConcat3.ts, 2, 34)) +>T : Symbol(T, Decl(arrayConcat3.ts, 2, 17)) +>a : Symbol(a, Decl(arrayConcat3.ts, 2, 49)) +>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>Fn : Symbol(Fn, Decl(arrayConcat3.ts, 0, 0)) +>T : Symbol(T, Decl(arrayConcat3.ts, 2, 17)) +>b : Symbol(b, Decl(arrayConcat3.ts, 2, 65)) +>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>Fn : Symbol(Fn, Decl(arrayConcat3.ts, 0, 0)) +>T1 : Symbol(T1, Decl(arrayConcat3.ts, 2, 34)) + + b.concat(a); +>b.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>b : Symbol(b, Decl(arrayConcat3.ts, 2, 65)) +>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>a : Symbol(a, Decl(arrayConcat3.ts, 2, 49)) +} + diff --git a/tests/baselines/reference/arrayConcat3.types b/tests/baselines/reference/arrayConcat3.types new file mode 100644 index 0000000000000..2bfbe09a1765d --- /dev/null +++ b/tests/baselines/reference/arrayConcat3.types @@ -0,0 +1,33 @@ +=== tests/cases/compiler/arrayConcat3.ts === +// TODO: remove lib hack when https://github.com/Microsoft/TypeScript/issues/20454 is fixed +type Fn = (subj: U) => U +>Fn : Fn +>T : T +>U : U +>T : T +>subj : U +>U : U +>U : U + +function doStuff(a: Array>, b: Array>) { +>doStuff : (a: Fn[], b: Fn[]) => void +>T : T +>T1 : T1 +>T : T +>a : Fn[] +>Array : T[] +>Fn : Fn +>T : T +>b : Fn[] +>Array : T[] +>Fn : Fn +>T1 : T1 + + b.concat(a); +>b.concat(a) : Fn[] +>b.concat : { (...items: (Fn[] | ReadonlyArray>)[]): Fn[]; (...items: (Fn | Fn[] | ReadonlyArray>)[]): Fn[]; } +>b : Fn[] +>concat : { (...items: (Fn[] | ReadonlyArray>)[]): Fn[]; (...items: (Fn | Fn[] | ReadonlyArray>)[]): Fn[]; } +>a : Fn[] +} + diff --git a/tests/baselines/reference/arrayConcatMap.types b/tests/baselines/reference/arrayConcatMap.types index db5b3774db0b2..cbb30b8304ad6 100644 --- a/tests/baselines/reference/arrayConcatMap.types +++ b/tests/baselines/reference/arrayConcatMap.types @@ -4,9 +4,9 @@ var x = [].concat([{ a: 1 }], [{ a: 2 }]) >[].concat([{ a: 1 }], [{ a: 2 }]) .map(b => b.a) : any[] >[].concat([{ a: 1 }], [{ a: 2 }]) .map : (callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any) => U[] >[].concat([{ a: 1 }], [{ a: 2 }]) : any[] ->[].concat : { (...items: ReadonlyArray[]): any[]; (...items: any[]): any[]; } +>[].concat : { (...items: (any[] | ReadonlyArray)[]): any[]; (...items: any[]): any[]; } >[] : undefined[] ->concat : { (...items: ReadonlyArray[]): any[]; (...items: any[]): any[]; } +>concat : { (...items: (any[] | ReadonlyArray)[]): any[]; (...items: any[]): any[]; } >[{ a: 1 }] : { a: number; }[] >{ a: 1 } : { a: number; } >a : number diff --git a/tests/baselines/reference/arrayFrom.errors.txt b/tests/baselines/reference/arrayFrom.errors.txt new file mode 100644 index 0000000000000..896125ee1ce1d --- /dev/null +++ b/tests/baselines/reference/arrayFrom.errors.txt @@ -0,0 +1,46 @@ +tests/cases/compiler/arrayFrom.ts(19,7): error TS2322: Type 'A[]' is not assignable to type 'B[]'. + Type 'A' is not assignable to type 'B'. + Property 'b' is missing in type 'A'. +tests/cases/compiler/arrayFrom.ts(22,7): error TS2322: Type 'A[]' is not assignable to type 'B[]'. + + +==== tests/cases/compiler/arrayFrom.ts (2 errors) ==== + // Tests fix for #20432, ensures Array.from accepts all valid inputs + // Also tests for #19682 + + interface A { + a: string; + } + + interface B { + b: string; + } + + const inputA: A[] = []; + const inputB: B[] = []; + const inputALike: ArrayLike = { length: 0 }; + const inputARand = getEither(inputA, inputALike); + + const result1: A[] = Array.from(inputA); + const result2: A[] = Array.from(inputA.values()); + const result3: B[] = Array.from(inputA.values()); // expect error + ~~~~~~~ +!!! error TS2322: Type 'A[]' is not assignable to type 'B[]'. +!!! error TS2322: Type 'A' is not assignable to type 'B'. +!!! error TS2322: Property 'b' is missing in type 'A'. + const result4: A[] = Array.from(inputB, ({ b }): A => ({ a: b })); + const result5: A[] = Array.from(inputALike); + const result6: B[] = Array.from(inputALike); // expect error + ~~~~~~~ +!!! error TS2322: Type 'A[]' is not assignable to type 'B[]'. + const result7: B[] = Array.from(inputALike, ({ a }): B => ({ b: a })); + const result8: A[] = Array.from(inputARand); + const result9: B[] = Array.from(inputARand, ({ a }): B => ({ b: a })); + + // if this is written inline, the compiler seems to infer + // the ?: as always taking the false branch, narrowing to ArrayLike, + // even when the type is written as : Iterable|ArrayLike + function getEither (in1: Iterable, in2: ArrayLike) { + return Math.random() > 0.5 ? in1 : in2; + } + \ No newline at end of file diff --git a/tests/baselines/reference/arrayFrom.js b/tests/baselines/reference/arrayFrom.js new file mode 100644 index 0000000000000..b9b7ff7526805 --- /dev/null +++ b/tests/baselines/reference/arrayFrom.js @@ -0,0 +1,66 @@ +//// [arrayFrom.ts] +// Tests fix for #20432, ensures Array.from accepts all valid inputs +// Also tests for #19682 + +interface A { + a: string; +} + +interface B { + b: string; +} + +const inputA: A[] = []; +const inputB: B[] = []; +const inputALike: ArrayLike = { length: 0 }; +const inputARand = getEither(inputA, inputALike); + +const result1: A[] = Array.from(inputA); +const result2: A[] = Array.from(inputA.values()); +const result3: B[] = Array.from(inputA.values()); // expect error +const result4: A[] = Array.from(inputB, ({ b }): A => ({ a: b })); +const result5: A[] = Array.from(inputALike); +const result6: B[] = Array.from(inputALike); // expect error +const result7: B[] = Array.from(inputALike, ({ a }): B => ({ b: a })); +const result8: A[] = Array.from(inputARand); +const result9: B[] = Array.from(inputARand, ({ a }): B => ({ b: a })); + +// if this is written inline, the compiler seems to infer +// the ?: as always taking the false branch, narrowing to ArrayLike, +// even when the type is written as : Iterable|ArrayLike +function getEither (in1: Iterable, in2: ArrayLike) { + return Math.random() > 0.5 ? in1 : in2; +} + + +//// [arrayFrom.js] +// Tests fix for #20432, ensures Array.from accepts all valid inputs +// Also tests for #19682 +var inputA = []; +var inputB = []; +var inputALike = { length: 0 }; +var inputARand = getEither(inputA, inputALike); +var result1 = Array.from(inputA); +var result2 = Array.from(inputA.values()); +var result3 = Array.from(inputA.values()); // expect error +var result4 = Array.from(inputB, function (_a) { + var b = _a.b; + return ({ a: b }); +}); +var result5 = Array.from(inputALike); +var result6 = Array.from(inputALike); // expect error +var result7 = Array.from(inputALike, function (_a) { + var a = _a.a; + return ({ b: a }); +}); +var result8 = Array.from(inputARand); +var result9 = Array.from(inputARand, function (_a) { + var a = _a.a; + return ({ b: a }); +}); +// if this is written inline, the compiler seems to infer +// the ?: as always taking the false branch, narrowing to ArrayLike, +// even when the type is written as : Iterable|ArrayLike +function getEither(in1, in2) { + return Math.random() > 0.5 ? in1 : in2; +} diff --git a/tests/baselines/reference/arrayFrom.symbols b/tests/baselines/reference/arrayFrom.symbols new file mode 100644 index 0000000000000..4a68122739f41 --- /dev/null +++ b/tests/baselines/reference/arrayFrom.symbols @@ -0,0 +1,147 @@ +=== tests/cases/compiler/arrayFrom.ts === +// Tests fix for #20432, ensures Array.from accepts all valid inputs +// Also tests for #19682 + +interface A { +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) + + a: string; +>a : Symbol(A.a, Decl(arrayFrom.ts, 3, 13)) +} + +interface B { +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) + + b: string; +>b : Symbol(B.b, Decl(arrayFrom.ts, 7, 13)) +} + +const inputA: A[] = []; +>inputA : Symbol(inputA, Decl(arrayFrom.ts, 11, 5)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) + +const inputB: B[] = []; +>inputB : Symbol(inputB, Decl(arrayFrom.ts, 12, 5)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) + +const inputALike: ArrayLike = { length: 0 }; +>inputALike : Symbol(inputALike, Decl(arrayFrom.ts, 13, 5)) +>ArrayLike : Symbol(ArrayLike, Decl(lib.es5.d.ts, --, --)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>length : Symbol(length, Decl(arrayFrom.ts, 13, 34)) + +const inputARand = getEither(inputA, inputALike); +>inputARand : Symbol(inputARand, Decl(arrayFrom.ts, 14, 5)) +>getEither : Symbol(getEither, Decl(arrayFrom.ts, 24, 70)) +>inputA : Symbol(inputA, Decl(arrayFrom.ts, 11, 5)) +>inputALike : Symbol(inputALike, Decl(arrayFrom.ts, 13, 5)) + +const result1: A[] = Array.from(inputA); +>result1 : Symbol(result1, Decl(arrayFrom.ts, 16, 5)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputA : Symbol(inputA, Decl(arrayFrom.ts, 11, 5)) + +const result2: A[] = Array.from(inputA.values()); +>result2 : Symbol(result2, Decl(arrayFrom.ts, 17, 5)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputA.values : Symbol(Array.values, Decl(lib.es2015.iterable.d.ts, --, --)) +>inputA : Symbol(inputA, Decl(arrayFrom.ts, 11, 5)) +>values : Symbol(Array.values, Decl(lib.es2015.iterable.d.ts, --, --)) + +const result3: B[] = Array.from(inputA.values()); // expect error +>result3 : Symbol(result3, Decl(arrayFrom.ts, 18, 5)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputA.values : Symbol(Array.values, Decl(lib.es2015.iterable.d.ts, --, --)) +>inputA : Symbol(inputA, Decl(arrayFrom.ts, 11, 5)) +>values : Symbol(Array.values, Decl(lib.es2015.iterable.d.ts, --, --)) + +const result4: A[] = Array.from(inputB, ({ b }): A => ({ a: b })); +>result4 : Symbol(result4, Decl(arrayFrom.ts, 19, 5)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputB : Symbol(inputB, Decl(arrayFrom.ts, 12, 5)) +>b : Symbol(b, Decl(arrayFrom.ts, 19, 42)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>a : Symbol(a, Decl(arrayFrom.ts, 19, 56)) +>b : Symbol(b, Decl(arrayFrom.ts, 19, 42)) + +const result5: A[] = Array.from(inputALike); +>result5 : Symbol(result5, Decl(arrayFrom.ts, 20, 5)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputALike : Symbol(inputALike, Decl(arrayFrom.ts, 13, 5)) + +const result6: B[] = Array.from(inputALike); // expect error +>result6 : Symbol(result6, Decl(arrayFrom.ts, 21, 5)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputALike : Symbol(inputALike, Decl(arrayFrom.ts, 13, 5)) + +const result7: B[] = Array.from(inputALike, ({ a }): B => ({ b: a })); +>result7 : Symbol(result7, Decl(arrayFrom.ts, 22, 5)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputALike : Symbol(inputALike, Decl(arrayFrom.ts, 13, 5)) +>a : Symbol(a, Decl(arrayFrom.ts, 22, 46)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) +>b : Symbol(b, Decl(arrayFrom.ts, 22, 60)) +>a : Symbol(a, Decl(arrayFrom.ts, 22, 46)) + +const result8: A[] = Array.from(inputARand); +>result8 : Symbol(result8, Decl(arrayFrom.ts, 23, 5)) +>A : Symbol(A, Decl(arrayFrom.ts, 0, 0)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputARand : Symbol(inputARand, Decl(arrayFrom.ts, 14, 5)) + +const result9: B[] = Array.from(inputARand, ({ a }): B => ({ b: a })); +>result9 : Symbol(result9, Decl(arrayFrom.ts, 24, 5)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) +>Array.from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>from : Symbol(ArrayConstructor.from, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>inputARand : Symbol(inputARand, Decl(arrayFrom.ts, 14, 5)) +>a : Symbol(a, Decl(arrayFrom.ts, 24, 46)) +>B : Symbol(B, Decl(arrayFrom.ts, 5, 1)) +>b : Symbol(b, Decl(arrayFrom.ts, 24, 60)) +>a : Symbol(a, Decl(arrayFrom.ts, 24, 46)) + +// if this is written inline, the compiler seems to infer +// the ?: as always taking the false branch, narrowing to ArrayLike, +// even when the type is written as : Iterable|ArrayLike +function getEither (in1: Iterable, in2: ArrayLike) { +>getEither : Symbol(getEither, Decl(arrayFrom.ts, 24, 70)) +>T : Symbol(T, Decl(arrayFrom.ts, 29, 19)) +>in1 : Symbol(in1, Decl(arrayFrom.ts, 29, 23)) +>Iterable : Symbol(Iterable, Decl(lib.es2015.iterable.d.ts, --, --)) +>T : Symbol(T, Decl(arrayFrom.ts, 29, 19)) +>in2 : Symbol(in2, Decl(arrayFrom.ts, 29, 40)) +>ArrayLike : Symbol(ArrayLike, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(arrayFrom.ts, 29, 19)) + + return Math.random() > 0.5 ? in1 : in2; +>Math.random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) +>in1 : Symbol(in1, Decl(arrayFrom.ts, 29, 23)) +>in2 : Symbol(in2, Decl(arrayFrom.ts, 29, 40)) +} + diff --git a/tests/baselines/reference/arrayFrom.types b/tests/baselines/reference/arrayFrom.types new file mode 100644 index 0000000000000..f6a04dc442357 --- /dev/null +++ b/tests/baselines/reference/arrayFrom.types @@ -0,0 +1,176 @@ +=== tests/cases/compiler/arrayFrom.ts === +// Tests fix for #20432, ensures Array.from accepts all valid inputs +// Also tests for #19682 + +interface A { +>A : A + + a: string; +>a : string +} + +interface B { +>B : B + + b: string; +>b : string +} + +const inputA: A[] = []; +>inputA : A[] +>A : A +>[] : undefined[] + +const inputB: B[] = []; +>inputB : B[] +>B : B +>[] : undefined[] + +const inputALike: ArrayLike = { length: 0 }; +>inputALike : ArrayLike +>ArrayLike : ArrayLike +>A : A +>{ length: 0 } : { length: number; } +>length : number +>0 : 0 + +const inputARand = getEither(inputA, inputALike); +>inputARand : ArrayLike | Iterable +>getEither(inputA, inputALike) : ArrayLike | Iterable +>getEither : (in1: Iterable, in2: ArrayLike) => Iterable | ArrayLike +>inputA : A[] +>inputALike : ArrayLike + +const result1: A[] = Array.from(inputA); +>result1 : A[] +>A : A +>Array.from(inputA) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputA : A[] + +const result2: A[] = Array.from(inputA.values()); +>result2 : A[] +>A : A +>Array.from(inputA.values()) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputA.values() : IterableIterator +>inputA.values : () => IterableIterator +>inputA : A[] +>values : () => IterableIterator + +const result3: B[] = Array.from(inputA.values()); // expect error +>result3 : B[] +>B : B +>Array.from(inputA.values()) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputA.values() : IterableIterator +>inputA.values : () => IterableIterator +>inputA : A[] +>values : () => IterableIterator + +const result4: A[] = Array.from(inputB, ({ b }): A => ({ a: b })); +>result4 : A[] +>A : A +>Array.from(inputB, ({ b }): A => ({ a: b })) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputB : B[] +>({ b }): A => ({ a: b }) : ({ b }: B) => A +>b : string +>A : A +>({ a: b }) : { a: string; } +>{ a: b } : { a: string; } +>a : string +>b : string + +const result5: A[] = Array.from(inputALike); +>result5 : A[] +>A : A +>Array.from(inputALike) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputALike : ArrayLike + +const result6: B[] = Array.from(inputALike); // expect error +>result6 : B[] +>B : B +>Array.from(inputALike) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputALike : ArrayLike + +const result7: B[] = Array.from(inputALike, ({ a }): B => ({ b: a })); +>result7 : B[] +>B : B +>Array.from(inputALike, ({ a }): B => ({ b: a })) : B[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputALike : ArrayLike +>({ a }): B => ({ b: a }) : ({ a }: A) => B +>a : string +>B : B +>({ b: a }) : { b: string; } +>{ b: a } : { b: string; } +>b : string +>a : string + +const result8: A[] = Array.from(inputARand); +>result8 : A[] +>A : A +>Array.from(inputARand) : A[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputARand : ArrayLike | Iterable + +const result9: B[] = Array.from(inputARand, ({ a }): B => ({ b: a })); +>result9 : B[] +>B : B +>Array.from(inputARand, ({ a }): B => ({ b: a })) : B[] +>Array.from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>Array : ArrayConstructor +>from : { (iterable: Iterable | ArrayLike): T[]; (iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; (arrayLike: ArrayLike): T[]; (arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } +>inputARand : ArrayLike | Iterable +>({ a }): B => ({ b: a }) : ({ a }: A) => B +>a : string +>B : B +>({ b: a }) : { b: string; } +>{ b: a } : { b: string; } +>b : string +>a : string + +// if this is written inline, the compiler seems to infer +// the ?: as always taking the false branch, narrowing to ArrayLike, +// even when the type is written as : Iterable|ArrayLike +function getEither (in1: Iterable, in2: ArrayLike) { +>getEither : (in1: Iterable, in2: ArrayLike) => Iterable | ArrayLike +>T : T +>in1 : Iterable +>Iterable : Iterable +>T : T +>in2 : ArrayLike +>ArrayLike : ArrayLike +>T : T + + return Math.random() > 0.5 ? in1 : in2; +>Math.random() > 0.5 ? in1 : in2 : Iterable | ArrayLike +>Math.random() > 0.5 : boolean +>Math.random() : number +>Math.random : () => number +>Math : Math +>random : () => number +>0.5 : 0.5 +>in1 : Iterable +>in2 : ArrayLike +} + diff --git a/tests/baselines/reference/arrayLiterals3.errors.txt b/tests/baselines/reference/arrayLiterals3.errors.txt index 8c36d7d59c148..a3a3b88bc4a8a 100644 --- a/tests/baselines/reference/arrayLiterals3.errors.txt +++ b/tests/baselines/reference/arrayLiterals3.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(10,5): error TS2322: Type 'undefined[]' is not assignable to type '[any, any, any]'. Property '0' is missing in type 'undefined[]'. -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,5): error TS2322: Type '["string", number, boolean]' is not assignable to type '[boolean, string, number]'. - Type '"string"' is not assignable to type 'boolean'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,5): error TS2322: Type '[string, number, boolean]' is not assignable to type '[boolean, string, number]'. + Type 'string' is not assignable to type 'boolean'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'. Types of property 'length' are incompatible. Type '4' is not assignable to type '2'. @@ -34,8 +34,8 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error !!! error TS2322: Property '0' is missing in type 'undefined[]'. var a1: [boolean, string, number] = ["string", 1, true]; // Error ~~ -!!! error TS2322: Type '["string", number, boolean]' is not assignable to type '[boolean, string, number]'. -!!! error TS2322: Type '"string"' is not assignable to type 'boolean'. +!!! error TS2322: Type '[string, number, boolean]' is not assignable to type '[boolean, string, number]'. +!!! error TS2322: Type 'string' is not assignable to type 'boolean'. // The resulting type an array literal expression is determined as follows: // - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1), diff --git a/tests/baselines/reference/arrayLiterals3.types b/tests/baselines/reference/arrayLiterals3.types index 827f35ead8cbd..926f1448a4466 100644 --- a/tests/baselines/reference/arrayLiterals3.types +++ b/tests/baselines/reference/arrayLiterals3.types @@ -14,7 +14,7 @@ var a0: [any, any, any] = []; // Error var a1: [boolean, string, number] = ["string", 1, true]; // Error >a1 : [boolean, string, number] ->["string", 1, true] : ["string", number, boolean] +>["string", 1, true] : [string, number, boolean] >"string" : "string" >1 : 1 >true : true diff --git a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt index 7ffe8317d4228..87c8b59ee1e61 100644 --- a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt +++ b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt @@ -1,12 +1,12 @@ tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(13,1): error TS2322: Type 'A[]' is not assignable to type 'ReadonlyArray'. Types of property 'concat' are incompatible. - Type '{ (...items: ReadonlyArray[]): A[]; (...items: (A | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: ReadonlyArray[]): B[]; (...items: (B | ReadonlyArray)[]): B[]; }'. + Type '{ (...items: (A[] | ReadonlyArray)[]): A[]; (...items: (A | A[] | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: (B[] | ReadonlyArray)[]): B[]; (...items: (B | B[] | ReadonlyArray)[]): B[]; }'. Type 'A[]' is not assignable to type 'B[]'. Type 'A' is not assignable to type 'B'. Property 'b' is missing in type 'A'. tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(18,1): error TS2322: Type 'C' is not assignable to type 'ReadonlyArray'. Types of property 'concat' are incompatible. - Type '{ (...items: ReadonlyArray[]): A[]; (...items: (A | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: ReadonlyArray[]): B[]; (...items: (B | ReadonlyArray)[]): B[]; }'. + Type '{ (...items: (A[] | ReadonlyArray)[]): A[]; (...items: (A | A[] | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: (B[] | ReadonlyArray)[]): B[]; (...items: (B | B[] | ReadonlyArray)[]): B[]; }'. Type 'A[]' is not assignable to type 'B[]'. @@ -27,7 +27,7 @@ tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(18,1): error T ~~~ !!! error TS2322: Type 'A[]' is not assignable to type 'ReadonlyArray'. !!! error TS2322: Types of property 'concat' are incompatible. -!!! error TS2322: Type '{ (...items: ReadonlyArray[]): A[]; (...items: (A | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: ReadonlyArray[]): B[]; (...items: (B | ReadonlyArray)[]): B[]; }'. +!!! error TS2322: Type '{ (...items: (A[] | ReadonlyArray)[]): A[]; (...items: (A | A[] | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: (B[] | ReadonlyArray)[]): B[]; (...items: (B | B[] | ReadonlyArray)[]): B[]; }'. !!! error TS2322: Type 'A[]' is not assignable to type 'B[]'. !!! error TS2322: Type 'A' is not assignable to type 'B'. !!! error TS2322: Property 'b' is missing in type 'A'. @@ -39,6 +39,6 @@ tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(18,1): error T ~~~ !!! error TS2322: Type 'C' is not assignable to type 'ReadonlyArray'. !!! error TS2322: Types of property 'concat' are incompatible. -!!! error TS2322: Type '{ (...items: ReadonlyArray[]): A[]; (...items: (A | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: ReadonlyArray[]): B[]; (...items: (B | ReadonlyArray)[]): B[]; }'. +!!! error TS2322: Type '{ (...items: (A[] | ReadonlyArray)[]): A[]; (...items: (A | A[] | ReadonlyArray)[]): A[]; }' is not assignable to type '{ (...items: (B[] | ReadonlyArray)[]): B[]; (...items: (B | B[] | ReadonlyArray)[]): B[]; }'. !!! error TS2322: Type 'A[]' is not assignable to type 'B[]'. \ No newline at end of file diff --git a/tests/baselines/reference/assignToFn.types b/tests/baselines/reference/assignToFn.types index 927f2261fcf3b..160b8d2755757 100644 --- a/tests/baselines/reference/assignToFn.types +++ b/tests/baselines/reference/assignToFn.types @@ -13,9 +13,9 @@ module M { var x:I={ f:function(n) { return true; } }; >x : I >I : I ->{ f:function(n) { return true; } } : { f: (n: number) => true; } ->f : (n: number) => true ->function(n) { return true; } : (n: number) => true +>{ f:function(n) { return true; } } : { f: (n: number) => boolean; } +>f : (n: number) => boolean +>function(n) { return true; } : (n: number) => boolean >n : number >true : true diff --git a/tests/baselines/reference/assignmentTypeNarrowing.types b/tests/baselines/reference/assignmentTypeNarrowing.types index 8c5fea315cec2..5b43771f086a7 100644 --- a/tests/baselines/reference/assignmentTypeNarrowing.types +++ b/tests/baselines/reference/assignmentTypeNarrowing.types @@ -12,14 +12,14 @@ x; // string >x : string [x] = [true]; ->[x] = [true] : [true] +>[x] = [true] : [boolean] >[x] : [string | number | boolean | RegExp] >x : string | number | boolean | RegExp ->[true] : [true] +>[true] : [boolean] >true : true x; // boolean ->x : true +>x : boolean [x = ""] = [1]; >[x = ""] = [1] : [number] @@ -34,24 +34,24 @@ x; // string | number >x : string | number ({x} = {x: true}); ->({x} = {x: true}) : { x: true; } ->{x} = {x: true} : { x: true; } +>({x} = {x: true}) : { x: boolean; } +>{x} = {x: true} : { x: boolean; } >{x} : { x: string | number | boolean | RegExp; } >x : string | number | boolean | RegExp ->{x: true} : { x: true; } +>{x: true} : { x: boolean; } >x : boolean >true : true x; // boolean ->x : true +>x : boolean ({y: x} = {y: 1}); ->({y: x} = {y: 1}) : { y: 1; } ->{y: x} = {y: 1} : { y: 1; } +>({y: x} = {y: 1}) : { y: number; } +>{y: x} = {y: 1} : { y: number; } >{y: x} : { y: string | number | boolean | RegExp; } >y : string | number | boolean | RegExp >x : string | number | boolean | RegExp ->{y: 1} : { y: 1; } +>{y: 1} : { y: number; } >y : number >1 : 1 @@ -59,16 +59,16 @@ x; // number >x : number ({x = ""} = {x: true}); ->({x = ""} = {x: true}) : { x?: true; } ->{x = ""} = {x: true} : { x?: true; } +>({x = ""} = {x: true}) : { x?: boolean; } +>{x = ""} = {x: true} : { x?: boolean; } >{x = ""} : { x?: string | number | boolean | RegExp; } >x : string | number | boolean | RegExp ->{x: true} : { x?: true; } +>{x: true} : { x?: boolean; } >x : boolean >true : true x; // string | boolean ->x : string | true +>x : string | boolean ({y: x = /a/} = {y: 1}); >({y: x = /a/} = {y: 1}) : { y?: number; } diff --git a/tests/baselines/reference/asyncFunctionReturnType.types b/tests/baselines/reference/asyncFunctionReturnType.types index d1dab14ba87c6..57fb294e49a14 100644 --- a/tests/baselines/reference/asyncFunctionReturnType.types +++ b/tests/baselines/reference/asyncFunctionReturnType.types @@ -15,7 +15,7 @@ async function fAsyncExplicit(): Promise<[number, boolean]> { // This is contextually typed as a tuple. return [1, true]; ->[1, true] : [number, true] +>[1, true] : [number, boolean] >1 : 1 >true : true } diff --git a/tests/baselines/reference/baseClassImprovedMismatchErrors.errors.txt b/tests/baselines/reference/baseClassImprovedMismatchErrors.errors.txt new file mode 100644 index 0000000000000..585c929d9a465 --- /dev/null +++ b/tests/baselines/reference/baseClassImprovedMismatchErrors.errors.txt @@ -0,0 +1,73 @@ +tests/cases/compiler/baseClassImprovedMismatchErrors.ts(8,5): error TS2416: Property 'n' in type 'Derived' is not assignable to the same property in base type 'string | Base'. + Type 'string | Derived' is not assignable to type 'string | Base'. + Type 'Derived' is not assignable to type 'string | Base'. + Type 'Derived' is not assignable to type 'Base'. + Types of property 'n' are incompatible. + Type 'string | Derived' is not assignable to type 'string | Base'. + Type 'Derived' is not assignable to type 'string | Base'. + Type 'Derived' is not assignable to type 'Base'. +tests/cases/compiler/baseClassImprovedMismatchErrors.ts(9,5): error TS2416: Property 'fn' in type 'Derived' is not assignable to the same property in base type '() => number'. + Type '() => string | number' is not assignable to type '() => number'. + Type 'string | number' is not assignable to type 'number'. + Type 'string' is not assignable to type 'number'. +tests/cases/compiler/baseClassImprovedMismatchErrors.ts(14,5): error TS2416: Property 'n' in type 'DerivedInterface' is not assignable to the same property in base type 'string | Base'. + Type 'string | DerivedInterface' is not assignable to type 'string | Base'. + Type 'DerivedInterface' is not assignable to type 'string | Base'. + Type 'DerivedInterface' is not assignable to type 'Base'. + Types of property 'n' are incompatible. + Type 'string | DerivedInterface' is not assignable to type 'string | Base'. + Type 'DerivedInterface' is not assignable to type 'string | Base'. + Type 'DerivedInterface' is not assignable to type 'Base'. +tests/cases/compiler/baseClassImprovedMismatchErrors.ts(15,5): error TS2416: Property 'fn' in type 'DerivedInterface' is not assignable to the same property in base type '() => number'. + Type '() => string | number' is not assignable to type '() => number'. + Type 'string | number' is not assignable to type 'number'. + Type 'string' is not assignable to type 'number'. + + +==== tests/cases/compiler/baseClassImprovedMismatchErrors.ts (4 errors) ==== + class Base { + n: Base | string; + fn() { + return 10; + } + } + class Derived extends Base { + n: Derived | string; + ~ +!!! error TS2416: Property 'n' in type 'Derived' is not assignable to the same property in base type 'string | Base'. +!!! error TS2416: Type 'string | Derived' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'Derived' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'Derived' is not assignable to type 'Base'. +!!! error TS2416: Types of property 'n' are incompatible. +!!! error TS2416: Type 'string | Derived' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'Derived' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'Derived' is not assignable to type 'Base'. + fn() { + ~~ +!!! error TS2416: Property 'fn' in type 'Derived' is not assignable to the same property in base type '() => number'. +!!! error TS2416: Type '() => string | number' is not assignable to type '() => number'. +!!! error TS2416: Type 'string | number' is not assignable to type 'number'. +!!! error TS2416: Type 'string' is not assignable to type 'number'. + return 10 as number | string; + } + } + class DerivedInterface implements Base { + n: DerivedInterface | string; + ~ +!!! error TS2416: Property 'n' in type 'DerivedInterface' is not assignable to the same property in base type 'string | Base'. +!!! error TS2416: Type 'string | DerivedInterface' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'DerivedInterface' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'DerivedInterface' is not assignable to type 'Base'. +!!! error TS2416: Types of property 'n' are incompatible. +!!! error TS2416: Type 'string | DerivedInterface' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'DerivedInterface' is not assignable to type 'string | Base'. +!!! error TS2416: Type 'DerivedInterface' is not assignable to type 'Base'. + fn() { + ~~ +!!! error TS2416: Property 'fn' in type 'DerivedInterface' is not assignable to the same property in base type '() => number'. +!!! error TS2416: Type '() => string | number' is not assignable to type '() => number'. +!!! error TS2416: Type 'string | number' is not assignable to type 'number'. +!!! error TS2416: Type 'string' is not assignable to type 'number'. + return 10 as number | string; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/baseClassImprovedMismatchErrors.js b/tests/baselines/reference/baseClassImprovedMismatchErrors.js new file mode 100644 index 0000000000000..296f9e6eb1c41 --- /dev/null +++ b/tests/baselines/reference/baseClassImprovedMismatchErrors.js @@ -0,0 +1,57 @@ +//// [baseClassImprovedMismatchErrors.ts] +class Base { + n: Base | string; + fn() { + return 10; + } +} +class Derived extends Base { + n: Derived | string; + fn() { + return 10 as number | string; + } +} +class DerivedInterface implements Base { + n: DerivedInterface | string; + fn() { + return 10 as number | string; + } +} + +//// [baseClassImprovedMismatchErrors.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var Base = /** @class */ (function () { + function Base() { + } + Base.prototype.fn = function () { + return 10; + }; + return Base; +}()); +var Derived = /** @class */ (function (_super) { + __extends(Derived, _super); + function Derived() { + return _super !== null && _super.apply(this, arguments) || this; + } + Derived.prototype.fn = function () { + return 10; + }; + return Derived; +}(Base)); +var DerivedInterface = /** @class */ (function () { + function DerivedInterface() { + } + DerivedInterface.prototype.fn = function () { + return 10; + }; + return DerivedInterface; +}()); diff --git a/tests/baselines/reference/baseClassImprovedMismatchErrors.symbols b/tests/baselines/reference/baseClassImprovedMismatchErrors.symbols new file mode 100644 index 0000000000000..19ac124a2e0be --- /dev/null +++ b/tests/baselines/reference/baseClassImprovedMismatchErrors.symbols @@ -0,0 +1,42 @@ +=== tests/cases/compiler/baseClassImprovedMismatchErrors.ts === +class Base { +>Base : Symbol(Base, Decl(baseClassImprovedMismatchErrors.ts, 0, 0)) + + n: Base | string; +>n : Symbol(Base.n, Decl(baseClassImprovedMismatchErrors.ts, 0, 12)) +>Base : Symbol(Base, Decl(baseClassImprovedMismatchErrors.ts, 0, 0)) + + fn() { +>fn : Symbol(Base.fn, Decl(baseClassImprovedMismatchErrors.ts, 1, 21)) + + return 10; + } +} +class Derived extends Base { +>Derived : Symbol(Derived, Decl(baseClassImprovedMismatchErrors.ts, 5, 1)) +>Base : Symbol(Base, Decl(baseClassImprovedMismatchErrors.ts, 0, 0)) + + n: Derived | string; +>n : Symbol(Derived.n, Decl(baseClassImprovedMismatchErrors.ts, 6, 28)) +>Derived : Symbol(Derived, Decl(baseClassImprovedMismatchErrors.ts, 5, 1)) + + fn() { +>fn : Symbol(Derived.fn, Decl(baseClassImprovedMismatchErrors.ts, 7, 24)) + + return 10 as number | string; + } +} +class DerivedInterface implements Base { +>DerivedInterface : Symbol(DerivedInterface, Decl(baseClassImprovedMismatchErrors.ts, 11, 1)) +>Base : Symbol(Base, Decl(baseClassImprovedMismatchErrors.ts, 0, 0)) + + n: DerivedInterface | string; +>n : Symbol(DerivedInterface.n, Decl(baseClassImprovedMismatchErrors.ts, 12, 40)) +>DerivedInterface : Symbol(DerivedInterface, Decl(baseClassImprovedMismatchErrors.ts, 11, 1)) + + fn() { +>fn : Symbol(DerivedInterface.fn, Decl(baseClassImprovedMismatchErrors.ts, 13, 33)) + + return 10 as number | string; + } +} diff --git a/tests/baselines/reference/baseClassImprovedMismatchErrors.types b/tests/baselines/reference/baseClassImprovedMismatchErrors.types new file mode 100644 index 0000000000000..0ca00a0224857 --- /dev/null +++ b/tests/baselines/reference/baseClassImprovedMismatchErrors.types @@ -0,0 +1,47 @@ +=== tests/cases/compiler/baseClassImprovedMismatchErrors.ts === +class Base { +>Base : Base + + n: Base | string; +>n : string | Base +>Base : Base + + fn() { +>fn : () => number + + return 10; +>10 : 10 + } +} +class Derived extends Base { +>Derived : Derived +>Base : Base + + n: Derived | string; +>n : string | Derived +>Derived : Derived + + fn() { +>fn : () => string | number + + return 10 as number | string; +>10 as number | string : string | number +>10 : 10 + } +} +class DerivedInterface implements Base { +>DerivedInterface : DerivedInterface +>Base : Base + + n: DerivedInterface | string; +>n : string | DerivedInterface +>DerivedInterface : DerivedInterface + + fn() { +>fn : () => string | number + + return 10 as number | string; +>10 as number | string : string | number +>10 : 10 + } +} diff --git a/tests/baselines/reference/bindingPatternOmittedExpressionNesting.js b/tests/baselines/reference/bindingPatternOmittedExpressionNesting.js index e2dff30887937..0a8542ee6375b 100644 --- a/tests/baselines/reference/bindingPatternOmittedExpressionNesting.js +++ b/tests/baselines/reference/bindingPatternOmittedExpressionNesting.js @@ -9,3 +9,4 @@ var _b, _c, _d, _e; //// [bindingPatternOmittedExpressionNesting.d.ts] +export {}; diff --git a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt index ecae349e19e63..e01fce657817d 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/jsx/file.tsx(42,27): error TS2322: Type '{ a: 10; b: "hi"; children: Element[]; }' is not assignable to type 'IntrinsicAttributes & SingleChildProp'. - Type '{ a: 10; b: "hi"; children: Element[]; }' is not assignable to type 'SingleChildProp'. +tests/cases/conformance/jsx/file.tsx(42,27): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'IntrinsicAttributes & SingleChildProp'. + Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. Types of property 'children' are incompatible. Type 'Element[]' is not assignable to type 'Element'. Property 'type' is missing in type 'Element[]'. @@ -49,8 +49,8 @@ tests/cases/conformance/jsx/file.tsx(42,27): error TS2322: Type '{ a: 10; b: "hi // Error let k5 = <>